├── .gitignore ├── AUTHORS ├── LICENSE ├── README.md ├── brocapi ├── __init__.py ├── brocapi.py ├── brocapi_syslog.py └── brocapi_worker.py ├── examples ├── brocapi.conf.example ├── brocapi.service.example ├── brocapi_worker.ini.example └── brocapi_worker.service.example ├── requirements.txt └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *,cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | 93 | # Rope project settings 94 | .ropeproject 95 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Alek Rollyson - alek.rollyson@fireeye.com 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Brocapi 2 | HTTP API for mass processing PCAPs through Bro IDS, tagging, and submitting the resulting logs to a syslog server. 3 | 4 | ## Overview 5 | Brocapi consists of two parts: 6 | * A Flask API for receiving PCAPS via HTTP POST and queues a job in Redis via RQ 7 | * An RQ worker that receives the jobs queued from the API to process the PCAPs through Bro and submit the resulting logs to a syslog server. 8 | 9 | ## Requirements 10 | ### Python Modules 11 | ``` 12 | flask 13 | rq 14 | redis 15 | ``` 16 | ### System Packages 17 | ``` 18 | Bro IDS 19 | Redis instance running on the same host as the worker 20 | A Syslog server accepting TCP or UDP connections 21 | ``` 22 | ### Optional 23 | ``` 24 | gunicorn 25 | supervisor 26 | ``` 27 | 28 | ## Configuration 29 | By default Brocapi expects the config to be located at /etc/brocapi.conf 30 | ``` 31 | [main] 32 | # debug logging 33 | debug = off 34 | # worker log file 35 | worker_log = /var/log/brocapi/brocapi_worker.log 36 | # api log file 37 | api_log = /var/log/brocapi/brocapi_api.log 38 | 39 | [bro] 40 | # location of your Bro binary 41 | bro_bin = /opt/bro/bin/bro 42 | # directory to contain job output 43 | processing_dir = /opt/brocapi/jobs/ 44 | # bro logs to ignore completely 45 | log_blacklist = ["loaded_scripts.log", "packet_filter.log", "reporter.log"] 46 | 47 | [syslog] 48 | # syslog host 49 | syslog_host = 127.0.0.1 50 | # syslog port 51 | syslog_port = 514 52 | # syslog protocol (tcp/udp) 53 | syslog_proto = tcp 54 | # syslog program prefix (format string). For example if you use "bro_" as the program prefix, your HTTP logs will have the syslog program bro_http 55 | syslog_prefix = bro25_%s% 56 | ``` 57 | 58 | ## Running Brocapi 59 | The API and workers can be run directly i.e.: 60 | ``` 61 | ./brocapi.py 62 | ``` 63 | but there are a few sample configurations for running Brocapi as a service under Systemd: 64 | * brocapi.service: Runs the flask app under gunicorn 65 | * brocapi_worker.service: Runs the brocapi worker under supervisor. Included the supervisor config in brocapi_worker.ini 66 | 67 | ## Submitting a Job 68 | Brocapi only has one route `/submit/pcap` and it expects a POST request with 1 required and 1 optional parameter: 69 | * 1 or more PCAPs in an array called 'file' 70 | * Optional 'tag' parameter which Brocapi will use as the value for the syslog hostname 71 | 72 | Example submission using Curl without a job tag: 73 | ``` 74 | {11:38}~/Desktop ➭ curl -k -X POST -F 'file[]=@2017-08-28-Fobos-campaign-Rig-EK-sends-Bunitu.pcap' https://127.0.0.1/submit/pcap 75 | {"status": "job queued", "files": ["2017-08-28-Fobos-campaign-Rig-EK-sends-Bunitu.pcap"], "tag": null, "job_id": "9179876e-08cf-4539-8de7-8a8bb3b0dcaf", "success": true} 76 | ``` 77 | Example submissions using Curl with a job tag: 78 | ``` 79 | {11:39}~/Desktop ➭ curl -k -X POST -F 'file[]=@2017-08-28-Fobos-campaign-Rig-EK-sends-Bunitu.pcap' -F 'tag=testing' https://127.0.0.1/submit/pcap 80 | {"status": "job queued", "files": ["2017-08-28-Fobos-campaign-Rig-EK-sends-Bunitu.pcap"], "tag": "testing", "job_id": "507965ab-6511-4cd4-9542-4671eb140f92", "success": true}% 81 | ``` 82 | 83 | ### Returned data: 84 | ``` 85 | { 86 | "status": "job queued", ## Status of the job. Right now the only value is "job queued" since we're not async and waiting on the full status 87 | "files": [ 88 | "2017-08-28-Fobos-campaign-Rig-EK-sends-Bunitu.pcap" ## An array of the pcaps that were submitted 89 | ], 90 | "tag": "testing", ## The tag that was supplied to mark the job 91 | "job_id": "507965ab-6511-4cd4-9542-4671eb140f92", ## UUID for the job 92 | "success": true ## Success or failure 93 | } 94 | ``` 95 | ## Job Directories 96 | Once a job is received, the API will create the following example directory structure for the job: 97 | ``` 98 | jobs # Configured jobs directory 99 | └── fe5f53b3-474d-4cb7-8ece-a2786f841af7 # UUID for the job 100 | ├── logs # Directory for all the logs 101 | │   ├── bro # Directory containing all the Bro logs 102 | │   │   ├── capture_loss.log 103 | │   │   ├── conn.log 104 | │   │   ├── dhcp.log 105 | │   │   ├── dns.log 106 | │   │   ├── files.log 107 | │   │   ├── http.log 108 | │   │   ├── loaded_scripts.log 109 | │   │   ├── packet_filter.log 110 | │   │   ├── ssl.log 111 | │   │   ├── stats.log 112 | │   │   ├── weird.log 113 | │   │   └── x509.log 114 | │   └── syslog # Not used right now 115 | └── pcaps # Directory containing the submitted PCAPS 116 | ├── 1725aa89-2f9e-5a44-88da-6bce278e77d3.pcap 117 | ├── 1ec8ca5f-66dd-5200-9cf2-235638ef13f9.pcap 118 | ├── 20a3341d-8134-5136-a03c-cb8c3d3fc5be.pcap 119 | ├── 20cf04e4-a9ef-5415-9f17-bf4c80214c33.pcap 120 | └── 2f506083-8a84-57c4-8d37-9304157b0899.pcap 121 | ``` 122 | 123 | ## Worker Activity 124 | Once the API queues a job into Redis via RQ, a worker will pick up the job and perform the following actions 125 | * Iterate through the supplied PCAPS and invoke Bro with the following paramters: `bro -C -r local` 126 | * If any logs were generated, create a connection to the configured syslog server 127 | * Iterate through each generated log type and submit each line to the configured syslog server 128 | 129 | ## TODO 130 | * Make config location configurable 131 | * Make log_blacklist configurable. It exists in the config, but isn't honored by the worker 132 | * Make the Redis host configurable 133 | * Support moving logs on the host post-job for setups where a log sender might be monitoring a directory 134 | * Add a route for retrieving logs, pcaps, status, etc of previously submitted jobs -------------------------------------------------------------------------------- /brocapi/__init__.py: -------------------------------------------------------------------------------- 1 | __copyright__ = """ 2 | Copyright 2017 FireEye, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | """ 16 | __license__ = "Apache 2.0" -------------------------------------------------------------------------------- /brocapi/brocapi.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Brocapi HTTP API 3 | __copyright__ = """ 4 | Copyright 2017 FireEye, Inc. 5 | 6 | Licensed under the Apache License, Version 2.0 (the "License"); 7 | you may not use this file except in compliance with the License. 8 | You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, software 13 | distributed under the License is distributed on an "AS IS" BASIS, 14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | See the License for the specific language governing permissions and 16 | limitations under the License. 17 | """ 18 | __license__ = "Apache 2.0" 19 | 20 | import ConfigParser 21 | import json 22 | import logging 23 | import os 24 | import sys 25 | import uuid 26 | 27 | import flask 28 | import redis 29 | import rq 30 | 31 | import brocapi_worker 32 | 33 | # Set up our logger format 34 | logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s: %(message)s [%(filename)s:%(funcName)s]') 35 | logger = logging.getLogger(__name__) 36 | 37 | # Grab config 38 | logging.info("Loading config file") 39 | try: 40 | config = ConfigParser.ConfigParser() 41 | config.read('/etc/brocapi.conf') 42 | except Exception as e: 43 | logging.error("Could not read config file. Exiting.") 44 | logging.error(e) 45 | sys.exit(1) 46 | logging.info("Config file loaded successfully.") 47 | 48 | # Set to debug logging if enabled in the config 49 | if config.getboolean("main", "debug"): 50 | logger.info("Debug logger enabled") 51 | logger.setLevel(logging.DEBUG) 52 | 53 | # Find our processing dir, create it if it doesn't exist 54 | BROCAPI_PROCESSING_DIR = config.get("bro", "processing_dir") 55 | logger.debug("Using processing dir: %s", BROCAPI_PROCESSING_DIR) 56 | if not os.path.isdir(BROCAPI_PROCESSING_DIR): 57 | logger.warning("Processing directory %s doesn't exist, attempting to create it", BROCAPI_PROCESSING_DIR) 58 | try: 59 | os.makedirs(BROCAPI_PROCESSING_DIR) 60 | except: 61 | logger.error("Could not create Brocapi tmp dirs.") 62 | sys.exit(1) 63 | logger.info("Successfully created the processing directory %s", BROCAPI_PROCESSING_DIR) 64 | 65 | # Create a connection to our rq worker queue 66 | logger.info("Connecting to worker queue..") 67 | try: 68 | rs = redis.Redis() 69 | # Test if the redis server is up 70 | rs.get(None) 71 | brocapi_queue = rq.Queue(connection=rs) 72 | except Exception as e: 73 | logger.error("Error attempting to connect to worker queue!") 74 | logger.error(e) 75 | sys.exit(1) 76 | logger.info("Successfully connected to worker queue") 77 | 78 | # Set up our Flask app 79 | app = flask.Flask(__name__) 80 | 81 | 82 | @app.route('/submit/pcap', methods=['POST']) 83 | def api_submit_pcap(): 84 | """API Endpoint for Bro pcap processing""" 85 | # Create a unique job uuid and folders 86 | job_uuid = str(uuid.uuid4()) 87 | 88 | # Grab the job tag if it was supplied 89 | if 'tag' in flask.request.form: 90 | job_tag = str(flask.request.form['tag']) 91 | else: 92 | job_tag = None 93 | 94 | # Make sure we can get the pcaps from the POST data 95 | try: 96 | submitted_pcaps = flask.request.files.getlist("file[]") 97 | except: 98 | logger.error("Error retrieving pcaps from job %s", job_uuid) 99 | response = json.dumps({"job_id": job_uuid, "success": False, "status": "error retrieving supplied pcaps", "tag": job_tag}) 100 | return response, 500 101 | # If we didn't get any pcaps in the request, don't waste our time 102 | if len(submitted_pcaps) == 0: 103 | logger.warning("Job %s contained no pcaps", job_uuid) 104 | response = json.dumps({"job_id": job_uuid, "success": False, "status": "no pcaps supplied", "tag": job_tag}) 105 | return response, 500 106 | 107 | logger.info("Received the following PCAP request: job: %s, tag: %s, files: %s", job_uuid, job_tag, str(submitted_pcaps)) 108 | 109 | # Create all the jobs dirs inside the processing dir 110 | job_path = os.path.join(BROCAPI_PROCESSING_DIR, job_uuid) 111 | job_logs_dir = os.path.join(job_path, "logs") 112 | job_logs_bro = os.path.join(job_logs_dir, "bro") 113 | job_logs_syslog = os.path.join(job_logs_dir, "syslog") 114 | job_pcaps_dir = os.path.join(job_path, "pcaps") 115 | try: 116 | logger.debug("Creating job directories for job %s", job_uuid) 117 | os.makedirs(job_logs_dir) 118 | os.makedirs(job_logs_bro) 119 | os.makedirs(job_logs_syslog) 120 | os.makedirs(job_pcaps_dir) 121 | except Exception as e: 122 | logger.error("Failed to create storage for job %s", job_uuid) 123 | logger.error(e) 124 | response = json.dumps({"job_id": job_uuid, "success": False, "status": "error creating job dirs", "tag": job_tag}) 125 | return response, 500 126 | 127 | # Save all the files that were uploaded 128 | uploaded_filenames = [] 129 | for _file in submitted_pcaps: 130 | filename = os.path.split(_file.filename)[-1] 131 | file_path = os.path.join(job_pcaps_dir, filename) 132 | _file.save(os.path.abspath(file_path)) 133 | uploaded_filenames.append(filename) 134 | 135 | # Once we created the jobs dirs and saved the pcaps, queue the job in the worker queue 136 | brocapi_queue.enqueue(brocapi_worker.process_job, job_uuid, job_tag, 137 | uploaded_filenames, config.get("bro", "bro_bin"), BROCAPI_PROCESSING_DIR, 138 | config.get("syslog", "syslog_host"), config.getint("syslog", "syslog_port"), 139 | config.get("syslog", "syslog_proto"), config.get("syslog", "syslog_prefix")) 140 | logger.info("Brocapi job added to worker queue: " + job_uuid) 141 | response = json.dumps({"job_id": job_uuid, "success": True, "status": "job queued", "tag": job_tag, "files": uploaded_filenames}) 142 | return response, 200 143 | -------------------------------------------------------------------------------- /brocapi/brocapi_syslog.py: -------------------------------------------------------------------------------- 1 | __copyright__ = """ 2 | Copyright 2017 FireEye, Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | """ 16 | __license__ = "Apache 2.0" 17 | 18 | import datetime 19 | import logging 20 | import socket 21 | 22 | # Below is simple syslog implementation written by Christian Stigen Larsen 23 | # Found here: http://csl.name/py-syslog-win32/ 24 | # Will work on Windows 25 | facility = { 26 | 'kern': 0, 'user': 1, 'mail': 2, 'daemon': 3, 27 | 'auth': 4, 'syslog': 5, 'lpr': 6, 'news': 7, 28 | 'uucp': 8, 'cron': 9, 'authpriv': 10, 'ftp': 11, 29 | 'local0': 16, 'local1': 17, 'local2': 18, 'local3': 19, 30 | 'local4': 20, 'local5': 21, 'local6': 22, 'local7': 23, 31 | } 32 | 33 | level = { 34 | 'emerg': 0, 'alert': 1, 'crit': 2, 'err': 3, 35 | 'warning': 4, 'notice': 5, 'info': 6, 'debug': 7 36 | } 37 | 38 | syslog_time_format = "%b %d %H:%M:%S" 39 | today = datetime.datetime.today() 40 | 41 | def connect_syslog(syslog_server, syslog_port, syslog_proto): 42 | # set up the syslog connection 43 | try: 44 | logging.info("Connecting to syslog server %s:%s via %s", syslog_server, syslog_port, syslog_proto) 45 | if syslog_proto == "tcp": 46 | broker_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 47 | elif syslog_proto == "udp": 48 | broker_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 49 | else: 50 | logging.error("Unrecognized Syslog protocol specified!") 51 | return 1 52 | broker_socket.connect((syslog_server, syslog_port)) 53 | logging.info("Connected to syslog server %s:%s via %s", syslog_server, syslog_port, syslog_proto) 54 | return broker_socket 55 | except Exception as e: 56 | logging.error("Could not connect to syslog server!") 57 | logging.error(e) 58 | return False 59 | 60 | def format_syslog_message(hostname, program, message): 61 | syslog_message = "%s %s %s: %s" % ( 62 | today.strftime('%b %d %H:%M:%S'), hostname, program, message) 63 | syslog_message = '<%d>%s' % ( 64 | level['notice'] + facility['daemon'] * 8, syslog_message) 65 | return syslog_message 66 | -------------------------------------------------------------------------------- /brocapi/brocapi_worker.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Brocapi RQ Worker 3 | __copyright__ = """ 4 | Copyright 2017 FireEye, Inc. 5 | 6 | Licensed under the Apache License, Version 2.0 (the "License"); 7 | you may not use this file except in compliance with the License. 8 | You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, software 13 | distributed under the License is distributed on an "AS IS" BASIS, 14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | See the License for the specific language governing permissions and 16 | limitations under the License. 17 | """ 18 | __license__ = "Apache 2.0" 19 | 20 | import glob 21 | import logging 22 | import os 23 | import subprocess 24 | 25 | import brocapi_syslog 26 | 27 | TYPE_BLACKLIST = [ 28 | "capture_loss", 29 | "stats", 30 | "loaded_scripts", 31 | "packet_filter" 32 | ] 33 | 34 | def process_job(job_uuid, job_tag, pcaps, bro_bin, 35 | bro_processing_dir, syslog_host, syslog_port, 36 | syslog_proto, syslog_prefix): 37 | 38 | logging.info("Received job: %s", job_uuid) 39 | 40 | bro_log_dir = bro_processing_dir + job_uuid + "/logs/bro/" 41 | logging.info("Moving into Bro log dir: %s", bro_log_dir) 42 | os.chdir(bro_log_dir) 43 | 44 | for pcap in pcaps: 45 | pcap_path = bro_processing_dir + job_uuid + '/pcaps/' + pcap 46 | logging.debug("Calling bro for pcap %s as part of job %s", pcap_path, job_uuid) 47 | try: 48 | subprocess.call([ 49 | bro_bin, 50 | "-C", 51 | "-r", 52 | pcap_path, 53 | "local"]) 54 | except Exception as e: 55 | logging.error("Bro processing failed for pcap %s", pcap) 56 | logging.error(e) 57 | 58 | # Get all the relevant bro logs in the dir 59 | bro_logs = glob.glob('*.log') 60 | logging.debug("Found bro logs: %s", str(bro_logs)) 61 | 62 | if len(bro_logs) == 0: 63 | logging.error("No bro logs present for job %s", job_uuid) 64 | return False 65 | 66 | # Connect to syslog server 67 | logging.debug("Creating a syslog broker socket to %s:%s over %s for job %s", syslog_host, syslog_port, syslog_proto, job_uuid) 68 | broker_socket = brocapi_syslog.connect_syslog(syslog_host, syslog_port, syslog_proto) 69 | if not broker_socket: 70 | return False 71 | 72 | # Loop through all log types 73 | for _log in bro_logs: 74 | logging.debug("Processing log %s for job %s", _log, job_uuid) 75 | bro_type = _log.split(".")[0] 76 | if bro_type in TYPE_BLACKLIST: 77 | logging.debug("Skipping blacklisted type %s for job %s", bro_type, job_uuid) 78 | continue 79 | syslog_program = syslog_prefix % bro_type 80 | # handle every line in the log file 81 | with open(_log) as bro_file: 82 | for line in bro_file: 83 | if line.startswith("#"): 84 | continue 85 | if job_tag is None: 86 | job_tag = "brocapi" 87 | syslog_message = brocapi_syslog.format_syslog_message(job_tag, syslog_program, line) 88 | broker_socket.send(syslog_message) 89 | 90 | # close out the socket 91 | broker_socket.close() 92 | -------------------------------------------------------------------------------- /examples/brocapi.conf.example: -------------------------------------------------------------------------------- 1 | [main] 2 | # debug logging 3 | debug = on 4 | # worker log file 5 | worker_log = /var/log/brocapi/brocapi_worker.log 6 | # api log file 7 | api_log = /var/log/brocapi/brocapi_api.log 8 | 9 | [bro] 10 | # location of your Bro binary 11 | bro_bin = /opt/bro/bin/bro 12 | # directory to contain job output 13 | processing_dir = /opt/brocapi/jobs/ 14 | # bro logs to ignore completely 15 | log_blacklist = ["loaded_scripts.log", "packet_filter.log", "reporter.log"] 16 | 17 | [syslog] 18 | # syslog host 19 | syslog_host = 127.0.0.1 20 | # syslog port 21 | syslog_port = 514 22 | # syslog protocol (tcp/udp) 23 | syslog_proto = tcp 24 | # syslog program prefix (format string) 25 | syslog_prefix = bro25_%s -------------------------------------------------------------------------------- /examples/brocapi.service.example: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Brocapi Service 3 | After=network.target 4 | 5 | [Service] 6 | RuntimeDirectory=brocapi 7 | PIDFile=/var/run/brocapi/brocapi.pid 8 | User=bro 9 | Group=bro 10 | WorkingDirectory=/opt/brocapi/brocapi 11 | ExecStart=/usr/bin/gunicorn -k gevent --bind 192.168.100.2:8888 --pid /var/run/brocapi/brocapi.pid --log-file=/var/log/brocapi/brocapi.log --log-level=DEBUG --workers 4 brocapi:app 12 | 13 | [Install] 14 | WantedBy=multi-user.target -------------------------------------------------------------------------------- /examples/brocapi_worker.ini.example: -------------------------------------------------------------------------------- 1 | [supervisord] 2 | logfile=/var/log/brocapi/supervisord.log ; (main log file;default $CWD/supervisord.log) 3 | logfile_maxbytes=50MB ; (max main logfile bytes b4 rotation;default 50MB) 4 | logfile_backups=10 ; (num of main logfile rotation backups;default 10) 5 | loglevel=info ; (log level;default info; others: debug,warn,trace) 6 | pidfile=/var/run/brocapi/supervisord.pid ; (supervisord pidfile;default supervisord.pid) 7 | nodaemon=true ; (start in foreground if true;default false) 8 | minfds=1024 ; (min. avail startup file descriptors;default 1024) 9 | minprocs=200 ; (min. avail process descriptors;default 200) 10 | ;umask=022 ; (process file creation umask;default 022) 11 | user=bro ; (default is current user, required if root) 12 | ;;identifier=supervisor ; (supervisord identifier, default is 'supervisor') 13 | ;;directory=/tmp ; (default is not to cd during start) 14 | ;;nocleanup=true ; (don't clean up tempfiles at start;default false) 15 | ;;childlogdir=/tmp ; ('AUTO' child log dir, default $TEMP) 16 | ;;environment=KEY=value ; (key value pairs to add to environment) 17 | ;;strip_ansi=false ; (strip ansi escape codes in logs; def. false) 18 | ; 19 | [program:brocapi_worker] 20 | ; Point the command to the specific rq command you want to run. 21 | ; If you use virtualenv, be sure to point it to 22 | ; /path/to/virtualenv/bin/rq 23 | ; Also, you probably want to include a settings module to configure this 24 | ; worker. For more info on that, see http://python-rq.org/docs/workers/ 25 | command=/usr/bin/rq worker 26 | process_name=%(program_name)s_%(process_num)02d 27 | stdout_logfile = /var/log/brocapi/brocapi_worker.log 28 | stderr_logfile = /var/log/brocapi/brocapi_worker.log 29 | 30 | ; If you want to run more than one worker instance, increase this 31 | numprocs=4 32 | user=bro 33 | 34 | ; This is the directory from which RQ is ran. Be sure to point this to the 35 | ; directory where your source code is importable from 36 | directory=/opt/brocapi/brocapi 37 | 38 | ; RQ requires the TERM signal to perform a warm shutdown. If RQ does not die 39 | ; within 10 seconds, supervisor will forcefully kill it 40 | stopsignal=TERM 41 | 42 | ; These are up to you 43 | autostart=true 44 | autorestart=true -------------------------------------------------------------------------------- /examples/brocapi_worker.service.example: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Brocapi Service 3 | After=network.target 4 | 5 | [Service] 6 | RuntimeDirectory=brocapi 7 | PIDFile=/var/run/brocapi/brocapi_worker.pid 8 | User=bro 9 | Group=bro 10 | WorkingDirectory=/opt/brocapi/brocapi 11 | ExecStart=/usr/bin/supervisord -c /etc/supervisord.d/brocapi.ini 12 | 13 | [Install] 14 | WantedBy=multi-user.target -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | flask 2 | redis 3 | rq -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from distutils.core import setup 4 | 5 | setup(name='brocapi', 6 | version='1.0', 7 | description='Bro PCAP API', 8 | author='Alek Rollyson', 9 | author_email='alek.rollyson@fireeye.com', 10 | url='https://github.com/fireeye/brocapi', 11 | packages=['brocapi']) 12 | --------------------------------------------------------------------------------