├── .gitignore ├── Dockerfile ├── LICENSE ├── README.rst ├── app ├── __init__.py ├── api.py └── templates │ └── docs.html ├── nginx-blockade.conf ├── requirements.txt ├── start.sh ├── supervisor-blockade.conf ├── test-scripts └── add-indicators.py ├── wsgi.ini └── wsgi.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *\.sw[a-z] 3 | *.egg-info/ 4 | build/ 5 | dist/ 6 | setuptools-* 7 | venv/ 8 | .pypirc 9 | *.pem 10 | *.DS_Store 11 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM debian 2 | 3 | RUN apt-get update && apt-get install -y python-pip python-dev libssl-dev mongodb-server build-essential libffi-dev 4 | 5 | COPY requirements.txt / 6 | 7 | RUN pip install -r /requirements.txt 8 | 9 | COPY app/api.py /usr/local/bin/api.py 10 | 11 | RUN chmod 740 /usr/local/bin/api.py 12 | 13 | ENTRYPOINT /usr/local/bin/api.py 14 | 15 | EXPOSE 5000 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | Blockade.io Cloud Node 2 | ====================== 3 | Blockade is able to provide blocking capabilities within the Chrome browser by using a cloud backend controlled by trusted analysts. Blockade subscribes to the "serverless_" concept and uses nothing but Amazon Web Services (AWS_) for all its public functionality. This repository offers an alternative local instance that can be run on any server with an Internet connection. To learn more about Blockade, visit the project page_. 4 | 5 | .. _serverless: https://aws.amazon.com/lambda/serverless-architectures-learn-more/ 6 | .. _AWS: https://aws.amazon.com 7 | .. _page: https://www.blockade.io/ 8 | 9 | Install 10 | ------- 11 | 12 | Install some depdencies first: 13 | 14 | $ sudo apt install python-pip python-dev libssl-dev libffi-dev mongodb-server 15 | 16 | Get virtualenv: 17 | 18 | $ pip install virtualenv 19 | 20 | Check out the repository and setup a virtualenv: 21 | 22 | $ virtualenv venv && source venv/bin/activate 23 | 24 | Install the requirements 25 | 26 | $ pip install -r requirements.txt 27 | 28 | Run the server using the local debug mode provided by Flask: 29 | 30 | $ python $REPOSITORY/app/api.py 31 | 32 | Add your first administrator user: 33 | 34 | $ curl -X POST "http://localhost:5000/admin/add-user" \ 35 | --data '{"user_email": "", "user_name": "", "user_role": "admin"}' \ 36 | -H "Content-Type: application/json" 37 | 38 | Perform any tests needed and deploy the server in a production_ capacity. 39 | 40 | .. _production: http://flask.pocoo.org/docs/0.12/deploying/ 41 | 42 | Endpoints 43 | --------- 44 | The following endpoints are exposed via this local node: 45 | 46 | - **//get-indicators**: Lists all the indicators for Blockade to consume 47 | - **//send-events**: Processes events collected from the browser using Blockade 48 | - **/admin/add-user**: Add users to the local installation in order to contribute 49 | - **/admin/validate-user**: Validate user against the local installation 50 | - **//admin/add-indicators**: Add indicators to the database from the toolbench_. 51 | - **//admin/get-events**: Get saved events from the database 52 | - **//admin/flush-events**: Flush events from the database 53 | 54 | For more documentation, including CURL samples, start the server and browse it. 55 | 56 | .. _toolbench: https://github.com/blockadeio/analyst_toolbench 57 | .. _wiki: https://github.com/blockadeio/cloud_node/wiki/Endpoints 58 | 59 | For users looking to host multiple databases on a single cloud node, replace the '' variable with the name of your database. This name will be used to load the database instance and perform actions on it. 60 | 61 | Docker 62 | --------- 63 | You can run cloud node in Docker. To do so, build the container and run it, specifying the mongo host via environment variable:: 64 | 65 | $ docker build -t cloud_node . 66 | $ docker run -d -p 5000:5000 --name cloud_node -e MONGO_HOST= cloud_node 67 | 68 | Mac Note: if you want to run mongo on your localhost, you'll need to specify your machine's actual IP address for the . Localhost WILL NOT WORK on a mac (but should on Linux). 69 | 70 | Docker Note: if you wish to link to a container, called in this example mongo, your command would look like:: 71 | 72 | $ docker run -d -p 5000:5000 --name cloud_node --link mongo:mongo -e MONGO_HOST=mongo cloud_node 73 | -------------------------------------------------------------------------------- /app/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/blockadeio/cloud_node/3b06dc7d2fcd45837b9bb96dde6d58c2493035fa/app/__init__.py -------------------------------------------------------------------------------- /app/api.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | 3 | """Basic REST API interface for Blockade.""" 4 | import datetime 5 | import hashlib 6 | import os 7 | import re 8 | import random 9 | from flask import Flask 10 | from flask import render_template 11 | from flask import request 12 | from flask_misaka import Misaka 13 | from flask_pymongo import PyMongo 14 | from flask_restful import Resource, Api, reqparse 15 | 16 | CONST_CORE_DB = 'blockade' 17 | CONST_EXT_KEY = 'EXTMONGO' 18 | CONST_PYMONGO = 'pymongo' 19 | if os.environ.get('MONGO_HOST', None): 20 | CONST_MONGO_HOST = os.environ['MONGO_HOST'] 21 | else: 22 | CONST_MONGO_HOST = '127.0.0.1' 23 | 24 | flask_app = Flask(__name__) 25 | flask_app.config['MONGO_DBNAME'] = CONST_CORE_DB 26 | flask_app.config['MONGO_HOST'] = CONST_MONGO_HOST 27 | 28 | api = Api(flask_app) 29 | mongo = PyMongo(flask_app) 30 | markdown = Misaka(flask_app, wrap=True, fenced_code=True) 31 | 32 | parser = reqparse.RequestParser() 33 | parser.add_argument('api_key') 34 | parser.add_argument('email') 35 | parser.add_argument('events') 36 | parser.add_argument('indicators') 37 | parser.add_argument('user_email') 38 | parser.add_argument('user_name') 39 | parser.add_argument('user_role') 40 | 41 | 42 | @flask_app.route('/') 43 | def docs(): 44 | """Render the documentation.""" 45 | return render_template('docs.html') 46 | 47 | # TODO: this should be replaced with urlparse. 48 | def extract_fqdn(url): 49 | """Extract the FQDN from a URL.""" 50 | replace = ['http://', 'https://'] 51 | for r in replace: 52 | url = url.replace(r, '') 53 | url = url.split('/')[0] 54 | return url 55 | 56 | 57 | def check_auth(args, role=None): 58 | """Check the user authentication.""" 59 | if mongo.db.users.count() == 0: 60 | return {'success': True, 'message': None, 'init': True} 61 | if not (args.get('email', None) and args.get('api_key', None)): 62 | mesg = "Invalid request: `email` and `api_key` are required" 63 | return {'success': False, 'message': mesg} 64 | user = mongo.db.users.find_one({'email': args['email']}, {'_id': 0}) 65 | if not user: 66 | return {'success': False, 'message': 'User does not exist.'} 67 | if user['api_key'] != args['api_key']: 68 | return {'success': False, 'message': 'API key was invalid.'} 69 | if role: 70 | if user['role'] not in role: 71 | mesg = 'User is not authorized to make this change.' 72 | return {'success': False, 'message': mesg} 73 | return {'success': True, 'message': None, 'user': user} 74 | 75 | 76 | def db_setup(f): 77 | """Handle tasking before and after any wrapped calls. 78 | 79 | For channels, we want the user to be able to specify which database to 80 | pull or send data to based on the URL slug. After loading a PyMongo 81 | instance, it will pollute the session space and throw errors unless cleaned 82 | up. Wrapping methods that require the database to be dynamic lets us do 83 | the needed session setup and tear-down for any call. 84 | """ 85 | def wrapper(self, sub_id=None): 86 | if not sub_id: 87 | sub_id = CONST_CORE_DB 88 | # Silently drop any non-DB name characters 89 | sub_id = ''.join(e for e in sub_id if e.isalnum() or e == '_') 90 | flask_app.config[CONST_EXT_KEY + "_DBNAME"] = sub_id 91 | flask_app.config[CONST_EXT_KEY + '_HOST'] = CONST_MONGO_HOST 92 | ext_mongo = PyMongo(flask_app, config_prefix=CONST_EXT_KEY) 93 | results = f(self, ext_mongo) 94 | for key in flask_app.config.keys(): 95 | if not key.startswith(CONST_EXT_KEY): 96 | continue 97 | flask_app.config.pop(key, None) 98 | flask_app.extensions[CONST_PYMONGO].pop(CONST_EXT_KEY, None) 99 | return results 100 | return wrapper 101 | 102 | 103 | def find_ip(): 104 | """Run through the request to identify the client IP address.""" 105 | ip = request.environ.get('HTTP_X_REAL_IP', None) 106 | if ip: 107 | return ip 108 | ip = request.access_route 109 | if len(ip) > 0: 110 | return ip[0] 111 | return request.remote_addr 112 | 113 | 114 | class ExtensionActions(Resource): 115 | 116 | """Endpoints for the pubic uses for information.""" 117 | 118 | @db_setup 119 | def get(self, ext_mongo): 120 | """Get the indicators from the database.""" 121 | output = {'success': True, 'indicators': list(), 'indicatorCount': 0} 122 | indicators = [x for x in ext_mongo.db.indicators.find({}, {'_id': 0})] 123 | for item in indicators: 124 | indicator = item.get('indicator', None) 125 | if not indicator: 126 | continue 127 | output['indicators'].append(indicator) 128 | output['indicators'] = list(set(output['indicators'])) 129 | output['indicatorCount'] = len(output['indicators']) 130 | return output 131 | 132 | @db_setup 133 | def post(self, ext_mongo): 134 | """Save the events into the local database.""" 135 | args = request.get_json(force=True) 136 | events = args.get('events', list()) 137 | if len(events) == 0: 138 | return {'success': False, 'message': "No events sent in"} 139 | client_ip = find_ip() 140 | for idx, event in enumerate(events): 141 | event['sourceIp'] = client_ip 142 | event['event'] = hashlib.sha256(str(event)).hexdigest() 143 | metadata = event['metadata'] 144 | timestamp = str(event['metadata']['timeStamp']) 145 | events[idx]['metadata']['timeStamp'] = timestamp 146 | obj = { 147 | 'match': event['indicatorMatch'], 148 | 'type': metadata['type'], 149 | 'url': metadata['url'], 150 | 'method': metadata['method'].lower(), 151 | 'time': event['analysisTime'], 152 | 'userAgent': event['userAgent'], 153 | 'ip': client_ip, 154 | 'contact': event['contact'] 155 | } 156 | ext_mongo.db.events.insert_one(obj) 157 | mesg = "Wrote {} events to the cloud".format(len(events)) 158 | return {'success': True, 'message': mesg} 159 | 160 | 161 | class IndicatorManagement(Resource): 162 | 163 | """Perform actions related to indicators.""" 164 | 165 | @db_setup 166 | def post(self, ext_mongo): 167 | """Save indicators into the local database.""" 168 | args = request.get_json(force=True) 169 | auth = check_auth(args, role=["analyst", "admin"]) 170 | if not auth['success']: 171 | return auth 172 | current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") 173 | indicators = args.get('indicators', list()) 174 | indicators = list(set(indicators)) 175 | tags = args.get('tags', list()) 176 | 177 | inserted = 0 178 | for item in indicators: 179 | original = None 180 | if re.search(r"^([a-fA-F\d]{32})$", item): 181 | hashed = item 182 | else: 183 | original = extract_fqdn(item) 184 | hashed = hashlib.md5(original).hexdigest() 185 | 186 | record = ext_mongo.db.indicators.find_one({'indicator': hashed}) 187 | if not record: 188 | obj = {'indicator': hashed, 'original': original, 'tags': tags, 189 | 'creator': auth['user']['email'], 190 | 'datetime': current_time} 191 | ext_mongo.db.indicators.insert_one(obj) 192 | inserted += 1 193 | 194 | msg = "Wrote {} indicators".format(inserted) 195 | return {'success': True, 'message': msg, 'writeCount': inserted} 196 | 197 | @db_setup 198 | def delete(self, ext_mongo): 199 | """Delete indicators from the local database.""" 200 | args = request.get_json(force=True) 201 | auth = check_auth(args, role=['admin']) 202 | if not auth['success']: 203 | return auth 204 | deleted = 0 205 | indicators = args.get('indicators', list()) 206 | indicators = list(set(indicators)) 207 | for item in indicators: 208 | # Expecting MD5 indicators, so hash everything else. 209 | if len(item) != 32: 210 | item = extract_fqdn(item) # Just in case 211 | item = hashlib.md5(item).hexdigest() 212 | d = ext_mongo.db.events.delete_one({'indicator': item}) 213 | deleted += d.deleted_count 214 | msg = "Deleted {} indicators".format(deleted) 215 | output = {'success': True, 'message': msg, 216 | 'deleteCount': deleted} 217 | return output 218 | 219 | 220 | class EventsManagement(Resource): 221 | 222 | """Perform actions related to events.""" 223 | 224 | @db_setup 225 | def post(self, ext_mongo): 226 | """Get recorded events.""" 227 | args = request.get_json(force=True) 228 | auth = check_auth(args, role=['analyst', 'admin']) 229 | if not auth['success']: 230 | return auth 231 | output = {'success': True, 'events': list(), 'eventsCount': 0} 232 | output['events'] = [x for x in ext_mongo.db.events.find({}, {'_id': 0})] 233 | output['eventsCount'] = len(output['events']) 234 | return output 235 | 236 | @db_setup 237 | def delete(self, ext_mongo): 238 | """Delete recorded events.""" 239 | args = parser.parse_args() 240 | auth = check_auth(args, role=['admin']) 241 | if not auth['success']: 242 | return auth 243 | ext_mongo.db.events.delete_many(dict()) 244 | output = {'success': True} 245 | return output 246 | 247 | 248 | class UserManagement(Resource): 249 | 250 | """Perform actions related to users.""" 251 | 252 | def get(self): 253 | """Validate users to confirm their account.""" 254 | args = parser.parse_args() 255 | auth = check_auth(args, role=["admin"]) 256 | if not auth['success']: 257 | return auth 258 | return {'success': True, 'message': 'User is valid.'} 259 | 260 | def post(self): 261 | """Added new users to the system.""" 262 | args = parser.parse_args() 263 | auth = check_auth(args, role=["admin"]) 264 | if not auth['success']: 265 | return auth 266 | user_email = args.get('user_email', None) 267 | if not user_email: 268 | msg = "Missing user_email parameter in your request." 269 | return {'success': False, 'message': msg} 270 | user_role = args.get('user_role', None) 271 | if not user_role: 272 | msg = "Missing user role: `admin`, `analyst`" 273 | return {'success': False, 'message': msg} 274 | user_name = args.get('user_name', '') 275 | seed = random.randint(100000000, 999999999) 276 | hash_key = "{}{}".format(user_email, seed) 277 | api_key = hashlib.sha256(hash_key).hexdigest() 278 | if auth.get('init', False): 279 | user_role = 'admin' 280 | else: 281 | user_role = user_role 282 | obj = {'email': user_email, 'name': user_name, 'api_key': api_key, 283 | 'role': user_role} 284 | mongo.db.users.insert_one(obj) 285 | obj.pop('_id', None) 286 | return obj 287 | 288 | 289 | api.add_resource(ExtensionActions, '//get-indicators', 290 | '//send-events', 291 | '/get-indicators', '/send-events') 292 | api.add_resource(IndicatorManagement, '//admin/add-indicators', 293 | '//admin/remove-indicators', 294 | '/admin/add-indicators', 295 | '/admin/remove-indicators') 296 | api.add_resource(EventsManagement, '//admin/get-events', 297 | '//admin/flush-events', 298 | '/admin/get-events', '/admin/flush-events') 299 | api.add_resource(UserManagement, '/admin/add-user', '/admin/validate-user') 300 | -------------------------------------------------------------------------------- /app/templates/docs.html: -------------------------------------------------------------------------------- 1 | {% filter markdown %} 2 | 3 | # Blockade Cloud Node 4 | ------------------------ 5 | You've stumbled upon a wild Blockade cloud node. This page documents the micro API available on this server and how you can interact with it. 6 | 7 | **Endpoints**: 8 | 9 | * [/get-indicators](#get-indicators) 10 | * [/send-events](#send-events) 11 | * [/admin/add-user](#admin-add-user) 12 | * [/admin/validate-user](#admin-validate-user) 13 | * [/admin/add-indicators](#admin-add-indicators) 14 | * [/admin/remove-indicators](#admin-remove-indicators) 15 | * [/admin/get-events](#admin-get-events) 16 | * [/admin/flush-events](#admin-flush-events) 17 | 18 | ## General 19 | 20 | These calls are used by the Blockade extension in order to function. 21 | 22 | 23 | ###

`GET` /*:optional-database-name:*/get-indicators

24 | 25 | Get indicators is used by the Chrome Extension in order to build its database of known-bad signatures. If the optional database-name is included in the URL path, it will be used inside of the application as the primary database to pull from. 26 | 27 | #### Params 28 | 29 | N/A 30 | 31 | #### Sample Curl 32 | 33 | ~~~ 34 | $ curl -X GET "http://localhost:5000/get-indicators" 35 | ~~~ 36 | 37 | #### Response 38 | 39 | ~~~ 40 | { 41 | "indicators": [ 42 | "8c32e34aa474f279478d41357d7799eb", 43 | "37ebc68d21b3f12cc2b4f1055eabb20e", 44 | "ece4ddec111e1111d98c8b69638e3e18" 45 | ] 46 | "indicatorCount": 3, 47 | "success": true 48 | } 49 | ~~~ 50 | 51 | 52 | ###

`POST` /*:optional-database-name:*/send-events

53 | 54 | Send events is used by the Chrome Extension in order to send alerted events back to the analysts. If the optional database-name is included in the URL path, it will be used inside of the application as the primary database to store data in. 55 | 56 | #### Params 57 | 58 | * **events (*list* of *dicts*)**: Listing of generated events 59 | * **analysisTime (*string*)**: Time of analysis 60 | * **userAgent (*string*)**: User-agent of the browser 61 | * **indicatorMatch (*string*)**: Indicator that was matched 62 | * **metadata** (*dict*): Free-form data collected from the browser 63 | * **hashMatch** (*string*): MD5 hash of the indicator match 64 | * **contact** (*string*): Optional email contact for the browser install 65 | 66 | #### Sample Curl 67 | 68 | ~~~ 69 | $ curl -X POST "http://localhost:5000/send-events" \ 70 | --data '{"events":[{"analysisTime":"2017-01-30T07:45:03.496Z","userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36","indicatorMatch":"test.blockade.io","metadata":{"frameId":0,"method":"GET","parentFrameId":-1,"requestId":"36572","tabId":735,"timeStamp":1485762303489.0251,"type":"image","url":"http://test.blockade.io/no-face.jpg?29957"},"hashMatch":"ece4ddec111e1111d98c8b69638e3e18"}]}' \ 71 | -H "Content-Type: application/json" 72 | ~~~ 73 | 74 | #### Response 75 | 76 | ~~~ 77 | { 78 | "success": true, 79 | "message": "Wrote 5 events to the cloud" 80 | } 81 | ~~~ 82 | 83 | ## Administration 84 | 85 | Administration endpoints allow users to control details of the cloud node. 86 | 87 | 88 | ###

`POST` /admin/add-user

89 | 90 | Add users to the local installation in order to contribute indicators. 91 | 92 | #### Params 93 | 94 | First-time loading: 95 | 96 | * **user_email (*string*)**: Email of the administrator 97 | * **user_name (*string*)**: Name of the administrator 98 | * **user_role (*string*)**: Role of the user (admin for first time) 99 | 100 | Follow-on calls: 101 | 102 | * **user_email (*string*)**: Email of the user 103 | * **user_name (*string*)**: Name of the user 104 | * **user_role (*string*)**: Role of the user (*admin* or *analyst*) 105 | * **email (*string*)**: Email of the administrator 106 | * **api_key (*string*)**: API key of the administrator 107 | 108 | #### Sample Curl 109 | 110 | ~~~ 111 | $ curl -X POST "http://localhost:5000/admin/add-user" \ 112 | --data '{"user_email": "info@blockade.io", "user_name": "Blockade", "user_role": "admin"}' \ 113 | -H "Content-Type: application/json" 114 | ~~~ 115 | 116 | #### Response 117 | 118 | ~~~ 119 | { 120 | "api_key" : "00d587c50e41b2722829010665a25042b94544dc5585a326859d562b0e437ac1", 121 | "role" : "admin", 122 | "email" : "info@blockade.io", 123 | "name" : "Blockade" 124 | } 125 | ~~~ 126 | 127 | 128 | ###

`GET` /admin/validate-user

129 | 130 | Validate user against the local installation. 131 | 132 | #### Params 133 | 134 | * **email (*string*)**: Email of the administrator 135 | * **api_key (*string*)**: API key of the administrator 136 | 137 | #### Sample Curl 138 | 139 | ~~~ 140 | $ curl -X GET "http://localhost:5000/admin/validate-user" \ 141 | --data '{"email": "info@blockade.io", "api_key": "foobar"}' \ 142 | -H "Content-Type: application/json" 143 | ~~~ 144 | 145 | #### Response 146 | 147 | ~~~ 148 | { 149 | "message": "User is valid.", 150 | "success": true 151 | } 152 | ~~~ 153 | 154 | 155 | ###

`POST` /*:optional-database-name:*/admin/add-indicators

156 | 157 | Add indicators is an admin-based API to add indicators to the cloud node that are then sent to the Blockade installations. Indicators sent in are instantly sent out to users, so be sure double check what is sent and ensure nothing good is blocked. Indicators stored in Blockade are assumed to be MD5 hashed before being sent in. This endpoint will attempt to detect raw indicators and clean them up for the database. If the optional database-name is included in the URL path, it will be used inside of the application as the primary database. 158 | 159 | #### Params 160 | 161 | * **email (*string*)**: Email of the administrator 162 | * **api_key (*string*)**: API key of the administrator 163 | * **indicators (*list* of *strings*)**: MD5 hashed indicators to save 164 | 165 | #### Sample Curl 166 | 167 | ~~~ 168 | $ curl -X POST "http://localhost:5000/admin/add-indicators" \ 169 | --data '{"email": "info@blockade.io", "api_key": "foobar", "indicators": ["ece4ddec111e1111d98c8b69638e3e18"]}' \ 170 | -H "Content-Type: application/json" 171 | ~~~ 172 | 173 | #### Response 174 | 175 | ~~~ 176 | { 177 | "success": true, 178 | "message": "Wrote 1 indicators to the cloud", 179 | "writeCount": 1 180 | } 181 | ~~~ 182 | 183 | 184 | ###

`DELETE` /*:optional-database-name:*/admin/remove-indicators

185 | 186 | Remove indicators is an admin-based API to remove indicators from the cloud node. This endpoint will attempt to detect raw indicators and clean them up for the database. If the optional database-name is included in the URL path, it will be used inside of the application as the primary database. 187 | 188 | #### Params 189 | 190 | * **email (*string*)**: Email of the administrator 191 | * **api_key (*string*)**: API key of the administrator 192 | * **indicators (*list* of *strings*)**: MD5 hashed indicators to remove 193 | 194 | #### Sample Curl 195 | 196 | ~~~ 197 | $ curl -X DELETE "http://localhost:5000/admin/remove-indicators" \ 198 | --data '{"email": "info@blockade.io", "api_key": "foobar", "indicators": ["ece4ddec111e1111d98c8b69638e3e18"]}' \ 199 | -H "Content-Type: application/json" 200 | ~~~ 201 | 202 | #### Response 203 | 204 | ~~~ 205 | { 206 | "success": true, 207 | "message": "Deleted 1 indicators to the cloud", 208 | "deleteCount": 1 209 | } 210 | ~~~ 211 | 212 | 213 | ###

`GET` /*:optional-database-name:*/admin/get-events

214 | 215 | Get events stored from the local database. If the optional database-name is included in the URL path, it will be used inside of the application as the primary database. 216 | 217 | #### Params 218 | 219 | * **email (*string*)**: Email of the administrator 220 | * **api_key (*string*)**: API key of the administrator 221 | 222 | #### Sample Curl 223 | 224 | ~~~ 225 | $ curl -X GET "http://localhost:5000/admin/get-events" \ 226 | --data '{"email": "info@blockade.io", "api_key": "foobar"}' \ 227 | -H "Content-Type: application/json" 228 | ~~~ 229 | 230 | #### Response 231 | 232 | ~~~ 233 | { 234 | "events": [ 235 | { 236 | "ip": "142.254.99.55", 237 | "contact": "info@blockade.io", 238 | "match": "www.zhubert.com", 239 | "method": "get", 240 | "time": "2017-03-06T02:40:02.591Z", 241 | "type": "main_frame", 242 | "url": "http://www.zhubert.com/blog/2017/02/25/how-to-self-publish-a-novel-in-2017/", 243 | "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36" 244 | } 245 | ], 246 | "eventsCount": 1, 247 | "success": true 248 | } 249 | ~~~ 250 | 251 | 252 | ###

`DELETE` /*:optional-database-name:*/admin/flush-events

253 | 254 | Flush events stored from the local database. If the optional database-name is included in the URL path, it will be used inside of the application as the primary database. 255 | 256 | #### Params 257 | 258 | * **email (*string*)**: Email of the administrator 259 | * **api_key (*string*)**: API key of the administrator 260 | 261 | #### Sample Curl 262 | 263 | ~~~ 264 | $ curl -X DELETE "http://localhost:5000/admin/flush-events" \ 265 | --data '{"email": "info@blockade.io", "api_key": "foobar"}' \ 266 | -H "Content-Type: application/json" 267 | ~~~ 268 | 269 | #### Response 270 | 271 | ~~~ 272 | { 273 | "success": true 274 | } 275 | ~~~ 276 | 277 | {% endfilter %} -------------------------------------------------------------------------------- /nginx-blockade.conf: -------------------------------------------------------------------------------- 1 | server { 2 | listen 80 default_server; 3 | server_name blockade.threatlabs.io; 4 | 5 | access_log /var/log/nginx/blockade-access.log; 6 | error_log /var/log/nginx/blockade-error.log; 7 | 8 | location / { try_files $uri @blockade; } 9 | location @blockade { 10 | #proxy_pass http://127.0.0.1:5000; 11 | uwsgi_pass 127.0.0.1:5000; 12 | include uwsgi_params; 13 | #uwsgi_pass unix:/tmp/blockade.sock; 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | aniso8601==1.2.0 2 | cffi==1.9.1 3 | click==6.7 4 | cryptography==1.7.1 5 | enum34==1.1.6 6 | Flask==0.12 7 | Flask-Misaka==0.4.1 8 | Flask-PyMongo==0.4.1 9 | Flask-RESTful==0.3.5 10 | idna==2.2 11 | ipaddress==1.0.18 12 | itsdangerous==0.24 13 | Jinja2==2.9.4 14 | Markdown==2.6.8 15 | MarkupSafe==0.23 16 | misaka==2.1.0 17 | pyasn1==0.1.9 18 | pycparser==2.17 19 | pymongo==3.4.0 20 | pyOpenSSL==16.2.0 21 | python-dateutil==2.6.0 22 | pytz==2016.10 23 | requests==2.12.4 24 | six==1.10.0 25 | Werkzeug==0.11.15 -------------------------------------------------------------------------------- /start.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | NAME="blockade" # Name of the application 3 | WORKDIR=/opt/cloud_node/ 4 | echo "Starting $NAME as `whoami`" 5 | 6 | # Activate the virtual environment 7 | cd $WORKDIR 8 | source venv/bin/activate 9 | cd $WORKDIR/app 10 | 11 | # Start your Django Unicorn 12 | # Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon) 13 | exec uwsgi --ini wsgi.ini 14 | -------------------------------------------------------------------------------- /supervisor-blockade.conf: -------------------------------------------------------------------------------- 1 | [program:blockade] 2 | user = blockade 3 | #autostart=true 4 | #autorestart=true 5 | command = /opt/cloud_node/start.sh 6 | stdout_logfile = /tmp/blockade.log 7 | redirect_stderr = true 8 | environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 9 | -------------------------------------------------------------------------------- /test-scripts/add-indicators.py: -------------------------------------------------------------------------------- 1 | """Simple toy script to generate mock data for Blockade load tests.""" 2 | import hashlib 3 | import json 4 | import random 5 | import requests 6 | import string 7 | import sys 8 | 9 | CLOUD_HOST = "--YOUR-HOST--" 10 | CLOUD_USER = "--YOUR-USER--" 11 | CLOUD_KEY = "--YOUR-API-KEY--" 12 | 13 | 14 | def id_generator(size=6, chars=string.ascii_lowercase): 15 | """Generate a random string.""" 16 | return ''.join(random.choice(chars) for _ in range(size)) 17 | 18 | 19 | def gen_md5_urls(amount): 20 | """Generate a bunch of fake domains.""" 21 | urls = list() 22 | for i in range(0, amount): 23 | rando = "{core}.com".format(core=id_generator(size=15)) 24 | if rando[0].isdigit(): 25 | rando = rando[1:] 26 | urls.append(hashlib.md5(rando).hexdigest()) 27 | return list(set(urls)) 28 | 29 | 30 | def post_indicators(indicators): 31 | """Send indicators to the blockade cloud node.""" 32 | headers = {'Content-Type': 'application/json'} 33 | data = {'indicators': indicators, 'email': CLOUD_USER, 34 | 'api_key': CLOUD_KEY} 35 | url = "http://{}/admin/add-indicators".format(CLOUD_HOST) 36 | try: 37 | args = {'url': url, 'headers': headers, 'data': json.dumps(data), 38 | 'timeout': 120} 39 | response = requests.post(**args) 40 | except Exception, e: 41 | raise Exception("Error Posting: %s" % str(e)) 42 | if response.status_code not in range(200, 299): 43 | raise Exception("Error: {}".format(response.content)) 44 | loaded = json.loads(response.content) 45 | return loaded 46 | 47 | 48 | def main(): 49 | """Input fake URLs for testing.""" 50 | if len(sys.argv) < 2: 51 | print("Usage: python add-indicators.py ") 52 | sys.exit(1) 53 | amount = int(sys.argv[1]) 54 | test_domains = gen_md5_urls(amount) 55 | print(post_indicators(test_domains)) 56 | 57 | 58 | if __name__ == "__main__": 59 | main() 60 | -------------------------------------------------------------------------------- /wsgi.ini: -------------------------------------------------------------------------------- 1 | [uwsgi] 2 | module = wsgi 3 | callable = application 4 | master = true 5 | threads = 10 6 | chmod-socket=666 7 | uid = www-data 8 | gid = www-data 9 | wsgi-file = wsgi.py 10 | socket = 0.0.0.0:5000 11 | die-on-term = true 12 | -------------------------------------------------------------------------------- /wsgi.py: -------------------------------------------------------------------------------- 1 | from app.api import flask_app as application 2 | 3 | if __name__ == "__main__": 4 | application.run(debug=True, host='0.0.0.0') 5 | --------------------------------------------------------------------------------