diff --git a/LICENSE-2.0.txt b/LICENSE-2.0.txt new file mode 100755 index 0000000..d645695 --- /dev/null +++ b/LICENSE-2.0.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100755 index 0000000..64950af --- /dev/null +++ b/README.md @@ -0,0 +1,58 @@ +# SIEM Sample Script + +#### Powered By Sophos Central +![N|Solid](https://www.sophos.com/en-us/medialibrary/SophosNext/Images/LP/SophosCentral/central-logo-cir.png?la=en) + + +This repository contains a sample for the SIEM endpoint of the Sophos Event +API. This sample is provided for reference purposes. + +Any issues discovered using the samples should be reported on the Github +issues tracker. + + +### SIEM Sample + +Script in this directory demonstrate how to use the SIEM Event API. + +Access to the APIs requires access token that can be setup on Sophos Central UI by going to System Settings from navigation bar and then selecting API Token Management. From this page, you can click on Add Token button to create a new token. +Here is more information available on how to setup API Token: https://community.sophos.com/kb/en-us/125169 + +You can view API Swagger Specification by accessing API Access URL from the access token created under Api Token Management in Sophos Central UI. + + +### Installation ### + +Download and extract from the following link +Script requires Python 2.7.9+ to run. Its not supported on Python 3.x. + +### Configuration ### + +SIEM script gets last 12 hours of events by default. Maximum 24 hours of historical data can be retrieved. Script keeps tab of its state, it will always pick-up from where it left off based on a state file stored in state folder. Script calls the server until there are no more events available. There is also a built-in retry mechanism if there are any network issues. Script exits if there are no more events available or when retry fails. In this case next scheduled run of the script will pick-up cursor from the last run using the state file. + +Set SOPHOS_SIEM_HOME environment variable to point to the folder where config.ini, siem_cef_mapping.txt, state and log folders will be located. state and log folders are created when the script is run for the first time. + +config.ini is a configuration file that exists by default in the siem-scripts folder. + +Here are the steps to configure siem script: +1) Open config.ini in a text editor. +2) Under 'API Access URL + Headers' in the config file, copy and paste the API Access URL + Headers block from the Api Token Management page in Sophos Central. +3) Under json, cef or keyvalue, you could choose the preferred output of the response i.e. json, cef or keyvalue. +4) Under filename, you can specify the filename that your output would be saved to. Options are syslog, stdout or any custom file name. Custom files are created in a folder named log. +5) If you are using syslog then under syslog properties in the config file, configure address, facility and socktype. + + +### Running the script + +Run 'python siem.py' and you should see the results as specified in the config file. +For more options and help on running the script run 'python siem.py -h' + + +### License + +Copyright 2016 Sophos Limited + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. +You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. diff --git a/config.ini b/config.ini new file mode 100755 index 0000000..d0f91dd --- /dev/null +++ b/config.ini @@ -0,0 +1,22 @@ +[login] +# API Access URL + Headers +# API token setup steps: https://community.sophos.com/kb/en-us/125169 +token_info = + + +# format can be json, cef or keyvalue +format = json + +# filename can be syslog, stdout, any custom filename +filename = result.txt + +# endpoint can be event, alert or all +endpoint = event + +# syslog properties +# for remote address use :, for e.g. 192.1.2.3:514 +# for linux local systems use /dev/log +# for MAC OSX use /var/run/syslog +address = /var/run/syslog +facility = daemon +socktype = udp diff --git a/name_mapping.txt b/name_mapping.txt new file mode 100755 index 0000000..5c6590b --- /dev/null +++ b/name_mapping.txt @@ -0,0 +1,15 @@ +# This file is used for splitting 'name' field into its parts using the provided regex. + +# Format +# type regex_to_split_name_field new_field_name_1 new_field_name_2 ..... +Event::Endpoint::Threat::Detected \'(.*?)\' detection_identity_name filePath +Event::Endpoint::Threat::CleanedUp \'(.*?)\' detection_identity_name filePath +Event::Endpoint::Threat::HIPSDismissed \'(.*?)\' detection_identity_name filePath +Event::Endpoint::Threat::HIPSDetected \'(.*?)\' detection_identity_name filePath +Event::Endpoint::Threat::PuaDetected \'(.*?)\' detection_identity_name filePath +Event::Endpoint::Threat::PuaCleanupFailed \'(.*?)\' detection_identity_name filePath +Event::Endpoint::Threat::HIPSDetected \'(.*?)\' detection_identity_name filePath +Event::Endpoint::Threat::HIPSDismissed \'(.*?)\' detection_identity_name filePath +Event::Endpoint::Threat::CleanupFailed \'(.*?)\' detection_identity_name filePath +Event::Endpoint::Threat::CommandAndControlDismissed \'(.*?)\' detection_identity_name filePath +Event::Endpoint::Threat::HIPSCleanupFailed \'(.*?)\' detection_identity_name filePath \ No newline at end of file diff --git a/siem.py b/siem.py new file mode 100755 index 0000000..13e0401 --- /dev/null +++ b/siem.py @@ -0,0 +1,556 @@ +#!/usr/bin/env python + +# Copyright 2016 Sophos Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in +# compliance with the License. +# You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software distributed under the License is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +# implied. See the License for the specific language governing permissions and limitations under the +# License. +# +import sys +req_version = (2, 7, 9) +cur_version = sys.version_info +if cur_version >= (3, 0): + sys.stderr.write("Python 3.x is not supported. %s") + sys.exit(1) +elif cur_version < req_version: + sys.stderr.write("Python 2.7.9+ is supported.") + sys.exit(1) +import calendar +import ConfigParser +import collections +import datetime +import json +import logging +import logging.handlers +import os +import pickle +import re +import socket +import time +import urllib2 +from optparse import OptionParser +from random import randint + +try: + import syslog + + SYSLOG_FACILITY = {'auth': syslog.LOG_AUTH, + 'cron': syslog.LOG_CRON, + 'daemon': syslog.LOG_DAEMON, + 'kern': syslog.LOG_KERN, + 'lpr': syslog.LOG_LPR, + 'mail': syslog.LOG_MAIL, + 'news': syslog.LOG_NEWS, + 'syslog': syslog.LOG_SYSLOG, + 'user': syslog.LOG_USER, + 'uucp': syslog.LOG_UUCP, + 'local0': syslog.LOG_LOCAL0, + 'local1': syslog.LOG_LOCAL1, + 'local2': syslog.LOG_LOCAL2, + 'local3': syslog.LOG_LOCAL3, + 'local4': syslog.LOG_LOCAL4, + 'local5': syslog.LOG_LOCAL5, + 'local6': syslog.LOG_LOCAL6, + 'local7': syslog.LOG_LOCAL7} + + SYSLOG_SOCKTYPE = {'udp': socket.SOCK_DGRAM, + 'tcp': socket.SOCK_STREAM} + +except ImportError: + syslog = None + + +VERSION = '1.0.0' +LIGHT = False +DEBUG = False +QUIET = False +MISSING_VALUE = 'NA' +DEFAULT_ENDPOINT = 'event' +PREFIX_PATTERN = re.compile(r'([|\\])') +EXTENSION_PATTERN = re.compile(r'([=\\])') + +SEVERITY_MAP = {'none': 0, + 'low': 1, + 'medium': 5, + 'high': 8, + 'very_high': 10} + +NOISY_EVENTTYPES = ['Event::Endpoint::NonCompliant', + 'Event::Endpoint::Compliant', + 'Event::Endpoint::Device::AlertedOnly', + 'Event::Endpoint::UpdateFailure', + 'Event::Endpoint::SavScanComplete', + 'Event::Endpoint::Application::Allowed', + 'Event::Endpoint::UpdateSuccess', + 'Event::Endpoint::WebControlViolation', + 'Event::Endpoint::WebFilteringBlocked'] + +ENDPOINT_MAP = {'event': ['/siem/v1/events'], + 'alert': ['/siem/v1/alerts'], + 'all': ['/siem/v1/events', '/siem/v1/alerts']} + +CEF_CONFIG = {'cef.version': '0', 'cef.device_vendor': 'sophos', + 'cef.device_product': 'sophos central', 'cef.device_version': 1.0} + +# CEF format from https://www.protect724.hpe.com/docs/DOC-1072 +CEF_FORMAT = ('CEF:%(version)s|%(device_vendor)s|%(device_product)s|' + '%(device_version)s|%(device_event_class_id)s|%(name)s|%(severity)s|') + + +def main(): + global NOISY_EVENTTYPES, LIGHT, DEBUG, CEF_MAPPING, NAME_MAPPING, QUIET + + if 'SOPHOS_SIEM_HOME' in os.environ: + app_path = os.environ['SOPHOS_SIEM_HOME'] + else: + # Setup path + app_path = os.path.join(os.getcwd()) + + config_file = os.path.join(app_path, 'config.ini') + + parser = OptionParser(description="Download event and/or alert data and output to various formats. " + "config.ini is a configuration file that exists by default in the siem-scripts " + "folder." + "Script keeps tab of its state, it will always pick-up from where it left-off " + "based on a state file stored in state folder. Set SOPHOS_SIEM_HOME environment " + "variable to point to the folder where config.ini, mapping files, state " + "and log folders will be located. state and log folders are created when the " + "script is run for the first time. ") + parser.add_option('-s', '--since', default=False, action='store', help="Return results since specified Unix " + "Timestamp, max last 24 hours, defaults to " + "last 12 hours if there is no state file") + parser.add_option('-c', '--config', default=config_file, action='store', help="Specify a configuration file, " + "defaults to config.ini") + parser.add_option('-l', '--light', default=False, action='store_true', help="Ignore noisy events - web control, " + "device control, update failure, " + "application allowed, (non)compliant") + parser.add_option('-d', '--debug', default=False, action='store_true', help="Print debug logs") + parser.add_option('-v', '--version', default=False, action='store_true', help="Print version") + parser.add_option('-q', '--quiet', default=False, action='store_true', help="Suppress status messages") + + options, args = parser.parse_args() + + if options.config is None: + parser.error("Need a config file specified") + + if options.version: + log(VERSION) + sys.exit(0) + if options.quiet: + QUIET = True + + # Read config file + config = ConfigParser.ConfigParser() + config.read(options.config) + + try: + token_info = config.get('login', 'token_info') + token_list = token_info.split(',') + url = token_list[0].split(': ')[1] + api_key = token_list[1].strip() + authorization = token_list[2].strip() + log("Config loaded, retrieving results for '%s'" % api_key) + log("Config retrieving results for '%s'" % authorization) + except: + e = sys.exc_info()[0] + log("Failed to parse token_info in config file, %s" % e) + sys.exit(1) + + if config.get('login', 'endpoint') in ENDPOINT_MAP: + tuple_endpoint = ENDPOINT_MAP[config.get('login', 'endpoint')] + else: + tuple_endpoint = ENDPOINT_MAP[DEFAULT_ENDPOINT] + + log_format = config.get('login', 'format') + filename = config.get('login', 'filename') + if filename == 'syslog': + if syslog is None: + log('syslog is not supported on this platform') + sys.exit(1) + + CEF_MAPPING = read_cef_mapping_file(app_path) + NAME_MAPPING = read_name_mapping_file(app_path) + + state_dir = os.path.join(app_path, 'state') + log_dir = os.path.join(app_path, 'log') + + create_log_and_state_dir(state_dir, log_dir) + + if options.light: + LIGHT = True + + if options.debug: + DEBUG = True + handler = urllib2.HTTPSHandler(debuglevel=1) + else: + handler = urllib2.HTTPSHandler() + opener = urllib2.build_opener(handler) + + creds = {'url': url, + 'api_key': api_key, + 'authorization': authorization + } + + endpoint_config = {'format': log_format, + 'filename': filename, + 'state_dir': state_dir, + 'log_dir': log_dir, + 'since': options.since} + if filename == 'syslog': + endpoint_config['facility'] = (config.get('login', 'facility')).strip() + endpoint_config['address'] = config.get('login', 'address') + endpoint_config['socktype'] = (config.get('login', 'socktype')).strip() + + for endpoint in tuple_endpoint: + process_endpoint(endpoint, opener, endpoint_config, creds) + + +def process_endpoint(endpoint, opener, endpoint_config, creds): + state_file_name = "siem_lastrun_" + endpoint.rsplit('/', 1)[-1] + ".obj" + state_file_path = os.path.join(endpoint_config['state_dir'], state_file_name) + if LIGHT and endpoint == ENDPOINT_MAP['event']: + log("Light mode - not retrieving:%s" % '; '.join(NOISY_EVENTTYPES)) + + log("Config endpoint=%s, filename='%s' and format='%s'" % + (endpoint, endpoint_config['filename'], endpoint_config['format'])) + log("Config state_file='%s' and cwd='%s'" % (state_file_path, os.getcwd())) + cursor = False + since = False + if endpoint_config['since']: # Run since supplied datetime + since = endpoint_config['since'] + else: + try: # Run since last run (retrieve from state_file) + with open(state_file_path, 'r') as f: + cursor = pickle.load(f) + except IOError: # Default to current time + since = int(calendar.timegm(((datetime.datetime.utcnow() - datetime.timedelta(hours=12)).timetuple()))) + log("No datetime found, defaulting to last 12 hours for results") + + if since is not False: + log('Retrieving results since: %s' % since) + else: + log('Retrieving results starting cursor: %s' % cursor) + + siem_logger = logging.getLogger('SIEM') + logging.basicConfig(format='%(message)s') + siem_logger.setLevel(logging.INFO) + siem_logger.propagate = False + if endpoint_config['filename'] == 'syslog': + facility = SYSLOG_FACILITY[endpoint_config['facility']] + address = endpoint_config['address'] + if ':' in address: + result = address.split(':') + host = result[0] + port = result[1] + address = (host, int(port)) + + socktype = SYSLOG_SOCKTYPE[endpoint_config['socktype']] + logging_handler = logging.handlers.SysLogHandler(address, facility, socktype) + elif endpoint_config['filename'] == 'stdout': + logging_handler = logging.StreamHandler(sys.stdout) + else: + logging_handler = logging.\ + FileHandler(os.path.join(endpoint_config['log_dir'], endpoint_config['filename']), 'a', encoding='utf-8') + siem_logger.addHandler(logging_handler) + + results = call_endpoint(opener, endpoint, since, cursor, state_file_path, creds) + + if endpoint_config['format'] == 'json': + write_json_format(results, siem_logger) + elif endpoint_config['format'] == 'keyvalue': + write_keyvalue_format(results, siem_logger) + elif endpoint_config['format'] == 'cef': + write_cef_format(results, siem_logger) + else: + write_json_format(results, siem_logger) + + +def to_str(data): + if isinstance(data, unicode): + return data.encode('utf8') + return str(data) + + +def write_json_format(results, siem_logger): + for i in results: + i = remove_null_values(i) + update_cef_keys(i) + update_name_field(i) + siem_logger.info(json.dumps(i, ensure_ascii=False) + u'\n') + + +def write_keyvalue_format(results, siem_logger): + for i in results: + i = remove_null_values(i) + update_cef_keys(i) + update_name_field(i) + date = i[u'created_at'] + events = list('%s="%s";' % (k, (convert(v))) for k, v in i.items()) + siem_logger.info(' '.join([date, ] + events) + u'\n') + + +# Split 'name' field into multiple fields based on regex and field names specified in the name_mapping.txt +# Original 'name' field is replaced with the first value returned by regex used for splitting 'name' field. +def update_name_field(data): + if data[u'type'] in NAME_MAPPING: + try: + # name_list has a compiled regex followed by new field names in which name field needs to be split into. + name_list = NAME_MAPPING[data[u'type']] + prog_regex = name_list[0] + result = prog_regex.findall(data[u'name']) + if len(result) == len(name_list) - 1: + # update name with the first value for CEF as its name is a required header in CEF + data[u'name'] = result[0] + for idx, item in enumerate(name_list[1:]): + data[item] = result[idx] + + except: + e = sys.exc_info()[0] + log("Failed to split name field for event type %s, error %s" % (data[u'type'], e)) + + +# Fastest way to convert a dict's keys & values from `unicode` to `str`? +# from http://stackoverflow.com/questions/1254454/fastest-way-to-convert-a-dicts-keys-values-from-unicode-to-str +def convert(data): + # encoding unicode strings with utf8 + # print type(data) + if isinstance(data, unicode): + return data.encode('utf8') + elif isinstance(data, collections.Mapping): + return dict(map(convert, data.iteritems())) + elif isinstance(data, collections.Iterable): + return type(data)(map(convert, data)) + return str(data) + + +def write_cef_format(results, siem_logger): + for i in results: + i = remove_null_values(i) + update_name_field(i) + siem_logger.info(format_cef(flatten_json(i)) + u'\n') + + +def create_log_and_state_dir(state_dir, log_dir): + if not os.path.exists(state_dir): + try: + os.makedirs(state_dir) + except OSError as e: + log("Failed to create %s, %s" % (state_dir, str(e))) + sys.exit(1) + if not os.path.exists(log_dir): + try: + os.makedirs(log_dir) + except OSError as e: + log("Failed to create %s, %s" % (log_dir, str(e))) + sys.exit(1) + + +def call_endpoint(opener, endpoint, since, cursor, state_file_path, creds): + default_headers = {'Content-Type': 'application/json; charset=utf-8', + 'Accept': 'application/json', + 'X-Locale': 'en', + 'Authorization': creds['authorization'].split(":")[1], + 'x-api-key': creds['api_key'].split(":")[1]} + + params = { + 'limit': 1000 + } + if not cursor: + params['from_date'] = since + else: + params['cursor'] = cursor + jitter() + + while True: + if LIGHT and endpoint == ENDPOINT_MAP['event']: + types = ','.join(["%s" % t for t in NOISY_EVENTTYPES]) + types = 'exclude_types=' + types + args = '&'.join(['%s=%s' % (k, v) for k, v in params.items()]+[types, ]) + else: + args = '&'.join(['%s=%s' % (k, v) for k, v in params.items()]) + events_request_url = '%s%s?%s' % (creds['url'], endpoint, args) + log("URL: %s" % events_request_url) + events_request = urllib2.Request(events_request_url, None, default_headers) + + for k, v in default_headers.items(): + events_request.add_header(k, v) + + events_response = request_url(opener, events_request) + if DEBUG: + log("RESPONSE: %s" % events_response) + events = json.loads(events_response) + + # events looks like this + # { + # u'chart_detail': {u'2014-10-01T00:00:00.000Z': 3638}, + # u'event_counts': {u'Event::Endpoint::Compliant': 679, + # u'events': {} + # } + for e in events['items']: + yield e + + store_state(events['next_cursor'], state_file_path) + if not events['has_more']: + break + else: + params['cursor'] = events['next_cursor'] + params.pop('from_date', None) + + +def store_state(next_cursor, state_file_path): + # Store cursor + log("Next run will retrieve results using cursor %s\n" % next_cursor) + with open(state_file_path, 'wb') as f: + pickle.dump(next_cursor, f) + + +# Flattening JSON objects in Python +# https://medium.com/@amirziai/flattening-json-objects-in-python-f5343c794b10#.37u7axqta +def flatten_json(y): + out = {} + + def flatten(x, name=''): + if type(x) is dict: + for a in x: + flatten(x[a], name + a + '_') + else: + out[name[:-1]] = x + + flatten(y) + return out + + +def log(s): + if not QUIET: + sys.stderr.write('%s\n' % s) + + +def read_cef_mapping_file(app_path): + cef_mapping = {} + with open(os.path.join(app_path, "siem_cef_mapping.txt")) as f: + for line in f: + if line.startswith('#') or line == "\n": + pass + else: + (key, val) = line.split() + cef_mapping[key] = val + return cef_mapping + + +def read_name_mapping_file(app_path): + name_mapping = {} + with open(os.path.join(app_path, "name_mapping.txt")) as f: + for line in f: + if line.startswith('#') or line == "\n": + pass + else: + words = line.split() + name_list = list(words[2:]) + name_list.insert(0, re.compile(words[1])) + name_mapping[words[0]] = name_list + return name_mapping + + +def jitter(): + time.sleep(randint(0, 10)) + + +def request_url(opener, request): + for i in [1, 2, 3]: # Some ops we simply retry + try: + response = opener.open(request) + except urllib2.HTTPError as e: + if e.code in (503, 504, 403, 429): + log('Error "%s" (code %s) on attempt #%s of 3, retrying' % (e, e.code, i)) + if i < 3: + continue + log('Error during request. Error code: %s, Error message: %s' % (e.code, e.read())) + raise + return response.read() + + +def format_prefix(data): + # pipe and backslash in header must be escaped + data = to_str(data) + # escape group with backslash + return PREFIX_PATTERN.sub(r'\\\1', data) + + +def format_extension(data): + # equal sign and backslash in extension value must be escaped + data = to_str(data) + # escape group with backslash + return EXTENSION_PATTERN.sub(r'\\\1', data) + + +def map_severity(severity): + if severity in SEVERITY_MAP: + return SEVERITY_MAP[severity] + else: + msg = 'The "%s" severity can not be mapped, defaulting to 0' % severity + log(msg) + return SEVERITY_MAP['none'] + + +def extract_prefix_fields(data): + # extract prefix fields and remove those from data dictionary + name_field = CEF_MAPPING['name'] + device_event_class_id_field = CEF_MAPPING['device_event_class_id'] + severity_field = CEF_MAPPING['severity'] + + name = data.get(name_field, MISSING_VALUE) + name = format_prefix(name) + data.pop(name_field, None) + + device_event_class_id = data.get(device_event_class_id_field, MISSING_VALUE) + device_event_class_id = format_prefix(device_event_class_id) + data.pop(device_event_class_id_field, None) + + severity = data.get(severity_field, MISSING_VALUE) + severity = map_severity(severity) + data.pop(severity_field, None) + + fields = {'name': name, + 'device_event_class_id': device_event_class_id, + 'severity': severity, + 'version': CEF_CONFIG['cef.version'], + 'device_vendor': CEF_CONFIG['cef.device_vendor'], + 'device_version': CEF_CONFIG['cef.device_version'], + 'device_product': CEF_CONFIG['cef.device_product']} + return fields + + +def update_cef_keys(data): + # Replace if there is a mapped CEF key + for key, value in list(data.items()): + new_key = CEF_MAPPING.get(to_str(key), key) + if new_key == key: + continue + data[new_key] = to_str(value) + del data[key] + + +def format_cef(data): + fields = extract_prefix_fields(data) + msg = CEF_FORMAT % fields + + update_cef_keys(data) + for index, (key, value) in enumerate(data.items()): + value = format_extension(value) + if index > 0: + msg += ' %s=%s' % (key, value) + else: + msg += '%s=%s' % (key, value) + return msg + + +def remove_null_values(data): + return {k: v for k, v in data.items() if v is not None} + +if __name__ == "__main__": + main() diff --git a/siem_cef_mapping.txt b/siem_cef_mapping.txt new file mode 100755 index 0000000..59f88b4 --- /dev/null +++ b/siem_cef_mapping.txt @@ -0,0 +1,18 @@ +# This file is used for mapping CEF header prefix and extension to json returned by server + +# CEF header prefix to json mapping +# Format +# CEF_header_prefix JSON_key +device_event_class_id type +name name +severity severity + +# json to CEF extension mapping +# Format +# JSON_key CEF_extension +source suser +when end +user_id duid +created_at rt +full_file_path filePath +location dhost \ No newline at end of file