├── .stignore ├── requirements.txt ├── okteto-pipeline.yml ├── stack.yml ├── okteto.yml ├── update.py ├── Dockerfile ├── deploy ├── deploy.sh └── ecs-deploy ├── logging.conf ├── .circleci └── config.yml ├── config.py ├── .gitignore ├── app.py ├── CODE_OF_CONDUCT.md ├── HISTORY.md ├── README.md └── LICENSE.md /.stignore: -------------------------------------------------------------------------------- 1 | .git 2 | __pycache__ 3 | env 4 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # Installed using Alpine packages 2 | #flask==1.1.2 3 | #gunicorn==20.0.4 4 | 5 | apscheduler==3.8.1 6 | gglsbl==1.4.15 7 | -------------------------------------------------------------------------------- /okteto-pipeline.yml: -------------------------------------------------------------------------------- 1 | deploy: 2 | - okteto build -t okteto.dev/gglsbl:${OKTETO_GIT_COMMIT} . 3 | - okteto stack deploy 4 | devs: 5 | - okteto.yml -------------------------------------------------------------------------------- /stack.yml: -------------------------------------------------------------------------------- 1 | name: gglsbl 2 | services: 3 | rest: 4 | public: true 5 | image: okteto.dev/gglsbl:${OKTETO_GIT_COMMIT} 6 | build: . 7 | environment: 8 | - GSB_API_KEY=${GSB_API_KEY} 9 | ports: 10 | - 5000 11 | -------------------------------------------------------------------------------- /okteto.yml: -------------------------------------------------------------------------------- 1 | name: rest 2 | image: okteto/python:3 3 | command: 4 | - bash 5 | - -c 6 | - python3 -m venv env && source env/bin/activate && bash 7 | workdir: /okteto 8 | forward: 9 | - 5000:5000 10 | resources: 11 | limits: 12 | cpu: "1" 13 | memory: 2Gi 14 | volumes: 15 | - /root/.cache/ 16 | persistentVolume: 17 | enabled: true -------------------------------------------------------------------------------- /update.py: -------------------------------------------------------------------------------- 1 | import logging.config 2 | from os import environ, path 3 | 4 | from gglsbl import SafeBrowsingList 5 | 6 | # basic app configuration and options 7 | gsb_api_key = environ['GSB_API_KEY'] 8 | dbfile = path.join(environ.get('GSB_DB_DIR', '/tmp'), 'sqlite.db') 9 | logger = logging.getLogger('update') 10 | 11 | 12 | # function that updates the hash prefix cache if necessary 13 | def update_hash_prefix_cache(): 14 | logger.info('opening database at ' + dbfile) 15 | sbl = SafeBrowsingList(gsb_api_key, dbfile, True) 16 | 17 | logger.info('updating database at ' + dbfile) 18 | sbl.update_hash_prefix_cache() 19 | 20 | logger.info('checkpointing database at ' + dbfile) 21 | with sbl.storage.get_cursor() as dbc: 22 | dbc.execute('PRAGMA wal_checkpoint(FULL)') 23 | sbl.storage.db.commit() 24 | 25 | logger.info("all done!") 26 | 27 | 28 | if __name__ == '__main__': 29 | logging.config.fileConfig(environ.get("LOGGING_CONFIG", 'logging.conf')) 30 | update_hash_prefix_cache() 31 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM alpine:3.15 2 | 3 | # Install necessary OS packages and create non-root user for service 4 | RUN apk update && \ 5 | apk upgrade && \ 6 | apk add -u python3 py3-pip py3-setuptools py3-wheel py3-multidict py3-yarl py3-flask py3-gunicorn && \ 7 | adduser -D -s /sbin/nologin gglsbl 8 | 9 | ## Populate app directory 10 | WORKDIR /home/gglsbl 11 | ENV GSB_DB_DIR /home/gglsbl/db 12 | COPY ["requirements.txt", "./"] 13 | ENV LOGGING_CONFIG /home/gglsbl/logging.conf 14 | 15 | # Install Python packages, cleanup and set permissions 16 | RUN pip3 install -r requirements.txt && \ 17 | rm -rf /root/.cache/pip/* && \ 18 | rm -rf /var/cache/apk/* && \ 19 | rm -rf /tmp/* && \ 20 | rm -rf /root/.cache/ && \ 21 | mkdir -p $GSB_DB_DIR && \ 22 | chown -R gglsbl:gglsbl * 23 | 24 | # CVE-2019-5021 25 | RUN sed -i -e 's/^root::/root:!:/' /etc/shadow 26 | 27 | # Run as a non-root user for security 28 | USER gglsbl:gglsbl 29 | 30 | EXPOSE 5000 31 | 32 | COPY ["*.py", "logging.conf", "./"] 33 | 34 | # Start app 35 | ENTRYPOINT exec gunicorn --config config.py --log-config ${LOGGING_CONFIG} app:app 36 | -------------------------------------------------------------------------------- /deploy/deploy.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # Script to deploy gglsbl-rest to an AWS ECS cluster repository and service using "ecs-deploy". 4 | # 5 | # Please provide the following environment variables: 6 | # 7 | # REPO: the part of the ECS full repository URI before the slash 8 | # SERVICE: the part of the ECS full repository URI after the slash 9 | # CLUSTER: the name of the ECS cluster 10 | # PROFILE: the AWS CLI profile to use (in ~/.aws/credentials), if missing will use "default" 11 | # 12 | 13 | if [ -z "$PROFILE" ]; then 14 | PROFILE=default 15 | fi 16 | 17 | if [ -z "$SERVICE" ] || [ -z "$REPO" ] || [ -z "$CLUSTER" ]; then 18 | echo Please define SERVICE, REPO and CLUSTER correctly 19 | else 20 | set -e 21 | TAG=`git rev-parse --verify HEAD` 22 | IMAGE=$REPO/$SERVICE:${TAG} 23 | echo Building $IMAGE ... 24 | docker build -t $IMAGE . 25 | echo Pushing $IMAGE ... 26 | eval $(aws ecr get-login --no-include-email --profile ${PROFILE}) 27 | docker push $IMAGE 28 | echo Deploy $IMAGE to profile $PROFILE, cluster $CLUSTER and service $SERVICE ... 29 | deploy/ecs-deploy -p ${PROFILE} -c ${CLUSTER} -n $SERVICE -i $IMAGE -m 50 30 | echo Deployed! 31 | docker logout 32 | docker rmi $IMAGE 33 | fi 34 | -------------------------------------------------------------------------------- /logging.conf: -------------------------------------------------------------------------------- 1 | [loggers] 2 | keys=root, update, gunicorn.error, gunicorn.access, gglsbl-rest, __config__ 3 | [handlers] 4 | keys=console, console_access 5 | 6 | [formatters] 7 | keys=generic, access 8 | 9 | [logger_root] 10 | level=ERROR 11 | handlers=console 12 | 13 | [logger_update] 14 | level=DEBUG 15 | handlers=console 16 | propagate=0 17 | qualname=update 18 | 19 | [logger_gunicorn.error] 20 | level=INFO 21 | handlers=console 22 | propagate=0 23 | qualname=gunicorn.error 24 | 25 | [logger_gunicorn.access] 26 | level=INFO 27 | handlers=console_access 28 | propagate=0 29 | qualname=gunicorn.access 30 | 31 | [logger_gglsbl-rest] 32 | level=DEBUG 33 | handlers=console 34 | propagate=0 35 | qualname=gglsbl-rest 36 | 37 | [logger___config__] 38 | level=INFO 39 | handlers=console 40 | propagate=0 41 | qualname=__config__ 42 | 43 | [handler_console] 44 | class=StreamHandler 45 | formatter=generic 46 | args=(sys.stdout, ) 47 | 48 | [handler_console_access] 49 | class=StreamHandler 50 | formatter=access 51 | args=(sys.stdout, ) 52 | 53 | [formatter_generic] 54 | format=%(asctime)s pid=%(process)d %(module)s %(levelname)s %(message)s 55 | datefmt=%Y-%m-%dT%H:%M:%S%z 56 | class=logging.Formatter 57 | 58 | [formatter_access] 59 | format=%(asctime)s pid=%(process)d %(message)s 60 | datefmt=%Y-%m-%dT%H:%M:%S%z 61 | class=logging.Formatter 62 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | jobs: 2 | build: 3 | docker: 4 | - image: docker:git 5 | steps: 6 | - checkout 7 | - setup_remote_docker 8 | - run: 9 | name: Build image 10 | command: docker build -t trivy-ci-test:${CIRCLE_SHA1} . 11 | - run: 12 | name: Install trivy 13 | command: | 14 | apk add --update-cache --upgrade curl rpm 15 | VERSION=$( 16 | curl --silent "https://api.github.com/repos/aquasecurity/trivy/releases/latest" | \ 17 | grep '"tag_name":' | \ 18 | sed -E 's/.*"v([^"]+)".*/\1/' 19 | ) 20 | 21 | wget https://github.com/aquasecurity/trivy/releases/download/v${VERSION}/trivy_${VERSION}_Linux-64bit.tar.gz 22 | tar zxvf trivy_${VERSION}_Linux-64bit.tar.gz 23 | mv trivy /usr/local/bin 24 | - run: 25 | name: Scan the local image with trivy 26 | command: trivy image --exit-code 1 --severity MEDIUM,HIGH,CRITICAL --no-progress --output /tmp/trivy.txt trivy-ci-test:${CIRCLE_SHA1} 27 | - store_artifacts: 28 | path: /tmp/trivy.txt 29 | workflows: 30 | version: 2 31 | release: 32 | jobs: 33 | - build 34 | nightly: 35 | triggers: 36 | - schedule: 37 | cron: "0 0 * * *" 38 | filters: 39 | branches: 40 | only: 41 | - master 42 | jobs: 43 | - build 44 | -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | from os import environ 2 | 3 | import logging.config 4 | from apscheduler.schedulers.background import BackgroundScheduler 5 | from multiprocessing import cpu_count 6 | from subprocess import Popen 7 | 8 | logging.config.fileConfig('logging.conf') 9 | 10 | bind = "0.0.0.0:5000" 11 | workers = int(environ.get('WORKERS', cpu_count() * 8 + 1)) 12 | timeout = int(environ.get('TIMEOUT', 120)) 13 | access_log_format = '%(h)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" "%({X-Forwarded-For}i)s" "%({X-Forwarded-Port}i)s" "%({X-Forwarded-Proto}i)s" "%({X-Amzn-Trace-Id}i)s"' 14 | max_requests = int(environ.get('MAX_REQUESTS', 16384)) 15 | limit_request_line = int(environ.get('LIMIT_REQUEST_LINE', 8190)) 16 | keepalive = int(environ.get('KEEPALIVE', 60)) 17 | 18 | log = logging.getLogger(__name__) 19 | 20 | 21 | def update(): 22 | log.info("Starting update process...") 23 | po = Popen("python3 update.py", shell=True) 24 | log.info("Update started as PID %d", po.pid) 25 | rc = po.wait() 26 | log.info("Update process finished with status code %d", rc) 27 | 28 | 29 | sched = None 30 | 31 | def on_starting(server): 32 | log.info("Initial database load...") 33 | po = Popen("python3 update.py", shell=True) 34 | log.info("Update started as PID %d", po.pid) 35 | rc = po.wait() 36 | log.info("Update process finished with status code %d", rc) 37 | 38 | log.info("Starting scheduler...") 39 | global sched 40 | sched = BackgroundScheduler(timezone="UTC") 41 | sched.start() 42 | sched.add_job(update, id="update", coalesce=True, max_instances=1, trigger='interval', minutes=30) 43 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Python template 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | env/ 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | wheels/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *,cover 49 | .hypothesis/ 50 | 51 | # Translations 52 | *.mo 53 | *.pot 54 | 55 | # Django stuff: 56 | *.log 57 | local_settings.py 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # dotenv 85 | .env 86 | 87 | # virtualenv 88 | .venv 89 | venv/ 90 | ENV/ 91 | 92 | # Spyder project settings 93 | .spyderproject 94 | 95 | # Rope project settings 96 | .ropeproject 97 | 98 | *.db 99 | -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | from os import environ, path 2 | 3 | import logging.config 4 | import time 5 | from flask import Flask, request, jsonify, abort 6 | from gglsbl import SafeBrowsingList 7 | from subprocess import Popen 8 | 9 | # basic app configuration and options 10 | logging.config.fileConfig('logging.conf') 11 | app = Flask("gglsbl-rest") 12 | gsb_api_key = environ['GSB_API_KEY'] 13 | dbfile = path.join(environ.get('GSB_DB_DIR', '/tmp'), 'sqlite.db') 14 | environment = environ.get('ENVIRONMENT', 'prod').lower() 15 | max_retries = int(environ.get('MAX_RETRIES', "3")) 16 | 17 | # Keep last query object so we can try to re-use it across requests 18 | sbl = None 19 | last_api_key = None 20 | 21 | 22 | def _lookup(url, api_key, retry=1): 23 | # perform lookup 24 | global sbl, last_api_key 25 | try: 26 | if api_key != last_api_key: 27 | app.logger.info('re-opening database') 28 | sbl = SafeBrowsingList(api_key, dbfile, True) 29 | last_api_key = api_key 30 | return sbl.lookup_url(url) 31 | except: 32 | app.logger.exception("exception handling [" + url + "]") 33 | if retry >= max_retries: 34 | sbl = None 35 | last_api_key = None 36 | abort(500) 37 | else: 38 | return _lookup(url, api_key, retry + 1) 39 | 40 | 41 | @app.route('/gglsbl/lookup/', methods=['GET']) 42 | @app.route('/gglsbl/v1/lookup/', methods=['GET']) 43 | def app_lookup(url): 44 | # input validation 45 | if not isinstance(url, str): 46 | abort(400) 47 | 48 | # find out which API key to use 49 | api_key = request.headers.get('x-gsb-api-key', gsb_api_key) 50 | if not api_key: 51 | app.logger.error('no API key to use') 52 | abort(401) 53 | 54 | # look up URL 55 | matches = _lookup(url, api_key) 56 | if matches: 57 | return jsonify(url=url, matches=[{'threat': x.threat_type, 'platform': x.platform_type, 58 | 'threat_entry': x.threat_entry_type} for x in matches]) 59 | else: 60 | resp = jsonify(url=url, matches=[]) 61 | resp.status_code = 404 62 | return resp 63 | 64 | 65 | @app.route('/gglsbl/status', methods=['GET']) 66 | @app.route('/gglsbl/v1/status', methods=['GET']) 67 | def status_page(): 68 | return jsonify(environment=environment, 69 | alternatives=[{ 70 | 'active': True, 71 | 'name': dbfile, 72 | 'mtime': time.strftime('%Y-%m-%dT%H:%M:%S%z', time.gmtime(path.getmtime(dbfile))), 73 | 'ctime': time.strftime('%Y-%m-%dT%H:%M:%S%z', time.gmtime(path.getctime(dbfile))), 74 | 'size': path.getsize(dbfile) 75 | }]) 76 | 77 | 78 | # run development Flask server if executed directly 79 | if __name__ == '__main__': 80 | po = Popen("python update.py", shell=True) 81 | po.wait() 82 | app.env = 'development' 83 | app.run(processes=1, host="0.0.0.0", port=5001, debug=True) 84 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at contact@mlsecproject.org. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /HISTORY.md: -------------------------------------------------------------------------------- 1 | # gglsbl-rest 2 | 3 | ## v1.5.25 4 | Updated to Alpine 3.15. 5 | 6 | ## v1.5.24 (2021-11-17) 7 | Updated to Alpine 3.14.3 and APScheduler 3.8.1. 8 | 9 | ## v1.5.23 (2021-06-02) 10 | Updated to Alpine 3.13.5 for a variety of CVE fixes, such as CVE-2021-3449 , CVE-2021-3450 and CVE-2021-3177. 11 | 12 | ## v1.5.22 (2021-01-27) 13 | Updated to Alpine 3.13 and APScheduler 3.7.0. 14 | 15 | ## v1.5.21 (2020-09-29) 16 | Install yarl, multidict, flask and gunicorn with Alpine packages instead of using pip to avoid PEP 517 issues. 17 | 18 | ## v1.5.20 (2020-08-26) 19 | Contribution from @pchico83: 20 | * Added support for running on Okteto Cloud; 21 | * Improved docker build time by streamlining Dockerfile. 22 | 23 | ## v1.5.19 (2020-08-07) 24 | Updated to Alpine 3.12. 25 | 26 | ## v1.5.18 (2020-05-03) 27 | Updated to Alpine 3.11.6 and flask 1.1.2. 28 | 29 | ## v1.5.17 (2020-03-31) 30 | Updated to Alpine 3.11.5. 31 | 32 | ## v1.5.16 (2020-01-23) 33 | Updated to Alpine 3.11.3. 34 | 35 | ## v1.5.15 (2019-12-23) 36 | Updated to Alpine 3.11. 37 | 38 | ## v1.5.14 (2019-12-09) 39 | Updated to Alpine 3.10.3, APScheduler 3.6.3 and gunicorn 20.0.4 for functional and security fixes. 40 | 41 | ## v1.5.13 (2019-09-02) 42 | Updated to Alpine 3.10.2 and APScheduler 3.6.1 for functional and security fixes. 43 | 44 | ## v1.5.12 (2019-07-10) 45 | * Updated dependencies to Flask 1.1.1, which fixes a logging issue where some log entries were being duplicated. 46 | * Updated body of 404 response when no matches are found by gglsbl to contain the same JSON format as the 200 response. 47 | 48 | ## v1.5.11 (2019-06-21) 49 | Use alpine:3.10 for latest OS updates. 50 | 51 | ## v1.5.10 (2019-06-04) 52 | Updated dependencies Flask (1.0.3), APScheduler (3.6.0) and gglsbl (1.4.15). 53 | 54 | ## v1.5.9 (2019-05-10) 55 | Mitigate CVE-2019-5021 as per https://alpinelinux.org/posts/Docker-image-vulnerability-CVE-2019-5021.html 56 | 57 | ## v1.5.8 (2019-02-15) 58 | - Removed use of pid package since APScheduler max_instances=1 should already prevent concurrent executions of the update process. 59 | 60 | ## v1.5.7 (2019-02-01) 61 | - Use alpine:3.9 for latest OS updates; 62 | - Upgrade pid to 2.2.1. 63 | 64 | ## v1.5.6 (2019-01-08) 65 | - Migrate to Python 3. 66 | 67 | ## v1.5.5 (2018-12-21) 68 | - Use alpine:3.8 as base image directly for latest package and OS updates; 69 | - Update dependencies: gglsbl 1.4.14, and gunicorn 19.9.0; 70 | - Replace use of crond with apscheduler Python package to run regular updates; 71 | - Since crond is not longer used, no processes need to run as root and we can use `USER` Dockerfile directive to drop privileges. 72 | 73 | ## v1.5.4 (2018-06-28) 74 | - Upgrade Flask to 1.0.2; 75 | - Upgrade gglsbl to 1.4.11; 76 | - Upgrade gunicorn to 19.8.1. 77 | 78 | ## v1.5.3 (2018-04-14) 79 | - Upgraded to gglsbl-rest 1.4.10 and pid 2.2.0; 80 | - Removed dead code and unnecessary WAL mode setting from update.py. 81 | 82 | ## v1.5.2 (2018-03-07) 83 | - Updated gglsbl to version 1.4.8 for [fixes and improvements](https://github.com/afilipovich/gglsbl/releases). 84 | 85 | ## v1.5.1 (2017-12-14) 86 | - Use alpine:3.7 as base image directly for latest package and OS updates. 87 | 88 | ## v1.5.0 (2017-11-03) 89 | - Run update.py and main gunicorn process as a regular `gglsbl` user instead of root for added security. 90 | 91 | ## v1.4.0 (2017-10-30) 92 | - Use a single database in sqlite WAL mode (#10); 93 | - Default value of WORKERS is now 8 per detected CPU core plus one. 94 | 95 | ## v1.3.2 (2017-10-29) 96 | - Use Alpine 3.6 instead of 3.4, since this moves us from sqlite 3.13 to 3.20.1 and seems to solve https://github.com/afilipovich/gglsbl/issues/28 with gglsbl 1.4.6; 97 | - Use gglsbl 1.4.6 again. 98 | 99 | ## v1.3.1 (2017-10-28) 100 | - Revert to gglsbl 1.4.5 to avoid exceptions on queries as per https://github.com/afilipovich/gglsbl/issues/28; 101 | - Delete SafeBrowsingList object after database update to ensure sqlite connection is closed before moving the database file. 102 | 103 | ## v1.3.0 (2017-10-26) 104 | - Added environment variable KEEPALIVE to control persistent connection idle period; 105 | - Added environment variable LIMIT_REQUEST_LINE to increase the default gunicorn maximum HTTP request line size, since we embed full URLs into our URI. 106 | 107 | ## v1.2.0 (2017-10-25) 108 | - Updated logging configuration so that even background tasks write to Docker logs; 109 | - Define regular recycling of gunicorn workers as inspired by https://github.com/amrael/gglsbl-rest/commit/0fd51f17ee879c736387eeb93512a1d11223a68c. 110 | 111 | ## v1.1.0 (2017-10-19) 112 | - Updated to gglsbl v1.4.6 and Flask 0.12.2; 113 | - Reuse gglsbl SafeBrowsingList object across requests for improved performance (#2); 114 | - Retry gglsbl lookup a configurable number of times before giving up (#4). 115 | 116 | ## v1.0.0 (2017-06-05) 117 | Initial release. 118 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![docker stars](https://img.shields.io/docker/stars/mlsecproject/gglsbl-rest.svg)](https://hub.docker.com/r/mlsecproject/gglsbl-rest/) [![docker pulls](https://img.shields.io/docker/pulls/mlsecproject/gglsbl-rest.svg)](https://hub.docker.com/r/mlsecproject/gglsbl-rest/) [![docker build status](https://img.shields.io/docker/build/mlsecproject/gglsbl-rest.svg)](https://hub.docker.com/r/mlsecproject/gglsbl-rest/) [![](https://circleci.com/gh/mlsecproject/gglsbl-rest.svg?style=svg)](https://app.circleci.com/pipelines/github/mlsecproject/gglsbl-rest) 2 | 3 | # gglsbl-rest 4 | 5 | This repository implements a Dockerized REST service to look up URLs in Google Safe Browsing v4 API based on [gglsbl](https://github.com/afilipovich/gglsbl) using [Flask](https://pypi.python.org/pypi/Flask) and [gunicorn](https://pypi.python.org/pypi/gunicorn). 6 | 7 | ## Basic Design 8 | 9 | The main challenge with running gglsbl in a REST service is that the process of updating the local sqlite database takes several minutes. Plus, the sqlite database is locked during writes by default, so that would essentially cause very noticeable downtime or a race condition. 10 | 11 | So what gglsbl-rest does since version 1.4.0 is to set the sqlite database to [write-ahead logging](https://sqlite.org/wal.html) mode so that readers and writers can work concurrently. A scheduled task runs every 30 minutes to update the database and then performs a [full checkpoint](https://sqlite.org/pragma.html#pragma_wal_checkpoint) to ensure readers have optimal performance. 12 | 13 | Versions before 1.4.0 maintained two sets of files on disk and switched between them, which is why the status endpoint has the output format lists "alternatives". But the current approach has many advantages, as it reuses fresh downloaded data across updates and cached full hash data. 14 | 15 | The regular update is executed using [APScheduler](https://pypi.org/project/APScheduler/) on the [gunicorn](https://pypi.python.org/pypi/gunicorn) master process. For security reasons, [gunicorn](https://pypi.python.org/pypi/gunicorn) is executed with a regular user called `gglsbl` using the Dockerfile `USER` directive. 16 | 17 | ## Environment Variables 18 | 19 | The configuration of the REST service can be done using the following environment variables: 20 | 21 | * `GSB_API_KEY` is *required* and should contain your [Google Safe Browsing v4 API key](https://developers.google.com/safe-browsing/v4/get-started). 22 | 23 | * `WORKERS` controls how many gunicorn workers to instantiate. Defaults to 8 times the number of detected cores plus one. 24 | 25 | * `TIMEOUT` controls how many seconds before gunicorn times out on a request. Defaults to 120. 26 | 27 | * `MAX_REQUESTS` controls how many requests a worker can server before it is restarted, as per the [max_requests](http://docs.gunicorn.org/en/stable/settings.html#max-requests) gunicorn setting. Defaults to restarting workers after they serve 16,384 requests. 28 | 29 | * `LIMIT_REQUEST_LINE` controls the maximum size of the HTTP request line (operation, protocol version, URI and query parameters), as per the [limit_request_line](http://docs.gunicorn.org/en/stable/settings.html#limit-request-line) gunicorn setting. Defaults to 8190, set to 0 to allow any length. 30 | 31 | * `KEEPALIVE` controls how long a persistent connection can be idle before it is closed, as per the [keepalive](http://docs.gunicorn.org/en/stable/settings.html#keepalive) gunicorn setting. Defaults to 60 seconds. 32 | 33 | * `MAX_RETRIES` controls how many times the service should retry performing the request if an error occurs. Defaults to 3. 34 | 35 | * `HTTPS_PROXY` sets the proxy URL if the service is running behind a proxy. Not set by default. (HTTP_PROXY is not necessary as gglsbl-rest only queries HTTPS URLs) 36 | 37 | ## Running 38 | 39 | ### Docker 40 | 41 | You can run the latest automated build from [Docker Hub](https://hub.docker.com/r/mlsecproject/gglsbl-rest/) as follows: 42 | ```bash 43 | docker run -e GSB_API_KEY= -p 127.0.0.1:5000:5000 mlsecproject/gglsbl-rest 44 | ``` 45 | 46 | This will cause the service to listen on port 5000 of the host machine. Please realize that when the service first starts it downloads a new local partial hash database from scratch before starting the REST service. So it might take several minutes to become available. 47 | 48 | You can run `docker logs --follow ` to tail the output and determine when the gunicorn workers start, if necessary. 49 | 50 | ### Okteto Cloud 51 | 52 | First, [add a secret](https://okteto.com/docs/cloud/secrets) to your Okteto Cloud namespace with the value of your `GSB_API_KEY` key. 53 | 54 | Next, click on the following button to deploy the application: 55 | 56 | [![Develop on Okteto](https://okteto.com/develop-okteto.svg)](https://cloud.okteto.com/deploy?repository=https://github.com/mlsecproject/gglsbl-rest) 57 | 58 | This will execute an automated pipeline that will make the service listen on https://rest-[YOUR-GITHUB-ID].cloud.okteto.net/port. Please realize that when the service first starts it downloads a new local partial hash database from scratch before starting the REST service. So it might take several minutes to become available. 59 | 60 | You can see the logs from the Okteto Cloud dashboard to determine when the gunicorn workers start, if necessary. 61 | 62 | Once the application is running on Okteto Cloud, you can develop it by executing the following commands: 63 | 64 | ``` 65 | $ okteto up 66 | ✓ Development container activated 67 | ✓ Files synchronized 68 | Namespace: YOUR-GITHUB-ID 69 | Name: rest 70 | Forward: 5000 -> 5000 71 | 72 | Welcome to your development container. Happy coding! 73 | YOUR-GITHUB-ID:rest okteto> pip install -r requirements.txt 74 | YOUR-GITHUB-ID:rest okteto> python app.py 75 | ``` 76 | 77 | ### Production 78 | 79 | In production, you might want to mount `/home/gglsbl/db` in a [tmpfs RAM disk](https://docs.docker.com/engine/admin/volumes/tmpfs/) for improved performance. Recommended size is 4+ gigabytes, which is roughly twice of a freshly initialized database, but YMMV. 80 | 81 | ## Querying the REST Service 82 | 83 | The REST service will respond to queries for `/gglsbl/v1/lookup/`. Make sure you [percent encode](https://en.wikipedia.org/wiki/Percent-encoding) the URL you are querying. If no sign of maliciousness is found, the service will return with a 404 status. Otherwise, a 200 response with a JSON body is returned to describe it. 84 | 85 | Here's an example query and response to a test URL where matches are guaranteed to be found, pretty formatted using [jq](https://stedolan.github.io/jq/): 86 | ```bash 87 | $ curl "http://127.0.0.1:5000/gglsbl/v1/lookup/http%3A%2F%2Ftestsafebrowsing.appspot.com%2Fapiv4%2FANY_PLATFORM%2FSOCIAL_ENGINEERING%2FURL%2F" | jq 88 | { 89 | "matches": [ 90 | { 91 | "platform": "ANY_PLATFORM", 92 | "threat": "SOCIAL_ENGINEERING", 93 | "threat_entry": "URL" 94 | }, 95 | { 96 | "platform": "WINDOWS", 97 | "threat": "SOCIAL_ENGINEERING", 98 | "threat_entry": "URL" 99 | }, 100 | { 101 | "platform": "LINUX", 102 | "threat": "SOCIAL_ENGINEERING", 103 | "threat_entry": "URL" 104 | }, 105 | { 106 | "platform": "OSX", 107 | "threat": "SOCIAL_ENGINEERING", 108 | "threat_entry": "URL" 109 | }, 110 | { 111 | "platform": "ALL_PLATFORMS", 112 | "threat": "SOCIAL_ENGINEERING", 113 | "threat_entry": "URL" 114 | }, 115 | { 116 | "platform": "CHROME", 117 | "threat": "SOCIAL_ENGINEERING", 118 | "threat_entry": "URL" 119 | } 120 | ], 121 | "url": "http://testsafebrowsing.appspot.com/apiv4/ANY_PLATFORM/SOCIAL_ENGINEERING/URL/" 122 | } 123 | ``` 124 | 125 | Here's an example lookup of google.com which should yield no matches (notice the 404 status code): 126 | ```bash 127 | $ curl -i "http://127.0.0.1:5000/gglsbl/v1/lookup/http%3A%2F%2Fgoogle.com" 128 | HTTP/1.1 404 NOT FOUND 129 | Server: gunicorn/19.9.0 130 | Date: Wed, 10 Jul 2019 21:41:21 GMT 131 | Connection: close 132 | Content-Type: application/json 133 | Content-Length: 41 134 | 135 | {"matches":[],"url":"http://google.com"} 136 | ``` 137 | 138 | There' an additional `/gglsbl/v1/status` URL that you can access to check if the service is running and also get some indication of how old the current sqlite database is: 139 | ```bash 140 | $ curl "http://127.0.0.1:5000/gglsbl/v1/status" | jq 141 | { 142 | "alternatives": [ 143 | { 144 | "active": true, 145 | "ctime": "2017-10-30T20:20:55+0000", 146 | "mtime": "2017-10-30T20:20:55+0000", 147 | "name": "/home/gglsbl/db/sqlite.db", 148 | "size": 2079985664 149 | } 150 | ], 151 | "environment": "prod" 152 | } 153 | ``` 154 | 155 | A much more convenient way to query the service from the command-line, though, is to use [gglsbl-rest-client](https://github.com/seanmcfeely/gglsbl-rest-client), maintained by [Sean McFeely](https://github.com/seanmcfeely). 156 | 157 | 158 | ## Who's using gglsbl-rest 159 | 160 | * [neonknight](https://github.com/neonknight) reports gglsbl-rest is used as a bridge between the [fuglu mail filter engine](https://gitlab.com/fumail/fuglu) and Google Safebrowsing API through a [plug-in](https://gitlab.com/fumail/fuglu-extra-plugins/blob/master/safebrowsing/gglsbl.py). 161 | * [Sean McFeely](https://github.com/seanmcfeely) reports gglsbl-rest is used in [ACE - Analysis Correlation Engine](https://github.com/ace-ecosystem/ACE) to help security analysts perform their activities in a more automated manner, including Google Safebrowsing API lookup of URLs. 162 | 163 | If your project or company are using gglsbl-rest and you would like them to be listed here, please open a [GitHub issue](https://github.com/mlsecproject/gglsbl-rest/issues) and we'll include you. 164 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 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 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /deploy/ecs-deploy: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -o errexit 3 | set -o pipefail 4 | set -u 5 | 6 | function usage() { 7 | set -e 8 | cat < /dev/null 2>&1 || { 70 | echo "Some of the required software is not installed:" 71 | echo " please install $1" >&2; 72 | exit 1; 73 | } 74 | } 75 | 76 | # Check for AWS, AWS Command Line Interface 77 | require aws 78 | # Check for jq, Command-line JSON processor 79 | require jq 80 | 81 | # Setup default values for variables 82 | CLUSTER=false 83 | SERVICE=false 84 | TASK_DEFINITION=false 85 | MAX_DEFINITIONS=0 86 | IMAGE=false 87 | MIN=false 88 | MAX=false 89 | TIMEOUT=90 90 | VERBOSE=false 91 | TAGVAR=false 92 | AWS_CLI=$(which aws) 93 | AWS_ECS="$AWS_CLI --output json ecs" 94 | 95 | # Loop through arguments, two at a time for key and value 96 | while [[ $# -gt 0 ]] 97 | do 98 | key="$1" 99 | 100 | case $key in 101 | -k|--aws-access-key) 102 | AWS_ACCESS_KEY_ID="$2" 103 | shift # past argument 104 | ;; 105 | -s|--aws-secret-key) 106 | AWS_SECRET_ACCESS_KEY="$2" 107 | shift # past argument 108 | ;; 109 | -r|--region) 110 | AWS_DEFAULT_REGION="$2" 111 | shift # past argument 112 | ;; 113 | -p|--profile) 114 | AWS_PROFILE="$2" 115 | shift # past argument 116 | ;; 117 | --aws-instance-profile) 118 | echo "--aws-instance-profile is not yet in use" 119 | AWS_IAM_ROLE=true 120 | ;; 121 | -c|--cluster) 122 | CLUSTER="$2" 123 | shift # past argument 124 | ;; 125 | -n|--service-name) 126 | SERVICE="$2" 127 | shift # past argument 128 | ;; 129 | -d|--task-definition) 130 | TASK_DEFINITION="$2" 131 | shift 132 | ;; 133 | -i|--image) 134 | IMAGE="$2" 135 | shift 136 | ;; 137 | -t|--timeout) 138 | TIMEOUT="$2" 139 | shift 140 | ;; 141 | -m|--min) 142 | MIN="$2" 143 | shift 144 | ;; 145 | -M|--max) 146 | MAX="$2" 147 | shift 148 | ;; 149 | -D|--desired-count) 150 | DESIRED="$2" 151 | shift 152 | ;; 153 | -e|--tag-env-var) 154 | TAGVAR="$2" 155 | shift 156 | ;; 157 | --max-definitions) 158 | MAX_DEFINITIONS="$2" 159 | shift 160 | ;; 161 | -v|--verbose) 162 | VERBOSE=true 163 | ;; 164 | *) 165 | usage 166 | exit 2 167 | ;; 168 | esac 169 | shift # past argument or value 170 | done 171 | 172 | # AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION and AWS_PROFILE can be set as environment variables 173 | if [ -z ${AWS_ACCESS_KEY_ID+x} ]; then unset AWS_ACCESS_KEY_ID; fi 174 | if [ -z ${AWS_SECRET_ACCESS_KEY+x} ]; then unset AWS_SECRET_ACCESS_KEY; fi 175 | if [ -z ${AWS_DEFAULT_REGION+x} ]; 176 | then unset AWS_DEFAULT_REGION 177 | else 178 | AWS_ECS="$AWS_ECS --region $AWS_DEFAULT_REGION" 179 | fi 180 | if [ -z ${AWS_PROFILE+x} ]; 181 | then unset AWS_PROFILE 182 | else 183 | AWS_ECS="$AWS_ECS --profile $AWS_PROFILE" 184 | fi 185 | 186 | if [ $VERBOSE == true ]; then 187 | set -x 188 | fi 189 | 190 | if [ $SERVICE == false ] && [ $TASK_DEFINITION == false ]; then 191 | echo "One of SERVICE or TASK DEFINITON is required. You can pass the value using -n / --service-name for a service, or -d / --task-definiton for a task" 192 | exit 1 193 | fi 194 | if [ $SERVICE != false ] && [ $TASK_DEFINITION != false ]; then 195 | echo "Only one of SERVICE or TASK DEFINITON may be specified, but you supplied both" 196 | exit 1 197 | fi 198 | if [ $SERVICE != false ] && [ $CLUSTER == false ]; then 199 | echo "CLUSTER is required. You can pass the value using -c or --cluster" 200 | exit 1 201 | fi 202 | if [ $IMAGE == false ]; then 203 | echo "IMAGE is required. You can pass the value using -i or --image" 204 | exit 1 205 | fi 206 | if ! [[ $MAX_DEFINITIONS =~ ^-?[0-9]+$ ]]; then 207 | echo "MAX_DEFINITIONS must be numeric, or not defined." 208 | exit 1 209 | fi 210 | 211 | # Define regex for image name 212 | # This regex will create groups for: 213 | # - domain 214 | # - port 215 | # - repo 216 | # - image 217 | # - tag 218 | # If a group is missing it will be an empty string 219 | imageRegex="^([a-zA-Z0-9.\-]+):?([0-9]+)?/([a-zA-Z0-9_-]+)/?([a-zA-Z0-9_-]+)?:?([a-zA-Z0-9\._-]+)?$" 220 | 221 | if [[ $IMAGE =~ $imageRegex ]]; then 222 | # Define variables from matching groups 223 | domain=${BASH_REMATCH[1]} 224 | port=${BASH_REMATCH[2]} 225 | repo=${BASH_REMATCH[3]} 226 | img=${BASH_REMATCH[4]} 227 | tag=${BASH_REMATCH[5]} 228 | 229 | # Validate what we received to make sure we have the pieces needed 230 | if [[ "x$domain" == "x" ]]; then 231 | echo "Image name does not contain a domain or repo as expected. See usage for supported formats." && exit 1; 232 | fi 233 | if [[ "x$repo" == "x" ]]; then 234 | echo "Image name is missing the actual image name. See usage for supported formats." && exit 1; 235 | fi 236 | 237 | # When a match for image is not found, the image name was picked up by the repo group, so reset variables 238 | if [[ "x$img" == "x" ]]; then 239 | img=$repo 240 | repo="" 241 | fi 242 | 243 | else 244 | # check if using root level repo with format like mariadb or mariadb:latest 245 | rootRepoRegex="^([a-zA-Z0-9\-]+):?([a-zA-Z0-9\.\-]+)?$" 246 | if [[ $IMAGE =~ $rootRepoRegex ]]; then 247 | img=${BASH_REMATCH[1]} 248 | if [[ "x$img" == "x" ]]; then 249 | echo "Invalid image name. See usage for supported formats." && exit 1 250 | fi 251 | tag=${BASH_REMATCH[2]} 252 | else 253 | echo "Unable to parse image name: $IMAGE, check the format and try again" && exit 1 254 | fi 255 | fi 256 | 257 | # If tag is missing make sure we can get it from env var, or use latest as default 258 | if [[ "x$tag" == "x" ]]; then 259 | if [[ $TAGVAR == false ]]; then 260 | tag="latest" 261 | else 262 | tag=${!TAGVAR} 263 | if [[ "x$tag" == "x" ]]; then 264 | tag="latest" 265 | fi 266 | fi 267 | fi 268 | 269 | # Reassemble image name 270 | useImage="" 271 | if [[ ! -z ${domain+undefined-guard} ]]; then 272 | useImage="$domain" 273 | fi 274 | if [[ ! -z ${port} ]]; then 275 | useImage="$useImage:$port" 276 | fi 277 | if [[ ! -z ${repo+undefined-guard} ]]; then 278 | if [[ ! "x$repo" == "x" ]]; then 279 | useImage="$useImage/$repo" 280 | fi 281 | fi 282 | if [[ ! -z ${img+undefined-guard} ]]; then 283 | if [[ "x$useImage" == "x" ]]; then 284 | useImage="$img" 285 | else 286 | useImage="$useImage/$img" 287 | fi 288 | fi 289 | imageWithoutTag="$useImage" 290 | if [[ ! -z ${tag+undefined-guard} ]]; then 291 | useImage="$useImage:$tag" 292 | fi 293 | 294 | echo "Using image name: $useImage" 295 | 296 | if [ $SERVICE != false ]; then 297 | # Get current task definition name from service 298 | TASK_DEFINITION=`$AWS_ECS describe-services --services $SERVICE --cluster $CLUSTER | jq -r .services[0].taskDefinition` 299 | fi 300 | 301 | echo "Current task definition: $TASK_DEFINITION"; 302 | 303 | # Get a JSON representation of the current task definition 304 | # + Update definition to use new image name 305 | # + Filter the def 306 | td=$($AWS_ECS describe-task-definition --task-def "$TASK_DEFINITION" \ 307 | | jq '.taskDefinition') 308 | changedDefinition=$(echo "$td" | jq ".containerDefinitions | [.[] | .+{image: \"$useImage\"}]") 309 | DEF=$(echo "$td" | jq ".+{containerDefinitions: $changedDefinition}") 310 | 311 | # Default JQ filter for new task definition 312 | NEW_DEF_JQ_FILTER="family: .family, volumes: .volumes, containerDefinitions: .containerDefinitions" 313 | 314 | # Some options in task definition should only be included in new definition if present in 315 | # current definition. If found in current definition, append to JQ filter. 316 | CONDITIONAL_OPTIONS=(networkMode taskRoleArn) 317 | for i in "${CONDITIONAL_OPTIONS[@]}"; do 318 | re=".*${i}.*" 319 | if [[ "$DEF" =~ $re ]]; then 320 | NEW_DEF_JQ_FILTER="${NEW_DEF_JQ_FILTER}, ${i}: .${i}" 321 | fi 322 | done 323 | 324 | # Build new DEF with jq filter 325 | NEW_DEF=$(echo $DEF | jq "{${NEW_DEF_JQ_FILTER}}") 326 | 327 | # Register the new task definition, and store its ARN 328 | NEW_TASKDEF=`$AWS_ECS register-task-definition --cli-input-json "$NEW_DEF" | jq -r .taskDefinition.taskDefinitionArn` 329 | echo "New task definition: $NEW_TASKDEF"; 330 | 331 | if [ $SERVICE == false ]; then 332 | echo "Task definition updated successfully" 333 | else 334 | DEPLOYMENT_CONFIG="" 335 | if [ $MAX != false ]; then 336 | DEPLOYMENT_CONFIG=",maximumPercent=$MAX" 337 | fi 338 | if [ $MIN != false ]; then 339 | DEPLOYMENT_CONFIG="$DEPLOYMENT_CONFIG,minimumHealthyPercent=$MIN" 340 | fi 341 | if [ ! -z "$DEPLOYMENT_CONFIG" ]; then 342 | DEPLOYMENT_CONFIG="--deployment-configuration ${DEPLOYMENT_CONFIG:1}" 343 | fi 344 | 345 | DESIRED_COUNT="" 346 | if [ ! -z ${DESIRED+undefined-guard} ]; then 347 | DESIRED_COUNT="--desired-count $DESIRED" 348 | fi 349 | 350 | # Update the service 351 | UPDATE=`$AWS_ECS update-service --cluster $CLUSTER --service $SERVICE $DESIRED_COUNT --task-definition $NEW_TASKDEF $DEPLOYMENT_CONFIG` 352 | 353 | # Only excepts RUNNING state from services whose desired-count > 0 354 | SERVICE_DESIREDCOUNT=`$AWS_ECS describe-services --cluster $CLUSTER --service $SERVICE | jq '.services[]|.desiredCount'` 355 | if [ $SERVICE_DESIREDCOUNT -gt 0 ]; then 356 | # See if the service is able to come up again 357 | every=10 358 | i=0 359 | while [ $i -lt $TIMEOUT ] 360 | do 361 | # Scan the list of running tasks for that service, and see if one of them is the 362 | # new version of the task definition 363 | 364 | RUNNING_TASKS=$($AWS_ECS list-tasks --cluster "$CLUSTER" --service-name "$SERVICE" --desired-status RUNNING \ 365 | | jq -r '.taskArns[]') 366 | 367 | if [[ ! -z $RUNNING_TASKS ]] ; then 368 | RUNNING=$($AWS_ECS describe-tasks --cluster "$CLUSTER" --tasks $RUNNING_TASKS \ 369 | | jq ".tasks[]| if .taskDefinitionArn == \"$NEW_TASKDEF\" then . else empty end|.lastStatus" \ 370 | | grep -e "RUNNING") || : 371 | 372 | if [ "$RUNNING" ]; then 373 | echo "Service updated successfully, new task definition running."; 374 | 375 | if [[ $MAX_DEFINITIONS -gt 0 ]]; then 376 | FAMILY_PREFIX=${TASK_DEFINITION##*:task-definition/} 377 | FAMILY_PREFIX=${FAMILY_PREFIX%*:[0-9]*} 378 | TASK_REVISIONS=`$AWS_ECS list-task-definitions --family-prefix $FAMILY_PREFIX --status ACTIVE --sort ASC` 379 | 380 | NUM_ACTIVE_REVISIONS=$(echo "$TASK_REVISIONS" | jq ".taskDefinitionArns|length") 381 | 382 | if [[ $NUM_ACTIVE_REVISIONS -gt $MAX_DEFINITIONS ]]; then 383 | LAST_OUTDATED_INDEX=$(($NUM_ACTIVE_REVISIONS - $MAX_DEFINITIONS - 1)) 384 | for i in $(seq 0 $LAST_OUTDATED_INDEX); do 385 | OUTDATED_REVISION_ARN=$(echo "$TASK_REVISIONS" | jq -r ".taskDefinitionArns[$i]") 386 | 387 | echo "Deregistering outdated task revision: $OUTDATED_REVISION_ARN" 388 | 389 | $AWS_ECS deregister-task-definition --task-definition "$OUTDATED_REVISION_ARN" > /dev/null 390 | done 391 | fi 392 | fi 393 | 394 | exit 0 395 | fi 396 | fi 397 | 398 | sleep $every 399 | i=$(( $i + $every )) 400 | done 401 | 402 | # Timeout 403 | echo "ERROR: New task definition not running within $TIMEOUT seconds" 404 | exit 1 405 | else 406 | echo "Skipping check for running task definition, as desired-count <= 0" 407 | fi 408 | fi 409 | --------------------------------------------------------------------------------