Repository: we45/ThreatPlaybook Branch: master Commit: 36eb825b0ca3 Files: 108 Total size: 324.2 KB Directory structure: gitextract_ntphgy1z/ ├── .dockerignore ├── .github/ │ └── workflows/ │ └── main.yml ├── .gitignore ├── README.md ├── api/ │ ├── .vscode/ │ │ └── settings.json │ ├── Dockerfile │ ├── conftest.py │ ├── requirements.txt │ ├── tests/ │ │ └── test_flask.py │ └── tp_api/ │ ├── __init__.py │ ├── app.py │ ├── asvs/ │ │ └── asvs.csv │ ├── models.py │ ├── repo/ │ │ ├── aws_s3.yaml │ │ ├── cert_validation.yaml │ │ ├── code_injection.yaml │ │ ├── idor_pk.yaml │ │ ├── insecure_deserialization.yaml │ │ ├── password-bruteforce.yaml │ │ ├── plaintext-transmission.yaml │ │ ├── sql_injection.yaml │ │ ├── ssrf.yaml │ │ ├── weak-default-password.yaml │ │ ├── xss.yaml │ │ └── xxe.yaml │ ├── swagger/ │ │ ├── abuse-create.yml │ │ ├── change-password.yml │ │ ├── feature-create.yml │ │ ├── get-abuse.yml │ │ ├── get-feature.yml │ │ ├── get-project.yml │ │ ├── get-scenario.yml │ │ ├── get-tests.yml │ │ ├── scan-create.yml │ │ ├── scenario-inline.yml │ │ ├── scenario-repo.yml │ │ ├── target-create-update.yml │ │ ├── test-case-create.yml │ │ └── vulnerability-create.yml │ ├── utils.py │ └── wait-for ├── docker-compose.yml ├── documentation/ │ ├── .gitignore │ ├── README.md │ ├── babel.config.js │ ├── docs/ │ │ ├── client-ui.md │ │ ├── configure-cli.md │ │ ├── create-project.md │ │ ├── install-client.md │ │ ├── overview.md │ │ ├── quick-installation.md │ │ ├── story-driven.md │ │ ├── tutorial-client-ui.md │ │ └── tutorial.md │ ├── docusaurus.config.js │ ├── package.json │ ├── sidebars.js │ ├── src/ │ │ ├── css/ │ │ │ └── custom.css │ │ └── pages/ │ │ ├── index.js │ │ └── styles.module.css │ └── static/ │ └── .nojekyll ├── frontend/ │ └── Playbook-Frontend/ │ ├── .babelrc │ ├── .editorconfig │ ├── .gitignore │ ├── Dockerfile │ ├── README.md │ ├── assets/ │ │ └── variables.scss │ ├── components/ │ │ ├── Logo.vue │ │ ├── README.md │ │ ├── VuetifyLogo.vue │ │ ├── project/ │ │ │ ├── Content.vue │ │ │ └── Header.vue │ │ └── projects/ │ │ └── ProjectsPage.vue │ ├── jest.config.js │ ├── jsconfig.json │ ├── layouts/ │ │ ├── default.vue │ │ ├── error.vue │ │ └── main.vue │ ├── middleware/ │ │ └── README.md │ ├── nuxt.config.js │ ├── package.json │ ├── pages/ │ │ ├── home/ │ │ │ └── index.vue │ │ ├── index.vue │ │ ├── projects/ │ │ │ ├── _name/ │ │ │ │ ├── abuser-story.vue │ │ │ │ ├── project.vue │ │ │ │ ├── threat-map.vue │ │ │ │ ├── threat-scenario.vue │ │ │ │ ├── user-story.vue │ │ │ │ └── vulnerabilities.vue │ │ │ └── index.vue │ │ └── scan/ │ │ └── _name.vue │ ├── plugins/ │ │ ├── README.md │ │ ├── vue-apexchart.js │ │ └── vue-organization-chart.js │ ├── store/ │ │ ├── abuserStory.js │ │ ├── home.js │ │ ├── index.js │ │ ├── login.js │ │ ├── projects.js │ │ ├── scan.js │ │ ├── threatScenario.js │ │ ├── threatmap.js │ │ ├── userStory.js │ │ └── vulnerability.js │ └── test/ │ └── Logo.spec.js └── nginx/ ├── Dockerfile ├── alpine.df └── sites-enabled/ └── tp_nginx ================================================ FILE CONTENTS ================================================ ================================================ FILE: .dockerignore ================================================ */node_modules *.log ================================================ FILE: .github/workflows/main.yml ================================================ name: CI on: [push] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - name: Build API Docker Container run: cd $GITHUB_WORKSPACE/api/ && docker build . --file $GITHUB_WORKSPACE/api/Dockerfile --tag we45/threatplaybook-server - name: Test Secret run: echo $DOCKER_LOGIN_USER - name: Build and Push uses: zemuldo/docker-build-push@master env: DOCKER_USERNAME: "we45" DOCKER_NAMESPACE: "we45" DOCKER_PASSWORD: ${{ secrets.DOCKER_LOGIN_PASS }} REGISTRY_URL: "docker.io" with: image_name: "threatplaybook-server" image_tag: "latest" ================================================ FILE: .gitignore ================================================ example/*.html example/*.xml example/*.json example/*.png example/*.txt example/*.mmd example/*.md results/ tv/ ThreatPlaybook.egg-info/* dist/* threat_playbook/ThreatPlaybook.egg-info/dependency_links.txt threat_playbook/ThreatPlaybook.egg-info/entry_points.txt threat_playbook/ThreatPlaybook.egg-info/PKG-INFO threat_playbook/ThreatPlaybook.egg-info/requires.txt threat_playbook/ThreatPlaybook.egg-info/SOURCES.txt threat_playbook/ThreatPlaybook.egg-info/top_level.txt venv3/* v1/ThreatPlaybook.egg-info/top_level.txt v1/ThreatPlaybook.egg-info/SOURCES.txt v1/ThreatPlaybook.egg-info/requires.txt v1/ThreatPlaybook.egg-info/PKG-INFO v1/ThreatPlaybook.egg-info/entry_points.txt v1/ThreatPlaybook.egg-info/dependency_links.txt v3/cli/.cred v3/cli/schematest.json v3/cli/schema.schema v3/cli/threat_model_example.json v3/cli/case_example.json v3/cli/repo_gql.json v3/cli/feature_test.json v3/api/.env .idea/encodings.xml *.xml *.xml .idea/vcs.xml .idea/ThreatPlaybook.iml v3/api/.env v3/api/.env .idea/vcs.xml .idea/* v3/threatplaybook_db/ v3/robot/test/log.html v3/robot/test/report.html v3/.DS_Store v3/frontend/.DS_Store .DS_Store api/.env threatplaybook_db/* robot/test/log.html robot/test/report.html robot/test/log.html robot/test/report.html robot/test/log.html *.html v3/frontend/ThreatPlaybook-Frontend/node_modules/ v3/frontend/ThreatPlaybook-Frontend/dist/ v3/frontend/ThreatPlaybook-Frontend/npm-debug.log* v3/frontend/ThreatPlaybook-Frontend/yarn-debug.log* v3/frontend/ThreatPlaybook-Frontend/yarn-error.log* v3/frontend/ThreatPlaybook-Frontend/package-lock.json frontend/ThreatPlaybook-Frontend/node_modules/ frontend/ThreatPlaybook-Frontend/npm-debug.log* frontend/ThreatPlaybook-Frontend/yarn-debug.log* frontend/ThreatPlaybook-Frontend/yarn-error.log* frontend/ThreatPlaybook-Frontend/package-lock.json # frontend/ThreatPlaybook-Frontend/.babelrc # frontend/ThreatPlaybook-Frontend/.editorconfig Pipfile.lock Pipfile cli/dist/ThreatPlaybook-Client-3.0.3.tar.gz cli/playbook/.cred venv/ *.pyc api/__pycache__/utils.cpython-37.pyc api/__pycache__/models.cpython-37.pyc .vscode/settings.json *.lock apiv2/.vscode/settings.json apiv2/tp_api/logs/output.log apiv2/logs/output.log logs/output.log website/node_modules/* frontend/Playbook-Frontend/package-lock.json api/tp_api/logs/output.log ================================================ FILE: README.md ================================================ # ThreatPlaybook > This is version 3 (beta) ### What it was: A (relatively) Unopinionated framework that faciliates Threat Modeling as Code married with Application Security Automation on a single Fabric ### What it is now: A unified DevSecOps Framework that allows you to go from iterative, collaborative Threat Modeling to Application Security Test Orchestration [![Black Hat Arsenal USA](https://rawgit.com/toolswatch/badges/master/arsenal/usa/2018.svg)](https://www.blackhat.com/us-18/arsenal/schedule/index.html#threatplaybook-11697) [Documentation](https://threatplaybook.netlify.app) * [Quick Start](https://threatplaybook.netlify.app/docs/installation) * [Tutorial](https://threatplaybook.netlify.app/docs/tutorial) ![](img/tp-logo.png) ## Brought to you proudly by ![](img/we45logo.jpg) ================================================ FILE: api/.vscode/settings.json ================================================ { "python.formatting.provider": "black", "python.pythonPath": "venv/bin/python" } ================================================ FILE: api/Dockerfile ================================================ FROM python:alpine3.7 COPY tp_api/ /app COPY requirements.txt /app ADD https://github.com/ufoscout/docker-compose-wait/releases/download/2.2.1/wait ./wait RUN chmod +x ./wait WORKDIR /app RUN chmod +x wait-for RUN apk add --no-cache --virtual .build-deps g++ python3-dev libffi-dev libressl-dev && \ apk add --no-cache --update python3 && \ pip3 install --upgrade pip setuptools RUN pip install -r requirements.txt EXPOSE 5000 CMD ["/usr/local/bin/python", "/app/app.py"] ================================================ FILE: api/conftest.py ================================================ ================================================ FILE: api/requirements.txt ================================================ appdirs==1.4.3 attrs==19.3.0 bcrypt==3.1.7 black==19.10b0 blinker==1.4 cffi==1.14.0 click==7.1.1 entrypoints==0.3 flake8==3.7.9 flasgger==0.9.4 Flask==1.1.2 Flask-Cors==3.0.8 flask-mongoengine==0.9.5 Flask-WTF==0.14.3 importlib-metadata==1.6.0 itsdangerous==1.1.0 Jinja2==2.11.2 jsonschema==3.2.0 loguru==0.4.1 MarkupSafe==1.1.1 mccabe==0.6.1 mistune==0.8.4 mongoengine==0.19.1 more-itertools==8.2.0 packaging==20.3 pathspec==0.8.0 pluggy==0.13.1 py==1.8.1 pycodestyle==2.5.0 pycparser==2.20 pyflakes==2.1.1 PyJWT==1.7.1 pymongo==3.10.1 pyparsing==2.4.7 pyrsistent==0.16.0 pytest==5.4.1 pytest-flask==1.0.0 PyYAML==5.3.1 regex==2020.4.4 six==1.14.0 toml==0.10.0 typed-ast==1.4.1 wcwidth==0.1.9 Werkzeug==1.0.1 WTForms==2.3.1 zipp==3.1.0 ================================================ FILE: api/tests/test_flask.py ================================================ import pytest from tp_api.app import app import json import secrets token = "" project_name = "" use_case = "" abuse_case = "" threat_scenario = "" target_name = "" scan_name = "" cwe = 89 @pytest.fixture(scope="module") def client(): with app.test_client() as c: yield c def test_change_password(client): response = client.post( "/change-password", data=json.dumps( { "email": "admin@admin.com", "old_password": "supersecret", "new_password": "supersecret", "verify_password": "supersecret", } ), content_type="application/json", ) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") def test_login(client): response = client.post( "/login", data=json.dumps({"email": "admin@admin.com", "password": "supersecret"}), content_type="application/json", ) data = json.loads(response.get_data(as_text=True)) global token token = data.get("data").get("token") assert response.status_code == 200 assert data.get("success") def test_create_project(client): response = client.post( "/project/create", data=json.dumps( {"name": "test-project-{}".format(secrets.token_urlsafe(8))}), content_type="application/json", headers={"Authorization": token}, ) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") assert data.get("data").get("name") global project_name project_name = data.get("data").get("name") def test_create_feature(client): response = client.post( "/feature/create", data=json.dumps( { "short_name": "test-feature-{}".format(secrets.token_urlsafe(8)), "description": "This is a test description", "project": project_name, } ), content_type="application/json", headers={"Authorization": token}, ) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") assert data.get("data").get("short_name") global use_case use_case = data.get("data").get("short_name") def test_create_abuser_story(client): response = client.post( "/abuse-case/create", data=json.dumps( { "short_name": "test-abuser-story-{}".format(secrets.token_urlsafe(8)), "description": "This is a test description", "feature": use_case, } ), content_type="application/json", headers={"Authorization": token}, ) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") assert data.get("data").get("short_name") global abuse_case abuse_case = data.get("data").get("short_name") def test_create_threat_scenario_repo(client): response = client.post( "/scenario/repo/create", data=json.dumps( { "name": "threat-scenario-{}".format(secrets.token_urlsafe(8)), "description": "This is a test description", "feature": use_case, "abuser_story": abuse_case, "vul_name": "SQL Injection", "type": "repo", "repo_name": "sql_injection" } ), content_type="application/json", headers={"Authorization": token}, ) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") assert data.get("data").get("name") def test_create_threat_scenario(client): response = client.post( "/scenario/create", data=json.dumps( { "name": "threat-scenario-{}".format(secrets.token_urlsafe(8)), "description": "This is a test description", "feature": use_case, "abuser_story": abuse_case, "vul_name": "SQL Injection", "type": "inline" } ), content_type="application/json", headers={"Authorization": token}, ) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") assert data.get("data").get("name") global threat_scenario threat_scenario = data.get("data").get("name") def test_create_test_case(client): response = client.post( "/test/create", data=json.dumps( { "name": "test-case-{}".format(secrets.token_urlsafe(8)), "test_case": "some test case", "threat_scenario": threat_scenario, } ), content_type="application/json", headers={"Authorization": token}, ) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") assert data.get("data").get("name") def test_create_target(client): response = client.post( "/target/create", data=json.dumps( { "name": "test-target-{}".format(secrets.token_urlsafe(8)), "url": "http://example.com", "project": project_name, } ), content_type="application/json", headers={"Authorization": token}, ) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") assert data.get("data").get("name") global target_name target_name = data.get('data').get('name') def test_create_scan(client): response = client.post( "/scan/create", data=json.dumps( { "tool": "ZAP", "target": target_name, "scan_type": "DAST" } ), content_type="application/json", headers={"Authorization": token}, ) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") assert data.get("data").get("name") global scan_name scan_name = data.get('data').get('name') def test_create_vulnerability(client): response = client.post( "/vulnerability/create", data=json.dumps( { "name": "SQL Injection", "scan": scan_name, "vul_name": "SQL Injection", "cwe": 89, "severity": 3, "description": "Test Description", "evidences": [ { "log": "test log", "url": "attack.php", "param": "vulnId", "info": "Found this param by Vulnerability Scanning" } ] } ), content_type="application/json", headers={"Authorization": token}, ) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") assert data.get("data").get("name") def test_get_project(client): response = client.get("/project/read", headers={"Authorization": token}) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") def test_get_project_specific(client): response = client.post( "/project/read", data=json.dumps( {"name": project_name} ), content_type="application/json", headers={"Authorization": token}, ) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") def test_get_feature_by_project(client): response = client.post( "/feature/read", data=json.dumps( {"project": project_name} ), content_type="application/json", headers={"Authorization": token}, ) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") def test_get_abuse_case_specific(client): response = client.post( "/abuses/read", data=json.dumps( {"user_story": use_case} ), content_type="application/json", headers={"Authorization": token}, ) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") def test_get_threat_scenario(client): response = client.post( "/scenarios/read", data=json.dumps( {"abuser_story": abuse_case} ), content_type="application/json", headers={"Authorization": token}, ) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") def test_get_test_case(client): response = client.post( "/test/read", data=json.dumps( {"scenario": threat_scenario} ), content_type="application/json", headers={"Authorization": token}, ) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") def test_threat_scenario_severity(client): response = client.get("/scenario/severity", headers={"Authorization": token}) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") def test_vulnerability_severity(client): response = client.get("/vulnerability/severity", headers={"Authorization": token}) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") def test_get_scan(client): response = client.get("/scan/read", headers={"Authorization": token}) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") def test_get_threat_scenario_by_project(client): response = client.post( "/scenarios/project", data=json.dumps( {"project": project_name} ), content_type="application/json", headers={"Authorization": token}) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") def test_get_vulnerability(client): response = client.get( "/vulnerability/read", headers={"Authorization": token}) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") def test_get_vulnerability_by_project(client): response = client.post( "/vulnerability/project", data=json.dumps( {"project": project_name} ), content_type="application/json", headers={"Authorization": token}) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") def test_get_scan_by_project(client): response = client.post( "/scan/project", data=json.dumps( {"project": project_name} ), content_type="application/json", headers={"Authorization": token}) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") def test_get_user_story_tree_by_project(client): response = client.post( "/user-story/project", data=json.dumps( {"project": project_name} ), content_type="application/json", headers={"Authorization": token}) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") def test_get_abuser_story_tree_by_project(client): response = client.post( "/abuser-story/project", data=json.dumps( {"project": project_name} ), content_type="application/json", headers={"Authorization": token}) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") def test_get_threat_scenario_tree_by_project(client): response = client.post( "/threat-scenario/project", data=json.dumps( {"project": project_name} ), content_type="application/json", headers={"Authorization": token}) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") def test_get_threatmap_by_project(client): response = client.post( "/threatmap/project", data=json.dumps( {"project": project_name} ), content_type="application/json", headers={"Authorization": token}) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") def test_get_individual_scan_vuls(client): response = client.post( "/scan-vuls/project", data=json.dumps( {"name": scan_name} ), content_type="application/json", headers={"Authorization": token}) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") def test_get_asvs_vuls(client): response = client.post( "/asvs", data=json.dumps( {"cwe": cwe} ), content_type="application/json", headers={"Authorization": token}) data = json.loads(response.get_data(as_text=True)) assert response.status_code == 200 assert data.get("success") ================================================ FILE: api/tp_api/__init__.py ================================================ ================================================ FILE: api/tp_api/app.py ================================================ from flask import Flask, jsonify, request import jwt from secrets import token_urlsafe from os import getenv from utils import ( logger, connect_db, load_reload_asvs_db, load_reload_repo_db, initialize_superuser, respond, ) from models import * import bcrypt from functools import wraps import json from flask_cors import CORS import uuid from flasgger import Swagger, swag_from JWT_PASSWORD = getenv("JWT_PASS", token_urlsafe(16)) items_per_page = 20 db = connect_db() load_reload_repo_db() load_reload_asvs_db() initialize_superuser() app = Flask(__name__) swagger = Swagger(app) CORS(app) def validate_user(f): @wraps(f) def inner(*args, **kwargs): if "Authorization" not in request.headers and not request.headers.get( "Authorization" ): no_auth = respond(False, True, message="No Authentication data") return no_auth, 403 else: try: token = request.headers.get("Authorization") decoded = jwt.decode(token, JWT_PASSWORD, algorithms=["HS256"]) ref_user = User.objects.get(email=decoded["email"]) return f(*args, **kwargs) except Exception as e: logger.exception(e) token_err = respond(False, True, message="Invalid Token or User") return token_err, 403 return inner # swagger done @app.route("/api/change-password", methods=["POST"]) @swag_from("swagger/change-password.yml") def change_password(): if request.method == "POST": pass_data = request.get_json() if pass_data: if ( "email" not in pass_data and "old_password" not in pass_data and "verify_password" not in pass_data ): return ( jsonify( { "success": False, "error": True, "message": "Mandatory values in request unavailable", } ), 400, ) else: try: ref_user = User.objects.get(email=pass_data["email"]) except DoesNotExist: return ( jsonify( { "success": False, "error": True, "message": "No user found", } ), 403, ) verify_pass = bcrypt.checkpw( pass_data["old_password"].encode(), str(ref_user.password).encode() ) if verify_pass and ( pass_data["new_password"] == pass_data["verify_password"] ): hash_pass = bcrypt.hashpw( pass_data.get("new_password").encode(), bcrypt.gensalt() ).decode() ref_user.update(password=hash_pass, default_password=False) logger.info( "Changed password for user {}".format(pass_data["email"]) ) return jsonify( { "success": True, "error": False, "message": "Successfully changed password for user {}".format( pass_data["email"] ), } ) else: logger.error( "Change password exception. User passwords dont match OR old password is wrong for user {}".format( pass_data["email"] ) ) return ( jsonify( { "success": False, "error": True, "message": "Unable to change password for user {}".format( pass_data["email"] ), } ), 403, ) else: invalid_data = respond( False, True, message="Unable to decode request payload" ) return jsonify(invalid_data), 400 # swagger done @app.route("/api/login", methods=["POST"]) def login(): if request.method == "POST": login_data = request.get_json() if "email" not in login_data and "password" not in login_data: input_error = respond(False, True, message="Input Validation Error") return input_error, 400 else: try: ref_user = User.objects.get(email=login_data["email"]) except DoesNotExist: user_not_exists = respond(False, True, message="Invalid credentials") return user_not_exists, 403 verify_pass = bcrypt.checkpw( login_data["password"].encode(), str(ref_user.password).encode() ) if verify_pass: logger.info("User '{}' successfully logged in".format(ref_user.email)) token = jwt.encode( {"email": ref_user.email}, key=JWT_PASSWORD, algorithm="HS256" ).decode() success_message = respond( True, False, message="Logged in successfully", data={"token": token} ) return success_message else: invalid_credentials = respond( False, True, message="Invalid credentials" ) return invalid_credentials, 403 # swagger done @app.route("/api/project/create", methods=["POST"]) @validate_user def create_project(): data = request.get_json() if "name" not in data and not data.get("name"): logger.error("Input Validation Error - no 'name' param in request") inval_err = respond(False, True, "Mandatory param not in request") return inval_err, 400 else: try: Project(name=data.get("name")).save() success = respond( True, False, message="successfully saved project", data={"name": data.get("name")}, ) logger.info("Successfully created project {}".format(data.get("name"))) return success except Exception as e: logger.exception(e) exc = respond(False, True, "unable to save Project to DB") return exc, 400 # swagger done @app.route("/api/feature/create", methods=["POST"]) @validate_user @swag_from("swagger/feature-create.yml") def create_user_story(): data = request.get_json() if not set(("short_name", "description", "project")) <= set(data): logger.error( "Mandatory params 'short_name', 'description', 'project' not in request" ) input_val_err = respond( False, True, message="Mandatory params 'short_name', 'description', 'project' not in request", ) return input_val_err, 400 else: try: my_proj = Project.objects.get(name=data.get("project")) except DoesNotExist: project_not_exists = respond( False, True, message="Project '{}' does not exist".format(data.get("project")), ) return project_not_exists, 404 short_name = data.get("short_name") desc = data.get("description") try: ref_user_case = UseCase.objects(short_name=short_name).update_one( short_name=short_name, description=desc, project=my_proj, upsert=True, ) ref_feature = UseCase.objects.get(short_name=short_name) if ref_feature not in my_proj.features: my_proj.features.append(ref_feature) my_proj.save() logger.info( "Successfully created user-story/feature '{}'".format(short_name) ) return respond( True, False, message="Successfully created Feature '{}'".format(short_name), data={"short_name": short_name}, ) except Exception as e: logger.exception(e) return respond(False, True, message="Unable to create User Story"), 400 # swagger done @app.route("/api/abuse-case/create", methods=["POST"]) @validate_user @swag_from("swagger/abuse-create.yml") def create_abuser_story(): data = request.get_json() if not set(("short_name", "description", "feature")) <= set(data): logger.error( "Mandatory params 'short_name', 'description', 'feature' not in request" ) input_val_err = respond( False, True, message="Mandatory params 'short_name', 'description', 'feature' not in request", ) return input_val_err, 400 else: try: ref_user_story = UseCase.objects.get(short_name=data.get("feature")) except DoesNotExist: project_not_exists = respond( False, True, message="Feature '{}' does not exist".format(data.get("feature")), ) return project_not_exists, 404 short_name = data.get("short_name") desc = data.get("description") try: ref_user_case = AbuseCase.objects(short_name=short_name).update_one( short_name=short_name, description=desc, use_case=ref_user_story, upsert=True, ) ref_abuse = AbuseCase.objects.get(short_name=short_name) if ref_abuse not in ref_user_story.abuses: ref_user_story.abuses.append(ref_abuse) ref_user_story.save() logger.info("Successfully created abuser-story '{}'".format(short_name)) return respond( True, False, message="Successfully created Abuser Story '{}'".format(short_name), data={"short_name": short_name}, ) except Exception as e: logger.exception(e) return respond(False, True, message="Unable to create Abuser Story"), 400 # swagger done @app.route("/api/scenario/repo/create", methods=["POST"]) @validate_user @swag_from("swagger/scenario-repo.yml") def create_repo_scenario(): data = request.get_json() try: ref_user_story = UseCase.objects.get(short_name=data.get("feature")) except DoesNotExist: return ( respond(False, True, message="Unable to find reference User Story"), 400, ) try: ref_abuser_story = AbuseCase.objects.get(short_name=data.get("abuser_story")) except DoesNotExist: return ( respond(False, True, message="Unable to find reference Abuser Story"), 400, ) tm_name = data.get("name") description = data.get("description") if not data.get("type") == "repo" and data.get("repo_name"): return respond(False, True, message="Input Validation Error"), 400 else: repo_name = data.get("repo_name") severity = data.get("severity", 1) try: ref_repo = Repo.objects.get(short_name=repo_name) except Exception: return respond(False, True, message="repo not found"), 404 try: ThreatModel.objects(name=tm_name).update_one( name=tm_name, cwe=ref_repo.cwe, vul_name=ref_repo.name, description=description, use_case=ref_user_story, abuse_case=ref_abuser_story, mitigations=ref_repo.mitigations, categories=ref_repo.categories, severity=severity, upsert=True, ) ref_scenario = ThreatModel.objects.get(name=tm_name) if ref_scenario not in ref_abuser_story.scenarios: ref_abuser_story.scenarios.append(ref_scenario) ref_abuser_story.save() except Exception as e: logger.exception(e) return ( respond( False, True, message="Unable to store Threat Scenario: {}".format(tm_name), ), 500, ) if ref_repo.tests: for single_test in ref_repo.tests: try: Test.objects(name=single_test.name).update_one( name=single_test.name, test_case=single_test.test_case, executed=False, scenario=ref_scenario, tools=single_test.tools, upsert=True, ) ref_my_test = Test.objects.get( name=single_test.name, scenario=ref_scenario ) if ref_my_test not in ref_scenario.tests: ref_scenario.tests.append(ref_my_test) ref_scenario.save() except Exception as e: logger.exception(e) pass return respond( True, False, message="Successfully created Threat Scenario", data={"name": tm_name}, ) # swagger done @app.route("/api/scenario/create", methods=["POST"]) @validate_user @swag_from("swagger/scenario-inline.yml") def create_threat_scenario(): data = request.get_json() mandatory_params = ( "vul_name", "name", "description", "feature", "abuser_story", "type", ) if not set(mandatory_params) <= set(data): return ( respond( False, True, message="Input validation error", data={"mandatory_params": list(mandatory_params)}, ), 400, ) else: try: ref_user_story = UseCase.objects.get(short_name=data.get("feature")) except DoesNotExist: return ( respond(False, True, message="Unable to find reference User Story"), 400, ) try: ref_abuser_story = AbuseCase.objects.get( short_name=data.get("abuser_story") ) except DoesNotExist: return ( respond(False, True, message="Unable to find reference Abuser Story"), 400, ) try: tm_name = data.get("name") description = data.get("description") cwe_val = data.get("cwe", 0) mitigations = data.get("mitigations", []) severity = int(data.get("severity", 1)) vul_name = data.get("vul_name") ThreatModel.objects(name=tm_name).update_one( name=tm_name, vul_name=vul_name, cwe=cwe_val, severity=severity, mitigations=mitigations, description=description, use_case=ref_user_story, abuse_case=ref_abuser_story, upsert=True, ) ref_threat_model = ThreatModel.objects.get(name=tm_name) # if "categories" in data: # for single_category in data.categories: # if single_category not in ref_threat_model.categories: # ref_threat_model.categories.append(single_category) # ref_threat_model.save() if "mitigations" in data: ThreatModel.objects(name=tm_name).update_one( mitigations=data.get("mitigations"), upsert=True ) if ref_threat_model not in ref_abuser_story.scenarios: ref_abuser_story.scenarios.append(ref_threat_model) ref_abuser_story.save() logger.info("Created Threat Scenario '{}'".format(tm_name)) return respond( True, False, message="Successfully created Threat Scenario", data={"name": tm_name}, ) except Exception as e: logger.exception(e) return respond(False, True, message="Unable to load Threat Scenario"), 400 # swagger done @app.route("/api/test/create", methods=["POST"]) @validate_user @swag_from("swagger/test-case-create.yml") def create_test_case(): data = request.get_json() if not set(("test_case", "name", "threat_scenario")) <= set(data): logger.error( "Mandatory params 'test_case', 'name', 'threat_scenario' not in request" ) input_val_err = respond( False, True, message="Mandatory params 'test_case', 'name', 'threat_scenario' not in request", ) return input_val_err, 400 else: try: ref_scenario = ThreatModel.objects.get(name=data.get("threat_scenario")) except DoesNotExist: project_not_exists = respond( False, True, message="Threat Scenario '{}' does not exist".format( data.get("threat_scenario") ), ) return project_not_exists, 404 test_name = data.get("name") test_case = data.get("test_case") tool_list = data.get("tools", []) tag_list = data.get("tags", []) executed = data.get("executed", False) test_type = data.get("test_type", "discovery") try: Test.objects(name=test_name).update_one( name=test_name, test_case=test_case, executed=executed, test_type=test_type, scenario=ref_scenario, upsert=True, ) if tool_list: Test.objects(name=test_name, scenario=ref_scenario).update_one( tools=tool_list ) if tag_list: Test.objects(name=test_name, scenario=ref_scenario).update_one( tags=tag_list ) ref_test = Test.objects.get(name=test_name, scenario=ref_scenario) if ref_test not in ref_scenario.tests: ref_scenario.tests.append(ref_test) ref_scenario.save() logger.info( "Created Test-Case '{}' for Threat Scenario '{}'".format( test_name, ref_scenario.name ) ) return respond( True, False, message="Created Test-Case '{}' for Threat Scenario '{}'".format( test_name, ref_scenario.name ), data={"name": test_name}, ) except Exception as e: logger.exception(e) return respond(False, True, message="Unable to create Test Case"), 400 # swagger done @app.route("/api/target/create", methods=["POST"]) @validate_user @swag_from("swagger/target-create-update.yml") def create_target(): data = request.get_json() if not set(("name", "url", "project")) <= set(data): logger.error("Mandatory params 'name', 'url', 'project' not in request") input_val_err = respond( False, True, message="Mandatory params 'name', 'url', 'project' not in request", ) return input_val_err, 400 else: try: ref_project = Project.objects.get(name=data.get("project")) except Exception: return respond(False, True, message="Project not found"), 404 try: new_target = Target( name=data.get("name"), url=data.get("url"), project=ref_project ) new_target.save() return respond( True, False, message="successfully created target", data={"name": data.get("name")}, ) except Exception: return respond(False, True, message="Unable to create Target") @app.route("/api/scan/create", methods=["POST"]) @validate_user @swag_from("swagger/scan-create.yml") def create_scan(): data = request.get_json() if not set(("tool", "target")) <= set(data): logger.error("Mandatory params 'tool', 'target' not in request") input_val_err = respond( False, True, message="Mandatory params 'tool', 'target' not in request", ) return input_val_err, 400 else: try: ref_target = Target.objects.get(name=data.get("target")) ref_project = Project.objects.get(id=ref_target.project.id) except Exception: return respond(False, True, message="Target not found"), 404 try: new_scan = Scan(tool=data.get("tool"), target=ref_target) if "scan_type" in data: if data.get("scan_type") in ["SAST", "DAST", "SCA", "IAST", "Manual"]: new_scan.scan_type = data.get("scan_type") new_scan.save() if new_scan not in ref_target.scans: ref_target.scans.append(new_scan) ref_target.save() ref_features = UseCase.objects(project=ref_project) for single_feature in ref_features: ref_scenarios = ThreatModel.objects(use_case=single_feature) for single_scenario in ref_scenarios: for single_test in single_scenario.tests: ref_test = Test.objects.get(id=single_test.id) if data.get("tool") in ref_test.tools: ref_test.executed = True ref_test.save() return respond( True, False, message="successfully created scan", data={"name": new_scan.name}, ) except Exception as ex: logger.error(ex) return respond(False, True, message="Unable to create Scan") @app.route("/api/vulnerability/create", methods=["POST"]) @validate_user @swag_from("swagger/vulnerability-create.yml") def create_vulnerability(): data = request.get_json() if "name" not in data and "scan" not in data: return ( respond( False, True, message="Mandatory field 'name' and 'scan' not in request" ), 400, ) else: scan = data.get("scan") try: ref_scan = Scan.objects.get(name=scan) except Exception: return respond(False, True, message="Unable to find scan"), 404 try: ref_target = Target.objects.get(id=ref_scan.target.id) ref_project = Project.objects.get(id=ref_target.project.id) except Exception: return respond(False, True, message="Unable to find target"), 404 name = data.get("name") severity = data.get("severity", 1) cwe = data.get("cwe", 0) new_vul = Vulnerability(name=name, severity=severity, cwe=cwe) new_vul.scan = ref_scan new_vul.target = ref_target if "description" in data: new_vul.description = data.get("description") if "observation" in data: new_vul.description = data.get("observation") if "vul_name" in data: new_vul.description = data.get("vul_name") if "remediation" in data: new_vul.description = data.get("remediation") try: new_vul.save() if ( "evidences" in data and isinstance(data.get("evidences"), list) and data.get("evidences") ): all_evidences = data.get("evidences") for single in all_evidences: new_evid = VulnerabilityEvidence() new_evid.evidence_type = ref_scan.scan_type if "log" in single: new_evid.log = single.get("log") if "url" in single: new_evid.url = single.get("url") if "param" in single: new_evid.param = single.get("param") if "line_num" in single: new_evid.line_num = single.get("line_num") if "attack" in single: new_evid.attack = single.get("attack") if "info" in single: new_evid.info = single.get("info") new_evid.vuln = new_vul try: new_evid.save() if new_evid not in new_vul.evidences: new_vul.evidences.append(new_evid) new_vul.save() except Exception as ev_e: logger.error(ev_e) return ( respond(False, True, message="Unable to save evidence"), 500, ) return respond( True, False, message="Vulnerability successfully created", data={"name": name}, ) except Exception as vul_ex: logger.error(vul_ex) return ( respond( False, True, "Unable to save vulnerability with name '{}'".format(name), ), 500, ) @app.route("/api/project/read", methods=["GET", "POST"]) @app.route("/api/project/read/", methods=["GET", "POST"]) @validate_user @swag_from("swagger/get-project.yml") def get_project(page_num=1): if request.method == "GET": num_pages = (Project.objects.count() % items_per_page) + 1 if num_pages > 1 and page_num: if page_num == 1: project_list = json.loads( Project.objects.limit(items_per_page).to_json() ) return respond( True, False, message="Successfully retrieved data", data=project_list, ) else: offset = (page_num - 1) * items_per_page project_list = json.loads( Project.objects.skip(offset).limit(items_per_page).to_json() ) return respond( True, False, message="Successfully retrieved data", data=project_list, ) else: project_list = json.loads(Project.objects().to_json()) return respond(True, False, data=project_list) if request.method == "POST": data = request.get_json() if "name" in data: try: ref_project = json.loads( Project.objects.get(name=data.get("name")).to_json() ) return respond(True, False, data=ref_project) except Exception as e: logger.exception(e) return respond(False, True, message="Unable to find the project"), 404 @app.route("/api/feature/read", methods=["GET", "POST"]) @validate_user @swag_from("swagger/get-feature.yml") def get_features(): if request.method == "GET": user_story_list = json.loads(UseCase.objects().to_json()) return respond(True, False, data=user_story_list) elif request.method == "POST": data = request.get_json() if "project" in data: try: ref_project = Project.objects.get(name=data.get("project")) except Exception: return respond(False, True, message="Project does not exist"), 404 if "short_name" in data: try: ref_feature = json.loads( UseCase.objects.get( short_name=data.get("short_name"), project=ref_project ).to_json() ) return respond(True, False, data=ref_feature) except Exception as e: logger.exception(e) return ( respond( False, True, message="Unable to fetch the referenced user story", ), 404, ) else: if "page" in data: page_num = data.get("page") num_pages = (UseCase.objects.count() % items_per_page) + 1 if num_pages > 1 and page_num: if page_num == 1: feature_list = json.loads( UseCase.objects(project=ref_project) .limit(items_per_page) .to_json() ) return respond( True, False, message="Successfully retrieved data", data=feature_list, ) else: offset = (page_num - 1) * items_per_page feature_list = json.loads( UseCase.objects(project=ref_project) .skip(offset) .limit(items_per_page) .to_json() ) return respond( True, False, message="Successfully retrieved data", data=feature_list, ) else: feature_list = json.loads( UseCase.objects(project=ref_project).to_json() ) return respond( True, False, message="Successfully retrieved data", data=feature_list, ) else: return respond(False, True, message="Unable to find User Stories/Features"), 404 @app.route("/api/abuses/read", methods=["POST"]) @validate_user @swag_from("swagger/get-abuse.yml") def get_abuser_story(): data = request.get_json() if "user_story" in data: try: ref_use_case = UseCase.objects.get(short_name=data.get("user_story")) except Exception: return respond(False, True, message="User Story does not exist"), 404 if "short_name" in data: try: ref_abuse = json.loads( AbuseCase.objects.get( short_name=data.get("short_name"), use_case=ref_use_case ).to_json() ) return respond(True, False, data=ref_abuse) except Exception as e: logger.exception(e) return ( respond( False, True, message="Unable to fetch the referenced abuser story", ), 404, ) else: if "page" in data: page_num = data.get("page") num_pages = (AbuseCase.objects.count() % items_per_page) + 1 if num_pages > 1 and page_num: if page_num == 1: feature_list = json.loads( AbuseCase.objects(use_case=ref_use_case) .limit(items_per_page) .to_json() ) return respond( True, False, message="Successfully retrieved data", data=feature_list, ) else: offset = (page_num - 1) * items_per_page feature_list = json.loads( AbuseCase.objects(use_case=ref_use_case) .skip(offset) .limit(items_per_page) .to_json() ) return respond( True, False, message="Successfully retrieved data", data=feature_list, ) else: feature_list = json.loads( AbuseCase.objects(use_case=ref_use_case).to_json() ) return respond( True, False, message="Successfully retrieved data", data=feature_list, ) return ( respond( False, True, message="Unable to find Abuser Stories. You need to provide a reference feature/user story", ), 404, ) @app.route("/api/scenarios/read", methods=["GET", "POST"]) @validate_user @swag_from("swagger/get-scenario.yml") def get_threat_scenario(): if request.method == "GET": threat_scenario_list = json.loads(ThreatModel.objects().to_json()) return respond(True, False, data=threat_scenario_list) elif request.method == "POST": data = request.get_json() if "abuser_story" in data: try: ref_abuse = AbuseCase.objects.get(short_name=data.get("abuser_story")) except Exception: return respond(False, True, message="Abuser Story does not exist"), 404 if "name" in data: try: ref_scenario = json.loads( ThreatModel.objects.get( name=data.get("name"), abuse_case=ref_abuse ).to_json() ) return respond(True, False, data=ref_scenario) except Exception as e: logger.exception(e) return ( respond( False, True, message="Unable to fetch the referenced threat scenario", ), 404, ) else: if "page" in data: page_num = data.get("page") num_pages = (ThreatModel.objects.count() % items_per_page) + 1 if num_pages > 1 and page_num: if page_num == 1: feature_list = json.loads( ThreatModel.objects(abuse_case=ref_abuse) .limit(items_per_page) .to_json() ) return respond( True, False, message="Successfully retrieved data", data=feature_list, ) else: offset = (page_num - 1) * items_per_page feature_list = json.loads( ThreatModel.objects(abuse_case=ref_abuse) .skip(offset) .limit(items_per_page) .to_json() ) return respond( True, False, message="Successfully retrieved data", data=feature_list, ) else: feature_list = json.loads( ThreatModel.objects(abuse_case=ref_abuse).to_json() ) return respond( True, False, message="Successfully retrieved data", data=feature_list, ) else: return respond(False, True, message="Unable to find Threat Scenarios"), 404 @app.route("/api/test/read", methods=["POST"]) @validate_user @swag_from("swagger/get-tests.yml") def get_test_case(): data = request.get_json() if "scenario" in data: try: ref_scenario = ThreatModel.objects.get(name=data.get("scenario")) except Exception: return respond(False, True, message="Abuser Story does not exist"), 404 if "name" in data: try: ref_test = json.loads( Test.objects.get( name=data.get("name"), scenario=ref_scenario ).to_json() ) return respond(True, False, data=ref_test) except Exception as e: logger.exception(e) return ( respond( False, True, message="Unable to fetch the referenced test-case", ), 404, ) else: if "page" in data: page_num = data.get("page") num_pages = (Test.objects.count() % items_per_page) + 1 if num_pages > 1 and page_num: if page_num == 1: feature_list = json.loads( Test.objects(abuse_case=ref_scenario) .limit(items_per_page) .to_json() ) return respond( True, False, message="Successfully retrieved data", data=feature_list, ) else: offset = (page_num - 1) * items_per_page feature_list = json.loads( Test.objects(abuse_case=ref_scenario) .skip(offset) .limit(items_per_page) .to_json() ) return respond( True, False, message="Successfully retrieved data", data=feature_list, ) else: feature_list = json.loads(Test.objects(scenario=ref_scenario).to_json()) return respond( True, False, message="Successfully retrieved data", data=feature_list, ) return respond(False, True, message="Unable to find Threat Scenarios"), 404 @app.route("/api/scenario/vuln/", methods=["POST"]) @validate_user def map_threat_scenario_vul(): data = request.get_json() if "id" not in data: return respond(False, True, message="Mandatory param 'id' not in request"), 400 else: try: ref_scenario = ThreatModel.objects.get(id=data.get("id")) except Exception: return respond(False, True, message="Unable to find Threat Scenario") if ref_scenario.cwe: ref_abuse = AbuseCase.objects.get(id=ref_scenario.abuse.id) ref_use_case = UseCase.objects.get(id=ref_abuse.use_case.id) ref_project = Project.objects.get(id=ref_use_case.project.id) ref_targets = Target.objects(project=ref_project) for single_target in ref_targets: ref_vulns = Vulnerability.objects(target=single_target) if ref_vulns: return respond( True, False, message="successfully returned mapped objects", data={ "threat_scenario": json.loads(ref_scenario.to_json()), "vulnerabilities": json.loads(ref_vulns.to_json()), }, ) @app.route("/api/scenario/severity", methods=["GET"]) @validate_user def threat_scenario_severity(): if request.method == "GET": try: scenario_severity_list = json.loads( ThreatModel.objects().values_list("severity").to_json() ) return respond( True, False, message="Successfully retrieved data", data=scenario_severity_list, ) except Exception as e: logger.exception(e) return respond(False, True, message="Therat Scenario does not exist"), 404 else: return ( respond(False, True, message="Unable to find Threat Scenarios severity"), 404, ) @app.route("/api/vulnerability/severity", methods=["GET"]) @validate_user def vulnerability_severity(): if request.method == "GET": try: scenario_severity_list = json.loads( Vulnerability.objects().values_list("severity").to_json() ) return respond( True, False, message="Successfully retrieved data", data=scenario_severity_list, ) except Exception as e: logger.exception(e) return respond(False, True, message="Therat Scenario does not exist"), 404 else: return ( respond(False, True, message="Unable to find Threat Scenarios severity"), 404, ) ### Select APIs that we need # Get Vulnerabilities by Target @app.route("/api/target/read", methods=["GET", "POST"]) @validate_user def get_target(page_num=1): if request.method == "GET": num_pages = (Target.objects.count() % items_per_page) + 1 if num_pages > 1 and page_num: if page_num == 1: target_list = json.loads(Target.objects.limit(items_per_page).to_json()) return respond( True, False, message="Successfully retrieved data", data=target_list, ) else: offset = (page_num - 1) * items_per_page target_list = json.loads( Target.objects.skip(offset).limit(items_per_page).to_json() ) return respond( True, False, message="Successfully retrieved data", data=target_list, ) else: target_list = json.loads(Scan.objects().to_json()) return respond(True, False, data=scan_list) if request.method == "POST": data = request.get_json() if "project" in data: ref_project = Project.objects.get(name = data.get('project')) targets_for_project = json.loads( Target.objects(project=ref_project).to_json() ) return respond(True, False, data = targets_for_project) if "name" in data: specific_target = json.loads(Target.objects.get(name = data.get('name')).to_json()) return respond(True, False, data = specific_target) @app.route("/api/scan/read", methods=["GET", "POST"]) @validate_user def get_scan(page_num=1): if request.method == "GET": num_pages = (Scan.objects.count() % items_per_page) + 1 if num_pages > 1 and page_num: if page_num == 1: scan_list = json.loads(Scan.objects.limit(items_per_page).to_json()) return respond( True, False, message="Successfully retrieved data", data=scan_list, ) else: offset = (page_num - 1) * items_per_page scan_list = json.loads( Scan.objects.skip(offset).limit(items_per_page).to_json() ) return respond( True, False, message="Successfully retrieved data", data=scan_list, ) else: scan_list = json.loads(Scan.objects().to_json()) return respond(True, False, data=scan_list) if request.method == "POST": data = request.get_json() if "name" in data: try: ref_scan = json.loads(Scan.objects.get(name=data.get("name")).to_json()) return respond(True, False, data=ref_scan) except Exception as e: logger.exception(e) return respond(False, True, message="Unable to find the scan"), 404 @app.route("/api/scenarios/project", methods=["POST"]) @validate_user def get_threat_scenario_by_project(): data = request.get_json() if "project" in data: try: ref_project = Project.objects.get(name=data.get("project")) except Exception: return respond(False, True, message="Project does not exist"), 404 user_story = UseCase.objects(project=ref_project).to_json() d = json.loads(user_story) try: user_stories_list = [a.get("_id").get("$oid") for a in d] ref_threatScenario = json.loads( ThreatModel.objects.filter(use_case__in=user_stories_list).to_json() ) return respond(True, False, data=ref_threatScenario) except Exception as e: return respond(False, True, message="Scenario does not exist"), 404 else: return respond(False, True, message="Project does not exist"), 404 return respond(False, True, message="Scenario does not exist"), 404 @app.route("/api/vulnerability/read", methods=["GET", "POST"]) @validate_user def get_vulnerability(page_num=1): if request.method == "GET": num_pages = (Vulnerability.objects.count() % items_per_page) + 1 if num_pages > 1 and page_num: if page_num == 1: vul_list = json.loads( Vulnerability.objects.limit(items_per_page).to_json() ) return respond( True, False, message="Successfully retrieved data", data=vul_list, ) else: offset = (page_num - 1) * items_per_page vul_list = json.loads( Vulnerability.objects.skip(offset).limit(items_per_page).to_json() ) return respond( True, False, message="Successfully retrieved data", data=vul_list, ) else: vul_list = json.loads(Vulnerability.objects().to_json()) return respond(True, False, data=vul_list) if request.method == "POST": data = request.get_json() if "name" in data: try: ref_scan = json.loads( Vulnerability.objects.get(name=data.get("name")).to_json() ) return respond(True, False, data=ref_scan) except Exception as e: logger.exception(e) return ( respond(False, True, message="Unable to find the vulnerability"), 404, ) @app.route("/api/vulnerability/project", methods=["POST"]) @validate_user def get_vulnerability_by_project(): data = request.get_json() if "project" in data: vul_dict = {} try: ref_project = Project.objects.get(name=data.get("project")) except Exception: return respond(False, True, message="Project does not exist"), 404 try: target_obj = Target.objects(project=ref_project) except Exception: return respond(False, True, message="Target does not exist"), 404 try: for single_target in target_obj: ref_vuls = json.loads(Vulnerability.objects(target=single_target).to_json()) vul_dict['data'] = ref_vuls return respond(True, False, data=vul_dict) except Exception as e: return respond(False, True, message="Vulnerability does not exist"), 404 else: return respond(False, True, message="Project does not exist"), 404 return respond(False, True, message="Vulnerability does not exist"), 404 @app.route("/api/scan/project", methods=["POST"]) @validate_user def get_scan_by_project(): data = request.get_json() if "project" in data: resp_dict = {} try: ref_project = Project.objects.get(name=data.get("project")) resp_dict['project'] = ref_project.name except Exception: return respond(False, True, message="Project does not exist"), 404 try: target_obj = Target.objects(project=ref_project) except Exception: return respond(False, True, message="Target does not exist"), 404 try: resp_dict['data'] = [] for single_target in target_obj: ref_scans = Scan.objects(target=single_target) for single_scan in ref_scans: data_dict = { "name": single_scan.name, "target": single_target.name, "tool": single_scan.tool } resp_dict['data'].append(data_dict) return respond(True, False, data=resp_dict) except Exception as e: return respond(False, True, message="Scans does not exist"), 404 else: return respond(False, True, message="Project does not exist"), 404 return respond(False, True, message="Scans does not exist"), 404 @app.route("/api/user-story/project", methods=["POST"]) @validate_user def get_user_story_tree_by_project(): data = request.get_json() user_story_tree = [] if "project" in data: try: ref_project = Project.objects.get(name=data.get("project")) except Exception: return respond(False, True, message="Project does not exist"), 404 try: usecases_obj = UseCase.objects(project=ref_project.id) except Exception: return respond(False, True, message="Target does not exist"), 404 for usecase in usecases_obj: userStory_dict = {} userStory_dict["name"] = usecase.short_name userStory_dict["description"] = usecase.description userStory_dict["children"] = [] userStory_dict["type"] = "us" userStory_dict["title"] = "User Story" for abuses in usecase.abuses: abuserStory_dict = {} abuserStory_dict["name"] = abuses.short_name abuserStory_dict["description"] = abuses.description abuserStory_dict["children"] = [] abuserStory_dict["type"] = "as" abuserStory_dict["title"] = "Abuser Story" userStory_dict["children"].append(abuserStory_dict) for scenario in abuses.scenarios: threat_scenario_dict = {} threat_scenario_dict["name"] = scenario.name threat_scenario_dict["description"] = scenario.description threat_scenario_dict["vul_name"] = scenario.vul_name threat_scenario_dict["severity"] = scenario.severity threat_scenario_dict["cwe"] = scenario.cwe threat_scenario_dict["children"] = [] threat_scenario_dict["type"] = "sce" threat_scenario_dict["title"] = "Threat Scenario" abuserStory_dict["children"].append(threat_scenario_dict) for test in scenario.tests: test_dict = {} test_dict["name"] = test.name test_dict["test_case"] = test.test_case test_dict["tools"] = test.tools test_dict["test_type"] = test.test_type test_dict["executed"] = test.executed test_dict["type"] = "tc" test_dict["title"] = "Test Case" threat_scenario_dict["children"].append(test_dict) user_story_tree.append(userStory_dict) try: ref_scans = json.loads(json.dumps(user_story_tree)) return respond(True, False, data=ref_scans) except Exception as e: return respond(False, True, message="UserStory does not exist"), 404 else: return respond(False, True, message="Project does not exist"), 404 return respond(False, True, message="UserStory does not exist"), 404 @app.route("/api/abuser-story/project", methods=["POST"]) @validate_user def get_abuser_story_tree_by_project(): data = request.get_json() abuser_story_tree = [] if "project" in data: try: ref_project = Project.objects.get(name=data.get("project")) except Exception: return respond(False, True, message="Project does not exist"), 404 try: usecases_obj = UseCase.objects(project=ref_project.id) except Exception: return respond(False, True, message="Target does not exist"), 404 for usecase in usecases_obj: for abuses in usecase.abuses: abuserStory_dict = {} abuserStory_dict["name"] = abuses.short_name abuserStory_dict["description"] = abuses.description abuserStory_dict["children"] = [] abuserStory_dict["type"] = "as" abuserStory_dict["title"] = "Abuser Story" # userStory_dict['children'].append(abuserStory_dict) for scenario in abuses.scenarios: threat_scenario_dict = {} threat_scenario_dict["name"] = scenario.name threat_scenario_dict["description"] = scenario.description threat_scenario_dict["vul_name"] = scenario.vul_name threat_scenario_dict["severity"] = scenario.severity threat_scenario_dict["cwe"] = scenario.cwe threat_scenario_dict["children"] = [] threat_scenario_dict["type"] = "sce" threat_scenario_dict["title"] = "Threat Scenario" abuserStory_dict["children"].append(threat_scenario_dict) for test in scenario.tests: test_dict = {} test_dict["name"] = test.name test_dict["test_case"] = test.test_case test_dict["executed"] = test.executed test_dict["tools"] = test.tools test_dict["test_type"] = test.test_type test_dict["type"] = "tc" test_dict["title"] = "Test Case" threat_scenario_dict["children"].append(test_dict) abuser_story_tree.append(abuserStory_dict) try: ref_scans = json.loads(json.dumps(abuser_story_tree)) return respond(True, False, data=ref_scans) except Exception as e: return respond(False, True, message="AbuserStory does not exist"), 404 else: return respond(False, True, message="Project does not exist"), 404 return respond(False, True, message="AbuserStory does not exist"), 404 @app.route("/api/threat-scenario/project", methods=["POST"]) @validate_user def get_threat_scenario_tree_by_project(): data = request.get_json() threat_scenario_tree = [] if "project" in data: try: ref_project = Project.objects.get(name=data.get("project")) except Exception: return respond(False, True, message="Project does not exist"), 404 try: usecases_obj = UseCase.objects(project=ref_project.id) except Exception: return respond(False, True, message="Target does not exist"), 404 for usecase in usecases_obj: for abuses in usecase.abuses: for scenario in abuses.scenarios: threat_scenario_dict = {} threat_scenario_dict["name"] = scenario.name threat_scenario_dict["description"] = scenario.description threat_scenario_dict["vul_name"] = scenario.vul_name threat_scenario_dict["severity"] = scenario.severity threat_scenario_dict["cwe"] = scenario.cwe threat_scenario_dict["children"] = [] threat_scenario_dict["type"] = "sce" threat_scenario_dict["title"] = "Threat Scenario" for test in scenario.tests: test_dict = {} test_dict["name"] = test.name test_dict["test_case"] = test.test_case test_dict["tools"] = test.tools test_dict["test_type"] = test.test_type test_dict["executed"] = test.executed test_dict["type"] = "tc" test_dict["title"] = "Test Case" threat_scenario_dict["children"].append(test_dict) threat_scenario_tree.append(threat_scenario_dict) try: ref_scans = json.loads(json.dumps(threat_scenario_tree)) return respond(True, False, data=ref_scans) except Exception as e: return respond(False, True, message="ThreatScenario does not exist"), 404 else: return respond(False, True, message="Project does not exist"), 404 return respond(False, True, message="ThreatScenario does not exist"), 404 @app.route("/api/threatmap/project", methods=["POST"]) @validate_user def get_threatmap_by_project(): data = request.get_json() threat_map = {} if "project" in data: try: ref_project = Project.objects.get(name=data.get("project")) threat_map["name"] = ref_project.name threat_map["children"] = [] threat_map["type"] = "Project" threat_map["id"] = 1 except Exception: return respond(False, True, message="Project does not exist"), 404 try: usecases_obj = UseCase.objects(project=ref_project.id) except Exception: return respond(False, True, message="Target does not exist"), 404 for usecase in usecases_obj: userStory_id = str(uuid.uuid4()) userStory_dict = {} userStory_dict["id"] = userStory_id userStory_dict["name"] = usecase.short_name userStory_dict["title"] = usecase.description userStory_dict["type"] = "Feature" userStory_dict["children"] = [] threat_map["children"].append(userStory_dict) for abuses in usecase.abuses: abuserStory_id = str(uuid.uuid4()) abuserStory_dict = {} abuserStory_dict["id"] = abuserStory_id abuserStory_dict["name"] = abuses.short_name abuserStory_dict["title"] = abuses.description abuserStory_dict["children"] = [] abuserStory_dict["type"] = "Abuses" userStory_dict["children"].append(abuserStory_dict) for scenario in abuses.scenarios: scenario_id = str(uuid.uuid4()) threat_scenario_dict = {} threat_scenario_dict["id"] = scenario_id threat_scenario_dict["name"] = scenario.name threat_scenario_dict["title"] = scenario.description threat_scenario_dict["vul_name"] = scenario.vul_name threat_scenario_dict["severity"] = scenario.severity threat_scenario_dict["cwe"] = scenario.cwe threat_scenario_dict["children"] = [] threat_scenario_dict["type"] = "Scenarios" abuserStory_dict["children"].append(threat_scenario_dict) for test in scenario.tests: test_id = str(uuid.uuid4()) test_dict = {} test_dict["id"] = test_id test_dict["name"] = test.name test_dict["title"] = test.test_case test_dict["tools"] = test.tools test_dict["test_type"] = test.test_type test_dict["executed"] = test.executed test_dict["type"] = "Test Cases" threat_scenario_dict["children"].append(test_dict) try: ref_threatmap = json.loads(json.dumps(threat_map)) return respond(True, False, data=ref_threatmap) except Exception as e: return respond(False, True, message="THreatMap does not exist"), 404 else: return respond(False, True, message="Project does not exist"), 404 return respond(False, True, message="THreatMap does not exist"), 404 @app.route("/api/scan-vuls/project", methods=["POST"]) @validate_user def get_individual_scan_vuls(): data = request.get_json() if "name" in data: try: ref_scans = Scan.objects.get(name=data.get("name")) ref_vuls = json.loads(Vulnerability.objects(scan=ref_scans.id).to_json()) return respond(True, False, data=ref_vuls) except Exception as e: return respond(False, True, message="Scans does not exist"), 404 else: return respond(False, True, message="Project does not exist"), 404 return respond(False, True, message="Scans does not exist"), 404 @app.route("/api/asvs", methods=["POST"]) @validate_user def get_asvs_vuls(): data = request.get_json() if "cwe" in data: try: ref_asvs = json.loads(ASVS.objects(cwe=data.get("cwe")).to_json()) return respond(True, False, data=ref_asvs) except Exception as e: return respond(False, True, message="ASVS does not exist"), 404 else: return respond(False, True, message="Project does not exist"), 404 return respond(False, True, message="ASVS does not exist"), 404 @app.route("/api/delete/feature", methods=["POST"]) @validate_user def delete_feature(): data = request.get_json() if "name" not in data and "project" not in data: return ( respond( False, True, message="Mandatory fields 'name' and 'project' not in request", ), 400, ) try: ref_project = Project.objects.get(name=data.get("project")) ref_use_case = UseCase.objects.get( short_name=data.get("name"), project=ref_project ) ref_use_case.delete() return respond( True, False, message="Successfully deleted Feature: {}".format(data.get("name")), ) except Exception as del_e: logger.error(del_e) return respond(False, True, message="Unable to delete Use-Case"), 500 @app.route("/api/delete/abuser-story", methods=["POST"]) @validate_user def delete_abuse_case(): data = request.get_json() if "name" not in data and "feature" not in data: return ( respond( False, True, message="Mandatory fields 'name' and 'feature' not in request", ), 400, ) try: ref_use_case = UseCase.objects.get(short_name=data.get("feature")) ref_abuse = AbuseCase.objects.get( short_name=data.get("name"), use_case=ref_use_case ) ref_abuse.delete() return respond( True, False, message="Successfully deleted Abuser Story: {}".format(data.get("name")), ) except Exception as del_e: logger.error(del_e) return respond(False, True, message="Unable to delete Abuser Story"), 500 @app.route("/api/delete/scenario", methods=["POST"]) @validate_user def delete_scenario(): data = request.get_json() if "name" not in data and "abuser_story" not in data: return ( respond( False, True, message="Mandatory fields 'name' and 'abuser_story' not in request", ), 400, ) try: ref_abuse_case = AbuseCase.objects.get(short_name=data.get("abuser_story")) ref_scenario = ThreatModel.objects.get( name=data.get("name"), abuse_case=ref_abuse_case ) ref_scenario.delete() return respond( True, False, message="Successfully deleted Threat Scenario: {}".format(data.get("name")), ) except Exception as del_e: logger.error(del_e) return respond(False, True, message="Unable to delete Threat Scenario"), 500 @app.route("/api/delete/test", methods=["POST"]) @validate_user def delete_test(): data = request.get_json() if "name" not in data and "scenario" not in data: return ( respond( False, True, message="Mandatory fields 'name' and 'scenario' not in request", ), 400, ) try: ref_scenario = ThreatModel.objects.get(name=data.get("scenario")) ref_test = Test.objects.get(name=data.get("name"), scenario=ref_scenario) ref_scenario.delete() return respond( True, False, message="Successfully deleted Test-Case: {}".format(data.get("name")), ) except Exception as del_e: logger.error(del_e) return respond(False, True, message="Unable to delete Test Case"), 500 @app.route("/api/delete/project", methods=["POST"]) @validate_user def delete_project(): data = request.get_json() if "name" not in data: return ( respond(False, True, message="Mandatory fields 'name' not in request"), 400, ) try: ref_project = Project.objects.get(name=data.get("name")) ref_project.delete() return respond( True, False, message="Successfully deleted Project {}".format(data.get("name")), ) except Exception as del_e: logger.error(del_e) return respond(False, True, message="Unable to delete Project"), 500 if __name__ == "__main__": app.run(host="0.0.0.0", debug=True) ================================================ FILE: api/tp_api/asvs/asvs.csv ================================================ V1,Architecture,1.1.1,Verify the use of a secure software development lifecycle that addresses security in all stages of development. ([C1](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),,X,X,, V1,Architecture,1.1.2,"Verify the use of threat modeling for every design change or sprint planning to identify threats, plan for countermeasures, facilitate appropriate risk responses, and guide security testing.",,X,X,1053, V1,Architecture,1.1.3,"Verify that all user stories and features contain functional security constraints, such as ""As a user, I should be able to view and edit my profile. I should not be able to view or edit anyone else's profile""",,X,X,1110, V1,Architecture,1.1.4,"Verify documentation and justification of all the application's trust boundaries, components, and significant data flows.",,X,X,1059, V1,Architecture,1.1.5,Verify definition and security analysis of the application's high-level architecture and all connected remote services. ([C1](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),,X,X,1059, V1,Architecture,1.1.6,"Verify implementation of centralized, simple (economy of design), vetted, secure, and reusable security controls to avoid duplicate, missing, ineffective, or insecure controls. ([C10](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",,X,X,637, V1,Architecture,1.1.7,"Verify availability of a secure coding checklist, security requirements, guideline, or policy to all developers and testers.",,X,X,637, V1,Architecture,1.10.1,"Verify that a source code control system is in use, with procedures to ensure that check-ins are accompanied by issues or change tickets. The source code control system should have access control and identifiable users to allow traceability of any changes.",,X,X,284, V1,Architecture,1.11.1,Verify the definition and documentation of all application components in terms of the business or security functions they provide.,,X,X,1059, V1,Architecture,1.11.2,"Verify that all high-value business logic flows, including authentication, session management and access control, do not share unsynchronized state.",,X,X,362, V1,Architecture,1.11.3,"Verify that all high-value business logic flows, including authentication, session management and access control are thread safe and resistant to time-of-check and time-of-use race conditions.",,,X,367, V1,Architecture,1.12.1,Verify that user-uploaded files are stored outside of the web root.,,X,X,552, V1,Architecture,1.12.2,"Verify that user-uploaded files - if required to be displayed or downloaded from the application - are served by either octet stream downloads, or from an unrelated domain, such as a cloud file storage bucket. Implement a suitable content security policy to reduce the risk from XSS vectors or other attacks from the uploaded file.",,X,X,646, V1,Architecture,1.14.1,"Verify the segregation of components of differing trust levels through well-defined security controls, firewall rules, API gateways, reverse proxies, cloud-based security groups, or similar mechanisms.",,X,X,923, V1,Architecture,1.14.2,"Verify that if deploying binaries to untrusted devices makes use of binary signatures, trusted connections, and verified endpoints.",,X,X,494, V1,Architecture,1.14.3,Verify that the build pipeline warns of out-of-date or insecure components and takes appropriate actions.,,X,X,1104, V1,Architecture,1.14.4,"Verify that the build pipeline contains a build step to automatically build and verify the secure deployment of the application, particularly if the application infrastructure is software defined, such as cloud environment build scripts.",,X,X,, V1,Architecture,1.14.5,"Verify that application deployments adequately sandbox, containerize and/or isolate at the network level to delay and deter attackers from attacking other applications, especially when they are performing sensitive or dangerous actions such as deserialization. ([C5](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",,X,X,265, V1,Architecture,1.14.6,"Verify the application does not use unsupported, insecure, or deprecated client-side technologies such as NSAPI plugins, Flash, Shockwave, ActiveX, Silverlight, NACL, or client-side Java applets.",,X,X,477, V1,Architecture,1.2.1,"Verify the use of unique or special low-privilege operating system accounts for all application components, services, and servers. ([C3](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",,X,X,250, V1,Architecture,1.2.2,"Verify that communications between application components, including APIs, middleware and data layers, are authenticated. Components should have the least necessary privileges needed. ([C3](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",,X,X,306, V1,Architecture,1.2.3,"Verify that the application uses a single vetted authentication mechanism that is known to be secure, can be extended to include strong authentication, and has sufficient logging and monitoring to detect account abuse or breaches.",,X,X,306, V1,Architecture,1.2.4,"Verify that all authentication pathways and identity management APIs implement consistent authentication security control strength, such that there are no weaker alternatives per the risk of the application.",,X,X,306, V1,Architecture,1.4.1,"Verify that trusted enforcement points such as at access control gateways, servers, and serverless functions enforce access controls. Never enforce access controls on the client.",,X,X,602, V1,Architecture,1.4.2,Verify that the chosen access control solution is flexible enough to meet the application's needs.,,X,X,284, V1,Architecture,1.4.3,"Verify enforcement of the principle of least privilege in functions, data files, URLs, controllers, services, and other resources. This implies protection against spoofing and elevation of privilege.",,X,X,272, V1,Architecture,1.4.4,Verify the application uses a single and well-vetted access control mechanism for accessing protected data and resources. All requests must pass through this single mechanism to avoid copy and paste or insecure alternative paths. ([C7](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),,X,X,284, V1,Architecture,1.4.5,Verify that attribute or feature-based access control is used whereby the code checks the user's authorization for a feature/data item rather than just their role. Permissions should still be allocated using roles. ([C7](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),,X,X,275, V1,Architecture,1.5.1,"Verify that input and output requirements clearly define how to handle and process data based on type, content, and applicable laws, regulations, and other policy compliance.",,X,X,1029, V1,Architecture,1.5.2,"Verify that serialization is not used when communicating with untrusted clients. If this is not possible, ensure that adequate integrity controls (and possibly encryption if sensitive data is sent) are enforced to prevent deserialization attacks including object injection.",,X,X,502, V1,Architecture,1.5.3,Verify that input validation is enforced on a trusted service layer. ([C5](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),,X,X,602, V1,Architecture,1.5.4,Verify that output encoding occurs close to or by the interpreter for which it is intended. ([C4](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),,X,X,116, V1,Architecture,1.6.1,Verify that there is an explicit policy for management of cryptographic keys and that a cryptographic key lifecycle follows a key management standard such as NIST SP 800-57.,,X,X,320, V1,Architecture,1.6.2,Verify that consumers of cryptographic services protect key material and other secrets by using key vaults or API based alternatives.,,X,X,320, V1,Architecture,1.6.3,Verify that all keys and passwords are replaceable and are part of a well-defined process to re-encrypt sensitive data.,,X,X,320, V1,Architecture,1.6.4,"Verify that symmetric keys, passwords, or API secrets generated by or shared with clients are used only in protecting low risk secrets, such as encrypting local storage, or temporary ephemeral uses such as parameter obfuscation. Sharing secrets with clients is clear-text equivalent and architecturally should be treated as such.",,X,X,320, V1,Architecture,1.7.1,Verify that a common logging format and approach is used across the system. ([C9](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),,X,X,1009, V1,Architecture,1.7.2,"Verify that logs are securely transmitted to a preferably remote system for analysis, detection, alerting, and escalation. ([C9](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",,X,X,, V1,Architecture,1.8.1,Verify that all sensitive data is identified and classified into protection levels.,,X,X,, V1,Architecture,1.8.2,"Verify that all protection levels have an associated set of protection requirements, such as encryption requirements, integrity requirements, retention, privacy and other confidentiality requirements, and that these are applied in the architecture.",,X,X,, V1,Architecture,1.9.1,"Verify the application encrypts communications between components, particularly when these components are in different containers, systems, sites, or cloud providers. ([C3](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",,X,X,319, V1,Architecture,1.9.2,"Verify that application components verify the authenticity of each side in a communication link to prevent person-in-the-middle attacks. For example, application components should validate TLS certificates and chains.",,X,X,295, V2,Authentication,2.1.1,Verify that user set passwords are at least 12 characters in length. ([C6](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),X,X,X,521,5.1.1.2 V2,Authentication,2.1.10,Verify that there are no periodic credential rotation or password history requirements.,X,X,X,263,5.1.1.2 V2,Authentication,2.1.11,"Verify that ""paste"" functionality, browser password helpers, and external password managers are permitted.",X,X,X,521,5.1.1.2 V2,Authentication,2.1.12,"Verify that the user can choose to either temporarily view the entire masked password, or temporarily view the last typed character of the password on platforms that do not have this as native functionality.",X,X,X,521,5.1.1.2 V2,Authentication,2.1.2,Verify that passwords 64 characters or longer are permitted. ([C6](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),X,X,X,521,5.1.1.2 V2,Authentication,2.1.3,Verify that passwords can contain spaces and truncation is not performed. Consecutive multiple spaces MAY optionally be coalesced. ([C6](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),X,X,X,521,5.1.1.2 V2,Authentication,2.1.4,"Verify that Unicode characters are permitted in passwords. A single Unicode code point is considered a character, so 12 emoji or 64 kanji characters should be valid and permitted.",X,X,X,521,5.1.1.2 V2,Authentication,2.1.5,Verify users can change their password.,X,X,X,620,5.1.1.2 V2,Authentication,2.1.6,Verify that password change functionality requires the user's current and new password.,X,X,X,620,5.1.1.2 V2,Authentication,2.1.7,"Verify that passwords submitted during account registration, login, and password change are checked against a set of breached passwords either locally (such as the top 1,000 or 10,000 most common passwords which match the system's password policy) or using an external API. If using an API a zero knowledge proof or other mechanism should be used to ensure that the plain text password is not sent or used in verifying the breach status of the password. If the password is breached, the application must require the user to set a new non-breached password. ([C6](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",X,X,X,521,5.1.1.2 V2,Authentication,2.1.8,Verify that a password strength meter is provided to help users set a stronger password.,X,X,X,521,5.1.1.2 V2,Authentication,2.1.9,Verify that there are no password composition rules limiting the type of characters permitted. There should be no requirement for upper or lower case or numbers or special characters. ([C6](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),X,X,X,521,5.1.1.2 V2,Authentication,2.10.1,"Verify that integration secrets do not rely on unchanging passwords, such as API keys or shared privileged accounts.",,OS assisted,HSM,287,5.1.1.1 V2,Authentication,2.10.2,"Verify that if passwords are required, the credentials are not a default account.",,OS assisted,HSM,255,5.1.1.1 V2,Authentication,2.10.3,"Verify that passwords are stored with sufficient protection to prevent offline recovery attacks, including local system access.",,OS assisted,HSM,522,5.1.1.1 V2,Authentication,2.10.4,"Verify passwords, integrations with databases and third-party systems, seeds and internal secrets, and API keys are managed securely and not included in the source code or stored within source code repositories. Such storage SHOULD resist offline attacks. The use of a secure software key store (L1), hardware trusted platform module (TPM), or a hardware security module (L3) is recommended for password storage.",,OS assisted,HSM,798, V2,Authentication,2.2.1,"Verify that anti-automation controls are effective at mitigating breached credential testing, brute force, and account lockout attacks. Such controls include blocking the most common breached passwords, soft lockouts, rate limiting, CAPTCHA, ever increasing delays between attempts, IP address restrictions, or risk-based restrictions such as location, first login on a device, recent attempts to unlock the account, or similar. Verify that no more than 100 failed attempts per hour is possible on a single account.",X,X,X,307,5.2.2 / 5.1.1.2 / 5.1.4.2 / 5.1.5.2 V2,Authentication,2.2.2,"Verify that the use of weak authenticators (such as SMS and email) is limited to secondary verification and transaction approval and not as a replacement for more secure authentication methods. Verify that stronger methods are offered before weak methods, users are aware of the risks, or that proper measures are in place to limit the risks of account compromise.",X,X,X,304,5.2.10 V2,Authentication,2.2.3,"Verify that secure notifications are sent to users after updates to authentication details, such as credential resets, email or address changes, logging in from unknown or risky locations. The use of push notifications - rather than SMS or email - is preferred, but in the absence of push notifications, SMS or email is acceptable as long as no sensitive information is disclosed in the notification.",X,X,X,620, V2,Authentication,2.2.4,"Verify impersonation resistance against phishing, such as the use of multi-factor authentication, cryptographic devices with intent (such as connected keys with a push to authenticate), or at higher AAL levels, client-side certificates.",,,X,308,5.2.5 V2,Authentication,2.2.5,"Verify that where a credential service provider (CSP) and the application verifying authentication are separated, mutually authenticated TLS is in place between the two endpoints.",,,X,319,5.2.6 V2,Authentication,2.2.6,"Verify replay resistance through the mandated use of OTP devices, cryptographic authenticators, or lookup codes.",,,X,308,5.2.8 V2,Authentication,2.2.7,Verify intent to authenticate by requiring the entry of an OTP token or user-initiated action such as a button press on a FIDO hardware key.,,,X,308,5.2.9 V2,Authentication,2.3.1,"Verify system generated initial passwords or activation codes SHOULD be securely randomly generated, SHOULD be at least 6 characters long, and MAY contain letters and numbers, and expire after a short period of time. These initial secrets must not be permitted to become the long term password.",X,X,X,330,5.1.1.2 / A.3 V2,Authentication,2.3.2,"Verify that enrollment and use of subscriber-provided authentication devices are supported, such as a U2F or FIDO tokens.",,X,X,308,6.1.3 V2,Authentication,2.3.3,Verify that renewal instructions are sent with sufficient time to renew time bound authenticators.,,X,X,287,6.1.4 V2,Authentication,2.4.1,"Verify that passwords are stored in a form that is resistant to offline attacks. Passwords SHALL be salted and hashed using an approved one-way key derivation or password hashing function. Key derivation and password hashing functions take a password, a salt, and a cost factor as inputs when generating a password hash. ([C6](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",,X,X,916,5.1.1.2 V2,Authentication,2.4.2,"Verify that the salt is at least 32 bits in length and be chosen arbitrarily to minimize salt value collisions among stored hashes. For each credential, a unique salt value and the resulting hash SHALL be stored. ([C6](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",,X,X,916,5.1.1.2 V2,Authentication,2.4.3,"Verify that if PBKDF2 is used, the iteration count SHOULD be as large as verification server performance will allow, typically at least 100,000 iterations. ([C6](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",,X,X,916,5.1.1.2 V2,Authentication,2.4.4,"Verify that if bcrypt is used, the work factor SHOULD be as large as verification server performance will allow, typically at least 13. ([C6](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",,X,X,916,5.1.1.2 V2,Authentication,2.4.5,"Verify that an additional iteration of a key derivation function is performed, using a salt value that is secret and known only to the verifier. Generate the salt value using an approved random bit generator [SP 800-90Ar1] and provide at least the minimum security strength specified in the latest revision of SP 800-131A. The secret salt value SHALL be stored separately from the hashed passwords (e.g., in a specialized device like a hardware security module).",,X,X,916,5.1.1.2 V2,Authentication,2.5.1,Verify that a system generated initial activation or recovery secret is not sent in clear text to the user. ([C6](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),X,X,X,640,5.1.1.2 V2,Authentication,2.5.2,"Verify password hints or knowledge-based authentication (so-called ""secret questions"") are not present.",X,X,X,640,5.1.1.2 V2,Authentication,2.5.3,Verify password credential recovery does not reveal the current password in any way. ([C6](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),X,X,X,640,5.1.1.2 V2,Authentication,2.5.4,"Verify shared or default accounts are not present (e.g. ""root"", ""admin"", or ""sa"").",X,X,X,16,5.1.1.2 / A.3 V2,Authentication,2.5.5,"Verify that if an authentication factor is changed or replaced, that the user is notified of this event.",X,X,X,304,6.1.2.3 V2,Authentication,2.5.6,"Verify forgotten password, and other recovery paths use a secure recovery mechanism, such as TOTP or other soft token, mobile push, or another offline recovery mechanism. ([C6](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",X,X,X,640,5.1.1.2 V2,Authentication,2.5.7,"Verify that if OTP or multi-factor authentication factors are lost, that evidence of identity proofing is performed at the same level as during enrollment.",,X,X,308,6.1.2.3 V2,Authentication,2.6.1,Verify that lookup secrets can be used only once.,,X,X,308,5.1.2.2 V2,Authentication,2.6.2,"Verify that lookup secrets have sufficient randomness (112 bits of entropy), or if less than 112 bits of entropy, salted with a unique and random 32-bit salt and hashed with an approved one-way hash.",,X,X,330,5.1.2.2 V2,Authentication,2.6.3,"Verify that lookup secrets are resistant to offline attacks, such as predictable values.",,X,X,310,5.1.2.2 V2,Authentication,2.7.1,"Verify that clear text out of band (NIST ""restricted"") authenticators, such as SMS or PSTN, are not offered by default, and stronger alternatives such as push notifications are offered first.",X,X,X,287,5.1.3.2 V2,Authentication,2.7.2,"Verify that the out of band verifier expires out of band authentication requests, codes, or tokens after 10 minutes.",X,X,X,287,5.1.3.2 V2,Authentication,2.7.3,"Verify that the out of band verifier authentication requests, codes, or tokens are only usable once, and only for the original authentication request.",X,X,X,287,5.1.3.2 V2,Authentication,2.7.4,Verify that the out of band authenticator and verifier communicates over a secure independent channel.,X,X,X,523,5.1.3.2 V2,Authentication,2.7.5,Verify that the out of band verifier retains only a hashed version of the authentication code.,,X,X,256,5.1.3.2 V2,Authentication,2.7.6,"Verify that the initial authentication code is generated by a secure random number generator, containing at least 20 bits of entropy (typically a six digital random number is sufficient).",,X,X,310,5.1.3.2 V2,Authentication,2.8.1,Verify that time-based OTPs have a defined lifetime before expiring.,X,X,X,613,5.1.4.2 / 5.1.5.2 V2,Authentication,2.8.2,"Verify that symmetric keys used to verify submitted OTPs are highly protected, such as by using a hardware security module or secure operating system based key storage.",,X,X,320,5.1.4.2 / 5.1.5.2 V2,Authentication,2.8.3,"Verify that approved cryptographic algorithms are used in the generation, seeding, and verification.",,X,X,326,5.1.4.2 / 5.1.5.2 V2,Authentication,2.8.4,Verify that time-based OTP can be used only once within the validity period.,,X,X,287,5.1.4.2 / 5.1.5.2 V2,Authentication,2.8.5,"Verify that if a time-based multi factor OTP token is re-used during the validity period, it is logged and rejected with secure notifications being sent to the holder of the device.",,X,X,287,5.1.5.2 V2,Authentication,2.8.6,"Verify physical single factor OTP generator can be revoked in case of theft or other loss. Ensure that revocation is immediately effective across logged in sessions, regardless of location.",,X,X,613,5.2.1 V2,Authentication,2.8.7,Verify that biometric authenticators are limited to use only as secondary factors in conjunction with either something you have and something you know.,,o,X,308,5.2.3 V2,Authentication,2.9.1,"Verify that cryptographic keys used in verification are stored securely and protected against disclosure, such as using a TPM or HSM, or an OS service that can use this secure storage.",,X,X,320,5.1.7.2 V2,Authentication,2.9.2,"Verify that the challenge nonce is at least 64 bits in length, and statistically unique or unique over the lifetime of the cryptographic device.",,X,X,330,5.1.7.2 V2,Authentication,2.9.3,"Verify that approved cryptographic algorithms are used in the generation, seeding, and verification.",,X,X,327,5.1.7.2 V3,Session,3.1.1,Verify the application never reveals session tokens in URL parameters or error messages.,X,X,X,598, V3,Session,3.2.1,Verify the application generates a new session token on user authentication. ([C6](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),X,X,X,384,7.1 V3,Session,3.2.2,Verify that session tokens possess at least 64 bits of entropy. ([C6](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),X,X,X,331,7.1 V3,Session,3.2.3,Verify the application only stores session tokens in the browser using secure methods such as appropriately secured cookies (see section 3.4) or HTML 5 session storage.,X,X,X,539,7.1 V3,Session,3.2.4,Verify that session token are generated using approved cryptographic algorithms. ([C6](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),,X,X,331,7.1 V3,Session,3.3.1,"Verify that logout and expiration invalidate the session token, such that the back button or a downstream relying party does not resume an authenticated session, including across relying parties. ([C6](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",X,X,X,613,7.1 V3,Session,3.3.2,"If authenticators permit users to remain logged in, verify that re-authentication occurs periodically both when actively used or after an idle period. ([C6](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",30 days,"12 hours or 30 minutes of inactivity, 2FA optional","12 hours or 15 minutes of inactivity, with 2FA",613,7.2 V3,Session,3.3.3,"Verify that the application terminates all other active sessions after a successful password change, and that this is effective across the application, federated login (if present), and any relying parties.",,X,X,613, V3,Session,3.3.4,Verify that users are able to view and log out of any or all currently active sessions and devices.,,X,X,613,7.1 V3,Session,3.4.1,Verify that cookie-based session tokens have the 'Secure' attribute set. ([C6](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),X,X,X,614,7.1.1 V3,Session,3.4.2,Verify that cookie-based session tokens have the 'HttpOnly' attribute set. ([C6](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),X,X,X,1004,7.1.1 V3,Session,3.4.3,Verify that cookie-based session tokens utilize the 'SameSite' attribute to limit exposure to cross-site request forgery attacks. ([C6](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),X,X,X,16,7.1.1 V3,Session,3.4.4,"Verify that cookie-based session tokens use ""__Host-"" prefix (see references) to provide session cookie confidentiality.",X,X,X,16,7.1.1 V3,Session,3.4.5,"Verify that if the application is published under a domain name with other applications that set or use session cookies that might override or disclose the session cookies, set the path attribute in cookie-based session tokens using the most precise path possible. ([C6](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",X,X,X,16,7.1.1 V3,Session,3.5.1,Verify the application does not treat OAuth and refresh tokens — on their own — as the presence of the subscriber and allows users to terminate trust relationships with linked applications.,,X,X,290,7.1.2 V3,Session,3.5.2,"Verify the application uses session tokens rather than static API secrets and keys, except with legacy implementations.",,X,X,798, V3,Session,3.5.3,"Verify that stateless session tokens use digital signatures, encryption, and other countermeasures to protect against tampering, enveloping, replay, null cipher, and key substitution attacks.",,X,X,345, V3,Session,3.6.1,Verify that relying parties specify the maximum authentication time to CSPs and that CSPs re-authenticate the subscriber if they haven't used a session within that period.,,,X,613,7.2.1 V3,Session,3.6.2,"Verify that CSPs inform relying parties of the last authentication event, to allow RPs to determine if they need to re-authenticate the user.",,,X,613,7.2.1 V3,Session,3.7.1,Verify the application ensures a valid login session or requires re-authentication or secondary verification before allowing any sensitive transactions or account modifications.,X,X,X,778, V4,Access,4.1.1,"Verify that the application enforces access control rules on a trusted service layer, especially if client-side access control is present and could be bypassed.",X,X,X,602, V4,Access,4.1.2,Verify that all user and data attributes and policy information used by access controls cannot be manipulated by end users unless specifically authorized.,X,X,X,639, V4,Access,4.1.3,"Verify that the principle of least privilege exists - users should only be able to access functions, data files, URLs, controllers, services, and other resources, for which they possess specific authorization. This implies protection against spoofing and elevation of privilege. ([C7](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",X,X,X,285, V4,Access,4.1.4,Verify that the principle of deny by default exists whereby new users/roles start with minimal or no permissions and users/roles do not receive access to new features until access is explicitly assigned. ([C7](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),X,X,X,276, V4,Access,4.1.5,Verify that access controls fail securely including when an exception occurs. ([C10](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),X,X,X,285, V4,Access,4.2.1,"Verify that sensitive data and APIs are protected against direct object attacks targeting creation, reading, updating and deletion of records, such as creating or updating someone else's record, viewing everyone's records, or deleting all records.",X,X,X,639, V4,Access,4.2.2,"Verify that the application or framework enforces a strong anti-CSRF mechanism to protect authenticated functionality, and effective anti-automation or anti-CSRF protects unauthenticated functionality.",X,X,X,352, V4,Access,4.3.1,Verify administrative interfaces use appropriate multi-factor authentication to prevent unauthorized use.,X,X,X,419, V4,Access,4.3.2,"Verify that directory browsing is disabled unless deliberately desired. Additionally, applications should not allow discovery or disclosure of file or directory metadata, such as Thumbs.db, .DS_Store, .git or .svn folders.",X,X,X,548, V4,Access,4.3.3,"Verify the application has additional authorization (such as step up or adaptive authentication) for lower value systems, and / or segregation of duties for high value applications to enforce anti-fraud controls as per the risk of application and past fraud.",,X,X,732, V5,Validation,5.1.1,"Verify that the application has defenses against HTTP parameter pollution attacks, particularly if the application framework makes no distinction about the source of request parameters (GET, POST, cookies, headers, or environment variables).",X,X,X,235, V5,Validation,5.1.2,"Verify that frameworks protect against mass parameter assignment attacks, or that the application has countermeasures to protect against unsafe parameter assignment, such as marking fields private or similar. ([C5](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",X,X,X,915, V5,Validation,5.1.3,"Verify that all input (HTML form fields, REST requests, URL parameters, HTTP headers, cookies, batch files, RSS feeds, etc) is validated using positive validation (whitelisting). ([C5](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",X,X,X,20, V5,Validation,5.1.4,"Verify that structured data is strongly typed and validated against a defined schema including allowed characters, length and pattern (e.g. credit card numbers or telephone, or validating that two related fields are reasonable, such as checking that suburb and zip/postcode match). ([C5](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",X,X,X,20, V5,Validation,5.1.5,"Verify that URL redirects and forwards only allow whitelisted destinations, or show a warning when redirecting to potentially untrusted content.",X,X,X,601, V5,Validation,5.2.1,Verify that all untrusted HTML input from WYSIWYG editors or similar is properly sanitized with an HTML sanitizer library or framework feature. ([C5](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),X,X,X,116, V5,Validation,5.2.2,Verify that unstructured data is sanitized to enforce safety measures such as allowed characters and length.,X,X,X,138, V5,Validation,5.2.3,Verify that the application sanitizes user input before passing to mail systems to protect against SMTP or IMAP injection.,X,X,X,147, V5,Validation,5.2.4,"Verify that the application avoids the use of eval() or other dynamic code execution features. Where there is no alternative, any user input being included must be sanitized or sandboxed before being executed.",X,X,X,95, V5,Validation,5.2.5,Verify that the application protects against template injection attacks by ensuring that any user input being included is sanitized or sandboxed.,X,X,X,94, V5,Validation,5.2.6,"Verify that the application protects against SSRF attacks, by validating or sanitizing untrusted data or HTTP file metadata, such as filenames and URL input fields, use whitelisting of protocols, domains, paths and ports.",X,X,X,918, V5,Validation,5.2.7,"Verify that the application sanitizes, disables, or sandboxes user-supplied SVG scriptable content, especially as they relate to XSS resulting from inline scripts, and foreignObject.",X,X,X,159, V5,Validation,5.2.8,"Verify that the application sanitizes, disables, or sandboxes user-supplied scriptable or expression template language content, such as Markdown, CSS or XSL stylesheets, BBCode, or similar.",X,X,X,94, V5,Validation,5.3.1,"Verify that output encoding is relevant for the interpreter and context required. For example, use encoders specifically for HTML values, HTML attributes, JavaScript, URL Parameters, HTTP headers, SMTP, and others as the context requires, especially from untrusted inputs (e.g. names with Unicode or apostrophes, such as ねこ or O'Hara). ([C4](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",X,X,X,116, V5,Validation,5.3.10,Verify that the application protects against XPath injection or XML injection attacks. ([C4](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),X,X,X,643, V5,Validation,5.3.2,"Verify that output encoding preserves the user's chosen character set and locale, such that any Unicode character point is valid and safely handled. ([C4](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",X,X,X,176, V5,Validation,5.3.3,"Verify that context-aware, preferably automated - or at worst, manual - output escaping protects against reflected, stored, and DOM based XSS. ([C4](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",X,X,X,79, V5,Validation,5.3.4,"Verify that data selection or database queries (e.g. SQL, HQL, ORM, NoSQL) use parameterized queries, ORMs, entity frameworks, or are otherwise protected from database injection attacks. ([C3](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",X,X,X,89, V5,Validation,5.3.5,"Verify that where parameterized or safer mechanisms are not present, context-specific output encoding is used to protect against injection attacks, such as the use of SQL escaping to protect against SQL injection. ([C3, C4](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",X,X,X,89, V5,Validation,5.3.6,"Verify that the application projects against JavaScript or JSON injection attacks, including for eval attacks, remote JavaScript includes, CSP bypasses, DOM XSS, and JavaScript expression evaluation. ([C4](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",X,X,X,830, V5,Validation,5.3.7,"Verify that the application protects against LDAP Injection vulnerabilities, or that specific security controls to prevent LDAP Injection have been implemented. ([C4](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",X,X,X,943, V5,Validation,5.3.8,Verify that the application protects against OS command injection and that operating system calls use parameterized OS queries or use contextual command line output encoding. ([C4](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),X,X,X,78, V5,Validation,5.3.9,Verify that the application protects against Local File Inclusion (LFI) or Remote File Inclusion (RFI) attacks.,X,X,X,829, V5,Validation,5.4.1,"Verify that the application uses memory-safe string, safer memory copy and pointer arithmetic to detect or prevent stack, buffer, or heap overflows.",,X,X,120, V5,Validation,5.4.2,"Verify that format strings do not take potentially hostile input, and are constant.",,X,X,134, V5,Validation,5.4.3,"Verify that sign, range, and input validation techniques are used to prevent integer overflows.",,X,X,190, V5,Validation,5.5.1,Verify that serialized objects use integrity checks or are encrypted to prevent hostile object creation or data tampering. ([C5](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),X,X,X,502, V5,Validation,5.5.2,Verify that the application correctly restricts XML parsers to only use the most restrictive configuration possible and to ensure that unsafe features such as resolving external entities are disabled to prevent XXE.,X,X,X,611, V5,Validation,5.5.3,"Verify that deserialization of untrusted data is avoided or is protected in both custom code and third-party libraries (such as JSON, XML and YAML parsers).",X,X,X,502, V5,Validation,5.5.4,"Verify that when parsing JSON in browsers or JavaScript-based backends, JSON.parse is used to parse the JSON document. Do not use eval() to parse JSON.",X,X,X,95, V6,Cryptography,6.1.1,"Verify that regulated private data is stored encrypted while at rest, such as personally identifiable information (PII), sensitive personal information, or data assessed likely to be subject to EU's GDPR.",,X,X,311, V6,Cryptography,6.1.2,"Verify that regulated health data is stored encrypted while at rest, such as medical records, medical device details, or de-anonymized research records.",,X,X,311, V6,Cryptography,6.1.3,"Verify that regulated financial data is stored encrypted while at rest, such as financial accounts, defaults or credit history, tax records, pay history, beneficiaries, or de-anonymized market or research records.",,X,X,311, V6,Cryptography,6.2.1,"Verify that all cryptographic modules fail securely, and errors are handled in a way that does not enable Padding Oracle attacks.",X,X,X,310, V6,Cryptography,6.2.2,"Verify that industry proven or government approved cryptographic algorithms, modes, and libraries are used, instead of custom coded cryptography. ([C8](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",,X,X,327, V6,Cryptography,6.2.3,"Verify that encryption initialization vector, cipher configuration, and block modes are configured securely using the latest advice.",,X,X,326, V6,Cryptography,6.2.4,"Verify that random number, encryption or hashing algorithms, key lengths, rounds, ciphers or modes, can be reconfigured, upgraded, or swapped at any time, to protect against cryptographic breaks. ([C8](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",,X,X,326, V6,Cryptography,6.2.5,"Verify that known insecure block modes (i.e. ECB, etc.), padding modes (i.e. PKCS#1 v1.5, etc.), ciphers with small block sizes (i.e. Triple-DES, Blowfish, etc.), and weak hashing algorithms (i.e. MD5, SHA1, etc.) are not used unless required for backwards compatibility.",,X,X,326, V6,Cryptography,6.2.6,"Verify that nonces, initialization vectors, and other single use numbers must not be used more than once with a given encryption key. The method of generation must be appropriate for the algorithm being used.",,X,X,326, V6,Cryptography,6.2.7,"Verify that encrypted data is authenticated via signatures, authenticated cipher modes, or HMAC to ensure that ciphertext is not altered by an unauthorized party.",,,X,326, V6,Cryptography,6.2.8,"Verify that all cryptographic operations are constant-time, with no 'short-circuit' operations in comparisons, calculations, or returns, to avoid leaking information.",,,X,385, V6,Cryptography,6.3.1,"Verify that all random numbers, random file names, random GUIDs, and random strings are generated using the cryptographic module's approved cryptographically secure random number generator when these random values are intended to be not guessable by an attacker.",,X,X,338, V6,Cryptography,6.3.2,"Verify that random GUIDs are created using the GUID v4 algorithm, and a cryptographically-secure pseudo-random number generator (CSPRNG). GUIDs created using other pseudo-random number generators may be predictable.",,X,X,338, V6,Cryptography,6.3.3,"Verify that random numbers are created with proper entropy even when the application is under heavy load, or that the application degrades gracefully in such circumstances.",,,X,338, V6,Cryptography,6.4.1,"Verify that a secrets management solution such as a key vault is used to securely create, store, control access to and destroy secrets. ([C8](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",,X,X,798, V6,Cryptography,6.4.2,Verify that key material is not exposed to the application but instead uses an isolated security module like a vault for cryptographic operations. ([C8](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),,X,X,320, V7,Error,7.1.1,"Verify that the application does not log credentials or payment details. Session tokens should only be stored in logs in an irreversible, hashed form. ([C9, C10](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",X,X,X,532, V7,Error,7.1.2,Verify that the application does not log other sensitive data as defined under local privacy laws or relevant security policy. ([C9](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),X,X,X,532, V7,Error,7.1.3,"Verify that the application logs security relevant events including successful and failed authentication events, access control failures, deserialization failures and input validation failures. ([C5, C7](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",,X,X,778, V7,Error,7.1.4,Verify that each log event includes necessary information that would allow for a detailed investigation of the timeline when an event happens. ([C9](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),,X,X,778, V7,Error,7.2.1,"Verify that all authentication decisions are logged, without storing sensitive session identifiers or passwords. This should include requests with relevant metadata needed for security investigations.",,X,X,778, V7,Error,7.2.2,Verify that all access control decisions can be logged and all failed decisions are logged. This should include requests with relevant metadata needed for security investigations.,,X,X,285, V7,Error,7.3.1,Verify that the application appropriately encodes user-supplied data to prevent log injection. ([C9](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),,X,X,117, V7,Error,7.3.2,Verify that all events are protected from injection when viewed in log viewing software. ([C9](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),,X,X,117, V7,Error,7.3.3,Verify that security logs are protected from unauthorized access and modification. ([C9](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),,X,X,200, V7,Error,7.3.4,Verify that time sources are synchronized to the correct time and time zone. Strongly consider logging only in UTC if systems are global to assist with post-incident forensic analysis. ([C9](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),,X,X,, V7,Error,7.4.1,"Verify that a generic message is shown when an unexpected or security sensitive error occurs, potentially with a unique ID which support personnel can use to investigate. ([C10](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",X,X,X,210, V7,Error,7.4.2,Verify that exception handling (or a functional equivalent) is used across the codebase to account for expected and unexpected error conditions. ([C10](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),,X,X,544, V7,Error,7.4.3,"Verify that a ""last resort"" error handler is defined which will catch all unhandled exceptions. ([C10](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",,X,X,460, V8,Data,8.1.1,Verify the application protects sensitive data from being cached in server components such as load balancers and application caches.,,X,X,524, V8,Data,8.1.2,Verify that all cached or temporary copies of sensitive data stored on the server are protected from unauthorized access or purged/invalidated after the authorized user accesses the sensitive data.,,X,X,524, V8,Data,8.1.3,"Verify the application minimizes the number of parameters in a request, such as hidden fields, Ajax variables, cookies and header values.",,X,X,233, V8,Data,8.1.4,"Verify the application can detect and alert on abnormal numbers of requests, such as by IP, user, total per hour or day, or whatever makes sense for the application.",,X,X,770, V8,Data,8.1.5,Verify that regular backups of important data are performed and that test restoration of data is performed.,,,X,19, V8,Data,8.1.6,Verify that backups are stored securely to prevent data from being stolen or corrupted.,,,X,19, V8,Data,8.2.1,Verify the application sets sufficient anti-caching headers so that sensitive data is not cached in modern browsers.,X,X,X,525, V8,Data,8.2.2,"Verify that data stored in client side storage (such as HTML5 local storage, session storage, IndexedDB, regular cookies or Flash cookies) does not contain sensitive data or PII.",X,X,X,922, V8,Data,8.2.3,"Verify that authenticated data is cleared from client storage, such as the browser DOM, after the client or session is terminated.",X,X,X,922, V8,Data,8.3.1,"Verify that sensitive data is sent to the server in the HTTP message body or headers, and that query string parameters from any HTTP verb do not contain sensitive data.",X,X,X,319, V8,Data,8.3.2,Verify that users have a method to remove or export their data on demand.,X,X,X,212, V8,Data,8.3.3,Verify that users are provided clear language regarding collection and use of supplied personal information and that users have provided opt-in consent for the use of that data before it is used in any way.,X,X,X,285, V8,Data,8.3.4,"Verify that all sensitive data created and processed by the application has been identified, and ensure that a policy is in place on how to deal with sensitive data. ([C8](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",X,X,X,200, V8,Data,8.3.5,"Verify accessing sensitive data is audited (without logging the sensitive data itself), if the data is collected under relevant data protection directives or where logging of access is required.",,X,X,532, V8,Data,8.3.6,"Verify that sensitive information contained in memory is overwritten as soon as it is no longer required to mitigate memory dumping attacks, using zeroes or random data.",,X,X,226, V8,Data,8.3.7,"Verify that sensitive or private information that is required to be encrypted, is encrypted using approved algorithms that provide both confidentiality and integrity. ([C8](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",,X,X,327, V8,Data,8.3.8,"Verify that sensitive personal information is subject to data retention classification, such that old or out of date data is deleted automatically, on a schedule, or as the situation requires.",,X,X,285, V9,Communications,9.1.1,"Verify that secured TLS is used for all client connectivity, and does not fall back to insecure or unencrypted protocols. ([C8](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",X,X,X,319, V9,Communications,9.1.2,"Verify using online or up to date TLS testing tools that only strong algorithms, ciphers, and protocols are enabled, with the strongest algorithms and ciphers set as preferred.",X,X,X,326, V9,Communications,9.1.3,"Verify that old versions of SSL and TLS protocols, algorithms, ciphers, and configuration are disabled, such as SSLv2, SSLv3, or TLS 1.0 and TLS 1.1. The latest version of TLS should be the preferred cipher suite.",X,X,X,326, V9,Communications,9.2.1,"Verify that connections to and from the server use trusted TLS certificates. Where internally generated or self-signed certificates are used, the server must be configured to only trust specific internal CAs and specific self-signed certificates. All others should be rejected.",,X,X,295, V9,Communications,9.2.2,"Verify that encrypted communications such as TLS is used for all inbound and outbound connections, including for management ports, monitoring, authentication, API, or web service calls, database, cloud, serverless, mainframe, external, and partner connections. The server must not fall back to insecure or unencrypted protocols.",,X,X,319, V9,Communications,9.2.3,Verify that all encrypted connections to external systems that involve sensitive information or functions are authenticated.,,X,X,287, V9,Communications,9.2.4,"Verify that proper certification revocation, such as Online Certificate Status Protocol (OCSP) Stapling, is enabled and configured.",,X,X,299, V9,Communications,9.2.5,Verify that backend TLS connection failures are logged.,,,X,544, V10,Malicious,10.1.1,"Verify that a code analysis tool is in use that can detect potentially malicious code, such as time functions, unsafe file operations and network connections.",,,X,749, V10,Malicious,10.2.1,"Verify that the application source code and third party libraries do not contain unauthorized phone home or data collection capabilities. Where such functionality exists, obtain the user's permission for it to operate before collecting any data.",,X,X,359, V10,Malicious,10.2.2,"Verify that the application does not ask for unnecessary or excessive permissions to privacy related features or sensors, such as contacts, cameras, microphones, or location.",,X,X,272, V10,Malicious,10.2.3,"Verify that the application source code and third party libraries do not contain back doors, such as hard-coded or additional undocumented accounts or keys, code obfuscation, undocumented binary blobs, rootkits, or anti-debugging, insecure debugging features, or otherwise out of date, insecure, or hidden functionality that could be used maliciously if discovered.",,,X,507, V10,Malicious,10.2.4,Verify that the application source code and third party libraries does not contain time bombs by searching for date and time related functions.,,,X,511, V10,Malicious,10.2.5,"Verify that the application source code and third party libraries does not contain malicious code, such as salami attacks, logic bypasses, or logic bombs.",,,X,511, V10,Malicious,10.2.6,Verify that the application source code and third party libraries do not contain Easter eggs or any other potentially unwanted functionality.,,,X,507, V10,Malicious,10.3.1,"Verify that if the application has a client or server auto-update feature, updates should be obtained over secure channels and digitally signed. The update code must validate the digital signature of the update before installing or executing the update.",X,X,X,16, V10,Malicious,10.3.2,"Verify that the application employs integrity protections, such as code signing or sub-resource integrity. The application must not load or execute code from untrusted sources, such as loading includes, modules, plugins, code, or libraries from untrusted sources or the Internet.",X,X,X,353, V10,Malicious,10.3.3,"Verify that the application has protection from sub-domain takeovers if the application relies upon DNS entries or DNS sub-domains, such as expired domain names, out of date DNS pointers or CNAMEs, expired projects at public source code repos, or transient cloud APIs, serverless functions, or storage buckets (autogen-bucket-id.cloud.example.com) or similar. Protections can include ensuring that DNS names used by applications are regularly checked for expiry or change.",X,X,X,350, V11,BusLogic,11.1.1,Verify the application will only process business logic flows for the same user in sequential step order and without skipping steps.,X,X,X,841, V11,BusLogic,11.1.2,"Verify the application will only process business logic flows with all steps being processed in realistic human time, i.e. transactions are not submitted too quickly.",X,X,X,779, V11,BusLogic,11.1.3,Verify the application has appropriate limits for specific business actions or transactions which are correctly enforced on a per user basis.,X,X,X,770, V11,BusLogic,11.1.4,"Verify the application has sufficient anti-automation controls to detect and protect against data exfiltration, excessive business logic requests, excessive file uploads or denial of service attacks.",X,X,X,770, V11,BusLogic,11.1.5,"Verify the application has business logic limits or validation to protect against likely business risks or threats, identified using threat modelling or similar methodologies.",X,X,X,841, V11,BusLogic,11.1.6,"Verify the application does not suffer from ""time of check to time of use"" (TOCTOU) issues or other race conditions for sensitive operations.",,X,X,367, V11,BusLogic,11.1.7,"Verify the application monitors for unusual events or activity from a business logic perspective. For example, attempts to perform actions out of order or actions which a normal user would never attempt. ([C9](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",,X,X,754, V11,BusLogic,11.1.8,Verify the application has configurable alerting when automated attacks or unusual activity is detected.,,X,X,390, V12,Files,12.1.1,Verify that the application will not accept large files that could fill up storage or cause a denial of service attack.,X,X,X,400, V12,Files,12.1.2,"Verify that compressed files are checked for ""zip bombs"" - small input files that will decompress into huge files thus exhausting file storage limits.",,X,X,409, V12,Files,12.1.3,"Verify that a file size quota and maximum number of files per user is enforced to ensure that a single user cannot fill up the storage with too many files, or excessively large files.",,X,X,770, V12,Files,12.2.1,Verify that files obtained from untrusted sources are validated to be of expected type based on the file's content.,,X,X,434, V12,Files,12.3.1,Verify that user-submitted filename metadata is not used directly with system or framework file and URL API to protect against path traversal.,X,X,X,22, V12,Files,12.3.2,"Verify that user-submitted filename metadata is validated or ignored to prevent the disclosure, creation, updating or removal of local files (LFI).",X,X,X,73, V12,Files,12.3.3,"Verify that user-submitted filename metadata is validated or ignored to prevent the disclosure or execution of remote files (RFI), which may also lead to SSRF.",X,X,X,98, V12,Files,12.3.4,"Verify that the application protects against reflective file download (RFD) by validating or ignoring user-submitted filenames in a JSON, JSONP, or URL parameter, the response Content-Type header should be set to text/plain, and the Content-Disposition header should have a fixed filename.",X,X,X,641, V12,Files,12.3.5,"Verify that untrusted file metadata is not used directly with system API or libraries, to protect against OS command injection.",X,X,X,78, V12,Files,12.3.6,"Verify that the application does not include and execute functionality from untrusted sources, such as unverified content distribution networks, JavaScript libraries, node npm libraries, or server-side DLLs.",,X,X,829, V12,Files,12.4.1,"Verify that files obtained from untrusted sources are stored outside the web root, with limited permissions, preferably with strong validation.",X,X,X,922, V12,Files,12.4.2,Verify that files obtained from untrusted sources are scanned by antivirus scanners to prevent upload of known malicious content.,X,X,X,509, V12,Files,12.5.1,"Verify that the web tier is configured to serve only files with specific file extensions to prevent unintentional information and source code leakage. For example, backup files (e.g. .bak), temporary working files (e.g. .swp), compressed files (.zip, .tar.gz, etc) and other extensions commonly used by editors should be blocked unless required.",X,X,X,552, V12,Files,12.5.2,Verify that direct requests to uploaded files will never be executed as HTML/JavaScript content.,X,X,X,434, V12,Files,12.6.1,Verify that the web or application server is configured with a whitelist of resources or systems to which the server can send requests or load data/files from.,X,X,X,918, V13,API,13.1.1,Verify that all application components use the same encodings and parsers to avoid parsing attacks that exploit different URI or file parsing behavior that could be used in SSRF and RFI attacks.,X,X,X,116, V13,API,13.1.2,Verify that access to administration and management functions is limited to authorized administrators.,X,X,X,419, V13,API,13.1.3,"Verify API URLs do not expose sensitive information, such as the API key, session tokens etc.",X,X,X,598, V13,API,13.1.4,"Verify that authorization decisions are made at both the URI, enforced by programmatic or declarative security at the controller or router, and at the resource level, enforced by model-based permissions.",,X,X,285, V13,API,13.1.5,Verify that requests containing unexpected or missing content types are rejected with appropriate headers (HTTP response status 406 Unacceptable or 415 Unsupported Media Type).,,X,X,434, V13,API,13.2.1,"Verify that enabled RESTful HTTP methods are a valid choice for the user or action, such as preventing normal users using DELETE or PUT on protected API or resources.",X,X,X,650, V13,API,13.2.2,Verify that JSON schema validation is in place and verified before accepting input.,X,X,X,20, V13,API,13.2.3,"Verify that RESTful web services that utilize cookies are protected from Cross-Site Request Forgery via the use of at least one or more of the following: triple or double submit cookie pattern (see [references](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet)), CSRF nonces, or ORIGIN request header checks.",X,X,X,352, V13,API,13.2.4,"Verify that REST services have anti-automation controls to protect against excessive calls, especially if the API is unauthenticated.",,X,X,779, V13,API,13.2.5,"Verify that REST services explicitly check the incoming Content-Type to be the expected one, such as application/xml or application/JSON.",,X,X,436, V13,API,13.2.6,Verify that the message headers and payload are trustworthy and not modified in transit. Requiring strong encryption for transport (TLS only) may be sufficient in many cases as it provides both confidentiality and integrity protection. Per-message digital signatures can provide additional assurance on top of the transport protections for high-security applications but bring with them additional complexity and risks to weigh against the benefits.,,X,X,345, V13,API,13.3.1,"Verify that XSD schema validation takes place to ensure a properly formed XML document, followed by validation of each input field before any processing of that data takes place.",X,X,X,20, V13,API,13.3.2,Verify that the message payload is signed using WS-Security to ensure reliable transport between client and service.,,X,X,345, V13,API,13.4.1,"Verify that query whitelisting or a combination of depth limiting and amount limiting should be used to prevent GraphQL or data layer expression denial of service (DoS) as a result of expensive, nested queries. For more advanced scenarios, query cost analysis should be used.",,X,X,770, V13,API,13.4.2,Verify that GraphQL or other data layer authorization logic should be implemented at the business logic layer instead of the GraphQL layer.,,X,X,285, V14,Config,14.1.1,"Verify that the application build and deployment processes are performed in a secure and repeatable way, such as CI / CD automation, automated configuration management, and automated deployment scripts.",,X,X,, V14,Config,14.1.2,"Verify that compiler flags are configured to enable all available buffer overflow protections and warnings, including stack randomization, data execution prevention, and to break the build if an unsafe pointer, memory, format string, integer, or string operations are found.",,X,X,120, V14,Config,14.1.3,Verify that server configuration is hardened as per the recommendations of the application server and frameworks in use.,,X,X,16, V14,Config,14.1.4,"Verify that the application, configuration, and all dependencies can be re-deployed using automated deployment scripts, built from a documented and tested runbook in a reasonable time, or restored from backups in a timely fashion.",,X,X,, V14,Config,14.1.5,Verify that authorized administrators can verify the integrity of all security-relevant configurations to detect tampering.,,,X,, V14,Config,14.2.1,"Verify that all components are up to date, preferably using a dependency checker during build or compile time. ([C2](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",X,X,X,1026, V14,Config,14.2.2,"Verify that all unneeded features, documentation, samples, configurations are removed, such as sample applications, platform documentation, and default or example users.",X,X,X,1002, V14,Config,14.2.3,"Verify that if application assets, such as JavaScript libraries, CSS stylesheets or web fonts, are hosted externally on a content delivery network (CDN) or external provider, Subresource Integrity (SRI) is used to validate the integrity of the asset.",X,X,X,714, V14,Config,14.2.4,"Verify that third party components come from pre-defined, trusted and continually maintained repositories. ([C2](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering))",,X,X,829, V14,Config,14.2.5,Verify that an inventory catalog is maintained of all third party libraries in use. ([C2](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),,X,X,, V14,Config,14.2.6,Verify that the attack surface is reduced by sandboxing or encapsulating third party libraries to expose only the required behaviour into the application. ([C2](https://www.owasp.org/index.php/OWASP_Proactive_Controls#tab=Formal_Numbering)),,X,X,265, V14,Config,14.3.1,"Verify that web or application server and framework error messages are configured to deliver user actionable, customized responses to eliminate any unintended security disclosures.",X,X,X,209, V14,Config,14.3.2,"Verify that web or application server and application framework debug modes are disabled in production to eliminate debug features, developer consoles, and unintended security disclosures.",X,X,X,497, V14,Config,14.3.3,Verify that the HTTP headers or any part of the HTTP response do not expose detailed version information of system components.,X,X,X,200, V14,Config,14.4.1,"Verify that every HTTP response contains a content type header specifying a safe character set (e.g., UTF-8, ISO 8859-1).",X,X,X,173, V14,Config,14.4.2,"Verify that all API responses contain Content-Disposition: attachment; filename=""api.json"" (or other appropriate filename for the content type).",X,X,X,116, V14,Config,14.4.3,"Verify that a content security policy (CSPv2) is in place that helps mitigate impact for XSS attacks like HTML, DOM, JSON, and JavaScript injection vulnerabilities.",X,X,X,1021, V14,Config,14.4.4,Verify that all responses contain X-Content-Type-Options: nosniff.,X,X,X,116, V14,Config,14.4.5,"Verify that HTTP Strict Transport Security headers are included on all responses and for all subdomains, such as Strict-Transport-Security: max-age=15724800; includeSubdomains.",X,X,X,523, V14,Config,14.4.6,"Verify that a suitable ""Referrer-Policy"" header is included, such as ""no-referrer"" or ""same-origin"".",X,X,X,116, V14,Config,14.4.7,Verify that a suitable X-Frame-Options or Content-Security-Policy: frame-ancestors header is in use for sites where content should not be embedded in a third-party site.,X,X,X,346, V14,Config,14.5.1,"Verify that the application server only accepts the HTTP methods in use by the application or API, including pre-flight OPTIONS.",X,X,X,749, V14,Config,14.5.2,"Verify that the supplied Origin header is not used for authentication or access control decisions, as the Origin header can easily be changed by an attacker.",X,X,X,346, V14,Config,14.5.3,"Verify that the cross-domain resource sharing (CORS) Access-Control-Allow-Origin header uses a strict white-list of trusted domains to match against and does not support the ""null"" origin.",X,X,X,346, V14,Config,14.5.4,"Verify that HTTP headers added by a trusted proxy or SSO devices, such as a bearer token, are authenticated by the application.",,X,X,306, ================================================ FILE: api/tp_api/models.py ================================================ from mongoengine import * import datetime from uuid import uuid4 from hashlib import sha256 from mongoengine import signals def random_scan_name(): return str(uuid4()) class Project(Document): name = StringField(max_length=100, required=True, unique=True) orchy_webhook = StringField(required=False) features = ListField(ReferenceField("UseCase"), required=False) class RepoTestCase(Document): name = StringField() test_case = StringField() executed = BooleanField(default=False) tools = ListField(StringField()) type = StringField(max_length=20) tags = ListField(StringField()) class Repo(Document): short_name = StringField(required=True) name = StringField(required=True) cwe = IntField(required=True) description = StringField() variants = ListField(StringField()) categories = ListField(StringField()) mitigations = ListField(DictField()) risks = ListField(DictField()) tests = ListField(ReferenceField(RepoTestCase)) related_cwes = ListField(IntField()) class Interaction(Document): nature_choices = (("I", "Internal"), ("E", "External")) nature = StringField(choices=nature_choices) endpoint = StringField() data_flow = StringField() project = ReferenceField(Project, reverse_delete_rule=CASCADE) class UseCase(Document): short_name = StringField(unique=True) description = StringField() project = ReferenceField(Project, reverse_delete_rule=CASCADE, required=True) relations = ListField(ReferenceField(Interaction)) boundary = StringField() abuses = ListField(ReferenceField("AbuseCase")) class AbuseCase(Document): short_name = StringField(max_length=100, unique=True) description = StringField() use_case = ReferenceField(UseCase, reverse_delete_rule=CASCADE, required=True) scenarios = ListField(ReferenceField("ThreatModel"), required=False) model_type_choices = (("repo", "repo"), ("inline", "inline")) class Mitigations(EmbeddedDocument): phase = StringField() strategy = StringField() description = StringField() code = StringField() class Risk(EmbeddedDocument): description = StringField() phase = StringField() class ThreatModel(Document): # meta = {'collection': 'threat_model'} name = StringField() vul_name = StringField() description = StringField(required=True) severity = IntField() model_type = StringField(max_length=6, choices=model_type_choices) repo_vul_name = ReferenceField(Repo) use_case = ReferenceField(UseCase, reverse_delete_rule=CASCADE) abuse_case = ReferenceField(AbuseCase, reverse_delete_rule=CASCADE) cwe = IntField() risks = EmbeddedDocumentListField(Risk) categories = ListField(StringField(max_length=30)) mitigations = EmbeddedDocumentListField(Mitigations) tests = ListField(ReferenceField("Test")) class Test(Document): name = StringField() test_case = StringField() executed = BooleanField(default=False) tools = ListField(StringField()) test_type = StringField() tags = ListField(StringField()) scenario = ReferenceField(ThreatModel, reverse_delete_rule=CASCADE) class Risk(EmbeddedDocument): consequence = StringField() risk_type = StringField() class VulnerabilityEvidence(Document): evidence_type = StringField() log = StringField() url = StringField() line_num = IntField() param = StringField() attack = StringField() info = StringField() vuln = ReferenceField("Vulnerability") class Vulnerability(Document): severity_choices = ((3, "High"), (2, "Medium"), (1, "Low"), (0, "Info")) tool = StringField() name = StringField() cwe = IntField() severity = IntField(choices=severity_choices) description = StringField() observation = StringField() remediation = StringField() evidences = ListField(ReferenceField(VulnerabilityEvidence)) created_on = DateTimeField(default=datetime.datetime.utcnow) scan = ReferenceField("Scan") target = ReferenceField("Target") class Scan(Document): created_on = DateTimeField(default=datetime.datetime.utcnow) name = StringField(unique=True) vulnerabilities = ListField(ReferenceField("Vulnerability")) target = ReferenceField("Target") tool = StringField() scan_type = StringField( choices=( ("SAST", "Static Analysis"), ("DAST", "Dynamic Analysis"), ("SCA", "Source Composition Analysis"), ("IAST", "Interactive Analysis"), ("Manual", "Manual Scan"), ) ) @classmethod def pre_save(cls, sender, document, **kwargs): document.name = "{}-scan-{}-{}@{}".format( document.tool, document.target.name, document.target.project.name, datetime.datetime.utcnow().isoformat(), ) class Target(Document): name = StringField(unique=True) url = StringField() project = ReferenceField(Project, reverse_delete_rule=CASCADE) scans = ListField(ReferenceField(Scan)) class User(Document): user_type_choices = (("super", "superuser"), ("user", "user")) email = StringField(max_length=100, unique=True) password = StringField(max_length=100) user_type = StringField(choices=user_type_choices, max_length=6, default="user") default_password = BooleanField(default=True) class Settings(Document): orchy_url = StringField() orchy_user = StringField() orchy_password = StringField() class ASVS(Document): section = StringField() name = StringField() item = StringField() description = StringField() l1 = BooleanField(default=False) l2 = BooleanField(default=False) l3 = BooleanField(default=False) cwe = IntField() nist = StringField() signals.pre_save.connect(Scan.pre_save, sender = Scan) ================================================ FILE: api/tp_api/repo/aws_s3.yaml ================================================ name: Misconfigured AWS S3 Bucket cwe: 16 description: Misconfigured Amazon AWS S3 Bucket(s) might allow unauthorized users to read/write files in the specific S3 buckets mitigations: - description: Ensure that IAM Policies are set for AWS S3 to protect against public/unauthorized access to unauthorized users phase: Implementation - description: Consider implementation of encryption for data stored in AWS S3 phase: Implementation risk: - consequence: Unauthorized Users may gain access to files with sensitive information in the AWS S3 bucket(s) type: Confidentiality - consequence: Unauthorized Users may write/modify data in the AWS S3 bucket(s) type: Integrity test-cases: - name: automated-vulnerability-scanning test: run automated vulnerability discovery tools to identify misconfigured AWS S3 buckets tools: [scout2,prowler,weirdaal,burpsuite] type: discovery - name: manual test: test for misconfigured AWS S3 Buckets manually, as part of a Pentest or Bug-bounty type: manual categories: [cloud] ================================================ FILE: api/tp_api/repo/cert_validation.yaml ================================================ name: Improper Certificate Validation description: The software does not validate, or incorrectly validates, a certificate. cwe: 295 categories: [app_vulns,owasp] mitigations: - description: Certificates should be carefully managed and checked to assure that data are encrypted with the intended owner's public key. phase: Architecture and Design - description: Certificates should be deployed with strong CipherSuite Specs and Perfect Forward Secrecy for highest levels of protection phase: Implementation risk: - consequence: Attacker may be able to leverage a weak SSL Implementation to compromise the master key/keying materials, thereby compromising the transmission of sensitive information type: Confidentiality test-cases: - name: ssl-test test: Check for SSL/TLS implementation with automated tools tools: [ssllabs.com,testssl.sh,sslyze,sslscan,nmap] - name: source-composition-scanning test: Run Source Composition Scanners against the libraries being used by the application, to identify instances of misconfigured SSL/TLS Implementation or Plaintext Data Transmission tools: [retirejs,npm-audit,owasp-dependency-checker,blackduck,whitesource,snyk,safety] type: sca - name: static-analysis test: Run Static Analysis tools to identify instances that relate to misconfigured SSL/TLS Implementation or Plaintext Data Transmission tools: [checkmarx,brakeman,bandit,pyt,security-code-scan,veracode,nodejsscan,coverity] type: sast ================================================ FILE: api/tp_api/repo/code_injection.yaml ================================================ name: Code Injection description: The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment. categories: [app_vulns,owasp] cwe: 94 mitigations: - description: Refactor your program so that you do not have to dynamically generate code. phase: Architecture and Design - description: To reduce the likelihood of code injection, use stringent whitelists that limit which constructs are allowed. If you are dynamically constructing code that invokes a function, then verifying that the input is alphanumeric might be insufficient. An attacker might still be able to reference a dangerous function that you did not intend to allow, such as system(), exec(), or exit(). phase: Implementation - description: Use automated static analysis tools that target this type of weakness. Many modern techniques use data flow analysis to minimize the number of false positives. This is not a perfect solution, since 100% accuracy and coverage are not feasible. phase: Testing - description: Use dynamic tools and techniques that interact with the software using large test suites with many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The software's operation may slow down, but it should not become unstable, crash, or generate incorrect results. phase: Testing - description: Run the code in an environment that performs automatic taint propagation and prevents any command execution that uses tainted variables, such as Perl's "-T" switch. This will force the program to perform validation steps that remove the taint, although you must be careful to correctly validate your inputs so that you do not accidentally mark dangerous inputs as untainted (see CWE-183 and CWE-184). phase: Operation - description: Identify vulnerabilities in underlying libraries with Source Composition Scanning phase: Testing - description: Consider using low-logic templating systems, if you are using Templating Frameworks. Low-Logic Templating Systems like Mustache cannot expand objects and data-structures, thereby ensuring that remote code execution through Template Variables, does not happen phase: Implementation risk: - consequence: In some cases, injectable code controls authentication; this may lead to a remote vulnerability. type: Access_Control - consequence: Injected code can access resources that the attacker is directly prevented from accessing. type: Access_Control - consequence: Code injection attacks can lead to loss of data integrity in nearly all cases as the control-plane data injected is always incidental to data recall or writing. Additionally, code injection can often result in the execution of arbitrary code. type: Integrity - consequence: Often the actions performed by injected control code are unlogged. type: Non-Repudiation variants: - Server-Side Eval Injection - Server-Side Template Injection test-cases: - name: automated-vulnerability-scanning test: run automated vulnerability discovery tools and its Injection payloads against the application tools: [zap,burpsuite,arachni,acunetix,netsparker,appspider,w3af] type: discovery - name: manual test: test for Code Injection variants manually with pentesters, bug-bounty type: manual - name: exploit test: Run exploit tools to identify and exploit Code Injections in the application type: exploit tools: [sqlmap,netsparker,jsqli] - name: source-composition-scanning test: Run Source Composition Scanners against the libraries being used by the application, to identify instances of Code Injection tools: [retirejs,npm-audit,owasp-dependency-checker,blackduck,whitesource,snyk,safety] type: sca - name: static-analysis test: Run Static Analysis tools to identify instances of dynamic queries or stored procedures that are vulnerable to Code Injection tools: [checkmarx,brakeman,bandit,pyt,security-code-scan,veracode,nodejsscan,coverity] type: sast related_cwes: - 95 - 96 ================================================ FILE: api/tp_api/repo/idor_pk.yaml ================================================ name: Insecure Direct Object Reference - Primary Key cwe: 639 description: The system's authorization functionality does not prevent one user from gaining access to another user's data or record by modifying the key value identifying the data. mitigations: - description: For each and every data access, ensure that the user has sufficient privilege to access the record that is being requested. phase: Architecture and Design - description: Make sure that the key that is used in the lookup of a specific user's record is not controllable externally by the user or that any tampering can be detected. phase: Architecture and Design - description: Use encryption in order to make it more difficult to guess other legitimate values of the key or associate a digital signature with the key so that the server can verify that there has been no tampering. phase: Architecture and Design risk: - consequence: Access control checks for specific user data or functionality can be bypassed. type: Access_Control - consequence: Horizontal escalation of privilege is possible (one user can view/modify information of another user). type: Access_Control - consequence: Vertical escalation of privilege is possible if the user-controlled key is actually a flag that indicates administrator status, allowing the attacker to gain administrative access. type: Access_Control categories: [app_vulns] test-cases: - name: manual test: test for Insecure Direct Object References variants manually with pentesters, bug-bounty type: manual - name: fuzzing test: test for IDORs with Fuzzing with Automated tools tools: [burpsuite,owasp-zap,wfuzz,mitmproxy] type: automated - name: static-analysis test: Run Static Analysis tools to identify instances of improper input validation and output encoding for Insecure Deserialization tools: [checkmarx,brakeman,bandit,pyt,security-code-scan,veracode,nodejsscan,coverity] type: sast - name: source-composition-scanning test: Run Source Composition Scanners against the libraries being used by the application, to identify instances of Insecure Deserialization tools: [retirejs,npm-audit,owasp-dependency-checker,blackduck,whitesource,snyk,safety] type: sca related_cwes: - 284 - 285 ================================================ FILE: api/tp_api/repo/insecure_deserialization.yaml ================================================ name: Insecure Deserialization description: The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid. cwe: 502 mitigations: - description: If available, use the signing/sealing features of the programming language to assure that deserialized data has not been tainted. For example, a hash-based message authentication code (HMAC) could be used to ensure that data has not been modified. phase: Architecture and Design - description: When deserializing data, populate a new object rather than just deserializing. The result is that the data flows through safe input validation and that the functions are safe. phase: Implementation - description: An attempt to serialize and then deserialize a class containing transient fields will result in NULLs where the transient data should be. This is an excellent way to prevent time, environment-based, or sensitive variables from being carried over and used improperly. phase: Architecture and Design - description: Avoid having unnecessary types or gadgets available that can be leveraged for malicious ends. This limits the potential for unintended or unauthorized types and gadgets to be leveraged by the attacker. Whitelist acceptable classes. Note- new gadgets are constantly being discovered, so this alone is not a sufficient mitigation. phase: Implementation risk: - consequence: The consequences can vary widely, because it depends on which objects or methods are being deserialized, and how they are used. - consequence: Attackers can modify unexpected objects or data that was assumed to be safe from modification. type: Integrity - consequence: If a function is making an assumption on when to terminate, based on a sentry in a string, it could easily never terminate. type: Availability - consequence: Code could potentially make the assumption that information in the deserialized object is valid. Functions that make this dangerous assumption could be exploited. type: Authorization categories: [app_vulns,owasp] test-cases: - name: automated-vulnerability-scanning test: run automated vulnerability discovery tools and its Insecure Deserialization payloads against the application tools: [zap,burpsuite,arachni,acunetix,netsparker,appspider,w3af] type: discovery - name: manual test: test for Insecure Deserialization variants manually with pentesters, bug-bounty type: manual - name: static-analysis test: Run Static Analysis tools to identify instances of improper input validation and output encoding for Insecure Deserialization tools: [checkmarx,brakeman,bandit,pyt,security-code-scan,veracode,nodejsscan,coverity,] type: sast - name: source-composition-scanning test: Run Source Composition Scanners against the libraries being used by the application, to identify instances of Insecure Deserialization tools: [retirejs,npm-audit,owasp-dependency-checker,blackduck,whitesource,snyk,safety] type: sca ================================================ FILE: api/tp_api/repo/password-bruteforce.yaml ================================================ name: Bruteforce Passwords cwe: 307 categories: [attack] description: The application allows multiple/consecutive attempts at authentication (bruteforce). mitigations: - description: Ensure that users are locked out for a certain timeframe/till administrator's intervention when multiple authentication attempts are encountered. phase: Architecture and Design - description: Log invalid access attempts to ensure that potentially malicious bruteforce attempts are logged phase: Architecture and Design test-cases: - name: automated-vulnerability-scanning test: run automated vulnerability discovery tools and bruteforce against the application tools: [zap,burpsuite,arachni,acunetix,netsparker,appspider,w3af] type: discovery ================================================ FILE: api/tp_api/repo/plaintext-transmission.yaml ================================================ name: Plaintext transmission of sensitive data cwe: 319 categories: [app_vulns,owasp] description: The software transmits sensitive or security-critical data in cleartext in a communication channel that can be sniffed by unauthorized actors. mitigations: - description: Encrypt the data with a reliable encryption scheme before transmitting. phase: Architecture and Design - description: When using web applications with SSL, use SSL for the entire session from login to logout, not just for the initial login page. phase: Implementation - description: Use tools and techniques that require manual (human) analysis, such as penetration testing, threat modeling, and interactive tools that allow the tester to record and modify an active session. These may be more effective than strictly automated techniques. This is especially the case with weaknesses that are related to design and business rules. phase: Testing - description: Configure servers to use encrypted channels for communication, which may include SSL or other secure protocols. phase: Operation risk: - consequence: Anyone can read the information by gaining access to the channel being used for communication. type: Confidentiality test-cases: - name: ssl-test test: Check for SSL/TLS implementation with automated tools tools: [ssllabs.com,testssl.sh,sslyze,sslscan,nmap] type: discovery - name: source-composition-scanning test: Run Source Composition Scanners against the libraries being used by the application, to identify instances of misconfigured SSL/TLS Implementation or Plaintext Data Transmission tools: [retirejs,npm-audit,owasp-dependency-checker,blackduck,whitesource,snyk,safety] type: sca - name: static-analysis test: Run Static Analysis tools to identify instances that relate to misconfigured SSL/TLS Implementation or Plaintext Data Transmission tools: [checkmarx,brakeman,bandit,pyt,security-code-scan,veracode,nodejsscan,coverity] type: sast related_cwes: - 311 ================================================ FILE: api/tp_api/repo/sql_injection.yaml ================================================ name: SQL Injection cwe: 89 description: The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. mitigations: - description: Consider using ORMs (Object to Relation Mappers) to protect against SQL Injection. Nearly all of them perform Parameterized Queries and Query Encoding. phase: Architecture and Design strategy: Libraries or Frameworks - description: Process SQL queries using prepared statements, parameterized queries. Do not dynamically construct and execute query strings within these features using "exec" or similar functionality, since this may re-introduce the possibility of SQL injection. phase: Implementation - description: Specifically, follow the principle of least privilege when creating user accounts to a SQL database. The database users should only have the minimum privileges necessary to use their account. phase: Architecture and Design - description: In the context of SQL Injection, error messages revealing the structure of a SQL query can help attackers tailor successful attack strings. phase: Implementation - description: Use an application firewall that can detect attacks against this weakness. It can be beneficial in cases in which the code cannot be fixed,as an emergency prevention measure while more comprehensive software assurance measures are applied, or to provide defense in depth. phase: Operation risk: - consequence: Since SQL databases generally hold sensitive data, loss of confidentiality is a frequent problem with SQL injection vulnerabilities. type: Confidentiality - consequence: If poor SQL commands are used to check user names and passwords, it may be possible to connect to a system as another user with no previous knowledge of the password. type: Access_Control - consequence: If authorization information is held in a SQL database, it may be possible to change this information through the successful exploitation of a SQL injection vulnerability. type: Access_Control - consequence: Just as it may be possible to read sensitive information, it is also possible to make changes or even delete this information with a SQL injection attack. type: Integrity categories: [app_vulns,owasp] variants: - Blind SQL Injection - Time-Based SQL Injection - Union-Based SQL Injection - Error-Based SQL Injection - Second-Order SQL Injection test-cases: - name: automated-vulnerability-scanning test: run automated vulnerability discovery tools and its Injection payloads against the application tools: [zap,burpsuite,arachni,acunetix,netsparker,appspider,w3af] type: discovery - name: manual test: test for SQL Injection variants manually with pentesters, bug-bounty type: manual - name: exploit test: Run exploit tools to identify and exploit SQL Injections in the application type: exploit tools: [sqlmap,netsparker,jsqli] - name: source-composition-scanning test: Run Source Composition Scanners against the libraries being used by the application, to identify instances of SQL Injection tools: [retirejs,npm-audit,owasp-dependency-checker,blackduck,whitesource,snyk,safety] type: sca - name: static-analysis test: Run Static Analysis tools to identify instances of dynamic queries or stored procedures that are vulnerable to SQL Injection tools: [checkmarx,brakeman,bandit,pyt,security-code-scan,veracode,nodejsscan,coverity] type: sast ================================================ FILE: api/tp_api/repo/ssrf.yaml ================================================ name: Server-Side Request Forgery cwe: 918 description: The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. mitigations: - description: Consider scanning dependencies for SSRF vulnerabilities, including infrastructure components like Apache phase: Implementation - description: Consider implementing a URL whitelist to reduce the possibility of an attacker-controlled URL being resolved by your application phase: Implementation - description: Consider implementing additional Header validation to sensitive paths like EC2 Metadata, etc to mitigate the effects of an existing SSRF flaw phase: Implementation risk: - consequence: Unauthorized users may be able to gain access to sensitive information in internal/protected system components type: Confidentiality test-cases: - name: automated-vulnerability-scanning test: run automated vulnerability discovery tools to identify SSRF tools: [burpsuite,zap] type: discovery - name: manual test: test for misconfigured AWS S3 Buckets manually, as part of a Pentest or Bug-bounty type: manual categories: [cloud] ================================================ FILE: api/tp_api/repo/weak-default-password.yaml ================================================ name: Weak/Default Passwords cwe: 521 categories: [app_vulns,owasp] description: The application allows the users to set default or weak passwords mitigations: - description: Ensure that passwords set in the application are mandatorily strong. phase: Architecture and Design - description: Prevent Credential Stuffing by validating user passwords against Database of compromised passwords phase: Architecture and Design test-cases: - name: automated-vulnerability-scanning test: run automated vulnerability discovery tools and bruteforce against the application tools: [zap,burpsuite,arachni,acunetix,netsparker,appspider,w3af] type: discovery ================================================ FILE: api/tp_api/repo/xss.yaml ================================================ name: Cross-Site Scripting cwe: 79 description: The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. mitigations: - description: Examples of libraries and frameworks that make it easier to generate properly encoded output include Microsoft's Anti-XSS library, the OWASP ESAPI Encoding module, and Apache Wicket. phase: Architecture and Design - description: Understand all the potential areas where untrusted inputs can enter your software. Parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls. phase: Architecture and Design - description: For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side. phase: Architecture and Design - description: If available, use structured mechanisms that automatically enforce the separation between data and code. These mechanisms may be able to provide the relevant quoting, encoding, and validation automatically, instead of relying on the developer to provide this capability at every point where output is generated. phase: Architecture and Design - description: The problem of inconsistent output encodings often arises in web pages. If an encoding is not specified in an HTTP header, web browsers often guess about which encoding is being used. This can open up the browser to subtle XSS attacks. phase: Implementation - description: To help mitigate XSS attacks against the user's session cookie, set the session cookie to be HttpOnly. In browsers that support the HttpOnly feature (such as more recent versions of Internet Explorer and Firefox), this attribute can prevent the user's session cookie from being accessible to malicious client-side scripts that use document.cookie. This is not a complete solution, since HttpOnly is not supported by all browsers. More importantly, XMLHTTPRequest and other powerful browser technologies provide read access to HTTP headers, including the Set-Cookie header in which the HttpOnly flag is set. phase: Implementation - description: Ensure that you perform input validation at well-defined interfaces within the application. This will help protect the application even if a component is reused or moved elsewhere. phase: Implementation - description: When the set of acceptable objects, such as filenames or URLs, is limited or known, create a mapping from a set of fixed input values (such as numeric IDs) to the actual filenames or URLs, and reject all other inputs. phase: Architecture and Design - description: Use an application firewall that can detect attacks against this weakness. It can be beneficial in cases in which the code cannot be fixed (because it is controlled by a third party), as an emergency prevention measure while more comprehensive software assurance measures are applied, or to provide defense in depth. phase: Operation - description: Use a Content-Security-Policy Header for your application that is honored by a modern browser. Content Security Policy allows you to define specific execution scopes for attributes and elements that can be used to perform Cross-Site Scripting. phase: Implementation - description: Deploy a Cross-Origin-Resource Sharing implementation to prevent your application's front-end from accessing unauthorized third-party URLs that may be part of an attacker's Cross-Site Scripting Attack phase: Implementation categories: [app_vulns,owasp] risk: - consequence: The most common attack performed with cross-site scripting involves the disclosure of information stored in user cookies. Typically, a malicious user will craft a client-side script, which -- when parsed by a web browser -- performs some activity (such as sending all site cookies to a given E-mail address). This script will be loaded and run by each user visiting the web site. Since the site requesting to run the script has access to the cookies in question, the malicious script does also. type: Access_Control - consequence: In some circumstances it may be possible to run arbitrary code on a victim's computer when cross-site scripting is combined with other flaws. type: Integrity - consequence: The consequence of an XSS attack is the same regardless of whether it is stored or reflected. The difference is in how the payload arrives at the server. type: Confidentiality variants: - Persistent Cross-Site Scripting - Reflected Cross-Site Scripting - DOM-Based Cross Site Scripting test-cases: - name: automated-vulnerability-scanning test: run automated vulnerability discovery tools and its XSS payloads against the application tools: [zap,burpsuite,arachni,acunetix,netsparker,appspider,w3af] type: discovery - name: manual test: test for XSS variants manually with pentesters, bug-bounty type: manual - name: content-security-policy test: Look for Content Security Policy headers in the Application and validate if the application enforces content-security-policy headers with optimal efficacy type: recon - name: cors test: Look for Cross-Origin Resource Sharing to ensure that the application is unable to make calls to URLs outside a specific set of whitelisted URLs and domains type: discovery - name: static-analysis test: Run Static Analysis tools to identify instances of improper input validation and output encoding for Cross-Site Scripting tools: [checkmarx,brakeman,bandit,pyt,security-code-scan,veracode,nodejsscan,coverity,] type: sast - name: source-composition-scanning test: Run Source Composition Scanners against the libraries being used by the application, to identify instances of Cross-Site Scripting tools: [retirejs,npm-audit,owasp-dependency-checker,blackduck,whitesource,snyk,safety] type: sca related_cwes: - 80 - 116 ================================================ FILE: api/tp_api/repo/xxe.yaml ================================================ name: XML External Entities cwe: 611 description: The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output. categories: [app_vulns,owasp] mitigations: - description: XML parsers and validators must be configured to disable external entity expansion, general entities and parameter entity resolution phase: Implementation risk: - consequence: If the attacker is able to include a crafted DTD and a default entity resolver is enabled, the attacker may be able to access arbitrary files on the system. type: Confidentiality - consequence: The DTD may include arbitrary HTTP requests that the server may execute. This could lead to other attacks leveraging the server's trust relationship with other entities. type: Integrity - consequence: The software could consume excessive CPU cycles or memory using a URI that points to a large file, or a device that always returns data such as /dev/random. Alternately, the URI could reference a file that contains many nested or recursive entity references to further slow down parsing. type: Availability test-cases: - name: automated-vulnerability-scanning test: run automated vulnerability discovery tools and its XXE payloads against the application tools: [zap,burpsuite,arachni,acunetix,netsparker,appspider,w3af] type: discovery - name: manual test: test for XXE variants manually with pentesters, bug-bounty type: manual - name: source-composition-scanning test: Run Source Composition Scanners against the libraries being used by the application, to identify instances of XXE tools: [retirejs,npm-audit,owasp-dependency-checker,blackduck,whitesource,snyk,safety] type: sca - name: static-analysis test: Run Static Analysis tools to identify instances of dynamic queries or stored procedures that are vulnerable to XXE tools: [checkmarx,brakeman,bandit,pyt,security-code-scan,veracode,nodejsscan,coverity] type: sast ================================================ FILE: api/tp_api/swagger/abuse-create.yml ================================================ This is the API Endpoint that is used to create/update Abuser Stories linked to Feature/User Story --- parameters: - name: body in: body required: true schema: id: Abuser Story type: object required: - short_name - description - feature properties: short_name: type: string description: type: string feature: type: string responses: 200: description: Abuser Story successfully created 400: description: Input Validation Errors or other client Errors 404: description: Unable to find Feature/User Story ================================================ FILE: api/tp_api/swagger/change-password.yml ================================================ This is the API Endpoint that is used to change an existing user's password in ThreatPlaybook --- requestBody: required: true content: application/json: schema: type: object properties: email: type: string old_password: type: string new_password: type: string verify_password: type: string ================================================ FILE: api/tp_api/swagger/feature-create.yml ================================================ This is the API Endpoint that is used to create and update a User Story/Feature. --- parameters: - name: body in: body required: true schema: id: Feature type: object required: - short_name - description - project properties: short_name: type: string description: type: string project: type: string responses: 200: description: Feature/User Story successfully created 400: description: Input Validation Errors or other client Errors 404: description: Unable to find Project ================================================ FILE: api/tp_api/swagger/get-abuse.yml ================================================ This is the API Endpoint that is used retrieve a single Abuser Story or multiple Abuser Stories --- parameters: - name: body in: body required: true schema: id: Abuser Story type: object required: - feature properties: name: type: string page: type: integer feature: type: string responses: 200: description: Project or Projects successfully retrieved 404: description: Unable to find Scan or Target ================================================ FILE: api/tp_api/swagger/get-feature.yml ================================================ This is the API Endpoint that is used retrieve a single Feature/User Story or multiple Features/User Stories --- parameters: - name: body in: body schema: id: Feature type: object properties: name: type: string page: type: integer project: type: string responses: 200: description: Project or Projects successfully retrieved 404: description: Unable to find Scan or Target ================================================ FILE: api/tp_api/swagger/get-project.yml ================================================ This is the API Endpoint that is used retrieve a single Project or multiple Projects --- parameters: - name: body in: body schema: id: Project type: object properties: name: type: string responses: 200: description: Project or Projects successfully retrieved 404: description: Unable to find Scan or Target ================================================ FILE: api/tp_api/swagger/get-scenario.yml ================================================ This is the API Endpoint that is used retrieve a single Abuser Story or multiple Abuser Stories --- parameters: - name: body in: body required: true schema: id: Threat Scenario type: object required: - abuser_story properties: name: type: string page: type: integer abuser_story: type: string responses: 200: description: Threat Scenario or Scenarios successfully retrieved 404: description: Unable to find Threat Scenario or Abuser Story ================================================ FILE: api/tp_api/swagger/get-tests.yml ================================================ This is the API Endpoint that is used retrieve a single Abuser Story or multiple Abuser Stories --- parameters: - name: body in: body required: true schema: id: Security Test Case type: object required: - scenario properties: name: type: string page: type: integer scenario: type: string responses: 200: description: Project or Projects successfully retrieved 404: description: Unable to find Threat Scenario or Test Cases ================================================ FILE: api/tp_api/swagger/scan-create.yml ================================================ This is the API Endpoint that is used to create a scan for storing Vulnerability Results in the Database --- parameters: - name: body in: body required: true schema: id: Scan type: object required: - tool - target properties: tool: type: string target: type: string scan_type: type: string responses: 200: description: Scan successfully created 400: description: Input Validation Errors or other client Errors 404: description: Unable to find Target ================================================ FILE: api/tp_api/swagger/scenario-inline.yml ================================================ This is the API Endpoint that is used to create and update Inline Threat Scenarios that are NOT linked to existing Vulnerability Repositories --- parameters: - name: body in: body required: true schema: id: Threat Scenario type: object required: - name - abuser_story - feature - type - cwe - description - severity - vul_name properties: name: type: string description: type: string feature: type: string abuser_story: type: string type: type: string vul_name: type: string severity: type: integer cwe: type: integer responses: 200: description: Threat Scenario successfully created 400: description: Input Validation Errors or other client Errors 404: description: Unable to find User Story OR Abuser Story OR Repo Item ================================================ FILE: api/tp_api/swagger/scenario-repo.yml ================================================ This is the API Endpoint that is used to create and update Threat Scenarios that are linked to existing Vulnerability Repositories --- parameters: - name: body in: body required: true schema: id: Threat Scenario type: object required: - name - abuser_story - feature - type - repo_name - description properties: name: type: string description: type: string feature: type: string abuser_story: type: string type: type: string repo_name: type: string responses: 200: description: Threat Scenario successfully created 400: description: Input Validation Errors or other client Errors 404: description: Unable to find User Story OR Abuser Story OR Repo Item ================================================ FILE: api/tp_api/swagger/target-create-update.yml ================================================ This is the API Endpoint to create and update Targets for Vulnerability Scanning and Management --- securitySchemes: bearerAuth: type: http scheme: bearer format: JWT parameters: - name: body in: body required: true schema: id: Target type: object required: - name - url - project properties: name: type: string url: type: string project: type: string responses: 200: description: Target successfully created 400: description: Input Validation Errors or other client Errors 404: description: Unable to find Project ================================================ FILE: api/tp_api/swagger/test-case-create.yml ================================================ This is the API Endpoint to create and update Security Test Cases a.k.a Test Cases --- parameters: - name: body in: body required: true schema: id: Security Test Case type: object required: - test_case - name - threat_scenario - tools - tags - executed - test_type properties: name: type: string test_case: type: string threat_scenario: type: string tools: type: array items: type: string tags: type: array items: type: string executed: type: boolean test_type: type: string responses: 200: description: Test Case successfully created 400: description: Input Validation Errors or other client Errors 404: description: Unable to find threat scenario ================================================ FILE: api/tp_api/swagger/vulnerability-create.yml ================================================ This is the API Endpoint that is used to create a scan for storing Vulnerability Results in the Database --- parameters: - name: body in: body required: true schema: id: Vulnerability type: object required: - scan - name - vul_name - cwe properties: scan: type: string name: type: string description: type: string remediation: type: string observation: type: string vul_name: type: string cwe: type: integer evidences: type: array items: type: object properties: log: type: string url: type: string param: type: string line_num: type: integer attack: type: string info: type: string responses: 200: description: Vulnerability successfully created 400: description: Input Validation Errors or other client Errors 404: description: Unable to find Scan or Target ================================================ FILE: api/tp_api/utils.py ================================================ from mongoengine import * from loguru import logger from sys import exit import os from models import * from glob import glob import ntpath import yaml import bcrypt import csv from flask import jsonify logger.add("logs/output.log", backtrace=True, diagnose=True) def respond(success, error, message="", data=None): respond_dict = { "success": success, "error": error, } if message: respond_dict["message"] = message if data: respond_dict["data"] = data return jsonify(respond_dict) def connect_db(): if "MONGO_USER" not in os.environ: db = connect(os.environ.get("MONGO_DB", "threat_playbook")) else: try: db = connect( username=os.environ.get("MONGO_USER"), password=os.environ.get("MONGO_PASS"), host=os.environ.get("MONGO_HOST", "127.0.0.1"), db=os.environ.get("MONGO_DB", "threat_playbook"), port=int(os.environ.get("MONGO_PORT", 27017)), ) except Exception as e: logger.exception(e) print("Unable to connect to Database. Please see log for exception") exit(1) return db def load_reload_asvs_db(): if not ASVS.objects: asvs_file = os.path.join(os.path.abspath(os.path.curdir), "asvs/asvs.csv") if os.path.isfile(asvs_file): with open(asvs_file, "rt") as asvs_file: data = csv.reader(asvs_file) for row in data: cwe = row[7] if not cwe: cwe = 0 else: cwe = int(row[7]) new_item = ASVS( section=row[0], name=row[1], item=row[2], description=row[3], l1=row[4] or False, l2=row[5] or False, l3=row[6] or False, cwe=cwe, nist=row[8] or "", ).save() def load_reload_repo_db(): if not Repo.objects: print("No Repo items found. Loading...") repo_path = os.path.join(os.path.abspath(os.path.curdir), "repo/") for single in glob(repo_path + "*.yaml"): single_name = ntpath.basename(single).split(".")[0] with open(single, "r") as rfile: rval = rfile.read() rcon = yaml.safe_load(rval) test_case_list = [] test_case_load = rcon.get("test-cases", []) try: if test_case_load: for single in test_case_load: new_test_case = RepoTestCase( name=single.get("name", ""), test_case=single.get("test", ""), tools=single.get("tools", []), type=single.get("type", ""), tags=single.get("tags", []), ).save() test_case_list.append(new_test_case.id) new_repo_object = Repo( short_name=single_name, name=rcon["name"], cwe=rcon["cwe"], description=rcon.get("description", ""), mitigations=rcon.get("mitigations", []), risks=rcon.get("mitigations", []), categories=rcon.get("categories", []), variants=rcon.get("variants", []), related_cwes=rcon.get("related_cwes", []), tests=test_case_list, ).save() except Exception as e: logger.exception(e) print("Unable to load Repo Objects. Please see log") def initialize_superuser(): if not User.objects or not User.objects(user_type="super"): if "SUPERUSER_EMAIL" not in os.environ: print("Mandatory variable SUPERUSER_EMAIL not present") exit(1) else: admin_pass = os.environ.get("SUPERUSER_PASS", "pl@yb00k1234") hash_pass = bcrypt.hashpw(admin_pass.encode(), bcrypt.gensalt()).decode() User( email=os.environ.get("SUPERUSER_EMAIL"), password=hash_pass, user_type="super", ).save() print("Initialized SuperUser with default password") ================================================ FILE: api/tp_api/wait-for ================================================ #!/bin/sh TIMEOUT=90 QUIET=0 echoerr() { if [ "$QUIET" -ne 1 ]; then printf "%s\n" "$*" 1>&2; fi } usage() { exitcode="$1" cat << USAGE >&2 Usage: $cmdname host:port [-t timeout] [-- command args] -q | --quiet Do not output any status messages -t TIMEOUT | --timeout=timeout Timeout in seconds, zero for no timeout -- COMMAND ARGS Execute command with args after the test finishes USAGE exit "$exitcode" } wait_for() { for i in `seq $TIMEOUT` ; do nc -z "$HOST" "$PORT" > /dev/null 2>&1 result=$? if [ $result -eq 0 ] ; then if [ $# -gt 0 ] ; then exec "$@" fi exit 0 fi sleep 1 done echo "Operation timed out" >&2 exit 1 } while [ $# -gt 0 ] do case "$1" in *:* ) HOST=$(printf "%s\n" "$1"| cut -d : -f 1) PORT=$(printf "%s\n" "$1"| cut -d : -f 2) shift 1 ;; -q | --quiet) QUIET=1 shift 1 ;; -t) TIMEOUT="$2" if [ "$TIMEOUT" = "" ]; then break; fi shift 2 ;; --timeout=*) TIMEOUT="${1#*=}" shift 1 ;; --) shift break ;; --help) usage 0 ;; *) echoerr "Unknown argument: $1" usage 1 ;; esac done if [ "$HOST" = "" -o "$PORT" = "" ]; then echoerr "Error: you need to provide a host and port to test." usage 2 fi wait_for "$@" ================================================ FILE: docker-compose.yml ================================================ version: '3' services: nginx: image: we45/threatplaybook-nginx:latest ports: - "80:80" depends_on: - api links: - api mongo_db: image: 'docker.io/bitnami/mongodb:4.2-debian-10' volumes: - './playbook:/bitnami/mongodb' environment: - MONGODB_USERNAME=threatplaybook - MONGODB_PASSWORD=password123 - MONGODB_DATABASE=threat_playbook expose: - "27017" api: image: we45/threatplaybook-server:latest expose: - "5000" environment: - MONGO_HOST=mongo_db - MONGO_USER=threatplaybook - MONGO_PASS=password123 - MONGO_PORT=27017 - MONGO_DB=threat_playbook - SUPERUSER_EMAIL=admin@admin.com - SUPERUSER_PASS=supersecret - JWT_PASS=VGCxqDnhsN6vNQVqmXtrNVVe1AS36ZMQKTq6lYpj0ygHiuWunMOkFi2j17cHSbG-WId9x_yJpeSqy0TTFjs06Q - WAIT_HOSTS=mongo_db:27017 links: - mongo_db depends_on: - mongo_db command: sh -c "/app/wait-for mongo_db:27017 -- /usr/local/bin/python /app/app.py" frontend: image: we45/threatplaybook-frontend:latest environment: - VUE_APP_API_URL=http://api links: - api depends_on: - api ================================================ FILE: documentation/.gitignore ================================================ # Dependencies /node_modules # Production /build # Generated files .docusaurus .cache-loader # Misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: documentation/README.md ================================================ # Website This website is built using [Docusaurus 2](https://v2.docusaurus.io/), a modern static website generator. ### Installation ``` $ yarn ``` ### Local Development ``` $ yarn start ``` This command starts a local development server and open up a browser window. Most changes are reflected live without having to restart the server. ### Build ``` $ yarn build ``` This command generates static content into the `build` directory and can be served using any static contents hosting service. ### Deployment ``` $ GIT_USER= USE_SSH=true yarn deploy ``` If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch. ================================================ FILE: documentation/babel.config.js ================================================ module.exports = { presets: [require.resolve('@docusaurus/core/lib/babel/preset')], }; ================================================ FILE: documentation/docs/client-ui.md ================================================ --- id: client-ui title: Web UI sidebar_label: Web UI --- #### Open Addressable IP Address on the browser ![Image](/img/login.png) >**Note:** Login using credentials ##### Once you logged in you should see a dashboard of Threat Playbook ![Image](/img/dashboard.png) ================================================ FILE: documentation/docs/configure-cli.md ================================================ --- id: configure-cli title: Configure CLI sidebar_label: Configure CLI --- ##### Create a Project Directory ``` mkdir -p /your/project/directory ``` ##### `cd` into your project directory ``` cd /your/project/directory ``` ##### Configure ``` playbook configure -e -u -p ``` > Please ensure that you substitute the following: > * `your-email` enter any email address, eample: admin@admin.com > * `host-info` for your addressable IP Address, example: 192.168.1.17 > * `port` for the nginx port, example: 80 ================================================ FILE: documentation/docs/create-project.md ================================================ --- id: create-project title: Create Project sidebar_label: Create Project --- ``` playbook apply project -n test-project ``` >**Note:** `test-project` is the name of the project. ### Create a single Feature with Threat Model * Now you'll be loading a story-driven threat model. It starts with the Feature/User-Story. * Each Feature/UserStory can have multiple Abuser Stories. * Each Abuser Story can have multiple Threat Scenarios * Each Threat Scenario can have multiple Test Cases and Mitigations #### Download example feature ``` wget -O feature.yaml https://raw.githubusercontent.com/we45/ThreatPlaybook-ClientV3/master/create-upload.yaml ``` #### Upload the features into `test-project` ``` playbook apply feature -f feature.yaml -p test-project ``` And that's it! You've created your first every Threat Model in ThreatPlaybook. ##### Of course, this is not all that ThreatPlaybook has to offer. It has: * A useful WebUI for viewing the Features/UserStories -> Abuser Stories -> Threat Models, Scans and more * Features for processing and managing Vulnerability Results ================================================ FILE: documentation/docs/install-client.md ================================================ --- id: client-install title: Install Client sidebar_label: Install Client --- ##### Mac ``` wget -O playbook https://github.com/we45/ThreatPlaybook-ClientV3/raw/master/dist/playbook_darwin64 && chmod +x playbook && mv playbook /usr/local/bin ``` ##### Linux ``` wget -O https://github.com/we45/ThreatPlaybook-ClientV3/raw/master/dist/playbook_linux64 playbook && chmod +x playbook && mv playbook /usr/bin ``` ##### Windows ``` https://github.com/we45/ThreatPlaybook-ClientV3/raw/master/dist/playbook_windows64.exe ``` > Please note that the CLI hasn't been tested on Windows OS #### Verify the cli installation ``` playbook -h ``` ================================================ FILE: documentation/docs/overview.md ================================================ --- id: overview title: Overview sidebar_label: Overview --- #### Threat Playbook has 3 components 1. Threat Playbook Server 2. Threat Playbook Client 3. Threat Playbook WebUI #### Prerequisite * Docker and Docker-Compose #### Container Images * API Container Image - Python Flask * MongoDB Container Image * VueJS Front-end Container Image * Nginx Reverse Proxy ================================================ FILE: documentation/docs/quick-installation.md ================================================ --- id: installation title: Install Server sidebar_label: Install Server --- ##### Download docker-compose file ``` git clone https://github.com/we45/ThreatPlaybook.git ``` ##### `cd` into the downloaded directory ``` cd ThreatPlaybook ``` > For Linux users, you might have to add another set of permissions for the MongoDB to work correctly. > > `sudo chown -R 1001 $PWD/playbook` ##### Run the Playbook server ``` docker-compose up -d ``` ================================================ FILE: documentation/docs/story-driven.md ================================================ --- id: story-driven title: Story-Driven Threat Modeling with ThreatPlaybook sidebar_label: Story-Driven Threat Modeling --- ## Objective In this tutorial, you will learn how you can create a story-driven threat model with ThreatPlaybook ## What is a Story-Driven Threat Model? ### User-Story Driven Threat Modeling Story-Driven Threat Modeling is different from System-Driven Threat Modeling that we are largely used to. Story-driven threat modeling starts with modeling user-stories (or feature definitions). The primary reasons behind story-driven threat modeling are: * **Speed** - Your Threat Models are able to keep pace with the Engineering Team's SDLC rather than a long-drawn system-wide threat model being performed on a periodic basis * **Focus** - The focus of your threat model in case of a story-driven threat model is the user-story itself. You waste little/no time on analyzing too many tangents * **Iterative** - Story-driven threat modeling evolves with the story. If the story changes, the threat model might change. It lends itself to more scalability and elasticity #### User Story/Feature The User Story is a Description of the Functionality. This concept is very popular in the world of Agile Development, where an Agile Team picks a bunch of user stories to get done in a sprint. It is a Unit of Work to be completed in a sprint. A user story typically looks like this > As a user (salesperson), I should be able to access my customer's profile to be able to log call information with the customer #### Abuser Story An Abuser Story is an "evil user's version" of a user story. An Abuser Story captures (at a high level) WHAT a threat actor can do to abuse the feature enumerated in the User Story. For example > As a rival salesperson, I will access other salespeople's customers in the application to poach customers from my colleagues #### Threat Model/Scenario A Threat Model/Scenario is a description of HOW a threat actor can bring the abuser story to life. This is a scenario detailing the Attack Vector (primary technique for attack) and approach to bringing the Abuser Story to life. One can use STRIDE as an approach to capture various threats and use DREAD/CVSSv3 to capture impact of said attack. For example: > Abuser Story: As a rival salesperson, I will access other salespeople's customers in the application to poach customers from my colleagues > > Threat Models: > * Attacker performs SQL Injection, to gain access to the Database of other customers in the System > * Attacker attempts to perform Insecure Direct Object Reference attacks, by incrementing the customer's ID value, gaining access to another customer's account > * Attacker steals a rival's session tokens by performing a Man-in-the-Middle Attack > .... ## Story-Driven Threat Modeling with ThreatPlaybook ### Start by making sure that you have your Server and CLI setup > Follow Steps 1 and 2 in the Quick Start Guide here ### Let's configure the CLI first > Currently, the CLI or the REST API are the only ways that data can be loaded into ThreatPlaybook. WebUI is view-only ##### Create a Project Directory ``` mkdir -p /your/project/directory ``` ##### `cd` into your project directory ``` cd /your/project/directory ``` ##### Configure ``` playbook configure -e -u -p ``` > Please ensure that you substitute the following: > * `your-email` enter any email address, eample: admin@admin.com > * `host-info` for your addressable IP Address, example: 192.168.1.17 > * `port` for the nginx port, example: 80 After this, the CLI prompts you for a password, which is the super-admin password that you've setup in Step 1 ### Let's create a Project > A Project is typically an application that you want to Threat Model. In the case of a micro-service, you may want to use either a single project or multiple projects if they are modeled and managed separately ```bash playbook apply project -n test-project ``` > `test-project` is the name of the project, in this case ### Let's create our User-Story/Feature YAML file In ThreatPlaybook, each user-story/feature is captured "as-code" in a single YAML file. The YAML file typically has a structure of: * Feature/User-Story * Abuser-Stories under the Feature/User-Story * Threat Scenarios under the Abuser Story * Test Cases for the Threat Scenario Let's look at a sample user-story/feature yaml ```yaml objectType: Feature #this is the user story name: create_upload_expense description: As a user, I am able to create and upload expenses within project limit that have been incurred by me for processing/payment by my manager, so I can get reimbursed abuse_cases: - name: manipulate expense information #this is an abuser story description: As a malicious user, I will manipulate expense management process to get larger or bogus expenses into the system. threat_scenarios: # these are the list of threat scenarios for the abuser story - name: sql injection expense limit bypass type: repo # repo type threat scenario description: Perform SQL Injection to compromise the Database, and raise project budget limits or bypass expense controls reference: {name: sql_injection, severity: 3} - name: upload-malware type: inline # inline type threat scenario description: I will upload malware as an expense to the system and compromise the application and create a DoS condition type: inline vul_name: Malicious File Upload severity: 3 cwe: 434 test-cases: - name: manual-pentesting test: upload files with reverse-shell and CSV injection payloads and attempt to trigger remote code execution on Project Manager's Computer type: exploit tools: manual ``` #### Let's examine this YAML file in more detail and some tips * ThreatPlaybook is name-based, so its important that you name your features/abuser-stories/threat-scenarios uniquely * Threat Scenarios can either be `repo` type or `inline` type: * **Repo Type**: ThreatPlaybook has a list of canned Vulnerability Definitions already pre-loaded in the system. Of course, you can create your own definitions as well. These form a repository or `repo`. So, when you want to declare a threat scenario is a `repo` type threat scenario, all you have to do is refer to the name of your canned vulnerability, and ThreatPlaybook automatically enumerates the following from the repo: * CWE * Mitigations * Test cases * other metadata fields * **Inline type**: When you declare and use inline threat scenarios, you are defining and declaring the threat scenario `inline` with the YAML. In this case, there's no canned vulnerability and you are declaring that vulnerability definition on the fly. Here, you need to declare all these attributes yourself: * name * cwe * vul_name * test-cases * severity * description * test cases ### Push YAML to ThreatPlaybook server When you're done defining your YAML, all you have to do is to push the Story-driven threat model to the ThreatPlaybook Server. This can be done with: ```bash playbook apply feature -f -p test-project ``` > You'll need to provide the absolute (full) path to the yaml file. Relative paths wont work If everything has worked, you should see a string of success messages of having created objects in ThreatPlaybook ================================================ FILE: documentation/docs/tutorial-client-ui.md ================================================ --- id: tutorial-client-ui title: Web UI sidebar_label: Web UI --- #### Open Addressable IP Address on the browser ![Image](/img/login.png) >**Note:** Login using credentials ##### Once you logged in you should see a dashboard of Threat Playbook ![Image](/img/dashboard.png) ================================================ FILE: documentation/docs/tutorial.md ================================================ --- id: tutorial title: Tutorial - Installation, Configuration and Extension sidebar_label: Installation and Configuration --- ##### Download docker-compose file ``` git clone https://github.com/we45/ThreatPlaybook.git ``` ##### `cd` into the downloaded directory ``` cd ThreatPlaybook ``` The ThreatPlaybook `docker-compose.yml` file has been written to get you up and running quickly. However, its not the best/most ideal configuration for running ThreatPlaybook, especially in prod. > Its meant only for experimental deployments on user's local machine ### Analyzing the Docker-Compose File ```yml version: '3' services: nginx: image: we45/threatplaybook-nginx:latest ports: - "80:80" depends_on: - api links: - api mongo_db: image: 'docker.io/bitnami/mongodb:4.2-debian-10' volumes: - '/tmp/playbook:/bitnami/mongodb' environment: - MONGODB_USERNAME=threatplaybook - MONGODB_PASSWORD=password123 - MONGODB_DATABASE=threat_playbook expose: - "27017" api: image: we45/threatplaybook-server:latest expose: - "5000" environment: - MONGO_HOST=mongo_db - MONGO_USER=threatplaybook - MONGO_PASS=password123 - MONGO_PORT=27017 - MONGO_DB=threat_playbook - SUPERUSER_EMAIL=admin@admin.com - SUPERUSER_PASS=supersecret - JWT_PASS=VGCxqDnhsN6vNQVqmXtrNVVe1AS36ZMQKTq6lYpj0ygHiuWunMOkFi2j17cHSbG-WId9x_yJpeSqy0TTFjs06Q - WAIT_HOSTS=mongo_db:27017 links: - mongo_db depends_on: - mongo_db command: sh -c "/app/wait-for mongo_db:27017 -- /usr/local/bin/python /app/app.py" frontend: image: we45/threatplaybook-frontend:latest environment: - VUE_APP_API_URL=http://api links: - api depends_on: - api ``` ### Change the Default Password! * The value set in the `SUPERUSER_EMAIL` and `SUPERUSER_PASS` are the values that ThreatPlaybook uses as the default values for the Superuser Account within ThreatPlaybook. > This is clearly a default password that you SHOULD NOT use as a permanent password to access the super-admin account on ThreatPlaybook. > > Please use `playbook change-password` feature in the CLI to change your default password. You have been warned! ### Logs There's a single output log that is generated in the `/app` directory within the container. If you want the logs to persist on a more permanent file-system, you'll need to volume mount a src path on your machine to the `/app/logs` path within the container. ``` # inside the container /app/logs # cat output.log 2020-06-21 10:41:01.282 | INFO | __main__:login:158 - User 'admin@admin.com' successfully logged in 2020-06-21 10:41:27.442 | INFO | __main__:create_project:191 - Successfully created project my-new-test 2020-06-21 10:41:40.753 | INFO | __main__:create_user_story:236 - Successfully created user-story/feature 'create_upload_expense' ``` ================================================ FILE: documentation/docusaurus.config.js ================================================ module.exports = { title: "Threat Playbook", tagline: "A (relatively) Unopinionated framework that faciliates Threat Modeling as Code married with Application Security Automation on a single Fabric", url: "https://your-docusaurus-test-site.com", baseUrl: "/", favicon: "img/favicon.ico", organizationName: "we45", projectName: "ThreatPlaybook", themeConfig: { navbar: { logo: { alt: "Logo", src: "img/logo.png", }, links: [ { to: "docs", activeBasePath: "/", label: "Documentation", position: "left", }, ], }, footer: { style: "dark", links: [ { title: "Community", items: [ { label: "Twitter", href: "https://twitter.com/we45", }, ], }, { title: "More", items: [ { label: "GitHub", href: "https://github.com/we45/ThreatPlaybook", }, ], }, ], copyright: `Copyright © ${new Date().getFullYear()} we45, Inc. Built with Docusaurus.`, }, }, presets: [ [ "@docusaurus/preset-classic", { docs: { homePageId: "overview", sidebarPath: require.resolve("./sidebars.js"), }, theme: { customCss: require.resolve("./src/css/custom.css"), }, }, ], ], }; ================================================ FILE: documentation/package.json ================================================ { "name": "documentation", "version": "0.0.0", "private": true, "scripts": { "start": "docusaurus start", "build": "docusaurus build", "swizzle": "docusaurus swizzle", "deploy": "docusaurus deploy" }, "dependencies": { "@docusaurus/core": "^2.0.0-alpha.58", "@docusaurus/preset-classic": "^2.0.0-alpha.58", "clsx": "^1.1.1", "react": "^16.8.4", "react-dom": "^16.8.4" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } ================================================ FILE: documentation/sidebars.js ================================================ module.exports = { someSidebar: { QuickStart: [ "overview", "installation", "client-install", "configure-cli", "create-project", "client-ui", ], Tutorial: ["tutorial", "story-driven", "tutorial-client-ui"], }, }; ================================================ FILE: documentation/src/css/custom.css ================================================ /* stylelint-disable docusaurus/copyright-header */ /** * Any CSS included here will be global. The classic template * bundles Infima by default. Infima is a CSS framework designed to * work well for content-centric websites. */ /* You can override the default Infima variables here. */ :root { --ifm-color-primary: #25c2a0; --ifm-color-primary-dark: rgb(33, 175, 144); --ifm-color-primary-darker: rgb(31, 165, 136); --ifm-color-primary-darkest: rgb(26, 136, 112); --ifm-color-primary-light: rgb(70, 203, 174); --ifm-color-primary-lighter: rgb(102, 212, 189); --ifm-color-primary-lightest: rgb(146, 224, 208); --ifm-code-font-size: 95%; } .docusaurus-highlight-code-line { background-color: rgb(72, 77, 91); display: block; margin: 0 calc(-1 * var(--ifm-pre-padding)); padding: 0 var(--ifm-pre-padding); } ================================================ FILE: documentation/src/pages/index.js ================================================ import React from 'react'; import clsx from 'clsx'; import Layout from '@theme/Layout'; import Link from '@docusaurus/Link'; import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; import useBaseUrl from '@docusaurus/useBaseUrl'; import styles from './styles.module.css'; const features = [ { title: <>Easy to Use, imageUrl: 'img/undraw_docusaurus_mountain.svg', description: ( <> Docusaurus was designed from the ground up to be easily installed and used to get your website up and running quickly. ), }, { title: <>Focus on What Matters, imageUrl: 'img/undraw_docusaurus_tree.svg', description: ( <> Docusaurus lets you focus on your docs, and we'll do the chores. Go ahead and move your docs into the docs directory. ), }, { title: <>Powered by React, imageUrl: 'img/undraw_docusaurus_react.svg', description: ( <> Extend or customize your website layout by reusing React. Docusaurus can be extended while reusing the same header and footer. ), }, ]; function Feature({imageUrl, title, description}) { const imgUrl = useBaseUrl(imageUrl); return (
{imgUrl && (
{title}
)}

{title}

{description}

); } function Home() { const context = useDocusaurusContext(); const {siteConfig = {}} = context; return (

{siteConfig.title}

{siteConfig.tagline}

Get Started
{/*
{features && features.length > 0 && (
{features.map((props, idx) => ( ))}
)}
*/}
); } export default Home; ================================================ FILE: documentation/src/pages/styles.module.css ================================================ /* stylelint-disable docusaurus/copyright-header */ /** * CSS files with the .module.css suffix will be treated as CSS modules * and scoped locally. */ .heroBanner { padding: 4rem 0; text-align: center; position: relative; overflow: hidden; } @media screen and (max-width: 966px) { .heroBanner { padding: 2rem; } } .buttons { display: flex; align-items: center; justify-content: center; } .features { display: flex; align-items: center; padding: 2rem 0; width: 100%; } .featureImage { height: 200px; width: 200px; } ================================================ FILE: documentation/static/.nojekyll ================================================ ================================================ FILE: frontend/Playbook-Frontend/.babelrc ================================================ { "env": { "test": { "presets": [ [ "@babel/preset-env", { "targets": { "node": "current" } } ] ] } } } ================================================ FILE: frontend/Playbook-Frontend/.editorconfig ================================================ # editorconfig.org root = true [*] indent_style = space indent_size = 2 end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true [*.md] trim_trailing_whitespace = false ================================================ FILE: frontend/Playbook-Frontend/.gitignore ================================================ # Created by .ignore support plugin (hsz.mobi) ### Node template # Logs /logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* # Runtime data pids *.pid *.seed *.pid.lock # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage # nyc test coverage .nyc_output # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) .grunt # Bower dependency directory (https://bower.io/) bower_components # node-waf configuration .lock-wscript # Compiled binary addons (https://nodejs.org/api/addons.html) build/Release # Dependency directories node_modules/ jspm_packages/ # TypeScript v1 declaration files typings/ # Optional npm cache directory .npm # Optional eslint cache .eslintcache # Optional REPL history .node_repl_history # Output of 'npm pack' *.tgz # Yarn Integrity file .yarn-integrity # dotenv environment variables file .env # parcel-bundler cache (https://parceljs.org/) .cache # next.js build output .next # nuxt.js build output .nuxt # Nuxt generate dist # vuepress build output .vuepress/dist # Serverless directories .serverless # IDE / Editor .idea # Service worker sw.* # macOS .DS_Store # Vim swap files *.swp ================================================ FILE: frontend/Playbook-Frontend/Dockerfile ================================================ FROM node:12 COPY dist ./dist RUN npm install -g serve ENV PORT=80 CMD serve -s dist -p 80 ================================================ FILE: frontend/Playbook-Frontend/README.md ================================================ # Playbook-Frontend > My swell Nuxt.js project ## Build Setup ```bash # install dependencies $ yarn install # serve with hot reload at localhost:3000 $ yarn dev # build for production and launch server $ yarn build $ yarn start # generate static project $ yarn generate ``` For detailed explanation on how things work, check out [Nuxt.js docs](https://nuxtjs.org). ================================================ FILE: frontend/Playbook-Frontend/assets/variables.scss ================================================ // Ref: https://github.com/nuxt-community/vuetify-module#customvariables // // The variables you want to modify // $font-size-root: 20px; // assets/variables.scss // Variables you want to modify $btn-border-radius: 0px; // If you need to extend Vuetify SASS lists // $material-light: ( cards: blue ); @import '~vuetify/src/styles/styles.sass'; ================================================ FILE: frontend/Playbook-Frontend/components/Logo.vue ================================================ ================================================ FILE: frontend/Playbook-Frontend/components/README.md ================================================ # COMPONENTS **This directory is not required, you can delete it if you don't want to use it.** The components directory contains your Vue.js Components. _Nuxt.js doesn't supercharge these components._ ================================================ FILE: frontend/Playbook-Frontend/components/VuetifyLogo.vue ================================================ ================================================ FILE: frontend/Playbook-Frontend/components/project/Content.vue ================================================ ================================================ FILE: frontend/Playbook-Frontend/components/project/Header.vue ================================================ ================================================ FILE: frontend/Playbook-Frontend/components/projects/ProjectsPage.vue ================================================ ================================================ FILE: frontend/Playbook-Frontend/jest.config.js ================================================ module.exports = { moduleNameMapper: { '^@/(.*)$': '/$1', '^~/(.*)$': '/$1', '^vue$': 'vue/dist/vue.common.js' }, moduleFileExtensions: [ 'js', 'vue', 'json' ], transform: { '^.+\\.js$': 'babel-jest', '.*\\.(vue)$': 'vue-jest' }, collectCoverage: true, collectCoverageFrom: [ '/components/**/*.vue', '/pages/**/*.vue' ] } ================================================ FILE: frontend/Playbook-Frontend/jsconfig.json ================================================ { "compilerOptions": { "baseUrl": ".", "paths": { "~/*": ["./*"], "@/*": ["./*"], "~~/*": ["./*"], "@@/*": ["./*"] } }, "exclude": ["node_modules", ".nuxt", "dist"] } ================================================ FILE: frontend/Playbook-Frontend/layouts/default.vue ================================================ ================================================ FILE: frontend/Playbook-Frontend/layouts/error.vue ================================================ ================================================ FILE: frontend/Playbook-Frontend/layouts/main.vue ================================================ ================================================ FILE: frontend/Playbook-Frontend/middleware/README.md ================================================ # MIDDLEWARE **This directory is not required, you can delete it if you don't want to use it.** This directory contains your application middleware. Middleware let you define custom functions that can be run before rendering either a page or a group of pages. More information about the usage of this directory in [the documentation](https://nuxtjs.org/guide/routing#middleware). ================================================ FILE: frontend/Playbook-Frontend/nuxt.config.js ================================================ import colors from "vuetify/es5/util/colors"; export default { mode: "universal", /* ** Headers of the page */ head: { titleTemplate: "%s - " + process.env.npm_package_name, title: process.env.npm_package_name || "", meta: [ { charset: "utf-8" }, { name: "viewport", content: "width=device-width, initial-scale=1" }, { hid: "description", name: "description", content: process.env.npm_package_description || "" } ], link: [{ rel: "icon", type: "image/x-icon", href: "/favicon.ico" }] }, /* ** Customize the progress-bar color */ env: { VUE_APP_API_URL: process.env.VUE_APP_API_URL }, loading: { color: "#fff" }, /* ** Global CSS */ css: [], /* ** Plugins to load before mounting the App */ plugins: [ { src: "~plugins/vue-apexchart.js", ssr: false }, { src: "~plugins/vue-organization-chart.js", ssr: false } ], /* ** Nuxt.js dev-modules */ buildModules: ["@nuxtjs/vuetify"], /* ** Nuxt.js modules */ modules: [ // Doc: https://axios.nuxtjs.org/usage "@nuxtjs/axios", "@nuxtjs/auth" ], /* ** Axios module configuration ** See https://axios.nuxtjs.org/options */ axios: { baseURL: process.env.VUE_APP_API_URL }, /* ** vuetify module configuration ** https://github.com/nuxt-community/vuetify-module */ vuetify: { customVariables: ["~/assets/variables.scss"], theme: { // disable: true, dark: false, themes: { dark: { primary: colors.blue.darken2, accent: colors.grey.darken3, secondary: colors.amber.darken3, info: colors.teal.lighten1, warning: colors.amber.base, error: colors.deepOrange.accent4, success: colors.green.accent3 } } } }, /* ** Build configuration */ build: { vendor: ["vue-apexchart"], /* ** You can extend webpack config here */ extend(config, ctx) { const vueLoader = config.module.rules.find( rule => rule.loader === "vue-loader" ); vueLoader.options.transformToRequire = { img: "src", image: "xlink:href", "b-img": "src", "b-img-lazy": ["src", "blank-src"], "b-card": "img-src", "b-card-img": "img-src", "b-carousel-slide": "img-src", "b-embed": "src" }; } } }; ================================================ FILE: frontend/Playbook-Frontend/package.json ================================================ { "name": "Playbook-Frontend", "version": "1.0.0", "description": "My swell Nuxt.js project", "author": "Tilak T", "private": true, "scripts": { "dev": "nuxt", "build": "nuxt build", "start": "nuxt start", "generate": "nuxt generate", "test": "jest" }, "dependencies": { "@nuxtjs/auth": "^4.9.1", "@nuxtjs/axios": "^5.3.6", "apexcharts": "^3.19.0", "nuxt": "^2.0.0", "uuid": "^8.0.0", "vue-apexcharts": "^1.5.3", "vue-organization-chart": "^1.1.6", "vuelidate": "^0.7.5" }, "devDependencies": { "@nuxtjs/vuetify": "^1.0.0", "@vue/test-utils": "^1.0.0-beta.27", "babel-jest": "^24.1.0", "jest": "^24.1.0", "vue-jest": "^4.0.0-0" } } ================================================ FILE: frontend/Playbook-Frontend/pages/home/index.vue ================================================ ================================================ FILE: frontend/Playbook-Frontend/pages/index.vue ================================================ ================================================ FILE: frontend/Playbook-Frontend/pages/projects/_name/abuser-story.vue ================================================ /* eslint-disable no-var */ ================================================ FILE: frontend/Playbook-Frontend/pages/projects/_name/project.vue ================================================ ================================================ FILE: frontend/Playbook-Frontend/pages/projects/_name/threat-map.vue ================================================ ================================================ FILE: frontend/Playbook-Frontend/pages/projects/_name/threat-scenario.vue ================================================ /* eslint-disable no-var */ ================================================ FILE: frontend/Playbook-Frontend/pages/projects/_name/user-story.vue ================================================ /* eslint-disable no-var */ ================================================ FILE: frontend/Playbook-Frontend/pages/projects/_name/vulnerabilities.vue ================================================ /* eslint-disable no-var */ ================================================ FILE: frontend/Playbook-Frontend/pages/projects/index.vue ================================================ ================================================ FILE: frontend/Playbook-Frontend/pages/scan/_name.vue ================================================ /* eslint-disable no-var */ ================================================ FILE: frontend/Playbook-Frontend/plugins/README.md ================================================ # PLUGINS **This directory is not required, you can delete it if you don't want to use it.** This directory contains Javascript plugins that you want to run before mounting the root Vue.js application. More information about the usage of this directory in [the documentation](https://nuxtjs.org/guide/plugins). ================================================ FILE: frontend/Playbook-Frontend/plugins/vue-apexchart.js ================================================ import Vue from "vue"; import VueApexCharts from "vue-apexcharts"; Vue.use({ install(Vue, options) { Vue.component("apexchart", VueApexCharts); } }); ================================================ FILE: frontend/Playbook-Frontend/plugins/vue-organization-chart.js ================================================ import Vue from "vue"; import OrganizationChart from "vue-organization-chart"; import "vue-organization-chart/dist/orgchart.css"; Vue.use({ install(Vue, options) { Vue.component("OrganizationChart", OrganizationChart); } }); ================================================ FILE: frontend/Playbook-Frontend/store/abuserStory.js ================================================ import axios from "axios"; const loginUrl = process.env.VUE_APP_API_URL; export const state = () => ({ isLoading: false, projectAbuserStoryTree: [] }); export const mutations = { IS_PAGE_LOADING(state, data) { state.isLoading = data; }, FETCH_PROJECT_ABUSER_STORY_TREE(state, data) { state.projectAbuserStoryTree = data; } }; export const actions = { showPageLoading({ commit }, data) { commit("IS_PAGE_LOADING", data); }, fetchAbuserStoryTreeByProject({ commit }, payload) { axios .post(loginUrl+"/api/abuser-story/project", payload, { headers: { Authorization: localStorage.getItem("token") } }) .then(res => { if (res.data.success) { commit("FETCH_PROJECT_ABUSER_STORY_TREE", res.data.data); } commit("IS_FETCHING", false); }) .catch(error => { commit("IS_FETCHING", false); if (error.response.status === 401) { } }); } }; export const getters = { isPageLoading(state) { return state.isLoading; }, getAbuserStoryProjectTree(state) { if (state.projectAbuserStoryTree) { return state.projectAbuserStoryTree; } } }; ================================================ FILE: frontend/Playbook-Frontend/store/home.js ================================================ export const state = () => ({ isLoading: false, data: [], projectCount: 0, userStoriesCount: 0, threatScenarioCount: 0, scanCount: 0, threatScenarioSevChart: [], severityChart: [] }) export const mutations = { IS_PAGE_LOADING(state, data) { state.isLoading = data }, FETCH_DATA(state, data) { state.data = data }, FETCH_PROJECT_COUNT(state, data) { state.projectCount = data }, FETCH_USER_STORIES_COUNT(state, data) { state.userStoriesCount = data }, FETCH_THREAT_SCENARIO_COUNT(state, data) { state.threatScenarioCount = data }, FETCH_SCAN_COUNT(state, data) { state.scanCount = data }, FETCH_THREAT_SCENARIO_SEVERITY_CHART(state, data) { state.threatScenarioSevChart = data }, FETCH_SEVERITY_CHART(state, data) { state.severityChart = data } } export const actions = { showPageLoading({ commit }, data) { commit('IS_PAGE_LOADING', data) }, fetchData({ commit }) { commit("IS_PAGE_LOADING", false); } } export const getters = { isPageLoading(state) { return state.isLoading }, getProjectCount(state) { if (state.projectCount) { return state.projectCount } }, getUserStoriesCount(state) { if (state.userStoriesCount) { return state.userStoriesCount } }, getThreatScenarioCount(state) { if (state.threatScenarioCount) { return state.threatScenarioCount } }, getScanCount(state) { if (state.scanCount) { return state.scanCount } }, getCountList(state) { if (state.data) { return state.data } }, fetchThreatScenarioSevChartData(state) { if (state.threatScenarioSevChart) { return state.threatScenarioSevChart } }, fetchSeverityChartData(state) { if (state.severityChart) { return state.severityChart } } } ================================================ FILE: frontend/Playbook-Frontend/store/index.js ================================================ export const state = () => ({}) export const getters = {} ================================================ FILE: frontend/Playbook-Frontend/store/login.js ================================================ import axios from "axios"; const loginUrl = process.env.VUE_APP_API_URL; export const state = () => ({ isLoading: false, token: "", errorMessage: "", isError: false }); export const mutations = { PAGE_LOADING(state, data) { state.isLoading = data; }, STORE_TOKEN(state, data) { state.token = data; localStorage.setItem("token", data); }, ERROR_MESSAGE(state, data) { state.errorMessage = data; }, ERROR_MESSAGE_STATUS(state, data) { state.isError = data; } }; export const actions = { pageLoadingError({ commit }, data) { commit("ERROR_MESSAGE_STATUS", data); }, pageLoading({ commit }, data) { commit("PAGE_LOADING", data); }, loginUser({ commit }, data) { axios .post("/api/login", data) .then(response => { if (response.data.success) { commit("STORE_TOKEN", response.data.data.token); commit("PAGE_LOADING", false); this.$router.push("/home"); } else { localStorage.removeItem("token"); commit("PAGE_LOADING", false); commit("ERROR_MESSAGE_STATUS", true); this.$router.push("/"); } commit("PAGE_LOADING", false); }) .catch(error => { if (error.response.status === 401) { commit("PAGE_LOADING", false); commit("ERROR_MESSAGE", "Invalid credentials"); commit("ERROR_MESSAGE_STATUS", true); } if (error.response.status === 502) { commit("PAGE_LOADING", false); commit("ERROR_MESSAGE", "Bad Gateway"); commit("ERROR_MESSAGE_STATUS", true); } if (error.response.status === 404) { commit("PAGE_LOADING", false); commit("ERROR_MESSAGE", "Page Not found"); commit("ERROR_MESSAGE_STATUS", true); } if (error.response.status === 403) { commit("PAGE_LOADING", false); commit("ERROR_MESSAGE", "Invalid credentials"); commit("ERROR_MESSAGE_STATUS", true); } commit("PAGE_LOADING", false); commit("ERROR_MESSAGE_STATUS", true); localStorage.removeItem("token"); this.$router.push("/"); }); } }; export const getters = { isPageLoading(state) { if (state.isLoading) { return state.isLoading; } }, userToken(state) { if (state.token) { return state.token; } }, loginErrorMessage(state) { if (state.errorMessage) { return state.errorMessage; } }, isLoginError(state) { if (state.isError) { return state.isError; } } }; ================================================ FILE: frontend/Playbook-Frontend/store/projects.js ================================================ import axios from "axios"; const loginUrl = process.env.VUE_APP_API_URL; export const state = () => ({ isLoading: false, data: [] }); export const mutations = { IS_PAGE_LOADING(state, data) { state.isLoading = data; }, FETCH_DATA(state, data) { state.data = data; } }; export const actions = { showPageLoading({ commit }, data) { commit("IS_PAGE_LOADING", data); }, fetchProjectData({ commit }) { axios .get("/api/project/read", { headers: { Authorization: localStorage.getItem("token") } }) .then(response => { if (response.data.success) { const projectData = []; for (const data of response.data.data) { projectData.push({ name: data.name }); } commit("FETCH_DATA", projectData); commit("IS_PAGE_LOADING", false); } commit("PAGE_LOADING", false); }) .catch(error => { if (error.response.status === 401) { commit("PAGE_LOADING", false); } }); } }; export const getters = { isPageLoading(state) { return state.isLoading; }, getProjectCount(state) { if (state.data) { return state.data.length; } }, getProjectData(state) { if (state.data) { return state.data; } } }; ================================================ FILE: frontend/Playbook-Frontend/store/scan.js ================================================ import axios from "axios"; const loginUrl = process.env.VUE_APP_API_URL; export const state = () => ({ isLoading: false, data: [], projectScanData: [], individualScanData: [] }); export const mutations = { IS_PAGE_LOADING(state, data) { state.isLoading = data; }, FETCH_DATA(state, data) { state.data = data; }, FETCH_SCAN_DATA_PROJECT(state, data) { state.projectScanData = data; }, FETCH_INDIVIDUAL_DATA(state, data) { state.individualScanData = data; } }; export const actions = { showPageLoading({ commit }, data) { commit("IS_PAGE_LOADING", data); }, fetchScanData({ commit }) { axios .get("/api/scan/read", { headers: { Authorization: localStorage.getItem("token") } }) .then(response => { if (response.data.success) { const scanData = []; for (const data of response.data.data) { scanData.push({ name: data.name }); } commit("FETCH_DATA", scanData); commit("IS_PAGE_LOADING", false); } commit("PAGE_LOADING", false); }) .catch(error => { if (error.response.status === 401) { commit("PAGE_LOADING", false); } }); }, fetchIndividualScanData({ commit }, payload) { axios .post("/api/scan-vuls/project", payload, { headers: { Authorization: localStorage.getItem("token") } }) .then(response => { if (response.data.success) { const scanData = []; for (const data of response.data.data) { scanData.push({ name: data.name, cwe: data.cwe, severity: data.severity, description: data.description }); } commit("FETCH_INDIVIDUAL_DATA", scanData); commit("IS_PAGE_LOADING", false); } commit("PAGE_LOADING", false); }) .catch(error => { if (error.response.status === 401) { commit("PAGE_LOADING", false); } }); }, fetchScanbyProject({ commit }, payload) { axios .post("/api/scan/project", payload, { headers: { Authorization: localStorage.getItem("token") } }) .then(response => { if (response.data.success) { const scanData = []; for (const scan of response.data.data.data) { scanData.push({ name: scan.name, scan_type: scan.scan_type, tool: scan.tool }); } commit("FETCH_SCAN_DATA_PROJECT", scanData); commit("IS_PAGE_LOADING", false); } commit("PAGE_LOADING", false); }) .catch(error => { if (error.response.status === 401) { commit("PAGE_LOADING", false); } }); } }; export const getters = { isPageLoading(state) { return state.isLoading; }, getScanCount(state) { if (state.data) { return state.data.length; } }, getScanProjectData(state) { if (state.projectScanData) { return state.projectScanData; } }, getScanIndividualData(state) { if (state.individualScanData) { return state.individualScanData; } } }; ================================================ FILE: frontend/Playbook-Frontend/store/threatScenario.js ================================================ import axios from "axios"; const loginUrl = process.env.VUE_APP_API_URL; export const state = () => ({ isLoading: false, data: [], sevData: [], projectScenarioData: [], projectScenarioTree: [] }); export const mutations = { IS_PAGE_LOADING(state, data) { state.isLoading = data; }, FETCH_DATA(state, data) { state.data = data; }, FETCH_SEV_DATA(state, data) { state.sevData = data; }, FETCH_PROJECT_THREAT_SCENARIO_DATA(state, data) { state.projectScenarioData = data; }, FETCH_PROJECT_THREAT_SCENARIO_TREE(state, data) { state.projectScenarioTree = data; } }; export const actions = { showPageLoading({ commit }, data) { commit("IS_PAGE_LOADING", data); }, fetchThreatScenarioData({ commit }) { axios .get("/api/scenarios/read", { headers: { Authorization: localStorage.getItem("token") } }) .then(response => { if (response.data.success) { const threatScenarioData = []; for (const data of response.data.data) { threatScenarioData.push({ name: data.name }); } commit("FETCH_DATA", threatScenarioData); commit("IS_PAGE_LOADING", false); } commit("PAGE_LOADING", false); }) .catch(error => { if (error.response.status === 401) { commit("PAGE_LOADING", false); } }); }, fetchThreatScenarioSevData({ commit }) { axios .get("/api/scenario/severity", { headers: { Authorization: localStorage.getItem("token") } }) .then(response => { if (response.data.success) { const donutSeries = []; const highCount = []; const mediumCount = []; const lowCount = []; for (const data of response.data.data) { if (data.severity === 3) { highCount.push(data.severity); } else if (data.severity === 2) { mediumCount.push(data.severity); } else { lowCount.push(data.severity); } } donutSeries.push(highCount.length); donutSeries.push(mediumCount.length); donutSeries.push(lowCount.length); commit("FETCH_SEV_DATA", donutSeries); commit("IS_PAGE_LOADING", false); } commit("PAGE_LOADING", false); }) .catch(error => { if (error.response.status === 401) { commit("PAGE_LOADING", false); } }); }, fetchProjectThreatScenarioData({ commit }, payload) { axios .post("/api/scenarios/project", payload, { headers: { Authorization: localStorage.getItem("token") } }) .then(response => { if (response.data.success) { const threatScenarioData = []; for (const data of response.data.data) { threatScenarioData.push({ name: data.name }); } commit("FETCH_PROJECT_THREAT_SCENARIO_DATA", threatScenarioData); commit("IS_PAGE_LOADING", false); } commit("PAGE_LOADING", false); }) .catch(error => { if (error.response.status === 401) { commit("PAGE_LOADING", false); } }); }, fetchThreatScenarioTreeByProject({ commit }, payload) { axios .post("/api/threat-scenario/project", payload, { headers: { Authorization: localStorage.getItem("token") } }) .then(res => { if (res.data.success) { commit("FETCH_PROJECT_THREAT_SCENARIO_TREE", res.data.data); } commit("IS_FETCHING", false); }) .catch(error => { commit("IS_FETCHING", false); if (error.response.status === 401) { } }); } }; export const getters = { get_project_scenario_count(state) { if (state.projectScenarioData) { return state.projectScenarioData.length; } }, isPageLoading(state) { return state.isLoading; }, getThreatScenarioCount(state) { if (state.data) { return state.data.length; } }, getThreatScenarioSevData(state) { if (state.sevData) { return state.sevData; } }, getThreatScenarioProjectTree(state) { if (state.projectScenarioTree) { return state.projectScenarioTree; } } }; ================================================ FILE: frontend/Playbook-Frontend/store/threatmap.js ================================================ import axios from "axios"; const loginUrl = process.env.VUE_APP_API_URL; export const state = () => ({ isLoading: false, threatMapDataProject: [] }); export const mutations = { IS_PAGE_LOADING(state, data) { state.isLoading = data; }, FETCH_THREAT_MAP_PROJECT(state, data) { state.threatMapDataProject = data; } }; export const actions = { showPageLoading({ commit }, data) { commit("IS_PAGE_LOADING", data); }, fetchThreatMapbyProject({ commit }, payload) { axios .post("/api/threatmap/project", payload, { headers: { Authorization: localStorage.getItem("token") } }) .then(response => { if (response.data.success) { commit("FETCH_THREAT_MAP_PROJECT", response.data.data); commit("IS_PAGE_LOADING", false); } commit("PAGE_LOADING", false); }) .catch(error => { if (error.response.status === 401) { commit("PAGE_LOADING", false); } }); } }; export const getters = { isPageLoading(state) { return state.isLoading; }, getThreatMapProjectData(state) { if (state.threatMapDataProject) { return state.threatMapDataProject; } } }; ================================================ FILE: frontend/Playbook-Frontend/store/userStory.js ================================================ import axios from "axios"; const loginUrl = process.env.VUE_APP_API_URL; export const state = () => ({ isLoading: false, data: [], userStorydata: [], projecytuserStorydata: [], projecytuserStoryID: [], projecytuserStoryTree: [], abuserStoryCount: 0 }); export const mutations = { IS_PAGE_LOADING(state, data) { state.isLoading = data; }, FETCH_DATA(state, data) { state.data = data; }, FETCH_PROJECT_USER_STORY_DATA(state, data) { state.projecytuserStorydata = data; }, FETCH_PROJECT_ABUSER_STORY_COUNT(state, data) { state.abuserStoryCount = data; }, FETCH_PROJECT_USER_STORY_ID(state, data) { state.projecytuserStoryID = data; }, FETCH_PROJECT_USER_STORY_TREE(state, data) { state.projecytuserStoryTree = data; } }; export const actions = { showPageLoading({ commit }, data) { commit("IS_PAGE_LOADING", data); }, fetchUserStoryData({ commit }) { axios .get("/api/feature/read", { headers: { Authorization: localStorage.getItem("token") } }) .then(response => { if (response.data.success) { const UserStoryData = []; for (const data of response.data.data) { UserStoryData.push({ name: data.short_name }); } commit("FETCH_DATA", UserStoryData); commit("IS_PAGE_LOADING", false); } commit("PAGE_LOADING", false); }) .catch(error => { if (error.response.status === 401) { commit("PAGE_LOADING", false); } }); }, fetchUserStoryByProject({ commit }, payload) { axios .post("/api/feature/read", payload, { headers: { Authorization: localStorage.getItem("token") } }) .then(res => { if (res.data.success) { const uStoryData = []; const aStoryData = []; const uStoryid = []; for (const u of res.data.data) { uStoryData.push({ name: u.short_name }); uStoryid.push(u._id.$oid); for (const c in u.abuses) { aStoryData.push(c.$oid); } } commit("FETCH_PROJECT_ABUSER_STORY_COUNT", aStoryData.length); commit("FETCH_PROJECT_USER_STORY_DATA", uStoryData); commit("FETCH_PROJECT_USER_STORY_ID", uStoryid); } commit("IS_FETCHING", false); }) .catch(error => { commit("IS_FETCHING", false); if (error.response.status === 401) { } }); }, fetchUserStoryTreeByProject({ commit }, payload) { axios .post("/api/user-story/project", payload, { headers: { Authorization: localStorage.getItem("token") } }) .then(res => { if (res.data.success) { commit("FETCH_PROJECT_USER_STORY_TREE", res.data.data); } commit("IS_FETCHING", false); }) .catch(error => { commit("IS_FETCHING", false); if (error.response.status === 401) { } }); } }; export const getters = { isPageLoading(state) { return state.isLoading; }, getUserStoryCount(state) { if (state.data) { return state.data.length; } }, getUserStoryProjectCount(state) { if (state.projecytuserStorydata) { return state.projecytuserStorydata.length; } }, getUserStoryProjectdata(state) { if (state.projecytuserStorydata) { return state.projecytuserStorydata; } }, getAbuserStoryProjectCount(state) { if (state.abuserStoryCount) { return state.abuserStoryCount; } }, getUserStoryProjectID(state) { if (state.projecytuserStoryID) { return state.projecytuserStoryID; } }, getUserStoryProjectTree(state) { if (state.projecytuserStoryTree) { return state.projecytuserStoryTree; } } }; ================================================ FILE: frontend/Playbook-Frontend/store/vulnerability.js ================================================ import axios from "axios"; const loginUrl = process.env.VUE_APP_API_URL; export const state = () => ({ isLoading: false, data: [], sevData: [], projectVuls: [], projectVulSevs: [], projectVulData: [], asvsData: [] }); export const mutations = { IS_PAGE_LOADING(state, data) { state.isLoading = data; }, FETCH_DATA(state, data) { state.data = data; }, FETCH_SEV_DATA(state, data) { state.sevData = data; }, FETCH_VULS_PROJECT(state, data) { state.projectVuls = data; }, FETCH_VULS_SEV_PROJECT(state, data) { state.projectVulSevs = data; }, FETCH_ASVS_DATA(state, data) { state.asvsData = []; state.asvsData = data; } }; export const actions = { showPageLoading({ commit }, data) { commit("IS_PAGE_LOADING", data); }, fetchVulnerabilitySevData({ commit }) { axios .get("/api/vulnerability/severity", { headers: { Authorization: localStorage.getItem("token") } }) .then(response => { if (response.data.success) { const pieChart = []; const highCount = []; const mediumCount = []; const lowCount = []; for (const data of response.data.data) { if (data.severity === 3) { highCount.push(data.severity); } else if (data.severity === 2) { mediumCount.push(data.severity); } else { lowCount.push(data.severity); } } pieChart.push(highCount.length); pieChart.push(mediumCount.length); pieChart.push(lowCount.length); commit("FETCH_SEV_DATA", pieChart); commit("IS_PAGE_LOADING", false); } commit("PAGE_LOADING", false); }) .catch(error => { if (error.response.status === 401) { commit("PAGE_LOADING", false); } }); }, fetchVulnerabilitybyProject({ commit }, payload) { axios .post("/api/vulnerability/project", payload, { headers: { Authorization: localStorage.getItem("token") } }) .then(response => { if (response.data.success) { const vulData = []; const pieSeries = []; const highPieCount = []; const mediumPieCount = []; const lowPieCount = []; for (const vul of response.data.data.data) { vulData.push({ name: vul.name, cwe: vul.cwe, severity: vul.severity, description: vul.description }); if (vul.severity === 3) { highPieCount.push(vul.severity); } else if (vul.severity === 2) { mediumPieCount.push(vul.severity); } else { lowPieCount.push(vul.severity); } } pieSeries.push(highPieCount.length); pieSeries.push(mediumPieCount.length); pieSeries.push(lowPieCount.length); commit("FETCH_VULS_PROJECT", vulData); commit("FETCH_VULS_SEV_PROJECT", pieSeries); commit("IS_PAGE_LOADING", false); } commit("PAGE_LOADING", false); }) .catch(error => { if (error.response.status === 401) { commit("PAGE_LOADING", false); } }); }, fetchASVSbyProject({ commit }, payload) { axios .post("/api/asvs", payload, { headers: { Authorization: localStorage.getItem("token") } }) .then(response => { if (response.data.success) { const vulData = []; for (const vul of response.data.data) { vulData.push({ name: vul.name, cwe: vul.cwe, item: vul.item, description: vul.description, l1: vul.l1, l2: vul.l2, l3: vul.l3, section: vul.section }); } commit("FETCH_ASVS_DATA", vulData); commit("IS_PAGE_LOADING", false); } commit("PAGE_LOADING", false); }) .catch(error => { if (error.response.status === 401) { commit("PAGE_LOADING", false); } }); } }; export const getters = { isPageLoading(state) { return state.isLoading; }, getVulnerabilitySevData(state) { if (state.sevData) { return state.sevData; } }, getVulnerabilityProjectCount(state) { if (state.projectVuls) { return state.projectVuls.length; } }, getVulnerabilityProjectSev(state) { if (state.projectVulSevs) { return state.projectVulSevs; } }, getVulnerabilityProjectData(state) { if (state.projectVuls) { return state.projectVuls; } }, getASVSData(state) { if (state.asvsData) { return state.asvsData; } } }; ================================================ FILE: frontend/Playbook-Frontend/test/Logo.spec.js ================================================ import { mount } from '@vue/test-utils' import Logo from '@/components/Logo.vue' describe('Logo', () => { test('is a Vue instance', () => { const wrapper = mount(Logo) expect(wrapper.isVueInstance()).toBeTruthy() }) }) ================================================ FILE: nginx/Dockerfile ================================================ FROM ubuntu:16.04 RUN apt-get update && apt-get install -y nginx && apt-get clean && rm -rf /var/lib/apt/lists/* RUN echo "daemon off;" >> /etc/nginx/nginx.conf RUN rm /etc/nginx/sites-enabled/default ADD sites-enabled/ /etc/nginx/sites-enabled/ EXPOSE 5000 EXPOSE 80 CMD ["/usr/sbin/nginx"] ================================================ FILE: nginx/alpine.df ================================================ FROM nginx:latest RUN echo "daemon off;" >> /etc/nginx/nginx.conf RUN rm /etc/nginx/sites-enabled/* ADD sites-enabled/ /etc/nginx/sites-enabled/ EXPOSE 5000 EXPOSE 80 CMD ["/usr/sbin/nginx"] ================================================ FILE: nginx/sites-enabled/tp_nginx ================================================ upstream frontend_server { server frontend:80 fail_timeout=1000; } server { listen 80; listen 5000; server_name 127.0.0.1; client_max_body_size 10G; autoindex off; gzip on; gzip_types text/plain text/css application/javascript; location /api { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; fastcgi_hide_header X-Powered-By; proxy_set_header Host $http_host; proxy_read_timeout 1000s; proxy_connect_timeout 1000s; proxy_send_timeout 1000s; proxy_pass http://api:5000; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; fastcgi_hide_header X-Powered-By; proxy_set_header Host $http_host; proxy_read_timeout 1000s; proxy_connect_timeout 1000s; proxy_send_timeout 1000s; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://frontend_server; break; } } }