├── tests ├── __init__.py ├── unit_tests │ ├── __init__.py │ ├── test_related_crypto_material.py │ ├── data │ │ └── codeql │ │ │ ├── fernet.sarif │ │ │ ├── aes.sarif │ │ │ ├── dsa.sarif │ │ │ └── rsa.sarif │ ├── test_certificate.py │ ├── conftest.py │ ├── test_utils.py │ └── test_algorithm.py └── integration_tests │ ├── __init__.py │ ├── test_cbom.py │ └── data │ ├── codeql │ ├── partial_results │ │ ├── symmetric_algorithms.sarif │ │ └── asymmetric_algorithms.sarif │ └── full.sarif │ └── cbom │ ├── cbom_exclusion_pattern.json │ └── cbom_full.json ├── cbom ├── cli │ ├── __init__.py │ └── cli.py ├── parser │ ├── __init__.py │ ├── utils.py │ ├── related_crypto_material.py │ ├── certificate.py │ └── algorithm.py ├── cryptocheck │ ├── __init__.py │ ├── validators.py │ ├── sarif.py │ └── cryptocheck.py ├── __init__.py ├── lib_utils.py └── resources │ ├── cryptocheck_schema.json │ ├── library.yml │ └── cryptocheck_rules.yml ├── MANIFEST.in ├── tox.ini ├── SECURITY.md ├── requirements.txt ├── .github └── workflows │ ├── pull_request.yml │ └── release.yml ├── CHANGELOG.rst ├── pyproject.toml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── .gitchangelog.rc ├── README.md └── LICENSE /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /cbom/cli/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /cbom/parser/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /cbom/cryptocheck/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/unit_tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/integration_tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /cbom/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '1.1.0' 2 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | recursive-include cbom/resources * 2 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | env_list = lint, sast, py{310, 311, 312} 3 | 4 | [testenv] 5 | description = Run unit tests with Pytest 6 | skip_install = True 7 | deps = 8 | -r {tox_root}/requirements.txt 9 | pytest 10 | commands = 11 | pytest --basetemp={env_tmp_dir} {posargs} 12 | 13 | [testenv:lint] 14 | description = Run lint scan with Ruff 15 | deps = 16 | ruff 17 | commands = 18 | ruff check . 19 | 20 | [testenv:sast] 21 | description = Run SAST scan with Bandit 22 | deps = 23 | ruff 24 | commands = 25 | ruff check ./cbom --select S 26 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | Cryptobom-forge is a best effort project , we will try to fix issues and welcome bug reports and feature requests. 6 | 7 | 8 | | Version | Supported | 9 | | ------- | ------------------ | 10 | | 1.0.0 | :white_check_mark: | 11 | 12 | ## Reporting a Vulnerability 13 | 14 | If you find a vulnerability please raise and issue and let us know! 15 | 16 | If you think you can fix then feel free to put it in a branch and raise a pull request. We appreciate the community support in helping make this tool accessible and useful to all. 17 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | attrs==23.1.0 2 | boolean.py==4.0 3 | build==1.0.3 4 | certifi==2024.7.4 5 | cffi==1.16.0 6 | charset-normalizer==3.3.2 7 | click~=8.1.7 8 | cyclonedx-python-lib @ git+https://git@github.com/pre-quantum-research/cyclonedx-python-lib.git@cbom#egg=cyclonedx-python-lib 9 | defusedxml==0.7.1 10 | gitchangelog==3.0.4 11 | idna==3.7 12 | iniconfig==2.0.0 13 | jsonschema==4.20.0 14 | jsonschema-specifications==2023.11.1 15 | license-expression==30.1.1 16 | packageurl-python==0.11.2 17 | packaging==23.2 18 | pbr==6.0.0 19 | pluggy==1.3.0 20 | py-serializable==0.11.1 21 | pycparser==2.21 22 | pyproject_hooks==1.0.0 23 | pystache==0.6.5 24 | pytest==7.4.3 25 | pyyaml==6.0.1 26 | referencing==0.31.0 27 | requests==2.32.0 28 | rpds-py==0.13.1 29 | sortedcontainers==2.4.0 30 | tox==4.11.4 31 | urllib3==2.2.2 32 | -------------------------------------------------------------------------------- /cbom/lib_utils.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | 3 | import yaml 4 | from requests.structures import CaseInsensitiveDict 5 | 6 | with open(Path(__file__).absolute().parent / 'resources/library.yml') as data: 7 | YAML_LIBRARY = yaml.safe_load(data) 8 | 9 | 10 | def get_algorithms(): 11 | return YAML_LIBRARY['crypto']['algorithms'] 12 | 13 | 14 | def get_block_modes(): 15 | return YAML_LIBRARY['crypto']['block-modes'] 16 | 17 | 18 | def get_functions(): 19 | return YAML_LIBRARY['crypto']['functions'] 20 | 21 | 22 | def get_key_lengths(): 23 | return YAML_LIBRARY['crypto']['key-lengths'] 24 | 25 | 26 | def get_padding_schemes(): 27 | return YAML_LIBRARY['crypto']['padding-schemes'] 28 | 29 | 30 | def get_primitive_mapping(algorithm): 31 | return CaseInsensitiveDict(YAML_LIBRARY['crypto']['primitive-mappings']).get(algorithm, 'unknown') 32 | -------------------------------------------------------------------------------- /tests/unit_tests/test_related_crypto_material.py: -------------------------------------------------------------------------------- 1 | from cbom.parser import related_crypto_material 2 | 3 | 4 | def test_private_key__should_extract_key_size_for_key(cbom, rsa): 5 | related_crypto_material.parse_private_key(cbom, rsa) 6 | 7 | assert len(cbom.components) == 1 8 | assert cbom.components[0].crypto_properties.related_crypto_material_properties.size == 2048 9 | 10 | 11 | def test_private_key__overlapping_detection_contexts__should_update_existing_detection_context(cbom, make_rsa_component): 12 | rsa1 = make_rsa_component(start_line=10, end_line=20) 13 | rsa2 = make_rsa_component(start_line=15, end_line=25) 14 | 15 | related_crypto_material.parse_private_key(cbom, rsa1) 16 | related_crypto_material.parse_private_key(cbom, rsa2) 17 | 18 | assert len(cbom.components) == 1 19 | assert len(cbom.components[0].crypto_properties.detection_context) == 1 20 | -------------------------------------------------------------------------------- /.github/workflows/pull_request.yml: -------------------------------------------------------------------------------- 1 | name: Scan Pull Request 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - dev 7 | 8 | jobs: 9 | scan: 10 | runs-on: ubuntu-latest 11 | strategy: 12 | max-parallel: 4 13 | matrix: 14 | python-version: [ '3.10', '3.11', '3.12' ] 15 | 16 | steps: 17 | - name: Checkout code 18 | uses: actions/checkout@v4 19 | 20 | - name: Set up Python 21 | uses: actions/setup-python@v4 22 | with: 23 | python-version: ${{ matrix.python-version }} 24 | 25 | - name: Install dependencies 26 | run: | 27 | python -m pip install --upgrade pip 28 | pip install -r requirements.txt 29 | 30 | - name: Run unit tests 31 | run: tox run -e py$version -- --junitxml results.xml 32 | 33 | - name: Upload test results 34 | uses: actions/upload-artifact@master 35 | with: 36 | name: Test results - ${{ matrix.python-version }} 37 | path: results.xml 38 | 39 | - name: Run linter 40 | uses: chartboost/ruff-action@v1 41 | 42 | - name: Run SAST 43 | uses: chartboost/ruff-action@v1 44 | with: 45 | src: cbom 46 | args: check --select S 47 | -------------------------------------------------------------------------------- /CHANGELOG.rst: -------------------------------------------------------------------------------- 1 | Changelog 2 | ========= 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on `keep a changelog`_, and this project adheres to `semantic versioning`_. 6 | 7 | This file is autogenerated by `gitchangelog`_. Please do not edit it manually. 8 | 9 | 10 | 1.1.0 (2024-01-25) 11 | ------------------ 12 | 13 | Changed 14 | ~~~~~~~ 15 | - Rewrite CLI using click. [emilejq] 16 | 17 | Fixed 18 | ~~~~~ 19 | - Reduce algorithms being reported as unknown. [emilejq] 20 | - Add aliases for Triple DES & Diffie-Hellman. [emilejq] 21 | - Align with CodeQL CLI SARIF output format. [emilejq] 22 | - Use region (not contextRegion) when extracting algorithm to avoid 23 | misidentification (#7) [Matt Colman] 24 | 25 | 26 | 1.0.1 (2023-12-07) 27 | ------------------ 28 | 29 | Added 30 | ~~~~~ 31 | - Add application name option to CLI. [emilejq] 32 | 33 | Fixed 34 | ~~~~~ 35 | - Add default root component when version control information is not 36 | available. [emilejq] 37 | 38 | 39 | 1.0.0 (2023-12-04) 40 | ------------ 41 | - Initial release. 42 | 43 | 44 | .. _keep a changelog: https://keepachangelog.com/en/1.0.0 45 | .. _semantic versioning: https://semver.org/spec/v2.0.0 46 | .. _gitchangelog: https://github.com/vaab/gitchangelog 47 | -------------------------------------------------------------------------------- /cbom/cryptocheck/validators.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def check_are_numbers(func): 5 | def is_numeric(expected_value, value): 6 | try: 7 | return func(int(expected_value), int(value)) 8 | except (TypeError, ValueError): 9 | return False 10 | 11 | return is_numeric 12 | 13 | 14 | @check_are_numbers 15 | def is_less_than(maximum_value, value): 16 | return value < maximum_value 17 | 18 | 19 | @check_are_numbers 20 | def is_greater_than(minimum_value, value): 21 | return value > minimum_value 22 | 23 | 24 | @check_are_numbers 25 | def is_less_than_or_equal(maximum_value, value): 26 | return value <= maximum_value 27 | 28 | 29 | @check_are_numbers 30 | def is_greater_than_or_equal(minimum_value, value): 31 | return value >= minimum_value 32 | 33 | 34 | def is_equal(expected_value, value): 35 | return value == expected_value 36 | 37 | 38 | def is_not_equal(disallowed_value, value): 39 | return value != disallowed_value 40 | 41 | 42 | def does_contain(expected_value, value): 43 | return bool(expected_value.lower() in value.lower()) 44 | 45 | 46 | def does_match_regex(regex_pattern, value): # todo: parameterize case sensitivity 47 | return bool(re.search(regex_pattern, value, flags=re.IGNORECASE)) 48 | -------------------------------------------------------------------------------- /tests/unit_tests/data/codeql/fernet.sarif: -------------------------------------------------------------------------------- 1 | { 2 | "ruleId": "py/quantum-readiness/cbom/all-cryptographic-algorithms", 3 | "ruleIndex": 0, 4 | "rule": { 5 | "id": "py/quantum-readiness/cbom/all-cryptographic-algorithms", 6 | "index": 0 7 | }, 8 | "message": { 9 | "text": "Use of algorithm FERNET" 10 | }, 11 | "locations": [ 12 | { 13 | "physicalLocation": { 14 | "artifactLocation": { 15 | "uri": "springfield-nuclear-power-plant/core-reactor.py", 16 | "uriBaseId": "%SRCROOT%", 17 | "index": 3 18 | }, 19 | "region": { 20 | "startLine": 30, 21 | "endLine": 33, 22 | "endColumn": 22 23 | }, 24 | "contextRegion": { 25 | "startLine": 28, 26 | "endLine": 35, 27 | "snippet": { 28 | "text": "# additional context region\n# additional context region\ndef encrypt(message):\n encryptor = Fernet(Fernet.generate_key())\n ciphertext = encryptor.encrypt(message.encode())\n return ciphertext\n# additional context region\n# additional context region" 29 | } 30 | } 31 | } 32 | } 33 | ], 34 | "partialFingerprints": { 35 | "primaryLocationLineHash": "61744bbabae05152:1", 36 | "primaryLocationStartColumnFingerprint": "0" 37 | } 38 | } -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ['setuptools >= 61.0'] 3 | build-backend = 'setuptools.build_meta' 4 | 5 | [project] 6 | dynamic = ['version'] 7 | 8 | name = 'cryptobom-forge' 9 | description = 'Generate a cryptographic bill of materials from CodeQL output!' 10 | dependencies = [ 11 | 'click >= 8.0.0', 12 | 'cyclonedx-python-lib @ git+ssh://git@github.com/pre-quantum-research/cyclonedx-python-lib.git@cbom#egg=cyclonedx-python-lib', 13 | 'jsonschema >= 2.0.0', 14 | 'pyyaml >= 3.10', 15 | 'requests >= 2.3.0' 16 | ] 17 | requires-python = '>=3.10' 18 | 19 | authors = [ 20 | {name = "Emile El-Qawas"}, 21 | {name = "Mark Carney", email="mark@quantumvillage.org"} 22 | ] 23 | readme = "README.md" 24 | license = {file = "LICENSE"} 25 | 26 | keywords = ['cbom', 'codeql', 'cryptocheck', 'cryptography', 'pqc'] 27 | classifiers = [ 28 | 'Development Status :: 3 - Beta', 29 | 'Environment :: Console', 30 | 'Natural Language :: English', 31 | 'Programming Language :: Python :: 3.10', 32 | 'Programming Language :: Python :: 3.11', 33 | 'Topic :: Security', 34 | 'Topic :: Security :: Cryptography' 35 | ] 36 | 37 | [project.scripts] 38 | cryptobom = 'cbom.cli.cli:start' 39 | 40 | [project.urls] 41 | Repository = "https://github.com/santandersecurityresearch/cryptobom-forge.git" 42 | Issues = "https://github.com/santandersecurityresearch/cryptobom-forge/issues" 43 | Changelog = "https://github.com/santandersecurityresearch/cryptobom-forge/blob/main/CHANGELOG.rst" 44 | 45 | [tool.setuptools.packages] 46 | find = {} 47 | 48 | [tool.setuptools.dynamic] 49 | version = {attr = 'cbom.__version__'} 50 | -------------------------------------------------------------------------------- /tests/unit_tests/data/codeql/aes.sarif: -------------------------------------------------------------------------------- 1 | { 2 | "ruleId": "py/quantum-readiness/cbom/all-cryptographic-algorithms", 3 | "ruleIndex": 0, 4 | "rule": { 5 | "id": "py/quantum-readiness/cbom/all-cryptographic-algorithms", 6 | "index": 0 7 | }, 8 | "message": { 9 | "text": "Use of algorithm AES" 10 | }, 11 | "locations": [ 12 | { 13 | "physicalLocation": { 14 | "artifactLocation": { 15 | "uri": "springfield-nuclear-power-plant/core-reactor.py", 16 | "uriBaseId": "%SRCROOT%", 17 | "index": 3 18 | }, 19 | "region": { 20 | "startLine": 30, 21 | "endLine": 41, 22 | "endColumn": 22 23 | }, 24 | "contextRegion": { 25 | "startLine": 28, 26 | "endLine": 43, 27 | "snippet": { 28 | "text": "# additional context region\n# additional context region\ndef encrypt(message):\n padder = padding.PKCS7(128).padder()\n message = padder.update(message.encode()) + padder.finalize()\n\n key = os.urandom(32)\n encryptor = Cipher(\n algorithms.AES(key),\n modes.ECB(initialization_vector=os.urandom(16))\n ).encryptor()\n\n ciphertext = encryptor.update(message) + encryptor.finalize()\n return ciphertext\n# additional context region\n# additional context region" 29 | } 30 | } 31 | } 32 | } 33 | ], 34 | "partialFingerprints": { 35 | "primaryLocationLineHash": "61744bbabae05152:1", 36 | "primaryLocationStartColumnFingerprint": "0" 37 | } 38 | } -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Create Release 2 | 3 | on: 4 | workflow_dispatch: 5 | 6 | permissions: 7 | contents: write 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - name: Checkout Code 15 | uses: actions/checkout@v4 16 | 17 | - name: Set up Python 3.10 18 | uses: actions/setup-python@v4 19 | with: 20 | python-version: '3.10' 21 | 22 | - name: Install Dependencies 23 | run: | 24 | python -m pip install --upgrade pip 25 | pip install build 26 | 27 | - name: Build Wheel 28 | run: python -m build --wheel 29 | 30 | - name: Get Release Version 31 | run: | 32 | echo "VERSION"=$(grep -i '__version__ = ' cbom/__init__.py | head -1 | tr -d "__version__ = '") >> $GITHUB_ENV 33 | 34 | - name: Create Release 35 | id: create_release 36 | uses: actions/create-release@v1 37 | env: 38 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 39 | with: 40 | tag_name: ${{ env.VERSION }} 41 | release_name: ${{ env.VERSION }} 42 | 43 | - name: Upload Wheel to Release 44 | uses: actions/upload-release-asset@v1 45 | env: 46 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 47 | with: 48 | upload_url: ${{ steps.create_release.outputs.upload_url }} 49 | asset_path: ./dist/cryptobom_forge-${{ env.VERSION }}-py3-none-any.whl 50 | asset_name: cryptobom_forge-${{ env.VERSION }}-py3-none-any.whl 51 | asset_content_type: application/x-python-wheel 52 | 53 | # - name: Publish Release to PyPI 54 | # env: 55 | # TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} 56 | # TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} 57 | # run: | 58 | # twine upload dist/* 59 | -------------------------------------------------------------------------------- /tests/unit_tests/test_certificate.py: -------------------------------------------------------------------------------- 1 | from cbom.parser import certificate 2 | 3 | 4 | def test_certificate__should_generate_distinguished_name(cbom, rsa): 5 | certificate.parse_x509_certificate_details(cbom, rsa) 6 | 7 | assert len(cbom.components) == 1 8 | assert cbom.components[0].crypto_properties.certificate_properties.subject_name == 'C=US, L=Springfield, O=Springfield Nuclear Power Plant, CN=springfield-nuclear.com' 9 | 10 | 11 | def test_certificate__should_extract_certificate_algorithm(cbom, rsa): 12 | certificate.parse_x509_certificate_details(cbom, rsa) 13 | 14 | assert len(cbom.components) == 1 15 | assert cbom.components[0].crypto_properties.certificate_properties.certificate_algorithm == 'RSA' 16 | 17 | 18 | def test_certificate__should_extract_signature_algorithm(cbom, rsa): 19 | certificate.parse_x509_certificate_details(cbom, rsa) 20 | 21 | assert len(cbom.components) == 1 22 | assert cbom.components[0].crypto_properties.certificate_properties.certificate_signature_algorithm == 'SHA256' 23 | 24 | 25 | def test_certificate__same_algorithm_with_overlapping_detection_contexts__should_update_existing_detection_context(cbom, make_rsa_component): 26 | rsa1 = make_rsa_component(start_line=10, end_line=20) 27 | rsa2 = make_rsa_component(start_line=15, end_line=25) 28 | 29 | certificate.parse_x509_certificate_details(cbom, rsa1) 30 | certificate.parse_x509_certificate_details(cbom, rsa2) 31 | 32 | assert len(cbom.components) == 1 33 | assert len(cbom.components[0].crypto_properties.detection_context) == 1 34 | 35 | 36 | def test_certificate__different_algorithms_with_overlapping_detection_contexts__should_not_update_existing_component(cbom, make_rsa_component, make_dsa_component): 37 | rsa = make_rsa_component(start_line=10, end_line=20) 38 | dsa = make_dsa_component(start_line=10, end_line=20) 39 | 40 | certificate.parse_x509_certificate_details(cbom, rsa) 41 | certificate.parse_x509_certificate_details(cbom, dsa) 42 | 43 | assert len(cbom.components) == 2 44 | -------------------------------------------------------------------------------- /cbom/resources/cryptocheck_schema.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "array", 3 | "items": { 4 | "type": "object", 5 | "properties": { 6 | "name": { 7 | "type": "string" 8 | }, 9 | "detection": { 10 | "type": "object", 11 | "properties": { 12 | "type": { 13 | "type": "string", 14 | "enum": [ 15 | "error", 16 | "warning", 17 | "note" 18 | ] 19 | }, 20 | "severity": { 21 | "type": "number", 22 | "minimum": 1, 23 | "maximum": 10 24 | }, 25 | "description": { 26 | "type": "string" 27 | } 28 | } 29 | }, 30 | "default": { 31 | "type": "object", 32 | "properties": { 33 | "type": { 34 | "type": "string", 35 | "enum": [ 36 | "error", 37 | "warning", 38 | "note" 39 | ] 40 | }, 41 | "severity": { 42 | "type": "number", 43 | "minimum": 1, 44 | "maximum": 10 45 | }, 46 | "description": { 47 | "type": "string" 48 | } 49 | } 50 | }, 51 | "patterns": { 52 | "type": "array", 53 | "items": { 54 | "type": "string", 55 | "pattern": "^\\('(algo|keylen|mode|padding)', ?'(r|s|lt|gt|lteq|gteq|eq|neq)', ?.*\\)$" 56 | } 57 | } 58 | }, 59 | "required": [ 60 | "name", 61 | "detection", 62 | "patterns" 63 | ] 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /tests/unit_tests/data/codeql/dsa.sarif: -------------------------------------------------------------------------------- 1 | { 2 | "ruleId": "py/quantum-readiness/cbom/all-cryptographic-algorithms", 3 | "ruleIndex": 0, 4 | "rule": { 5 | "id": "py/quantum-readiness/cbom/all-cryptographic-algorithms", 6 | "index": 0 7 | }, 8 | "message": { 9 | "text": "Use of algorithm DSA" 10 | }, 11 | "locations": [ 12 | { 13 | "physicalLocation": { 14 | "artifactLocation": { 15 | "uri": "springfield-nuclear-power-plant/core-reactor.py", 16 | "uriBaseId": "%SRCROOT%", 17 | "index": 3 18 | }, 19 | "region": { 20 | "startLine": 30, 21 | "endLine": 62, 22 | "endColumn": 22 23 | }, 24 | "contextRegion": { 25 | "startLine": 28, 26 | "endLine": 64, 27 | "snippet": { 28 | "text": "# additional context region\n# additional context region\ndef encrypt(message):\n private_key = dsa.generate_private_key(\n key_size=2048\n )\n\n subject = issuer = x509.Name([\n x509.NameAttribute(NameOID.COUNTRY_NAME, 'US'),\n x509.NameAttribute(NameOID.LOCALITY_NAME, 'Springfield'),\n x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'Springfield Nuclear Power Plant'),\n x509.NameAttribute(NameOID.COMMON_NAME, \"springfield-nuclear.com\")\n ])\n\n certificate = (\n x509.CertificateBuilder()\n .subject_name(subject)\n .issuer_name(issuer)\n .public_key(private_key.public_key())\n .serial_number(x509.random_serial_number())\n .not_valid_before(datetime.datetime.now(datetime.timezone.utc))\n .not_valid_after(datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=10))\n .add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]), critical=False)\n ).sign(private_key, hashes.SHA256())\n\n public_key = certificate.public_key()\n ciphertext = public_key.encrypt(\n message.encode(),\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None\n )\n )\n return ciphertext\n# additional context region\n# additional context region" 29 | } 30 | } 31 | } 32 | } 33 | ], 34 | "partialFingerprints": { 35 | "primaryLocationLineHash": "61744bbabae05152:1", 36 | "primaryLocationStartColumnFingerprint": "0" 37 | } 38 | } -------------------------------------------------------------------------------- /tests/unit_tests/data/codeql/rsa.sarif: -------------------------------------------------------------------------------- 1 | { 2 | "ruleId": "py/quantum-readiness/cbom/all-cryptographic-algorithms", 3 | "ruleIndex": 0, 4 | "rule": { 5 | "id": "py/quantum-readiness/cbom/all-cryptographic-algorithms", 6 | "index": 0 7 | }, 8 | "message": { 9 | "text": "Use of algorithm RSA" 10 | }, 11 | "locations": [ 12 | { 13 | "physicalLocation": { 14 | "artifactLocation": { 15 | "uri": "springfield-nuclear-power-plant/core-reactor.py", 16 | "uriBaseId": "%SRCROOT%", 17 | "index": 3 18 | }, 19 | "region": { 20 | "startLine": 30, 21 | "endLine": 63, 22 | "endColumn": 22 23 | }, 24 | "contextRegion": { 25 | "startLine": 28, 26 | "endLine": 65, 27 | "snippet": { 28 | "text": "# additional context region\n# additional context region\ndef encrypt(message):\n private_key = rsa.generate_private_key(\n public_exponent=65537,\n key_size=2048\n )\n\n subject = issuer = x509.Name([\n x509.NameAttribute(NameOID.COUNTRY_NAME, 'US'),\n x509.NameAttribute(NameOID.LOCALITY_NAME, 'Springfield'),\n x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'Springfield Nuclear Power Plant'),\n x509.NameAttribute(NameOID.COMMON_NAME, \"springfield-nuclear.com\")\n ])\n\n certificate = (\n x509.CertificateBuilder()\n .subject_name(subject)\n .issuer_name(issuer)\n .public_key(private_key.public_key())\n .serial_number(x509.random_serial_number())\n .not_valid_before(datetime.datetime.now(datetime.timezone.utc))\n .not_valid_after(datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=10))\n .add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]), critical=False)\n ).sign(private_key, hashes.SHA256())\n\n public_key = certificate.public_key()\n ciphertext = public_key.encrypt(\n message.encode(),\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None\n )\n )\n return ciphertext\n# additional context region\n# additional context region" 29 | } 30 | } 31 | } 32 | } 33 | ], 34 | "partialFingerprints": { 35 | "primaryLocationLineHash": "61744bbabae05152:1", 36 | "primaryLocationStartColumnFingerprint": "0" 37 | } 38 | } -------------------------------------------------------------------------------- /tests/unit_tests/conftest.py: -------------------------------------------------------------------------------- 1 | import copy 2 | import json 3 | from pathlib import Path 4 | 5 | import pytest 6 | from cyclonedx.model.bom import Bom 7 | from cyclonedx.model.component import Component, ComponentType 8 | 9 | 10 | @pytest.fixture 11 | def cbom(): 12 | cbom = Bom() 13 | 14 | root_component = Component( 15 | bom_ref='root', 16 | name='springfield-nuclear-power-plant', 17 | type=ComponentType.APPLICATION 18 | ) 19 | cbom.metadata.component = root_component 20 | return cbom 21 | 22 | 23 | @pytest.fixture() 24 | def aes(): 25 | with open(Path(__file__).absolute().parent / 'data' / 'codeql' / 'aes.sarif') as data: 26 | data = json.load(data) 27 | return data['locations'][0]['physicalLocation'] 28 | 29 | 30 | @pytest.fixture 31 | def make_aes_component(aes): 32 | 33 | def _make_component(start_line, end_line): 34 | data = copy.deepcopy(aes) 35 | data['region']['startLine'] = start_line 36 | data['region']['endLine'] = end_line 37 | 38 | data['contextRegion']['startLine'] = start_line - 2 39 | data['contextRegion']['endLine'] = end_line + 2 40 | return data 41 | 42 | return _make_component 43 | 44 | 45 | @pytest.fixture() 46 | def dsa(): 47 | with open(Path(__file__).absolute().parent / 'data' / 'codeql' / 'dsa.sarif') as data: 48 | data = json.load(data) 49 | return data['locations'][0]['physicalLocation'] 50 | 51 | 52 | @pytest.fixture 53 | def make_dsa_component(dsa): 54 | 55 | def _make_component(start_line, end_line): 56 | data = copy.deepcopy(dsa) 57 | data['region']['startLine'] = start_line 58 | data['region']['endLine'] = end_line 59 | 60 | data['contextRegion']['startLine'] = start_line - 2 61 | data['contextRegion']['endLine'] = end_line + 2 62 | return data 63 | 64 | return _make_component 65 | 66 | 67 | @pytest.fixture() 68 | def fernet(): 69 | with open(Path(__file__).absolute().parent / 'data' / 'codeql' / 'fernet.sarif') as data: 70 | data = json.load(data) 71 | return data['locations'][0]['physicalLocation'] 72 | 73 | 74 | @pytest.fixture() 75 | def rsa(): 76 | with open(Path(__file__).absolute().parent / 'data' / 'codeql' / 'rsa.sarif') as data: 77 | data = json.load(data) 78 | return data['locations'][0]['physicalLocation'] 79 | 80 | 81 | @pytest.fixture 82 | def make_rsa_component(rsa): 83 | 84 | def _make_component(start_line, end_line): 85 | data = copy.deepcopy(rsa) 86 | data['region']['startLine'] = start_line 87 | data['region']['endLine'] = end_line 88 | 89 | data['contextRegion']['startLine'] = start_line - 2 90 | data['contextRegion']['endLine'] = end_line + 2 91 | return data 92 | 93 | return _make_component 94 | -------------------------------------------------------------------------------- /tests/integration_tests/test_cbom.py: -------------------------------------------------------------------------------- 1 | import json 2 | import tempfile 3 | from pathlib import Path 4 | 5 | import pytest 6 | from click.testing import CliRunner 7 | 8 | from cbom.cli import cli 9 | 10 | 11 | def test_generate_cbom__should_generate_full_cbom(cbom_expected_full): 12 | path = Path(__file__).parent / 'data' / 'codeql' / 'full.sarif' 13 | 14 | response = CliRunner().invoke(cli.cryptobom, ['generate', str(path)]) 15 | cbom = json.loads(response.output) 16 | 17 | assert len(cbom['components']) == len(cbom_expected_full['components']) 18 | 19 | 20 | def test_generate_cbom__should_handle_directory(cbom_expected_full): 21 | path = Path(__file__).parent / 'data' / 'codeql' / 'partial_results' 22 | 23 | response = CliRunner().invoke(cli.cryptobom, ['generate', str(path)]) 24 | cbom = json.loads(response.output) 25 | 26 | assert len(cbom['components']) == len(cbom_expected_full['components']) 27 | 28 | 29 | def test_generate_cbom__should_generate_root_component(): 30 | path = Path(__file__).parent / 'data' / 'codeql' / 'full.sarif' 31 | 32 | response = CliRunner().invoke(cli.cryptobom, ['generate', str(path), '-n', 'core-reactor']) 33 | cbom = json.loads(response.output) 34 | 35 | assert cbom['metadata']['component'] 36 | 37 | 38 | def test_generate_cbom__should_set_root_component_name(): 39 | path = Path(__file__).parent / 'data' / 'codeql' / 'full.sarif' 40 | 41 | response = CliRunner().invoke(cli.cryptobom, ['generate', str(path), '-n', 'core-reactor']) 42 | cbom = json.loads(response.output) 43 | 44 | assert cbom['metadata']['component']['name'] == 'core-reactor' 45 | 46 | 47 | def test_generate_cbom__should_exclude_finding_when_exclusion_pattern_match(cbom_expected_exclusion_pattern): 48 | path = Path(__file__).parent / 'data' / 'codeql' / 'full.sarif' 49 | 50 | response = CliRunner().invoke(cli.cryptobom, ['generate', str(path), '-e', '(.*/)?test(s)?.*']) 51 | cbom = json.loads(response.output) 52 | 53 | assert len(cbom['components']) == len(cbom_expected_exclusion_pattern['components']) 54 | 55 | 56 | def test_generate_cbom__should_write_to_file(cbom_expected_full): 57 | path = Path(__file__).parent / 'data' / 'codeql' / 'full.sarif' 58 | 59 | output_file = tempfile.NamedTemporaryFile() 60 | CliRunner().invoke(cli.cryptobom, ['generate', str(path), '--output-file', output_file.name]) 61 | 62 | with open(output_file.name, 'r') as tmp: 63 | cbom = json.load(tmp) 64 | assert len(cbom['components']) == len(cbom_expected_full['components']) 65 | 66 | 67 | @pytest.fixture 68 | def cbom_expected_full(): 69 | with open(Path(__file__).parent / 'data' / 'cbom' / 'cbom_full.json') as cbom: 70 | return json.load(cbom) 71 | 72 | 73 | @pytest.fixture 74 | def cbom_expected_exclusion_pattern(): 75 | with open(Path(__file__).parent / 'data' / 'cbom' / 'cbom_exclusion_pattern.json') as cbom: 76 | return json.load(cbom) 77 | -------------------------------------------------------------------------------- /cbom/parser/utils.py: -------------------------------------------------------------------------------- 1 | import re 2 | from difflib import SequenceMatcher 3 | 4 | from cyclonedx.model.crypto import DetectionContext 5 | 6 | from cbom import lib_utils 7 | 8 | _ALGORITHM_REGEX = re.compile(f"{'|'.join(lib_utils.get_algorithms())}", flags=re.IGNORECASE) 9 | _KEY_LENGTH_REGEX = re.compile(f"\\D({'|'.join([str(key_length) for key_length in lib_utils.get_key_lengths()])})\\D") 10 | 11 | 12 | def get_algorithm(code_snippet): 13 | match = _ALGORITHM_REGEX.search(code_snippet) 14 | if match: 15 | algorithm = match.group().upper() 16 | return lib_utils.get_algorithms().get(algorithm) or algorithm # return full algorithm name if algorithm is aliased e.g. diffiehellman instead of dh 17 | return 'unknown' 18 | 19 | 20 | def get_detection_context(physical_location): 21 | file_path = physical_location['artifactLocation']['uri'] 22 | if context_region := physical_location.get('contextRegion'): 23 | line_numbers = list(range(context_region['startLine'], context_region['endLine'] + 1)) 24 | code_snippet = context_region.get('snippet').get('text') 25 | return DetectionContext(file_path=file_path, line_numbers=line_numbers, additional_context=code_snippet) 26 | 27 | 28 | def get_key_size(code_snippet): 29 | match = _KEY_LENGTH_REGEX.search(code_snippet) 30 | if match: 31 | return _KEY_LENGTH_REGEX.sub('\\1', match.group()) 32 | 33 | 34 | def is_existing_detection_context_match(component, new_context): 35 | for context in component.crypto_properties.detection_context: 36 | if context.file_path == new_context.file_path and context.line_numbers.intersection(new_context.line_numbers): 37 | return context 38 | 39 | 40 | def merge_code_snippets(dc1, dc2): 41 | first = (dc1 if min(dc1.line_numbers) < min(dc2.line_numbers) else dc2).additional_context 42 | second = (dc1 if max(dc1.line_numbers) > max(dc2.line_numbers) else dc2).additional_context 43 | 44 | match = SequenceMatcher(None, first, second).find_longest_match() 45 | return f'{first[:match.a]}{second[:match.size]}{second[match.size:]}' 46 | 47 | 48 | def extract_precise_snippet(snippet, region): 49 | line_start = region['startLine'] 50 | line_end = region.get('endLine') 51 | line_start_col = region.get('startColumn', 1) 52 | line_end_col = region['endColumn'] 53 | 54 | match line_start: 55 | case 1: 56 | array_of_lines = snippet.split('\n') 57 | case 2: 58 | array_of_lines = snippet.split('\n')[1:] 59 | case _: 60 | array_of_lines = snippet.split('\n')[2:] 61 | 62 | if not line_end: 63 | actual_line = array_of_lines[0] 64 | return actual_line[line_start_col - 1:line_end_col] 65 | else: 66 | end_line_index = (line_end - line_start) 67 | actual_lines = array_of_lines[:end_line_index + 1] 68 | actual_lines[0] = actual_lines[0][line_start_col - 1:] 69 | actual_lines[-1] = actual_lines[-1][:line_end_col] 70 | return '\n'.join(actual_lines) 71 | -------------------------------------------------------------------------------- /tests/unit_tests/test_utils.py: -------------------------------------------------------------------------------- 1 | from cyclonedx.model.crypto import DetectionContext 2 | 3 | from cbom.parser import utils 4 | 5 | _CODE_SNIPPET = ''' 6 | def encrypt(message): 7 | key = os.urandom(32) 8 | encryptor = Cipher( 9 | algorithms.AES(key), 10 | modes.ECB(initialization_vector=os.urandom(16)) 11 | ).encryptor() 12 | 13 | ciphertext = encryptor.update(message) + encryptor.finalize() 14 | return ciphertext 15 | ''' 16 | 17 | 18 | def test_get_algorithm__should_return_full_name_when_matched_algorithm_is_aliased(): 19 | code_snippet = 'parameters = dh.generate_parameters(generator=2, key_size=2048)' 20 | algorithm = utils.get_algorithm(code_snippet) 21 | 22 | assert algorithm == 'DIFFIEHELLMAN' 23 | 24 | 25 | def test_extract_precise_snippet__should_extract_line(): 26 | region = { 27 | 'startLine': 10, 28 | 'endColumn': 25 29 | } 30 | expected = ' key = os.urandom(32)' 31 | 32 | assert utils.extract_precise_snippet(_CODE_SNIPPET, region) == expected 33 | 34 | 35 | def test_extract_precise_snippet__should_handle_column_start_index(): 36 | region = { 37 | 'startLine': 3, 38 | 'startColumn': 5, 39 | 'endColumn': 25 40 | } 41 | expected = 'key = os.urandom(32)' 42 | 43 | assert utils.extract_precise_snippet(_CODE_SNIPPET, region) == expected 44 | 45 | 46 | def test_extract_precise_snippet__should_handle_start_of_file_region(): 47 | region = { 48 | 'startLine': 2, 49 | 'endColumn': 22 50 | } 51 | expected = 'def encrypt(message):' 52 | 53 | assert utils.extract_precise_snippet(_CODE_SNIPPET, region) == expected 54 | 55 | 56 | def test_extract_precise_snippet__should_handle_multiline_region(): 57 | region = { 58 | 'startLine': 10, 59 | 'startColumn': 5, 60 | 'endLine': 12, 61 | 'endColumn': 27 62 | } 63 | expected = 'key = os.urandom(32)\n encryptor = Cipher(\n algorithms.AES(key)' 64 | 65 | assert utils.extract_precise_snippet(_CODE_SNIPPET, region) == expected 66 | 67 | 68 | def test_merge_code_snippets__should_handle_partially_overlapping_contexts(): 69 | partial_code_snippet_1 = '\n'.join(_CODE_SNIPPET.split('\n')[:5]) 70 | partial_code_snippet_2 = '\n'.join(_CODE_SNIPPET.split('\n')[2:]) 71 | 72 | dc1 = DetectionContext(line_numbers=[10, 11, 12, 13, 14], additional_context=partial_code_snippet_1) 73 | dc2 = DetectionContext(line_numbers=[12, 13, 14, 15, 16, 17, 18], additional_context=partial_code_snippet_2) 74 | 75 | assert utils.merge_code_snippets(dc1, dc2) == _CODE_SNIPPET 76 | 77 | 78 | def test_merge_code_snippets__should_handle_wholly_overlapping_contexts(): 79 | partial_code_snippet = '\n'.join(_CODE_SNIPPET.split('\n')[2:5]) 80 | 81 | dc1 = DetectionContext(line_numbers=[10, 11, 12, 13, 14, 15, 16, 17, 18], additional_context=_CODE_SNIPPET) 82 | dc2 = DetectionContext(line_numbers=[12, 13, 14, 15], additional_context=partial_code_snippet) 83 | 84 | assert utils.merge_code_snippets(dc1, dc2) == _CODE_SNIPPET 85 | -------------------------------------------------------------------------------- /cbom/cryptocheck/sarif.py: -------------------------------------------------------------------------------- 1 | import copy 2 | import itertools 3 | 4 | _SARIF_TEMPLATE = { 5 | "version": "2.1.0", 6 | "$schema": "http://json.schemastore.org/sarif-2.1.0-rtm.4", 7 | "runs": [{ 8 | "tool": { 9 | "driver": { 10 | "name": "CryptoCheck", 11 | "rules": [] 12 | } 13 | }, 14 | "results": [] 15 | }] 16 | } 17 | 18 | 19 | def build_cryptocheck_sarif(cbom, rules, rule_violations, *, aggressive_aggregation=False): 20 | sarif = copy.deepcopy(_SARIF_TEMPLATE) 21 | 22 | for violation in rule_violations: 23 | violation_context = violation['detection'] 24 | if aggressive_aggregation: 25 | affected_components = (_get_bom_component(cbom, bom_ref).crypto_properties.detection_context for bom_ref in violation['bom-refs']) 26 | detection_contexts = list(itertools.chain.from_iterable(affected_components)) 27 | 28 | sarif['runs'][0]['results'].append({ 29 | 'ruleId': violation['name'], 30 | 'ruleIndex': 0, 31 | 'message': { 32 | 'text': violation_context['description'] 33 | }, 34 | 'level': violation_context['type'], 35 | 'locations': [_build_location_object(dc) for dc in detection_contexts] 36 | }) 37 | else: 38 | for bom_ref in violation['bom-refs']: 39 | affected_component = _get_bom_component(cbom, bom_ref) 40 | for detection_context in affected_component.crypto_properties.detection_context: 41 | sarif['runs'][0]['results'].append({ 42 | 'ruleId': violation['name'], 43 | 'ruleIndex': 0, 44 | 'message': { 45 | 'text': violation_context['description'] 46 | }, 47 | 'level': violation_context['type'], 48 | 'locations': [_build_location_object(detection_context)] 49 | }) 50 | 51 | _add_rules_to_sarif(sarif, rules) 52 | return sarif 53 | 54 | 55 | def _add_rules_to_sarif(sarif, rules): 56 | for rule in rules: 57 | sarif['runs'][0]['tool']['driver']['rules'].append({ 58 | 'id': rule['name'], 59 | 'shortDescription': { 60 | 'text': rule['name'].replace('-', ' ') 61 | }, 62 | 'properties': { 63 | 'category': 'function', 64 | 'tags': ['cryptography'], 65 | 'problem.severity': rule['detection']['type'], # todo: handle default 66 | 'security-severity': str(rule['detection']['severity']) # todo: handle default 67 | } 68 | }) 69 | 70 | 71 | def _build_location_object(detection_context): 72 | return { 73 | 'physicalLocation': { 74 | 'artifactLocation': { 75 | 'uri': detection_context.file_path, 76 | 'index': 0, 77 | 'uriBaseId': '%SRCROOT%' 78 | }, 79 | 'region': { 80 | 'startLine': detection_context.line_numbers[0], 81 | 'endLine': detection_context.line_numbers[-1] 82 | } 83 | } 84 | } 85 | 86 | 87 | def _get_bom_component(cbom, bom_ref): 88 | for component in cbom.components: 89 | if component.bom_ref == bom_ref: 90 | return component 91 | -------------------------------------------------------------------------------- /cbom/parser/related_crypto_material.py: -------------------------------------------------------------------------------- 1 | import uuid 2 | 3 | from cyclonedx.model.component import Component, ComponentType 4 | from cyclonedx.model.crypto import CryptoProperties, AssetType, RelatedCryptoMaterialProperties, \ 5 | RelatedCryptoMaterialType 6 | 7 | from cbom.parser import utils 8 | 9 | 10 | def parse_initialization_vector(cbom, finding): 11 | crypto_properties = _generate_crypto_component(finding, RelatedCryptoMaterialType.INITIALIZATION_VECTOR) 12 | unique_identifier = uuid.uuid4() 13 | 14 | component = Component( 15 | bom_ref=f'cryptography:iv:{unique_identifier}', 16 | name=str(unique_identifier), 17 | type=ComponentType.CRYPTO_ASSET, 18 | crypto_properties=crypto_properties 19 | ) 20 | cbom.components.add(component) 21 | return component 22 | 23 | 24 | def parse_private_key(cbom, finding): 25 | key_size = utils.get_key_size(finding['contextRegion']['snippet']['text']) 26 | if key_size: 27 | key_size = int(key_size) 28 | 29 | crypto_properties = _generate_crypto_component(finding, RelatedCryptoMaterialType.PRIVATE_KEY, size=key_size) 30 | unique_identifier = uuid.uuid4() 31 | 32 | component = Component( 33 | bom_ref=f'cryptography:private_key:{unique_identifier}', 34 | name=str(unique_identifier), 35 | type=ComponentType.CRYPTO_ASSET, 36 | crypto_properties=crypto_properties 37 | ) 38 | if not (existing_component := _is_existing_component_overlap(cbom, component)): 39 | cbom.components.add(component) 40 | else: 41 | component = _update_existing_component(existing_component, component) 42 | return component 43 | 44 | 45 | def _generate_crypto_component(component, material_type, *, size=None): 46 | return CryptoProperties( 47 | asset_type=AssetType.RELATED_CRYPTO_MATERIAL, 48 | related_crypto_material_properties=RelatedCryptoMaterialProperties( 49 | related_crypto_material_type=material_type, 50 | size=size 51 | ), 52 | detection_context=[utils.get_detection_context(component)] 53 | ) 54 | 55 | 56 | def _is_existing_component_overlap(cbom, component): 57 | related_crypto_material_components = (c for c in cbom.components if c.crypto_properties.asset_type == AssetType.RELATED_CRYPTO_MATERIAL) 58 | 59 | for existing_component in related_crypto_material_components: 60 | if utils.is_existing_detection_context_match(existing_component, component.crypto_properties.detection_context[0]): 61 | return existing_component 62 | 63 | 64 | def _update_existing_component(existing_component, component): 65 | context = component.crypto_properties.detection_context[0] 66 | 67 | if existing_context := utils.is_existing_detection_context_match(existing_component, context): 68 | existing_context.additional_context = utils.merge_code_snippets(existing_context, context) 69 | existing_context.line_numbers = existing_context.line_numbers.union(context.line_numbers) 70 | 71 | for field in vars(component.crypto_properties.related_crypto_material_properties): 72 | if not getattr(existing_component.crypto_properties.related_crypto_material_properties, field): 73 | field_value = getattr(component.crypto_properties.related_crypto_material_properties, field) 74 | setattr(existing_component.crypto_properties.related_crypto_material_properties, field, field_value) 75 | return existing_component 76 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | ./venv/* 6 | .DS_Store 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | wheels/ 25 | share/python-wheels/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | MANIFEST 30 | 31 | # PyInstaller 32 | # Usually these files are written by a python script from a template 33 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 34 | *.manifest 35 | *.spec 36 | 37 | # Installer logs 38 | pip-log.txt 39 | pip-delete-this-directory.txt 40 | 41 | # Unit test / coverage reports 42 | htmlcov/ 43 | .tox/ 44 | .nox/ 45 | .coverage 46 | .coverage.* 47 | .cache 48 | nosetests.xml 49 | coverage.xml 50 | *.cover 51 | *.py,cover 52 | .hypothesis/ 53 | .pytest_cache/ 54 | cover/ 55 | 56 | # Translations 57 | *.mo 58 | *.pot 59 | 60 | # Django stuff: 61 | *.log 62 | local_settings.py 63 | db.sqlite3 64 | db.sqlite3-journal 65 | 66 | # Flask stuff: 67 | instance/ 68 | .webassets-cache 69 | 70 | # Scrapy stuff: 71 | .scrapy 72 | 73 | # Sphinx documentation 74 | docs/_build/ 75 | 76 | # PyBuilder 77 | .pybuilder/ 78 | target/ 79 | 80 | # Jupyter Notebook 81 | .ipynb_checkpoints 82 | 83 | # IPython 84 | profile_default/ 85 | ipython_config.py 86 | 87 | # pyenv 88 | # For a library or package, you might want to ignore these files since the code is 89 | # intended to run in multiple environments; otherwise, check them in: 90 | # .python-version 91 | 92 | # pipenv 93 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 94 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 95 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 96 | # install all needed dependencies. 97 | #Pipfile.lock 98 | 99 | # poetry 100 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 101 | # This is especially recommended for binary packages to ensure reproducibility, and is more 102 | # commonly ignored for libraries. 103 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 104 | #poetry.lock 105 | 106 | # pdm 107 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 108 | #pdm.lock 109 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 110 | # in version control. 111 | # https://pdm.fming.dev/#use-with-ide 112 | .pdm.toml 113 | 114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 115 | __pypackages__/ 116 | 117 | # Celery stuff 118 | celerybeat-schedule 119 | celerybeat.pid 120 | 121 | # SageMath parsed files 122 | *.sage.py 123 | 124 | # Environments 125 | .env 126 | .venv 127 | env/ 128 | venv/ 129 | ENV/ 130 | env.bak/ 131 | venv.bak/ 132 | 133 | # Spyder project settings 134 | .spyderproject 135 | .spyproject 136 | 137 | # Rope project settings 138 | .ropeproject 139 | 140 | # mkdocs documentation 141 | /site 142 | 143 | # mypy 144 | .mypy_cache/ 145 | .dmypy.json 146 | dmypy.json 147 | 148 | # Pyre type checker 149 | .pyre/ 150 | 151 | # pytype static type analyzer 152 | .pytype/ 153 | 154 | # Cython debug symbols 155 | cython_debug/ 156 | 157 | # PyCharm 158 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 159 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 160 | # and can be added to the global gitignore or merged into this file. For a more nuclear 161 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 162 | .idea/ 163 | 164 | # Other 165 | cbom.json 166 | cryptocheck.sarif 167 | mrva/ 168 | -------------------------------------------------------------------------------- /cbom/resources/library.yml: -------------------------------------------------------------------------------- 1 | crypto: 2 | algorithms: 3 | 3DES: TRIPLEDES 4 | AES: 5 | ARC4: 6 | BLAKE2B: 7 | BLAKE2S: 8 | BRAINPOOLP256R1: 9 | BRAINPOOLP384R1: 10 | BRAINPOOLP512R1: 11 | CAMELLIA: 12 | CAST5: 13 | CHACHA20: 14 | CHACHA20POLY1305: 15 | CONCATKDFHASH: 16 | CONCATKDFHMAC: 17 | DES3: TRIPLEDES 18 | DESEDE: TRIPLEDES 19 | DIFFIEHELLMAN: 20 | DH: DIFFIEHELLMAN 21 | DSA: 22 | ECDSA: 23 | EDDSA: 24 | FERNET: 25 | HKDF: 26 | HKDFEXPAND: 27 | IDEA: 28 | KBKDFCMAC: 29 | KBKDFHMAC: 30 | MD5: 31 | PBKDF2HMAC: 32 | PSS: 33 | RSA: 34 | SCRYPT: 35 | SECP192R1: 36 | SECP224R1: 37 | SECP256K1: 38 | SECP256R1: 39 | SECP384R1: 40 | SECP521R1: 41 | SECT163K1: 42 | SECT163R2: 43 | SECT233K1: 44 | SECT233R1: 45 | SECT283K1: 46 | SECT283R1: 47 | SECT409K1: 48 | SECT409R1: 49 | SECT571K1: 50 | SECT571R1: 51 | SEED: 52 | SHA1: 53 | SHA224: 54 | SHA256: 55 | SHA3224: 56 | SHA3256: 57 | SHA3384: 58 | SHA3512: 59 | SHA384: 60 | SHA512: 61 | SHA512224: 62 | SHA512256: 63 | SHAKE: 64 | SM3: 65 | SM4: 66 | TRIPLEDES: 67 | X963KDF: 68 | 69 | block-modes: 70 | - CBC 71 | - CCM 72 | - CFB 73 | - CFB1 74 | - CFB8 75 | - CTR 76 | - ECB 77 | - GCM 78 | - OFB 79 | - SIV 80 | - XTS 81 | 82 | functions: 83 | - decapsulate 84 | - decrypt 85 | - digest 86 | - encapsulate 87 | - encrypt 88 | - generate 89 | - keyderive 90 | - keygen 91 | - sign 92 | - tag 93 | - verify 94 | 95 | key-lengths: 96 | - 128 97 | - 196 98 | - 256 99 | - 512 100 | - 1024 101 | - 2048 102 | - 3072 103 | - 4096 104 | 105 | padding-schemes: 106 | - OAEP 107 | - PKCS1V15 108 | - PKCS7 109 | 110 | primitive-mappings: 111 | chacha20poly1305: ae 112 | rsa: pke 113 | aes: blockcipher 114 | aes128: blockcipher 115 | aes256: blockcipher 116 | idea: blockcipher 117 | camellia: blockcipher 118 | sm4: blockcipher 119 | cast5: blockcipher 120 | tripledes: blockcipher 121 | chacha20: streamcipher 122 | arc4: streamcipher 123 | shake128: xof 124 | kbkdfhmac: mac 125 | hkdfexpand: kdf 126 | hkdf: kdf 127 | kbkdfcmac: kdf 128 | x963kdf: kdf 129 | pbkdf2hmac: kdf 130 | concatkdfhmac: kdf 131 | concatkdfhash: kdf 132 | diffiehellman: keyagree 133 | sha3256: hash 134 | sm3: hash 135 | shake256: hash # TODO - identify this as SHA-3? - MC 136 | sha224: hash 137 | sha3224: hash 138 | sha3512: hash 139 | blake2s: hash 140 | md5: hash 141 | sha512: hash 142 | sha384: hash 143 | sha256: hash 144 | sha512256: hash 145 | scrypt: hash 146 | sha1: hash 147 | sha3384: hash 148 | blake2b: hash 149 | pss: signature 150 | dsa: signature 151 | sect283r1: other # TODO - add Elliptic Curve Parameters to IBM CBOM as PR from SANRESEARCH repo. - MC 152 | secp256k1: other # BITCOIN EC parameters - only used by miners and malware. - MC 153 | sect283k1: other # EC CURVE PARAM 154 | sect571k1: other # EC CURVE PARAM 155 | brainpoolp512r1: other # EC CURVE PARAM 156 | brainpoolp384r1: other # EC CURVE PARAM 157 | seed: other 158 | sect409r1: other # EC CURVE PARAM 159 | secp192r1: other # EC CURVE PARAM 160 | secp256r1: other # EC CURVE PARAM 161 | sect233k1: other # EC CURVE PARAM 162 | sect163k1: other # EC CURVE PARAM 163 | secp384r1: other # EC CURVE PARAM 164 | sect571r1: other # EC CURVE PARAM 165 | sect409k1: other # EC CURVE PARAM 166 | brainpoolp256r1: other # EC CURVE PARAM 167 | sect163r2: other # EC CURVE PARAM 168 | sect233r1: other # EC CURVE PARAM 169 | secp224r1: other # EC CURVE PARAM 170 | secp521r1: other # EC CURVE PARAM 171 | sha512224: other # EC CURVE PARAM 172 | -------------------------------------------------------------------------------- /tests/unit_tests/test_algorithm.py: -------------------------------------------------------------------------------- 1 | from unittest.mock import patch 2 | 3 | import pytest 4 | from cyclonedx.model.component import Component, ComponentType 5 | from cyclonedx.model.crypto import Mode, Padding, Primitive 6 | 7 | from cbom.parser import algorithm 8 | 9 | 10 | def test_algorithm__should_infer_primitive(cbom, aes): 11 | algorithm.parse_algorithm(cbom, aes) 12 | 13 | assert len(cbom.components) == 1 14 | assert cbom.components[0].crypto_properties.algorithm_properties.primitive == Primitive.BLOCK_CIPHER 15 | 16 | 17 | def test_algorithm__should_extract_block_mode(cbom, aes): 18 | algorithm.parse_algorithm(cbom, aes) 19 | 20 | assert len(cbom.components) == 1 21 | assert cbom.components[0].crypto_properties.algorithm_properties.mode == Mode.ECB 22 | 23 | 24 | def test_algorithm__should_extract_padding(cbom, aes): 25 | algorithm.parse_algorithm(cbom, aes) 26 | 27 | assert len(cbom.components) == 1 28 | assert cbom.components[0].crypto_properties.algorithm_properties.padding == Padding.PKCS7 29 | 30 | 31 | def test_algorithm__should_extract_crypto_functions(cbom, rsa): 32 | algorithm.parse_algorithm(cbom, rsa) 33 | 34 | assert len(cbom.components) == 1 35 | assert cbom.components[0].crypto_properties.algorithm_properties.crypto_functions == {'generate', 'encrypt', 'sign'} 36 | 37 | 38 | def test_algorithm__should_not_identify_non_function_match_as_crypto_function(cbom, rsa): 39 | rsa['contextRegion']['snippet']['text'] += '\n\ndef decrypt(): ...' 40 | 41 | algorithm.parse_algorithm(cbom, rsa) 42 | 43 | assert len(cbom.components) == 1 44 | assert 'decrypt' not in cbom.components[0].crypto_properties.algorithm_properties.crypto_functions 45 | 46 | 47 | def test_algorithm__should_transform_fernet(cbom, fernet): 48 | algorithm.parse_algorithm(cbom, fernet) 49 | 50 | assert len(cbom.components) == 1 51 | assert cbom.components[0].crypto_properties.algorithm_properties.variant == 'AES-128-CBC' 52 | 53 | 54 | def test_algorithm__public_key_encryption__should_generate_certificate_component(cbom, rsa, certificate_mock): 55 | algorithm.parse_algorithm(cbom, rsa) 56 | 57 | certificate_mock.assert_called_once_with(cbom, rsa) 58 | 59 | 60 | def test_algorithm__public_key_encryption__should_generate_private_key_component(cbom, rsa, private_key_mock): 61 | algorithm.parse_algorithm(cbom, rsa) 62 | 63 | private_key_mock.assert_called_once_with(cbom, rsa) 64 | 65 | 66 | def test_algorithm__same_algorithm_with_overlapping_detection_contexts__should_update_existing_detection_context(cbom, make_aes_component): 67 | aes1 = make_aes_component(start_line=10, end_line=20) 68 | aes2 = make_aes_component(start_line=15, end_line=25) 69 | 70 | algorithm.parse_algorithm(cbom, aes1) 71 | algorithm.parse_algorithm(cbom, aes2) 72 | 73 | assert len(cbom.components) == 1 74 | assert len(cbom.components[0].crypto_properties.detection_context) == 1 75 | 76 | 77 | def test_algorithm__same_algorithm_with_non_overlapping_detection_contexts__should_update_existing_component_with_new_detection_context(cbom, make_aes_component): 78 | aes1 = make_aes_component(start_line=10, end_line=20) 79 | aes2 = make_aes_component(start_line=50, end_line=60) 80 | 81 | algorithm.parse_algorithm(cbom, aes1) 82 | algorithm.parse_algorithm(cbom, aes2) 83 | 84 | assert len(cbom.components) == 1 85 | assert len(cbom.components[0].crypto_properties.detection_context) == 2 86 | 87 | 88 | def test_algorithm__different_algorithms_with_overlapping_detection_contexts__should_not_update_existing_component(cbom, make_aes_component, make_rsa_component): 89 | aes = make_aes_component(start_line=10, end_line=20) 90 | rsa = make_rsa_component(start_line=10, end_line=20) 91 | 92 | algorithm.parse_algorithm(cbom, aes) 93 | algorithm.parse_algorithm(cbom, rsa) 94 | 95 | assert len(cbom.components) == 2 96 | 97 | 98 | @pytest.fixture(autouse=True) 99 | def certificate_mock(): 100 | with patch.object(algorithm.certificate, 'parse_x509_certificate_details') as mock: 101 | mock.return_value = Component(name='certificate-component', type=ComponentType.CRYPTO_ASSET) 102 | yield mock 103 | 104 | 105 | @pytest.fixture(autouse=True) 106 | def private_key_mock(): 107 | with patch.object(algorithm.related_crypto_material, 'parse_private_key') as mock: 108 | mock.return_value = Component(name='private-key-component', type=ComponentType.CRYPTO_ASSET) 109 | yield mock 110 | -------------------------------------------------------------------------------- /cbom/parser/certificate.py: -------------------------------------------------------------------------------- 1 | import re 2 | import uuid 3 | 4 | from cyclonedx.model.component import ComponentType, Component 5 | from cyclonedx.model.crypto import CertificateProperties, CryptoProperties, AssetType 6 | 7 | from cbom import lib_utils 8 | from cbom.parser import utils 9 | 10 | _X509_ATTRIBUTE_NAMES = { 11 | 'COMMON_NAME': 'CN', # 2.5.4.3 12 | 'LOCALITY_NAME': 'L', # 2.5.4.7 13 | 'STATE_OR_PROVINCE_NAME': 'ST', # 2.5.4.8 14 | 'ORGANIZATION_NAME': 'O', # 2.5.4.10 15 | 'ORGANIZATIONAL_UNIT_NAME': 'OU', # 2.5.4.11 16 | 'COUNTRY_NAME': 'C', # 2.5.4.6 17 | 'DOMAIN_COMPONENT': 'DC', # 0.9.2342.19200300.100.1.2 18 | 'USER_ID': 'UID', # 0.9.2342.19200300.100.1.1 19 | } 20 | 21 | _X509_ATTRIBUTES_REGEX = re.compile(f"({'|'.join(_X509_ATTRIBUTE_NAMES.keys())})(.*['\"].*['\"])", flags=re.IGNORECASE) 22 | _SIGNING_ALGORITHM_REGEX = re.compile(f"sign[A-Z\\d_$]*\\(.*({'|'.join(lib_utils.get_algorithms())}).*\\)", flags=re.IGNORECASE) 23 | 24 | 25 | def parse_x509_certificate_details(cbom, finding): 26 | crypto_properties = _generate_crypto_component(finding) 27 | unique_identifier = uuid.uuid4() 28 | 29 | component = Component( 30 | bom_ref=f'cryptography:certificate:{unique_identifier}', 31 | name=str(unique_identifier), 32 | type=ComponentType.CRYPTO_ASSET, 33 | crypto_properties=crypto_properties 34 | ) 35 | if not (existing_component := _is_existing_component_overlap(cbom, component)): 36 | cbom.components.add(component) 37 | else: 38 | component = _update_existing_component(existing_component, component) 39 | return component 40 | 41 | 42 | def _generate_crypto_component(finding): 43 | code_snippet = finding['contextRegion']['snippet']['text'] 44 | subject = issuer = _generate_distinguished_name(code_snippet) 45 | 46 | return CryptoProperties( 47 | asset_type=AssetType.CERTIFICATE, 48 | certificate_properties=CertificateProperties( 49 | subject_name=subject, 50 | issuer_name=issuer, 51 | certificate_algorithm=utils.get_algorithm(code_snippet), 52 | certificate_signature_algorithm=_extract_signature_algorithm(code_snippet), # todo: dependency relation for signing algorithm 53 | certificate_format='X.509' 54 | ), 55 | detection_context=[utils.get_detection_context(finding)] 56 | ) 57 | 58 | 59 | def _generate_distinguished_name(code_snippet): 60 | 61 | def append(text): 62 | nonlocal distinguished_name 63 | distinguished_name += f', {text}' if distinguished_name else text 64 | 65 | distinguished_name = '' 66 | for attribute_name, attribute_value in re.findall(_X509_ATTRIBUTES_REGEX, code_snippet): 67 | start_index = attribute_value.index(attribute_value[-1]) 68 | attribute_value = attribute_value[start_index + 1:len(attribute_value) - 1] 69 | append(f'{_X509_ATTRIBUTE_NAMES[attribute_name.upper()]}={attribute_value}') 70 | return distinguished_name 71 | 72 | 73 | def _extract_signature_algorithm(code_snippet): 74 | match = _SIGNING_ALGORITHM_REGEX.search(code_snippet) 75 | if match: 76 | return _SIGNING_ALGORITHM_REGEX.sub('\\1', match.group()) 77 | 78 | 79 | def _is_existing_component_overlap(cbom, component): 80 | certificate_components = (c for c in cbom.components if c.crypto_properties.asset_type == AssetType.CERTIFICATE) 81 | 82 | for existing_component in certificate_components: 83 | if ( # same certificate algorithm & overlapping detection context 84 | existing_component.crypto_properties.certificate_properties.certificate_algorithm == component.crypto_properties.certificate_properties.certificate_algorithm and 85 | utils.is_existing_detection_context_match(existing_component, component.crypto_properties.detection_context[0]) 86 | ): 87 | return existing_component 88 | 89 | 90 | def _update_existing_component(existing_component, component): 91 | context = component.crypto_properties.detection_context[0] 92 | 93 | if existing_context := utils.is_existing_detection_context_match(existing_component, context): 94 | existing_context.additional_context = utils.merge_code_snippets(existing_context, context) 95 | existing_context.line_numbers = existing_context.line_numbers.union(context.line_numbers) 96 | 97 | for field in vars(component.crypto_properties.certificate_properties): 98 | if not getattr(existing_component.crypto_properties.certificate_properties, field): 99 | field_value = getattr(component.crypto_properties.certificate_properties, field) 100 | setattr(existing_component.crypto_properties.certificate_properties, field, field_value) 101 | return existing_component 102 | -------------------------------------------------------------------------------- /cbom/cli/cli.py: -------------------------------------------------------------------------------- 1 | import json 2 | import pathlib 3 | import re 4 | 5 | import click 6 | from click import Path 7 | from cyclonedx.model.bom import Bom, Tool 8 | from cyclonedx.model.component import Component, ComponentType 9 | from cyclonedx.output.json import JsonV1Dot4CbomV1Dot0 10 | 11 | from cbom import __version__ 12 | from cbom.cryptocheck import cryptocheck 13 | from cbom.parser import algorithm 14 | 15 | 16 | @click.group(context_settings={ 17 | 'max_content_width': 120, 18 | 'show_default': True 19 | }) 20 | @click.version_option(__version__, '--version', '-v') 21 | def cryptobom(): 22 | """\b 23 | _ _ __ \b 24 | | | | | / _| \b 25 | ___ _ __ _ _ _ __ | |_ ___ | |__ ___ _ __ ___ | |_ ___ _ __ __ _ ___ \b 26 | / __|| '__|| | | || '_ \ | __| / _ \ | '_ \ / _ \ | '_ ` _ \ ______ | _| / _ \ | '__| / _` | / _ \ \b 27 | | (__ | | | |_| || |_) || |_ | (_) || |_) || (_) || | | | | ||______|| | | (_) || | | (_| || __/ \b 28 | \___||_| \__, || .__/ \__| \___/ |_.__/ \___/ |_| |_| |_| |_| \___/ |_| \__, | \___| \b 29 | __/ || | __/ | \b 30 | |___/ |_| |___/ 31 | 32 | Welcome to cryptobom-forge! 33 | 34 | This script is intended to be used in conjunction with the SARIF output from the CodeQL cryptography experimental 35 | queries. 36 | 37 | You can use this script to generate a cryptographic bill of materials (CBOM) for a repository, and analyse your 38 | cryptographic inventory for weak and non-pqc-safe cryptography. 39 | """ 40 | 41 | 42 | @cryptobom.command(context_settings={ 43 | 'default_map': { 44 | 'application_name': 'root', 45 | 'cryptocheck_output_file': 'cryptocheck.sarif' 46 | } 47 | }) 48 | @click.argument('path', type=Path(exists=True, path_type=pathlib.Path), required=True) 49 | @click.option('--application-name', '-n', help='Root application name') 50 | @click.option('--cryptocheck', '-cc', 'enable_cryptocheck', is_flag=True, help='Enable crypto vulnerability scanning') 51 | @click.option('--exclude', '-e', 'exclusion_pattern', metavar='REGEX', help='Exclude CodeQL findings in file paths that match ') 52 | @click.option('--output-file', '-o', help='CBOM output file') 53 | @click.option('--rules-file', '-r', type=Path(exists=True, path_type=pathlib.Path), help='Custom ruleset for cryptocheck analysis') 54 | @click.option('--cryptocheck-output-file', help='Cryptocheck analysis output file') 55 | def generate(path, application_name, enable_cryptocheck, exclusion_pattern, output_file, rules_file, cryptocheck_output_file): 56 | """Generate a CBOM from CodeQL SARIF output.""" 57 | cbom = Bom() 58 | cbom.metadata.component = Component(name=application_name, type=ComponentType.APPLICATION) 59 | 60 | if exclusion_pattern: 61 | exclusion_pattern = re.compile(exclusion_pattern) 62 | 63 | if path.is_file(): 64 | _process_file(cbom, path, exclusion_pattern=exclusion_pattern) 65 | else: 66 | for file_path in [*list(path.glob('*.sarif')), *list(path.glob('*.json'))]: 67 | _process_file(cbom, file_path, exclusion_pattern=exclusion_pattern) 68 | 69 | if enable_cryptocheck: 70 | cryptocheck_output = cryptocheck.validate_cbom(cbom, rules_file) 71 | with open(cryptocheck_output_file, 'w') as file: 72 | click.echo(message=json.dumps(cryptocheck_output, indent=4, sort_keys=True), file=file) 73 | 74 | cbom = json.loads(JsonV1Dot4CbomV1Dot0(cbom).output_as_string(bom_format='CBOM')) 75 | if output_file: 76 | with open(output_file, 'w') as file: 77 | click.echo(message=json.dumps(cbom, indent=4), file=file) 78 | else: 79 | click.echo(message=json.dumps(cbom, indent=4)) 80 | 81 | 82 | def start(): 83 | try: 84 | cryptobom() 85 | except Exception as e: 86 | click.secho(str(e), fg='red') 87 | 88 | 89 | def _process_file(cbom, query_file, exclusion_pattern=None): 90 | with open(query_file) as query_output: 91 | query_output = json.load(query_output)['runs'][0] 92 | 93 | driver = query_output['tool']['driver'] 94 | cbom.metadata.tools.add(Tool( 95 | vendor=driver['organization'], 96 | name=driver['name'], 97 | version=driver.get('version', driver.get('semanticVersion')) # fixme: sarif misaligned 98 | )) 99 | 100 | for result in query_output['results']: 101 | result = result['locations'][0]['physicalLocation'] 102 | if not exclusion_pattern or not exclusion_pattern.fullmatch(result['artifactLocation']['uri']): 103 | algorithm.parse_algorithm(cbom, result) 104 | 105 | 106 | if __name__ == '__main__': 107 | start() 108 | -------------------------------------------------------------------------------- /cbom/cryptocheck/cryptocheck.py: -------------------------------------------------------------------------------- 1 | """CryptoCheck - a small, fast cryptography checker for use with SARIF files generated by 2 | CodeQL queries defined by Microsoft and GitHub as part of the Pre-Quantum Research project.""" 3 | 4 | import ast 5 | import json 6 | from decimal import Decimal 7 | from pathlib import Path 8 | 9 | import jsonschema 10 | import yaml 11 | from cyclonedx.model import XsUri 12 | from cyclonedx.model.vulnerability import BomTarget, Vulnerability, VulnerabilityAdvisory, VulnerabilityRating, \ 13 | VulnerabilitySeverity, VulnerabilitySource 14 | 15 | from cbom.cryptocheck import sarif, validators 16 | 17 | """ 18 | All rules are in the form match_type(criteria, target_to_check) 19 | """ 20 | 21 | _VALIDATORS = { 22 | 'r': validators.does_match_regex, 23 | 's': validators.does_contain, 24 | 'lt': validators.is_less_than, 25 | 'gt': validators.is_greater_than, 26 | 'lteq': validators.is_less_than_or_equal, 27 | 'gteq': validators.is_greater_than_or_equal, 28 | 'eq': validators.is_equal, 29 | 'neq': validators.is_not_equal 30 | } 31 | 32 | 33 | def validate_cbom(cbom, rules_file=None, *, enrich_cbom=True): 34 | """ 35 | compare everything to everything 36 | """ 37 | rules = _load_rules(rules_file) 38 | 39 | rule_violations = [] 40 | for rule in rules: 41 | non_compliant_components = [] 42 | algorithm_components = (c for c in cbom.components if c.type == 'crypto-asset' and c.crypto_properties.asset_type == 'algorithm') 43 | 44 | for algorithm_component in algorithm_components: 45 | algorithm_properties = algorithm_component.crypto_properties.algorithm_properties 46 | variant = algorithm_properties.variant.split('-') 47 | variant = { 48 | 'algo': variant[0], 49 | 'keylen': int(variant[1]) if len(variant) > 1 and variant[1].isnumeric() else None, 50 | 'mode': algorithm_properties.mode, 51 | 'padding': algorithm_properties.padding 52 | } 53 | 54 | is_match = map(lambda pattern: _VALIDATORS[pattern[1]](pattern[2], variant[pattern[0]]), rule['patterns']) 55 | if all(is_match): 56 | non_compliant_components.append(algorithm_component.bom_ref) 57 | 58 | if non_compliant_components: # todo: handle default 59 | rule_violations.append({ 60 | 'name': rule['name'], 61 | 'detection': rule['detection'], 62 | 'bom-refs': non_compliant_components 63 | }) 64 | 65 | if enrich_cbom: 66 | _add_vulnerabilities_to_cbom(cbom, rule_violations) 67 | return sarif.build_cryptocheck_sarif(cbom, rules, rule_violations) 68 | 69 | 70 | def _load_rules(file_path=None): 71 | if not file_path: 72 | file_path = Path(__file__).absolute().parent.parent / 'resources/cryptocheck_rules.yml' 73 | 74 | with ( 75 | open(file_path) as rules, 76 | open(Path(__file__).absolute().parent.parent / 'resources/cryptocheck_schema.json') as schema 77 | ): 78 | rules = yaml.safe_load(rules) 79 | jsonschema.validate(rules, json.load(schema)) 80 | for rule in rules: 81 | rule['patterns'] = [ast.literal_eval(pattern) for pattern in rule['patterns']] 82 | return rules 83 | 84 | 85 | def _add_vulnerabilities_to_cbom(cbom, rule_violations): 86 | for violation in rule_violations: 87 | affected_components = [BomTarget(ref=bom_ref.value) for bom_ref in violation['bom-refs']] 88 | rating = VulnerabilityRating( 89 | source=VulnerabilitySource( 90 | url=XsUri('To follow'), # todo 91 | name='cryptocheck from SAN, MS, GH' # todo 92 | ), 93 | score=Decimal(violation['detection']['severity']), 94 | severity=_get_severity_from_score(violation['detection']['severity']) 95 | ) 96 | 97 | cbom.vulnerabilities.add(Vulnerability( 98 | bom_ref=f"cryptocheck:{violation['name']}", 99 | id=violation['name'], 100 | ratings=[rating], 101 | cwes=[], # todo 102 | description=violation['detection']['description'], 103 | recommendation='Please review the use of cryptography, and make plans according to best practices.', 104 | advisories=[ 105 | VulnerabilityAdvisory(url=XsUri('To follow')) # todo 106 | ], 107 | # published='2023-12-05T09:00:00.000Z', # todo 108 | affects=affected_components 109 | )) 110 | 111 | 112 | def _get_severity_from_score(score): 113 | match score: 114 | case score if score >= 9.0: 115 | return VulnerabilitySeverity.CRITICAL 116 | case score if score >= 7.0: 117 | return VulnerabilitySeverity.HIGH 118 | case score if score >= 4.0: 119 | return VulnerabilitySeverity.MEDIUM 120 | case score if score < 4.0: 121 | return VulnerabilitySeverity.LOW 122 | case _: 123 | return VulnerabilitySeverity.INFO 124 | -------------------------------------------------------------------------------- /tests/integration_tests/data/codeql/partial_results/symmetric_algorithms.sarif: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/sarif-2.1.0.json", 3 | "version": "2.1.0", 4 | "runs": [ 5 | { 6 | "tool": { 7 | "driver": { 8 | "name": "CodeQL", 9 | "organization": "GitHub", 10 | "semanticVersion": "2.15.4" 11 | } 12 | }, 13 | "artifacts": [ 14 | { 15 | "location": { 16 | "uri": "springfield-nuclear-power-plant/core-reactor.py", 17 | "uriBaseId": "%SRCROOT%", 18 | "index": 0 19 | } 20 | }, 21 | { 22 | "location": { 23 | "uri": "springfield-nuclear-power-plant/tests/core-reactor.py", 24 | "uriBaseId": "%SRCROOT%", 25 | "index": 1 26 | } 27 | } 28 | ], 29 | "results": [ 30 | { 31 | "ruleId": "py/quantum-readiness/cbom/all-cryptographic-algorithms", 32 | "ruleIndex": 0, 33 | "rule": { 34 | "id": "py/quantum-readiness/cbom/all-cryptographic-algorithms", 35 | "index": 0 36 | }, 37 | "message": { 38 | "text": "Use of algorithm AES" 39 | }, 40 | "locations": [ 41 | { 42 | "physicalLocation": { 43 | "artifactLocation": { 44 | "uri": "springfield-nuclear-power-plant/core-reactor.py", 45 | "uriBaseId": "%SRCROOT%", 46 | "index": 0 47 | }, 48 | "region": { 49 | "startLine": 30, 50 | "endLine": 41, 51 | "endColumn": 22 52 | }, 53 | "contextRegion": { 54 | "startLine": 28, 55 | "endLine": 43, 56 | "snippet": { 57 | "text": "# additional context region\n# additional context region\ndef encrypt(message):\n padder = padding.PKCS7(128).padder()\n message = padder.update(message.encode()) + padder.finalize()\n\n key = os.urandom(32)\n encryptor = Cipher(\n algorithms.AES(key),\n modes.ECB(initialization_vector=os.urandom(16))\n ).encryptor()\n\n ciphertext = encryptor.update(message) + encryptor.finalize()\n return ciphertext\n# additional context region\n# additional context region" 58 | } 59 | } 60 | } 61 | } 62 | ], 63 | "partialFingerprints": { 64 | "primaryLocationLineHash": "61744bbabae05152:1", 65 | "primaryLocationStartColumnFingerprint": "0" 66 | } 67 | }, 68 | { 69 | "ruleId": "py/quantum-readiness/cbom/all-cryptographic-algorithms", 70 | "ruleIndex": 0, 71 | "rule": { 72 | "id": "py/quantum-readiness/cbom/all-cryptographic-algorithms", 73 | "index": 0 74 | }, 75 | "message": { 76 | "text": "Use of algorithm FERNET" 77 | }, 78 | "locations": [ 79 | { 80 | "physicalLocation": { 81 | "artifactLocation": { 82 | "uri": "springfield-nuclear-power-plant/tests/core-reactor.py", 83 | "uriBaseId": "%SRCROOT%", 84 | "index": 1 85 | }, 86 | "region": { 87 | "startLine": 30, 88 | "endLine": 33, 89 | "endColumn": 22 90 | }, 91 | "contextRegion": { 92 | "startLine": 28, 93 | "endLine": 35, 94 | "snippet": { 95 | "text": "# additional context region\n# additional context region\ndef encrypt(message):\n encryptor = Fernet(Fernet.generate_key())\n ciphertext = encryptor.encrypt(message.encode())\n return ciphertext\n# additional context region\n# additional context region" 96 | } 97 | } 98 | } 99 | } 100 | ], 101 | "partialFingerprints": { 102 | "primaryLocationLineHash": "61744bbabae05152:1", 103 | "primaryLocationStartColumnFingerprint": "0" 104 | } 105 | } 106 | ], 107 | "columnKind": "unicodeCodePoints", 108 | "properties": { 109 | "semmle.formatSpecifier": "sarifv2.1.0" 110 | } 111 | } 112 | ] 113 | } -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | 2 | # Contributor Covenant Code of Conduct 3 | 4 | ## Our Pledge 5 | 6 | We as members, contributors, and leaders pledge to make participation in our 7 | community a harassment-free experience for everyone, regardless of age, body 8 | size, visible or invisible disability, ethnicity, sex characteristics, gender 9 | identity and expression, level of experience, education, socio-economic status, 10 | nationality, personal appearance, race, caste, color, religion, or sexual 11 | identity and orientation. 12 | 13 | We pledge to act and interact in ways that contribute to an open, welcoming, 14 | diverse, inclusive, and healthy community. 15 | 16 | ## Our Standards 17 | 18 | Examples of behavior that contributes to a positive environment for our 19 | community include: 20 | 21 | * Demonstrating empathy and kindness toward other people 22 | * Being respectful of differing opinions, viewpoints, and experiences 23 | * Giving and gracefully accepting constructive feedback 24 | * Accepting responsibility and apologizing to those affected by our mistakes, 25 | and learning from the experience 26 | * Focusing on what is best not just for us as individuals, but for the overall 27 | community 28 | 29 | Examples of unacceptable behavior include: 30 | 31 | * The use of sexualized language or imagery, and sexual attention or advances of 32 | any kind 33 | * Trolling, insulting or derogatory comments, and personal or political attacks 34 | * Public or private harassment 35 | * Publishing others' private information, such as a physical or email address, 36 | without their explicit permission 37 | * Other conduct which could reasonably be considered inappropriate in a 38 | professional setting 39 | 40 | ## Enforcement Responsibilities 41 | 42 | Community leaders are responsible for clarifying and enforcing our standards of 43 | acceptable behavior and will take appropriate and fair corrective action in 44 | response to any behavior that they deem inappropriate, threatening, offensive, 45 | or harmful. 46 | 47 | Community leaders have the right and responsibility to remove, edit, or reject 48 | comments, commits, code, wiki edits, issues, and other contributions that are 49 | not aligned to this Code of Conduct, and will communicate reasons for moderation 50 | decisions when appropriate. 51 | 52 | ## Scope 53 | 54 | This Code of Conduct applies within all community spaces, and also applies when 55 | an individual is officially representing the community in public spaces. 56 | Examples of representing our community include using an official email address, 57 | posting via an official social media account, or acting as an appointed 58 | representative at an online or offline event. 59 | 60 | [//]: # (## Enforcement) 61 | 62 | [//]: # () 63 | [//]: # (Instances of abusive, harassing, or otherwise unacceptable behavior may be) 64 | 65 | [//]: # (reported to the community leaders responsible for enforcement at) 66 | 67 | [//]: # ([INSERT CONTACT METHOD].) 68 | 69 | [//]: # (All complaints will be reviewed and investigated promptly and fairly.) 70 | 71 | [//]: # () 72 | [//]: # (All community leaders are obligated to respect the privacy and security of the) 73 | 74 | [//]: # (reporter of any incident.) 75 | 76 | ## Enforcement Guidelines 77 | 78 | Community leaders will follow these Community Impact Guidelines in determining 79 | the consequences for any action they deem in violation of this Code of Conduct: 80 | 81 | ### 1. Correction 82 | 83 | **Community Impact**: Use of inappropriate language or other behavior deemed 84 | unprofessional or unwelcome in the community. 85 | 86 | **Consequence**: A private, written warning from community leaders, providing 87 | clarity around the nature of the violation and an explanation of why the 88 | behavior was inappropriate. A public apology may be requested. 89 | 90 | ### 2. Warning 91 | 92 | **Community Impact**: A violation through a single incident or series of 93 | actions. 94 | 95 | **Consequence**: A warning with consequences for continued behavior. No 96 | interaction with the people involved, including unsolicited interaction with 97 | those enforcing the Code of Conduct, for a specified period of time. This 98 | includes avoiding interactions in community spaces as well as external channels 99 | like social media. Violating these terms may lead to a temporary or permanent 100 | ban. 101 | 102 | ### 3. Temporary Ban 103 | 104 | **Community Impact**: A serious violation of community standards, including 105 | sustained inappropriate behavior. 106 | 107 | **Consequence**: A temporary ban from any sort of interaction or public 108 | communication with the community for a specified period of time. No public or 109 | private interaction with the people involved, including unsolicited interaction 110 | with those enforcing the Code of Conduct, is allowed during this period. 111 | Violating these terms may lead to a permanent ban. 112 | 113 | ### 4. Permanent Ban 114 | 115 | **Community Impact**: Demonstrating a pattern of violation of community 116 | standards, including sustained inappropriate behavior, harassment of an 117 | individual, or aggression toward or disparagement of classes of individuals. 118 | 119 | **Consequence**: A permanent ban from any sort of public interaction within the 120 | community. 121 | 122 | ## Attribution 123 | 124 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 125 | version 2.1, available at 126 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. 127 | 128 | Community Impact Guidelines were inspired by 129 | [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. 130 | 131 | For answers to common questions about this code of conduct, see the FAQ at 132 | [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at 133 | [https://www.contributor-covenant.org/translations][translations]. 134 | 135 | [homepage]: https://www.contributor-covenant.org 136 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html 137 | [Mozilla CoC]: https://github.com/mozilla/diversity 138 | [FAQ]: https://www.contributor-covenant.org/faq 139 | [translations]: https://www.contributor-covenant.org/translations 140 | -------------------------------------------------------------------------------- /cbom/parser/algorithm.py: -------------------------------------------------------------------------------- 1 | import re 2 | import uuid 3 | 4 | from cyclonedx.model.component import ComponentType, Component 5 | from cyclonedx.model.crypto import Primitive, CryptoProperties, AssetType, AlgorithmProperties, Mode, Padding 6 | 7 | from cbom import lib_utils 8 | from cbom.parser import certificate, utils, related_crypto_material 9 | 10 | _BLOCK_MODE_REGEX = re.compile(f"{'|'.join(lib_utils.get_block_modes())}", flags=re.IGNORECASE) 11 | _FUNCTION_REGEX = re.compile(f"\\.[A-Z_\\d]*({'|'.join(lib_utils.get_functions())})[A-Z_\\d]*") 12 | _PADDING_REGEX = re.compile(f"{'|'.join(lib_utils.get_padding_schemes())}", flags=re.IGNORECASE) 13 | 14 | 15 | def parse_algorithm(cbom, finding): 16 | crypto_properties = _generate_crypto_component(finding) 17 | if (padding := crypto_properties.algorithm_properties.padding) not in [Padding.OTHER, Padding.UNKNOWN]: 18 | name = f'{crypto_properties.algorithm_properties.variant}-{padding.value.upper()}' 19 | else: 20 | name = crypto_properties.algorithm_properties.variant 21 | 22 | algorithm_component = Component( 23 | bom_ref=f'cryptography:algorithm:{uuid.uuid4()}', 24 | name=name, 25 | type=ComponentType.CRYPTO_ASSET, 26 | crypto_properties=crypto_properties 27 | ) 28 | 29 | if not (existing_component := _is_existing_component_overlap(cbom, algorithm_component)): 30 | cbom.components.add(algorithm_component) 31 | cbom.register_dependency(cbom.metadata.component, depends_on=[algorithm_component]) 32 | else: 33 | algorithm_component = _update_existing_component(existing_component, algorithm_component) 34 | 35 | if crypto_properties.algorithm_properties.primitive == Primitive.PUBLIC_KEY_ENCRYPTION: 36 | code_snippet = finding['contextRegion']['snippet']['text'] 37 | if 'key' in code_snippet.lower(): 38 | private_key_component = related_crypto_material.parse_private_key(cbom, finding) 39 | cbom.register_dependency(algorithm_component, depends_on=[private_key_component]) 40 | 41 | if 'x509' in code_snippet.lower() or 'x.509' in code_snippet.lower(): 42 | certificate_component = certificate.parse_x509_certificate_details(cbom, finding) 43 | cbom.register_dependency(algorithm_component, depends_on=[certificate_component]) 44 | 45 | 46 | def _generate_crypto_component(finding): 47 | code_snippet = finding['contextRegion']['snippet']['text'] 48 | algorithm = utils.get_algorithm(utils.extract_precise_snippet(code_snippet, finding['region'])) 49 | 50 | if algorithm == 'unknown': 51 | algorithm = utils.get_algorithm(code_snippet) 52 | 53 | if algorithm == 'FERNET': 54 | algorithm, key_size, mode = 'AES', '128', Mode.CBC 55 | primitive = Primitive.BLOCK_CIPHER 56 | else: 57 | primitive = _infer_primitive(algorithm) 58 | if 'key' in code_snippet.lower() and primitive != Primitive.HASH: 59 | key_size = utils.get_key_size(code_snippet) 60 | else: 61 | key_size = None 62 | 63 | try: 64 | if primitive == Primitive.BLOCK_CIPHER: 65 | mode = _extract_mode(code_snippet) 66 | mode = Mode(mode.lower()) if mode else Mode.UNKNOWN 67 | else: 68 | mode = None 69 | except ValueError: 70 | mode = Mode.OTHER 71 | 72 | try: 73 | padding = _extract_padding(code_snippet) 74 | padding = Padding(padding.lower()) if padding else Padding.UNKNOWN 75 | except ValueError: 76 | padding = Padding.OTHER 77 | 78 | return CryptoProperties( 79 | asset_type=AssetType.ALGORITHM, 80 | algorithm_properties=AlgorithmProperties( 81 | primitive=primitive, 82 | variant=_build_variant(algorithm, key_size=key_size, block_mode=mode), 83 | mode=mode, 84 | padding=padding, 85 | crypto_functions=_extract_crypto_functions(code_snippet) 86 | ), 87 | detection_context=[utils.get_detection_context(finding)] 88 | ) 89 | 90 | 91 | def _build_variant(algorithm, *, key_size=None, block_mode=None): 92 | variant = algorithm.upper() 93 | if key_size: 94 | variant += f'-{key_size}' 95 | if block_mode and block_mode not in [Mode.OTHER, Mode.UNKNOWN]: 96 | variant += f'-{block_mode.value.upper()}' 97 | return variant 98 | 99 | 100 | def _extract_crypto_functions(code_snippet): 101 | matches = _FUNCTION_REGEX.findall(''.join(code_snippet.split())) 102 | matches = [_FUNCTION_REGEX.sub('\\1', m) for m in matches] 103 | return set(matches) 104 | 105 | 106 | def _extract_mode(code_snippet): 107 | match = _BLOCK_MODE_REGEX.search(code_snippet) 108 | if match: 109 | return match.group() 110 | 111 | 112 | def _extract_padding(code_snippet): 113 | match = _PADDING_REGEX.search(code_snippet) 114 | if match: 115 | return match.group() 116 | 117 | 118 | def _infer_primitive(algorithm, additional_context=None): 119 | primitive = lib_utils.get_primitive_mapping(algorithm.lower()) 120 | return Primitive(primitive) 121 | 122 | 123 | def _is_existing_component_overlap(cbom, component): 124 | algorithm_components = (c for c in cbom.components if c.crypto_properties.asset_type == AssetType.ALGORITHM) 125 | 126 | for existing_component in algorithm_components: 127 | if existing_component.name == component.name: 128 | return existing_component 129 | 130 | 131 | def _update_existing_component(existing_component, component): 132 | new_context = component.crypto_properties.detection_context[0] 133 | 134 | if existing_context := utils.is_existing_detection_context_match(existing_component, new_context): 135 | existing_context.additional_context = utils.merge_code_snippets(existing_context, new_context) 136 | existing_context.line_numbers = existing_context.line_numbers.union(new_context.line_numbers) 137 | return existing_component 138 | else: 139 | existing_component.crypto_properties.algorithm_properties.crypto_functions.update(component.crypto_properties.algorithm_properties.crypto_functions) 140 | existing_component.crypto_properties.detection_context.add(new_context) 141 | return existing_component 142 | -------------------------------------------------------------------------------- /cbom/resources/cryptocheck_rules.yml: -------------------------------------------------------------------------------- 1 | ################################ 2 | # BAD CRYPTO 3 | ################################ 4 | 5 | - name: MD5-detect 6 | detection: 7 | type: error 8 | severity: 9.0 9 | description: MD5 was detected, which is a deprecated hashing algorithm that is prone to collisions, and should not be used. 10 | patterns: 11 | - ('algo', 'r', '(?i)MD5') 12 | 13 | - name: SHA1-detect 14 | detection: 15 | type: error 16 | severity: 7.0 17 | description: SHA1 was detected, which is a recognized unsafe hashing algorithm. This should be removed as soon as possible to prevent cryptographic issues. 18 | patterns: 19 | - ('algo', 'r', '(?i)SHA1') 20 | 21 | - name: RSA-unsafe-key 22 | detection: 23 | type: warning 24 | severity: 5.0 25 | description: The RSA key was found to be too short. 26 | patterns: 27 | - ('keylen', 'lt', 2048) 28 | - ('algo', 'eq', 'RSA') 29 | 30 | - name: AES-ECB-mode 31 | detection: 32 | type: error 33 | severity: 9.0 34 | description: AES was found operating in ECB mode. Please don't. 35 | patterns: 36 | - ('algo', 's', 'AES') 37 | - ('mode', 's', 'ECB') 38 | 39 | - name: AES-CBC-mode 40 | detection: 41 | type: warning 42 | severity: 4.0 43 | description: AES was found operating in CBC mode, which will need manual review to determine if it is implemented safely. 44 | patterns: 45 | - ('algo', 'eq', 'AES') 46 | - ('mode', 's', 'CBC') 47 | 48 | - name: CAMELLIA-CBC-mode 49 | detection: 50 | type: warning 51 | severity: 4.0 52 | description: CAMELLIA was found operating in CBC mode, which will need manual review to determine if it is implemented safely. 53 | patterns: 54 | - ('algo', 'eq', 'CAMELLIA') 55 | - ('mode', 's', 'CBC') 56 | 57 | - name: 3DES-detect 58 | detection: 59 | type: warning 60 | severity: 9.0 61 | description: 3DES was found which is a now-deprecated algorithm. This should be changed as soon as practical. 62 | patterns: 63 | - ('algo', 'r', '(3DES|TRIPLEDES|2TDEA|3TDEA)') 64 | 65 | - name: PKCS-detect 66 | detection: 67 | type: warning 68 | severity: 3.0 69 | description: A potentially vulnerable version of PKCS was found to be in use - it should be checked that this is not a vulnerable version (1/1.5). 70 | patterns: 71 | - ('algo', 'r', 'PKCS(1|1.5)') 72 | 73 | - name: RC4-detect 74 | detection: 75 | type: error 76 | severity: 4.0 77 | description: RC4 was detected. This is a deprecated cipher that is highly vulnerable and should be replaced as soon as possible. 78 | patterns: 79 | - ('algo', 'r', '(?i)(RC4|ARCFOUR|ARC4)') 80 | 81 | 82 | - name: IDEA-detect 83 | detection: 84 | type: error 85 | severity: 4.0 86 | description: IDEA (International Data Encryption Algorithm) was detected. Whilst this is not necessarily insecure, it has been deprecated in RFC5469. 87 | patterns: 88 | - ('algo', 'r', '(?i)(IDEA)') 89 | 90 | - name: BLOWFISH-detect 91 | detection: 92 | type: error 93 | severity: 4.0 94 | description: BLOWFISH cipher was detected. This is a deprecated cipher that should be replaced as soon as possible. 95 | patterns: 96 | - ('algo', 'r', '(?i)(BLOWFISH)') 97 | 98 | #- name: Insecure-mode-detect 99 | # detection: 100 | # type: error 101 | # severity: 4.0 102 | # description: An insecure mode was detected - these modes (ECB, CFB, OFB, and CTR) are not considered best practice and should be replaced with more advanced modes such as GCM, or AEAD should be applied. 103 | # patterns: 104 | # - ('mode', 'r', '(ECB|CFB|OFB|CTR)') 105 | 106 | ################################ 107 | # NON-PQC CRYPTO 108 | ################################ 109 | 110 | 111 | - name: AES-128-not-PQC 112 | detection: 113 | type: warning 114 | severity: 3.0 115 | description: AES-128 was found, which is vulnerable to Grover's search cryptanalytic attack. 116 | patterns: 117 | - ('algo', 's', 'AES') 118 | - ('keylen', 'eq', 128) 119 | 120 | - name: AES-192-not-PQC 121 | detection: 122 | type: warning 123 | severity: 3.0 124 | description: AES-192 was found, which is vulnerable to Grover's search cryptanalytic attack. 125 | patterns: 126 | - ('algo', 's', 'AES') 127 | - ('keylen', 'eq', 192) 128 | 129 | - name: DH-detect 130 | detection: 131 | type: note 132 | severity: 3.0 133 | description: DH was found in use, which is not Post-Quantum Safe and should be flagged for migration to PQC algorithms when they become available. 134 | patterns: 135 | - ('algo', 's', '(DIFFIEHELLMAN|DH\w)') 136 | 137 | - name: RSA-detect 138 | detection: 139 | type: note 140 | severity: 3.0 141 | description: RSA was found in use, which is not Post-Quantum Safe and should be flagged for migration to PQC algorithms when they become available. 142 | patterns: 143 | - ('algo', 's', 'RSA') 144 | 145 | - name: RSA-quantum-unsafe-key 146 | detection: 147 | type: note 148 | severity: 3.0 149 | description: RSA was found in use, which is not Post-Quantum Safe and should be flagged for migration to PQC algorithms when they become available. 150 | patterns: 151 | - ('algo', 's', 'RSA') 152 | - ('keylen', 'gteq', 2048) 153 | - ('keylen', 'lt', 4096) 154 | 155 | - name: DSA-detect 156 | detection: 157 | type: note 158 | severity: 3.0 159 | description: DSA was found in use, which may not be Post-Quantum Safe and should be flagged for checking and migration to PQC algorithms when they become available. 160 | patterns: 161 | - ('algo', 'eq', 'DSA') 162 | 163 | - name: ECDSA-detect 164 | detection: 165 | type: note 166 | severity: 3.0 167 | description: ECDSA was found in use, which is not Post-Quantum Safe and should be flagged for migration to PQC algorithms when they become available. 168 | patterns: 169 | - ('algo', 'eq', 'ECDSA') 170 | 171 | - name: EdDSA-detect 172 | detection: 173 | type: note 174 | severity: 3.0 175 | description: EdDSA was found in use, which is not Post-Quantum Safe and should be flagged for migration to PQC algorithms when they become available. 176 | patterns: 177 | - ('algo', 'eq', 'EdDSA') 178 | 179 | - name: MAC-detect 180 | detection: 181 | type: note 182 | severity: 3.0 183 | description: A MAC was found in use. These should be manually reviewed to ensure they are Post-Quantum Safe and should be flagged for migration to PQC algorithms when they become available where necessary. 184 | patterns: 185 | - ('algo', 'r', '(HMAC|KMAC|CMAC)') 186 | -------------------------------------------------------------------------------- /tests/integration_tests/data/codeql/partial_results/asymmetric_algorithms.sarif: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/sarif-2.1.0.json", 3 | "version": "2.1.0", 4 | "runs": [ 5 | { 6 | "tool": { 7 | "driver": { 8 | "name": "CodeQL", 9 | "organization": "GitHub", 10 | "semanticVersion": "2.15.4" 11 | } 12 | }, 13 | "artifacts": [ 14 | { 15 | "location": { 16 | "uri": "springfield-nuclear-power-plant/core-reactor.py", 17 | "uriBaseId": "%SRCROOT%", 18 | "index": 0 19 | } 20 | }, 21 | { 22 | "location": { 23 | "uri": "springfield-nuclear-power-plant/tests/core-reactor.py", 24 | "uriBaseId": "%SRCROOT%", 25 | "index": 1 26 | } 27 | } 28 | ], 29 | "results": [ 30 | { 31 | "ruleId": "py/quantum-readiness/cbom/all-cryptographic-algorithms", 32 | "ruleIndex": 0, 33 | "rule": { 34 | "id": "py/quantum-readiness/cbom/all-cryptographic-algorithms", 35 | "index": 0 36 | }, 37 | "message": { 38 | "text": "Use of algorithm DSA" 39 | }, 40 | "locations": [ 41 | { 42 | "physicalLocation": { 43 | "artifactLocation": { 44 | "uri": "springfield-nuclear-power-plant/core-reactor.py", 45 | "uriBaseId": "%SRCROOT%", 46 | "index": 0 47 | }, 48 | "region": { 49 | "startLine": 30, 50 | "endLine": 62, 51 | "endColumn": 22 52 | }, 53 | "contextRegion": { 54 | "startLine": 28, 55 | "endLine": 64, 56 | "snippet": { 57 | "text": "# additional context region\n# additional context region\ndef encrypt(message):\n private_key = dsa.generate_private_key(\n key_size=2048\n )\n\n subject = issuer = x509.Name([\n x509.NameAttribute(NameOID.COUNTRY_NAME, 'US'),\n x509.NameAttribute(NameOID.LOCALITY_NAME, 'Springfield'),\n x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'Springfield Nuclear Power Plant'),\n x509.NameAttribute(NameOID.COMMON_NAME, \"springfield-nuclear.com\")\n ])\n\n certificate = (\n x509.CertificateBuilder()\n .subject_name(subject)\n .issuer_name(issuer)\n .public_key(private_key.public_key())\n .serial_number(x509.random_serial_number())\n .not_valid_before(datetime.datetime.now(datetime.timezone.utc))\n .not_valid_after(datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=10))\n .add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]), critical=False)\n ).sign(private_key, hashes.SHA256())\n\n public_key = certificate.public_key()\n ciphertext = public_key.encrypt(\n message.encode(),\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None\n )\n )\n return ciphertext\n# additional context region\n# additional context region" 58 | } 59 | } 60 | } 61 | } 62 | ], 63 | "partialFingerprints": { 64 | "primaryLocationLineHash": "61744bbabae05152:1", 65 | "primaryLocationStartColumnFingerprint": "0" 66 | } 67 | }, 68 | { 69 | "ruleId": "py/quantum-readiness/cbom/all-cryptographic-algorithms", 70 | "ruleIndex": 0, 71 | "rule": { 72 | "id": "py/quantum-readiness/cbom/all-cryptographic-algorithms", 73 | "index": 0 74 | }, 75 | "message": { 76 | "text": "Use of algorithm RSA" 77 | }, 78 | "locations": [ 79 | { 80 | "physicalLocation": { 81 | "artifactLocation": { 82 | "uri": "springfield-nuclear-power-plant/core-reactor.py", 83 | "uriBaseId": "%SRCROOT%", 84 | "index": 0 85 | }, 86 | "region": { 87 | "startLine": 30, 88 | "endLine": 63, 89 | "endColumn": 22 90 | }, 91 | "contextRegion": { 92 | "startLine": 28, 93 | "endLine": 65, 94 | "snippet": { 95 | "text": "# additional context region\n# additional context region\ndef encrypt(message):\n private_key = rsa.generate_private_key(\n public_exponent=65537,\n key_size=2048\n )\n\n subject = issuer = x509.Name([\n x509.NameAttribute(NameOID.COUNTRY_NAME, 'US'),\n x509.NameAttribute(NameOID.LOCALITY_NAME, 'Springfield'),\n x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'Springfield Nuclear Power Plant'),\n x509.NameAttribute(NameOID.COMMON_NAME, \"springfield-nuclear.com\")\n ])\n\n certificate = (\n x509.CertificateBuilder()\n .subject_name(subject)\n .issuer_name(issuer)\n .public_key(private_key.public_key())\n .serial_number(x509.random_serial_number())\n .not_valid_before(datetime.datetime.now(datetime.timezone.utc))\n .not_valid_after(datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=10))\n .add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]), critical=False)\n ).sign(private_key, hashes.SHA256())\n\n public_key = certificate.public_key()\n ciphertext = public_key.encrypt(\n message.encode(),\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None\n )\n )\n return ciphertext\n# additional context region\n# additional context region" 96 | } 97 | } 98 | } 99 | } 100 | ], 101 | "partialFingerprints": { 102 | "primaryLocationLineHash": "61744bbabae05152:1", 103 | "primaryLocationStartColumnFingerprint": "0" 104 | } 105 | } 106 | ], 107 | "columnKind": "unicodeCodePoints", 108 | "properties": { 109 | "semmle.formatSpecifier": "sarifv2.1.0" 110 | } 111 | } 112 | ] 113 | } -------------------------------------------------------------------------------- /.gitchangelog.rc: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8; mode: python -*- 2 | ## 3 | ## Format 4 | ## 5 | ## ACTION: COMMIT_MSG [!TAG ...] 6 | ## 7 | ## Description 8 | ## 9 | ## ACTION is one of 'Add', 'Change', 'Fix', 'Remove' 10 | ## 11 | ## Is WHAT the change is about. 12 | ## 13 | ## 'Add' is for new additions 14 | ## 'Change' is for changes to existing stuff 15 | ## 'Fix' is for bug fixes 16 | ## 'Remove' is for stuff that has been removed 17 | ## 18 | ## COMMIT_MSG is ... well ... the commit message itself. 19 | ## 20 | ## TAGs are additional adjective as 'refactor' 'minor' 21 | ## 22 | ## They are preceded with a '!'. Available tags are: 23 | ## 24 | ## 'refactor' is obviously for refactoring code only 25 | ## 'minor' is for a very meaningless change (a typo, adding a comment) 26 | ## 'tests' is for a change only to the tests 27 | ## 'wip' is for partial functionality but complete sub-functionality 28 | ## 'ignore' for any other commit that should be excluded from the changelog 29 | ## 'deprecate' is for deprecating things 30 | ## 'security' is for security patches 31 | ## 'breaking' is for breaking changes 32 | ## 33 | ## Example: 34 | ## 35 | ## new: support of bazaar implemented 36 | ## chg: refactor code modules !refactor 37 | ## new: updated code to be compatible with last version of killer lib. !breaking 38 | ## fix: updated year of licence coverage. 39 | ## new: added a bunch of tests around user usability of feature X. 40 | ## fix: typo in spelling my name in comment. !minor 41 | ## 42 | ## Please note that multi-line commit message are supported, and only the 43 | ## first line will be considered as the "summary" of the commit message. So 44 | ## tags, and other rules only applies to the summary. The body of the commit 45 | ## message will be displayed in the changelog without reformatting. 46 | 47 | 48 | ## 49 | ## ``ignore_regexps`` is a line of regexps 50 | ## 51 | ## Any commit having its full commit message matching any regexp listed here 52 | ## will be ignored and won't be reported in the changelog. 53 | ## 54 | ignore_regexps = [ 55 | r'!ignore', 56 | r'!minor', 57 | r'!refactor', 58 | r'!tests', 59 | r'!wip', 60 | r'^$', ## empty messages 61 | ] 62 | 63 | 64 | ## ``section_regexps`` is a list of 2-tuples associating a string label and a 65 | ## list of regexp 66 | ## 67 | ## Commit messages will be classified in sections thanks to this. Section 68 | ## titles are the label, and a commit is classified under this section if any 69 | ## of the regexps associated is matching. 70 | ## 71 | ## Please note that ``section_regexps`` will only classify commits and won't 72 | ## make any changes to the contents. So you'll probably want to go check 73 | ## ``subject_process`` (or ``body_process``) to do some changes to the subject, 74 | ## whenever you are tweaking this variable. 75 | ## 76 | section_regexps = [ 77 | ('Added', [ 78 | r'^[Ad]dd\s*:\s*([^\n]*)$', 79 | ]), 80 | ('Changed', [ 81 | r'^[Ch]hange\s*:\s*([^\n]*)$', 82 | ]), 83 | ('Deprecated', [ 84 | r'^(.*:)?\s*([^\n]*)!deprecate\s*((![A-Za-z]+)?)$', 85 | ]), 86 | ('Fixed', [ 87 | r'^[Ff]ix\s*:\s*([^\n]*)$', 88 | ]), 89 | ('Removed', [ 90 | r'^[Rr]emove\s*:\s*([^\n]*)$', 91 | ]), 92 | ('Security', [ 93 | r'^(.*:)?\s*([^\n]*)!security\s*((![A-Za-z]+)?)$', 94 | ]), 95 | ('Other', None) ## Match all lines 96 | ] 97 | 98 | 99 | ## ``body_process`` is a callable 100 | ## 101 | ## This callable will be given the original body and result will 102 | ## be used in the changelog. 103 | ## 104 | ## Available constructs are: 105 | ## 106 | ## - any python callable that take one txt argument and return txt argument. 107 | ## 108 | ## - ReSub(pattern, replacement): will apply regexp substitution. 109 | ## 110 | ## - Indent(chars=" "): will indent the text with the prefix 111 | ## Please remember that template engines gets also to modify the text and 112 | ## will usually indent themselves the text if needed. 113 | ## 114 | ## - Wrap(regexp=r"\n\n"): re-wrap text in separate paragraph to fill 80-Columns 115 | ## 116 | ## - noop: do nothing 117 | ## 118 | ## - ucfirst: ensure the first letter is uppercase. 119 | ## (usually used in the ``subject_process`` pipeline) 120 | ## 121 | ## - final_dot: ensure text finishes with a dot 122 | ## (usually used in the ``subject_process`` pipeline) 123 | ## 124 | ## - strip: remove any spaces before or after the content of the string 125 | ## 126 | ## - SetIfEmpty(msg="No commit message."): will set the text to 127 | ## whatever given ``msg`` if the current text is empty. 128 | ## 129 | ## Additionally, you can `pipe` the provided filters, for instance: 130 | #body_process = Wrap(regexp=r'\n(?=\w+\s*:)') | Indent(chars=" ") 131 | #body_process = Wrap(regexp=r'\n(?=\w+\s*:)') 132 | #body_process = noop 133 | body_process = ReSub(r'((^|\n)[A-Z]\w+(-\w+)*: .*(\n\s+.*)*)+$', r'') | strip 134 | 135 | 136 | ## ``subject_process`` is a callable 137 | ## 138 | ## This callable will be given the original subject and result will 139 | ## be used in the changelog. 140 | ## 141 | ## Available constructs are those listed in ``body_process`` doc. 142 | subject_process = ( 143 | ReSub(r'^([Aa]dd|[Ch]hange|[Dd]eprecate|[Ff]ix|[Rr]emove|[Ss]ecurity)\s*:\s*([^\n]*)$', r'\2') # trim action 144 | | ReSub(r'(\s!deprecate|\s!security)', r'') # trim tags 145 | | ReSub(r'(!breaking)', r'**BREAKING CHANGE**') 146 | | SetIfEmpty("No commit message.") 147 | | strip 148 | | ucfirst 149 | | final_dot 150 | ) 151 | 152 | 153 | ## ``tag_filter_regexp`` is a regexp 154 | ## 155 | ## Tags that will be used for the changelog must match this regexp. 156 | ## 157 | tag_filter_regexp = r'^v?[0-9]+\.[0-9]+(\.[0-9]+)?$' 158 | 159 | 160 | ## ``unreleased_version_label`` is a string or a callable that outputs a string 161 | ## 162 | ## This label will be used as the changelog Title of the last set of changes 163 | ## between last valid tag and HEAD if any. 164 | unreleased_version_label = "(Unreleased)" 165 | 166 | 167 | 168 | ## ``output_engine`` is a callable 169 | ## 170 | ## This will change the output format of the generated changelog file 171 | ## 172 | ## Available choices are: 173 | ## 174 | ## - rest_py 175 | ## 176 | ## Legacy pure python engine, outputs ReSTructured text. 177 | ## This is the default. 178 | ## 179 | ## - mustache() 180 | ## 181 | ## Template name could be any of the available templates in 182 | ## ``templates/mustache/*.tpl``. 183 | ## Requires python package ``pystache``. 184 | ## Examples: 185 | ## - mustache("markdown") 186 | ## - mustache("restructuredtext") 187 | ## 188 | ## - makotemplate() 189 | ## 190 | ## Template name could be any of the available templates in 191 | ## ``templates/mako/*.tpl``. 192 | ## Requires python package ``mako``. 193 | ## Examples: 194 | ## - makotemplate("restructuredtext") 195 | ## 196 | output_engine = rest_py 197 | #output_engine = mustache("restructuredtext") 198 | #output_engine = mustache("markdown") 199 | #output_engine = makotemplate("restructuredtext") 200 | 201 | 202 | ## ``include_merge`` is a boolean 203 | ## 204 | ## This option tells git-log whether to include merge commits in the log. 205 | ## The default is to include them. 206 | include_merge = False 207 | 208 | 209 | ## ``log_encoding`` is a string identifier 210 | ## 211 | ## This option tells gitchangelog what encoding is output by ``git log``. 212 | ## The default is to be clever about it: it checks ``git config`` for 213 | ## ``i18n.logOutputEncoding``, and if not found will default to git's own 214 | ## default: ``utf-8``. 215 | #log_encoding = 'utf-8' 216 | 217 | 218 | ## ``publish`` is a callable 219 | ## 220 | ## Sets what ``gitchangelog`` should do with the output generated by 221 | ## the output engine. ``publish`` is a callable taking one argument 222 | ## that is an interator on lines from the output engine. 223 | ## 224 | ## Some helper callable are provided: 225 | ## 226 | ## Available choices are: 227 | ## 228 | ## - stdout 229 | ## 230 | ## Outputs directly to standard output 231 | ## (This is the default) 232 | ## 233 | ## - FileInsertAtFirstRegexMatch(file, pattern, idx=lamda m: m.start(), flags) 234 | ## 235 | ## Creates a callable that will parse given file for the given 236 | ## regex pattern and will insert the output in the file. 237 | ## ``idx`` is a callable that receive the matching object and 238 | ## must return a integer index point where to insert the 239 | ## the output in the file. Default is to return the position of 240 | ## the start of the matched string. 241 | ## 242 | ## - FileRegexSubst(file, pattern, replace, flags) 243 | ## 244 | ## Apply a replace inplace in the given file. Your regex pattern must 245 | ## take care of everything and might be more complex. Check the README 246 | ## for a complete copyable example. 247 | ## 248 | publish = FileInsertAtFirstRegexMatch("CHANGELOG.rst", r'v?\d\.\d\.\d\s+\(\d{4}-\d{2}-\d{2}\)') 249 | #publish = stdout 250 | 251 | 252 | ## ``revs`` is a list of callable or a list of string 253 | ## 254 | ## callable will be called to resolve as strings and allow dynamical 255 | ## computation of these. The result will be used as revisions for 256 | ## gitchangelog (as if directly stated on the command line). This allows 257 | ## to filter exactly which commits will be read by gitchangelog. 258 | ## 259 | ## To get a full documentation on the format of these strings, please 260 | ## refer to the ``git rev-list`` arguments. There are many examples. 261 | ## 262 | ## Using callables is especially useful, for instance, if you 263 | ## are using gitchangelog to generate incrementally your changelog. 264 | ## 265 | ## Some helpers are provided, you can use them:: 266 | ## 267 | ## - FileFirstRegexMatch(file, pattern): will return a callable that will 268 | ## return the first string match for the given pattern in the given file. 269 | ## If you use named sub-patterns in your regex pattern, it'll output only 270 | ## the string matching the regex pattern named "rev". 271 | ## 272 | ## - Caret(rev): will return the rev prefixed by a "^", which is a 273 | ## way to remove the given revision and all its ancestor. 274 | ## 275 | ## Please note that if you provide a rev-list on the command line, it'll 276 | ## replace this value (which will then be ignored). 277 | ## 278 | ## If empty, then ``gitchangelog`` will act as it had to generate a full 279 | ## changelog. 280 | ## 281 | ## The default is to use all commits to make the changelog. 282 | #revs = ["^1.0.3", ] 283 | #revs = [ 284 | # Caret( 285 | # FileFirstRegexMatch( 286 | # "CHANGELOG.rst", 287 | # r"(?P[0-9]+\.[0-9]+(\.[0-9]+)?)\s+\([0-9]+-[0-9]{2}-[0-9]{2}\)\n--+\n")), 288 | # "HEAD" 289 | #] 290 | revs = [] 291 | -------------------------------------------------------------------------------- /tests/integration_tests/data/codeql/full.sarif: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/sarif-2.1.0.json", 3 | "version": "2.1.0", 4 | "runs": [ 5 | { 6 | "tool": { 7 | "driver": { 8 | "name": "CodeQL", 9 | "organization": "GitHub", 10 | "semanticVersion": "2.15.4" 11 | } 12 | }, 13 | "artifacts": [ 14 | { 15 | "location": { 16 | "uri": "springfield-nuclear-power-plant/core-reactor.py", 17 | "uriBaseId": "%SRCROOT%", 18 | "index": 0 19 | } 20 | }, 21 | { 22 | "location": { 23 | "uri": "springfield-nuclear-power-plant/tests/core-reactor.py", 24 | "uriBaseId": "%SRCROOT%", 25 | "index": 1 26 | } 27 | } 28 | ], 29 | "results": [ 30 | { 31 | "ruleId": "py/quantum-readiness/cbom/all-cryptographic-algorithms", 32 | "ruleIndex": 0, 33 | "rule": { 34 | "id": "py/quantum-readiness/cbom/all-cryptographic-algorithms", 35 | "index": 0 36 | }, 37 | "message": { 38 | "text": "Use of algorithm AES" 39 | }, 40 | "locations": [ 41 | { 42 | "physicalLocation": { 43 | "artifactLocation": { 44 | "uri": "springfield-nuclear-power-plant/core-reactor.py", 45 | "uriBaseId": "%SRCROOT%", 46 | "index": 0 47 | }, 48 | "region": { 49 | "startLine": 30, 50 | "endLine": 41, 51 | "endColumn": 22 52 | }, 53 | "contextRegion": { 54 | "startLine": 28, 55 | "endLine": 43, 56 | "snippet": { 57 | "text": "# additional context region\n# additional context region\ndef encrypt(message):\n padder = padding.PKCS7(128).padder()\n message = padder.update(message.encode()) + padder.finalize()\n\n key = os.urandom(32)\n encryptor = Cipher(\n algorithms.AES(key),\n modes.ECB(initialization_vector=os.urandom(16))\n ).encryptor()\n\n ciphertext = encryptor.update(message) + encryptor.finalize()\n return ciphertext\n# additional context region\n# additional context region" 58 | } 59 | } 60 | } 61 | } 62 | ], 63 | "partialFingerprints": { 64 | "primaryLocationLineHash": "61744bbabae05152:1", 65 | "primaryLocationStartColumnFingerprint": "0" 66 | } 67 | }, 68 | { 69 | "ruleId": "py/quantum-readiness/cbom/all-cryptographic-algorithms", 70 | "ruleIndex": 0, 71 | "rule": { 72 | "id": "py/quantum-readiness/cbom/all-cryptographic-algorithms", 73 | "index": 0 74 | }, 75 | "message": { 76 | "text": "Use of algorithm DSA" 77 | }, 78 | "locations": [ 79 | { 80 | "physicalLocation": { 81 | "artifactLocation": { 82 | "uri": "springfield-nuclear-power-plant/core-reactor.py", 83 | "uriBaseId": "%SRCROOT%", 84 | "index": 0 85 | }, 86 | "region": { 87 | "startLine": 30, 88 | "endLine": 62, 89 | "endColumn": 22 90 | }, 91 | "contextRegion": { 92 | "startLine": 28, 93 | "endLine": 64, 94 | "snippet": { 95 | "text": "# additional context region\n# additional context region\ndef encrypt(message):\n private_key = dsa.generate_private_key(\n key_size=2048\n )\n\n subject = issuer = x509.Name([\n x509.NameAttribute(NameOID.COUNTRY_NAME, 'US'),\n x509.NameAttribute(NameOID.LOCALITY_NAME, 'Springfield'),\n x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'Springfield Nuclear Power Plant'),\n x509.NameAttribute(NameOID.COMMON_NAME, \"springfield-nuclear.com\")\n ])\n\n certificate = (\n x509.CertificateBuilder()\n .subject_name(subject)\n .issuer_name(issuer)\n .public_key(private_key.public_key())\n .serial_number(x509.random_serial_number())\n .not_valid_before(datetime.datetime.now(datetime.timezone.utc))\n .not_valid_after(datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=10))\n .add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]), critical=False)\n ).sign(private_key, hashes.SHA256())\n\n public_key = certificate.public_key()\n ciphertext = public_key.encrypt(\n message.encode(),\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None\n )\n )\n return ciphertext\n# additional context region\n# additional context region" 96 | } 97 | } 98 | } 99 | } 100 | ], 101 | "partialFingerprints": { 102 | "primaryLocationLineHash": "61744bbabae05152:1", 103 | "primaryLocationStartColumnFingerprint": "0" 104 | } 105 | }, 106 | { 107 | "ruleId": "py/quantum-readiness/cbom/all-cryptographic-algorithms", 108 | "ruleIndex": 0, 109 | "rule": { 110 | "id": "py/quantum-readiness/cbom/all-cryptographic-algorithms", 111 | "index": 0 112 | }, 113 | "message": { 114 | "text": "Use of algorithm FERNET" 115 | }, 116 | "locations": [ 117 | { 118 | "physicalLocation": { 119 | "artifactLocation": { 120 | "uri": "springfield-nuclear-power-plant/tests/core-reactor.py", 121 | "uriBaseId": "%SRCROOT%", 122 | "index": 1 123 | }, 124 | "region": { 125 | "startLine": 30, 126 | "endLine": 33, 127 | "endColumn": 22 128 | }, 129 | "contextRegion": { 130 | "startLine": 28, 131 | "endLine": 35, 132 | "snippet": { 133 | "text": "# additional context region\n# additional context region\ndef encrypt(message):\n encryptor = Fernet(Fernet.generate_key())\n ciphertext = encryptor.encrypt(message.encode())\n return ciphertext\n# additional context region\n# additional context region" 134 | } 135 | } 136 | } 137 | } 138 | ], 139 | "partialFingerprints": { 140 | "primaryLocationLineHash": "61744bbabae05152:1", 141 | "primaryLocationStartColumnFingerprint": "0" 142 | } 143 | }, 144 | { 145 | "ruleId": "py/quantum-readiness/cbom/all-cryptographic-algorithms", 146 | "ruleIndex": 0, 147 | "rule": { 148 | "id": "py/quantum-readiness/cbom/all-cryptographic-algorithms", 149 | "index": 0 150 | }, 151 | "message": { 152 | "text": "Use of algorithm RSA" 153 | }, 154 | "locations": [ 155 | { 156 | "physicalLocation": { 157 | "artifactLocation": { 158 | "uri": "springfield-nuclear-power-plant/core-reactor.py", 159 | "uriBaseId": "%SRCROOT%", 160 | "index": 0 161 | }, 162 | "region": { 163 | "startLine": 30, 164 | "endLine": 63, 165 | "endColumn": 22 166 | }, 167 | "contextRegion": { 168 | "startLine": 28, 169 | "endLine": 65, 170 | "snippet": { 171 | "text": "# additional context region\n# additional context region\ndef encrypt(message):\n private_key = rsa.generate_private_key(\n public_exponent=65537,\n key_size=2048\n )\n\n subject = issuer = x509.Name([\n x509.NameAttribute(NameOID.COUNTRY_NAME, 'US'),\n x509.NameAttribute(NameOID.LOCALITY_NAME, 'Springfield'),\n x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'Springfield Nuclear Power Plant'),\n x509.NameAttribute(NameOID.COMMON_NAME, \"springfield-nuclear.com\")\n ])\n\n certificate = (\n x509.CertificateBuilder()\n .subject_name(subject)\n .issuer_name(issuer)\n .public_key(private_key.public_key())\n .serial_number(x509.random_serial_number())\n .not_valid_before(datetime.datetime.now(datetime.timezone.utc))\n .not_valid_after(datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=10))\n .add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]), critical=False)\n ).sign(private_key, hashes.SHA256())\n\n public_key = certificate.public_key()\n ciphertext = public_key.encrypt(\n message.encode(),\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None\n )\n )\n return ciphertext\n# additional context region\n# additional context region" 172 | } 173 | } 174 | } 175 | } 176 | ], 177 | "partialFingerprints": { 178 | "primaryLocationLineHash": "61744bbabae05152:1", 179 | "primaryLocationStartColumnFingerprint": "0" 180 | } 181 | } 182 | ], 183 | "columnKind": "unicodeCodePoints", 184 | "properties": { 185 | "semmle.formatSpecifier": "sarifv2.1.0" 186 | } 187 | } 188 | ] 189 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Cryptobom Forge Tool: Generating Comprehensive CBOMs from CodeQL Outputs 2 | 3 | This repository houses all the tools and utilities one would need in order to parse the Multi-Repository Variant Analysis output from CodeQL runs. It is part of the wider release looking at analysing and creating Cryptographic Bill of Materials (CBOM) for [this](https://www.blackhat.com/eu-23/briefings/schedule/#the-magnetic-pull-of-mutable-protection-worked-examples-in-cryptographic-agility-36030) Blackhat talk 4 | 5 | 6 | 7 | ## Contents 8 | 9 | - [Quickstart](#quickstart) 10 | - [Excluding File Paths](#excluding-file-paths) 11 | - [Cryptography Checker](#cryptography-checker) 12 | - [Analysis Output](#analysis-output) 13 | - [YAML Rule Structure](#yaml-rule-structure) 14 | - [Example Rules](#example-rules) 15 | 16 | ## Quickstart 17 | 18 | **Prerequisites:** 19 | 20 | * Python 3.10 or higher is essential for the proper functioning of this tool. 21 | 22 | **Installation and Execution Steps:** 23 | 24 | Step 1 - Acquire the Latest Release: 25 | 26 | Visit the [releases](https://github.com/santandersecurityresearch/cryptobom-forge/releases) page to download the most recent version of Cryptobom Forge. This ensures that you have access to the latest features and security updates. 27 | 28 | **Step 2 - Installation:** 29 | 30 | Integrate the tool into your local Python environment using the Wheel package: 31 | 32 | ``` 33 | pip install cryptobom_forge-{VERSION}-py3-none-any.whl 34 | ``` 35 | Replace {VERSION} with the specific version number you downloaded. This step equips your environment with the necessary dependencies and modules for Cryptobom Forge. 36 | 37 | **Step 3 - Execution** 38 | 39 | Generate a CBOM using the following command: 40 | 41 | ``` 42 | cryptobom generate 43 | ``` 44 | 45 | The parameter is versatile, accepting either: 46 | 47 | * A path to a single CodeQL output file, or 48 | * A directory path containing multiple CodeQL outputs. 49 | 50 | For each file, Cryptobom Forge meticulously parses the data to produce a comprehensive CBOM. This CBOM encapsulates detailed insights into the cybersecurity aspects of your project, essential for advanced security analysis. 51 | 52 | Output Example: 53 | Upon successful execution, you will receive a detailed CBOM, structured as follows: 54 | 55 | 56 | ```json 57 | { 58 | "components": [ 59 | { 60 | "bom-ref": "algorithm:md5", 61 | "cryptoProperties": { 62 | "algorithmProperties": { 63 | "primitive": "hash", 64 | "variant": "MD5" 65 | }, 66 | "assetType": "algorithm", 67 | "detectionContext": [ 68 | { 69 | "additionalContext": " return (\n \"https://www.gravatar.com/avatar/\"\n f\"{hashlib.md5(email.encode('utf-8').lower()).hexdigest()}.jpg?s=80&d=wavatar\"\n )\n", 70 | "filePath": "homeassistant/components/device_tracker/legacy.py", 71 | "lineNumbers": [1036, 1037, 1038, 1039] 72 | }, 73 | { 74 | "additionalContext": "def _entity_unique_id(entity_id: str) -> str:\n \"\"\"Return the emulated_hue unique id for the entity_id.\"\"\"\n unique_id = hashlib.md5(entity_id.encode()).hexdigest()\n return (\n f\"00:{unique_id[0:2]}:{unique_id[2:4]}:\"\n", 75 | "filePath": "homeassistant/components/emulated_hue/hue_api.py", 76 | "lineNumbers": [740, 741, 742, 743, 744] 77 | } 78 | ] 79 | }, 80 | "name": "MD5", 81 | "type": "crypto-asset" 82 | }, 83 | { 84 | "bom-ref": "algorithm:sha1", 85 | "cryptoProperties": { 86 | "algorithmProperties": { 87 | "primitive": "hash", 88 | "variant": "SHA1" 89 | }, 90 | "assetType": "algorithm", 91 | "detectionContext": [ 92 | { 93 | "additionalContext": "from __future__ import annotations\n\nfrom hashlib import sha1\nimport logging\nimport os\n", 94 | "filePath": "homeassistant/components/demo/mailbox.py", 95 | "lineNumbers": [2, 3, 4, 5, 6] 96 | }, 97 | { 98 | "additionalContext": " \"\"\"Generate a cache key for a message.\"\"\"\n options_key = _hash_options(options) if options else \"-\"\n msg_hash = hashlib.sha1(bytes(message, \"utf-8\")).hexdigest()\n return KEY_PATTERN.format(\n msg_hash, language.replace(\"_\", \"-\"), options_key, engine\n", 99 | "filePath": "homeassistant/components/tts/__init__.py", 100 | "lineNumbers": [573, 574, 575, 576, 577] 101 | } 102 | ] 103 | }, 104 | "name": "SHA1", 105 | "type": "crypto-asset" 106 | }, 107 | { 108 | "bom-ref": "algorithm:sha256", 109 | "cryptoProperties": { 110 | "algorithmProperties": { 111 | "primitive": "hash", 112 | "variant": "SHA256" 113 | }, 114 | "assetType": "algorithm", 115 | "detectionContext": [ 116 | { 117 | "additionalContext": " \"duration\": entry[\"duration\"],\n }\n sha = hashlib.sha256(str(entry).encode(\"utf-8\")).hexdigest()\n msg = (\n f\"Destination: {entry['dest']}\\n\"\n", 118 | "filePath": "homeassistant/components/asterisk_cdr/mailbox.py", 119 | "lineNumbers": [53, 54, 55, 56, 57] 120 | }, 121 | { 122 | "additionalContext": "def hash_from_url(url: str):\n \"\"\"Hash url to create a unique ID.\"\"\"\n return hashlib.sha256(url.encode(\"utf-8\")).hexdigest()\n", 123 | "filePath": "homeassistant/components/nightscout/utils.py", 124 | "lineNumbers": [5, 6, 7] 125 | } 126 | ] 127 | }, 128 | "name": "SHA256", 129 | "type": "crypto-asset" 130 | } 131 | ], 132 | "dependencies": [ 133 | { 134 | "ref": "algorithm:md5" 135 | }, 136 | { 137 | "ref": "algorithm:sha1" 138 | }, 139 | { 140 | "ref": "algorithm:sha256" 141 | }, 142 | { 143 | "dependsOn": ["algorithm:md5", "algorithm:sha1", "algorithm:sha256"], 144 | "ref": "home-assistant/core" 145 | } 146 | ], 147 | "metadata": { 148 | "component": { 149 | "bom-ref": "home-assistant/core", 150 | "externalReferences": [ 151 | { 152 | "type": "vcs", 153 | "url": "https://github.com/home-assistant/core" 154 | } 155 | ], 156 | "name": "core", 157 | "type": "application" 158 | }, 159 | "timestamp": "2023-10-30T16:47:12.165802+00:00", 160 | "tools": [ 161 | { 162 | "externalReferences": [ 163 | { 164 | "type": "build-system", 165 | "url": "https://github.com/CycloneDX/cyclonedx-python-lib/actions" 166 | }, 167 | { 168 | "type": "distribution", 169 | "url": "https://pypi.org/project/cyclonedx-python-lib/" 170 | }, 171 | { 172 | "type": "documentation", 173 | "url": "https://cyclonedx.github.io/cyclonedx-python-lib/" 174 | }, 175 | { 176 | "type": "issue-tracker", 177 | "url": "https://github.com/CycloneDX/cyclonedx-python-lib/issues" 178 | }, 179 | { 180 | "type": "license", 181 | "url": "https://github.com/CycloneDX/cyclonedx-python-lib/blob/main/LICENSE" 182 | }, 183 | { 184 | "type": "release-notes", 185 | "url": "https://github.com/CycloneDX/cyclonedx-python-lib/blob/main/CHANGELOG.md" 186 | }, 187 | { 188 | "type": "vcs", 189 | "url": "https://github.com/CycloneDX/cyclonedx-python-lib" 190 | }, 191 | { 192 | "type": "website", 193 | "url": "https://cyclonedx.org" 194 | } 195 | ], 196 | "name": "cyclonedx-python-lib", 197 | "vendor": "CycloneDX", 198 | "version": "4.2.2" 199 | }, 200 | { 201 | "name": "CodeQL", 202 | "vendor": "GitHub", 203 | "version": "2.14.3" 204 | } 205 | ] 206 | }, 207 | "serialNumber": "urn:uuid:7b666731-bd55-4ce9-805b-ba0e1ff82b21", 208 | "version": 1, 209 | "$schema": "https://raw.githubusercontent.com/IBM/CBOM/main/bom-1.4-cbom-1.0.schema.json", 210 | "bomFormat": "CBOM", 211 | "specVersion": "1.4-cbom-1.0" 212 | } 213 | ``` 214 | 215 | By default, the output will be printed to `stdout`. You can alternatively write the output to a file using 216 | `--output-file` or `-o`. 217 | 218 | ```shell 219 | $ cryptobom generate --output-file cbom.json 220 | ``` 221 | 222 | ### Excluding File Paths 223 | 224 | You can optionally specify a regex string to ignore findings in files that match that path, using `--exclude` or `-e`. 225 | The complete file path must match in order for findings to be excluded. 226 | 227 | For example, you may wish to exclude findings in test files: 228 | 229 | ```shell 230 | $ cryptobom generate --exclude '(.*/)?test(s)?.*' 231 | ``` 232 | 233 | ## Cryptography Checker - Enhanced Cryptography Compliance Analysis 234 | 235 | **Overview:** 236 | 237 | *Cryptocheck* is designed to automate the process of cryptography compliance analysis. It integrates two distinct inputs to generate a SARIF (Static Analysis Results Interchange Format) file, detailing the findings from a comprehensive rule check against the CBOM contents. This approach offers a streamlined and precise method for ensuring cryptographic best practices in your codebase. 238 | 239 | ### Inputs: 240 | 241 | **CBOM (Cybersecurity Bill of Materials):** 242 | 243 | This input is derived from the parser of SARIF files generated by CodeQL. The CBOM provides an exhaustive inventory of all cybersecurity-related components in your project, including libraries, dependencies, and associated vulnerabilities. This comprehensive overview serves as the foundation for the subsequent rule checks. 244 | 245 | **Rules File (rules.yml):** 246 | 247 | A YAML-formatted file, typically named rules.yml, contains a set of predefined rules focused on cryptography compliance. These rules are crafted to evaluate various aspects of cryptographic implementation, such as key lengths, algorithms, and encryption protocols. The flexibility of the YAML format allows for easy updates and customization of the rule set to align with evolving best practices and organizational policies. 248 | 249 | ### Output: 250 | 251 | **SARIF File:** 252 | 253 | The script processes the CBOM against the set of rules in rules.yml and outputs its findings in a SARIF file. This file includes detailed information on any discrepancies, potential vulnerabilities, or non-compliance issues related to cryptography as identified by the rules. The SARIF format ensures that the output is standardized, making it compatible with a wide range of tools for further analysis and integration into continuous integration/continuous deployment (CI/CD) pipelines. 254 | 255 | ### Analysis Output 256 | 257 | The results from the analysis are appended as a SARIF file that has the following structure, in line with GitHub's 258 | recommended format: 259 | 260 | ```json 261 | { 262 | "$schema": "http://json.schemastore.org/sarif-2.1.0-rtm.4", 263 | "runs": [ 264 | { 265 | "results": [ 266 | { 267 | "level": "error", 268 | "locations": [ 269 | { 270 | "physicalLocation": { 271 | "artifactLocation": { 272 | "index": 0, 273 | "uri": "contrib/openssl/pyca-cryptography/src/cryptography/hazmat/primitives/keywrap.py", 274 | "uriBaseId": "%SRCROOT%" 275 | }, 276 | "region": { 277 | "startLine": 18 278 | } 279 | } 280 | } 281 | ], 282 | "message": { 283 | "text": "AES was found operating in ECB mode. Please don't." 284 | }, 285 | "ruleId": "AES in ECB mode", 286 | "ruleIndex": 0 287 | } 288 | ], 289 | "tool": { 290 | "driver": { 291 | "name": "CryptoCheck", 292 | "rules": [ 293 | { 294 | "id": "AES in ECB mode", 295 | "properties": { 296 | "category": "function", 297 | "problem.severity": "error", 298 | "security-severity": 9.0, 299 | "tags": ["cryptography"] 300 | }, 301 | "shortDescription": { 302 | "text": "AES was found operating in ECB mode. Please don't." 303 | } 304 | } 305 | ] 306 | } 307 | } 308 | } 309 | ], 310 | "version": "2.1.0" 311 | } 312 | ``` 313 | 314 | ### YAML Rule Structure 315 | 316 | Each YAML file has a list of objects with the following structure: 317 | 318 | - Each rule requires a `name` 319 | - Each rule requires a `detection` object that has two sub-objects 320 | - `severity` - a number from 1 to 10, taken as a mapping for vulnerabilities (critical: >=9.0, high: 7.0 - 8.9, 321 | medium: 4.0-6.9, low: <=3.9) 322 | - `description` - a string detailing a summary of what a detection means. 323 | - `type` - whether the detection should count as a `warning`, `error`, or `note` (these are the only valid values) 324 | - There is an optional `default` section that has the same parameters as the `detection` section - this is used when 325 | there is no detection, as a means of having a default output for no detection if required. 326 | - Each rule requires a `patterns` object, a written out tuple of the form: `(field, type, criteria)`, taken from the 327 | following: 328 | - `type` - the types of match/check, from the following: 329 | - `r` (regex), 330 | - `s` (string match by 'contains criteria string'), 331 | - `lt` (numeric less-than), 332 | - `gt` (numeric greater-than), 333 | - `lteq` (numeric less-than or equal to), 334 | - `gteq` (numeric greater-than or equal to), 335 | - `eq` (logical equal to), 336 | - `neq` (logical not equal to) 337 | - `field` - the fields that the check applies to, must be one of the following: 338 | - `algo` - the variant algorithm 339 | - `keylen` - the key length of the variant, if known 340 | - `mode` - the mode of the cipher variant, if known 341 | - `padding` - the padding algorithm, if known 342 | - `criteria` - a free-form field for the check criteria (string, regex, or numeric as required) 343 | 344 | **NOTE** - the tuples for `patterns` must have enclosing string single quote marks in order to be parsed by the script. 345 | This is because they are parsed by `ast.literal_eval`, which requires them to find a valid tuple for the rule pattern 346 | components. 347 | 348 | #### Example Rules 349 | 350 | The following rule detects MD5, and sets a default if nothing is found to be a problem: 351 | 352 | ```yaml 353 | - name: MD5-detect 354 | default: 355 | type: note 356 | severity: 0 357 | description: MD5 was not found! Which is a huge relief... 358 | detection: 359 | type: error 360 | severity: 9.0 361 | description: MD5 was detected, which is a deprecated hashing algorithm that is prone to collisions, and should not be used. 362 | patterns: 363 | - ('algo', 'r', '(?i)md5') 364 | ``` 365 | 366 | or for AES in CBC mode: 367 | 368 | ```yaml 369 | - name: AES in CBC mode 370 | detection: 371 | type: warning 372 | severity: 5.0 373 | description: AES was found operating in CBC mode, which will need manual review to determine if it is implemented safely. 374 | patterns: 375 | - ('algo', 'eq', 'AES') 376 | - ('mode', 'eq', 'CBC') 377 | ``` 378 | 379 | The format for the output can be found in the above extract from a SARIF output. 380 | 381 | 382 | ## Ongoing Development & The Community 383 | 384 | The need for adaptable and robust cryptographic solutions has never been greater. This project aims to address these challenges by developing tools and methodologies that can quickly and efficiently adapt to new cryptographic standards and threats. 385 | 386 | We are seeking contributors who are passionate about cryptography, security engineering, and the development of future-proof cryptographic systems. Whether you have ideas for new features, improvements to existing ones, or strategies to enhance the tool's accessibility and usability, your input is invaluable. 387 | 388 | We'd love to hear issues or accept pull requests to make it better. 389 | 390 | 391 | ## Who Is Behind It? 392 | 393 | This was developed by Emile El-qawas (@emilejq) of the Santander UK Security Engineering team with help from Mark Carney (@unprovable) and Daniel Cuthbert (@danielcuthbert) of Santander's Cyber Security Research (CSR) team as part of our Blackhat EU 2023 research release. 394 | -------------------------------------------------------------------------------- /tests/integration_tests/data/cbom/cbom_exclusion_pattern.json: -------------------------------------------------------------------------------- 1 | { 2 | "components": [ 3 | { 4 | "bom-ref": "cryptography:private_key:90d480d3-42b2-4342-b319-7c5df8856064", 5 | "cryptoProperties": { 6 | "assetType": "relatedCryptoMaterial", 7 | "detectionContext": [ 8 | { 9 | "additionalContext": "# additional context region\n# additional context region\ndef encrypt(message):\n private_key = rsa.generate_private_key(\n public_exponent=65537,\n key_size=2048\n )\n\n subject = issuer = x509.Name([\n x509.NameAttribute(NameOID.COUNTRY_NAME, 'US'),\n x509.NameAttribute(NameOID.LOCALITY_NAME, 'Springfield'),\n x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'Springfield Nuclear Power Plant'),\n x509.NameAttribute(NameOID.COMMON_NAME, \"springfield-nuclear.com\")\n ])\n\n certificate = (\n x509.CertificateBuilder()\n .subject_name(subject)\n .issuer_name(issuer)\n .public_key(private_key.public_key())\n .serial_number(x509.random_serial_number())\n .not_valid_before(datetime.datetime.now(datetime.timezone.utc))\n .not_valid_after(datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=10))\n .add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]), critical=False)\n ).sign(private_key, hashes.SHA256())\n\n public_key = certificate.public_key()\n ciphertext = public_key.encrypt(\n message.encode(),\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None\n )\n )\n return ciphertext\n# additional context region\n# additional context region", 10 | "filePath": "springfield-nuclear-power-plant/core-reactor.py", 11 | "lineNumbers": [ 12 | 28, 13 | 29, 14 | 30, 15 | 31, 16 | 32, 17 | 33, 18 | 34, 19 | 35, 20 | 36, 21 | 37, 22 | 38, 23 | 39, 24 | 40, 25 | 41, 26 | 42, 27 | 43, 28 | 44, 29 | 45, 30 | 46, 31 | 47, 32 | 48, 33 | 49, 34 | 50, 35 | 51, 36 | 52, 37 | 53, 38 | 54, 39 | 55, 40 | 56, 41 | 57, 42 | 58, 43 | 59, 44 | 60, 45 | 61, 46 | 62, 47 | 63, 48 | 64, 49 | 65 50 | ] 51 | } 52 | ], 53 | "relatedCryptoMaterialProperties": { 54 | "relatedCryptoMaterialType": "privateKey", 55 | "size": 2048 56 | } 57 | }, 58 | "name": "90d480d3-42b2-4342-b319-7c5df8856064", 59 | "type": "crypto-asset" 60 | }, 61 | { 62 | "bom-ref": "cryptography:algorithm:f959178c-6674-4041-bcd0-be09ca56c772", 63 | "cryptoProperties": { 64 | "algorithmProperties": { 65 | "cryptoFunctions": [ 66 | "encrypt" 67 | ], 68 | "mode": "ecb", 69 | "padding": "pkcs7", 70 | "primitive": "blockcipher", 71 | "variant": "AES-128-ECB" 72 | }, 73 | "assetType": "algorithm", 74 | "detectionContext": [ 75 | { 76 | "additionalContext": "# additional context region\n# additional context region\ndef encrypt(message):\n padder = padding.PKCS7(128).padder()\n message = padder.update(message.encode()) + padder.finalize()\n\n key = os.urandom(32)\n encryptor = Cipher(\n algorithms.AES(key),\n modes.ECB(initialization_vector=os.urandom(16))\n ).encryptor()\n\n ciphertext = encryptor.update(message) + encryptor.finalize()\n return ciphertext\n# additional context region\n# additional context region", 77 | "filePath": "springfield-nuclear-power-plant/core-reactor.py", 78 | "lineNumbers": [ 79 | 28, 80 | 29, 81 | 30, 82 | 31, 83 | 32, 84 | 33, 85 | 34, 86 | 35, 87 | 36, 88 | 37, 89 | 38, 90 | 39, 91 | 40, 92 | 41, 93 | 42, 94 | 43 95 | ] 96 | } 97 | ] 98 | }, 99 | "name": "AES-128-ECB-PKCS7", 100 | "type": "crypto-asset" 101 | }, 102 | { 103 | "bom-ref": "cryptography:algorithm:496f1dcb-ccbc-434e-8918-ff19da3e0819", 104 | "cryptoProperties": { 105 | "algorithmProperties": { 106 | "cryptoFunctions": [ 107 | "encrypt", 108 | "generate", 109 | "sign" 110 | ], 111 | "padding": "oaep", 112 | "primitive": "signature", 113 | "variant": "DSA-2048" 114 | }, 115 | "assetType": "algorithm", 116 | "detectionContext": [ 117 | { 118 | "additionalContext": "# additional context region\n# additional context region\ndef encrypt(message):\n private_key = dsa.generate_private_key(\n key_size=2048\n )\n\n subject = issuer = x509.Name([\n x509.NameAttribute(NameOID.COUNTRY_NAME, 'US'),\n x509.NameAttribute(NameOID.LOCALITY_NAME, 'Springfield'),\n x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'Springfield Nuclear Power Plant'),\n x509.NameAttribute(NameOID.COMMON_NAME, \"springfield-nuclear.com\")\n ])\n\n certificate = (\n x509.CertificateBuilder()\n .subject_name(subject)\n .issuer_name(issuer)\n .public_key(private_key.public_key())\n .serial_number(x509.random_serial_number())\n .not_valid_before(datetime.datetime.now(datetime.timezone.utc))\n .not_valid_after(datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=10))\n .add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]), critical=False)\n ).sign(private_key, hashes.SHA256())\n\n public_key = certificate.public_key()\n ciphertext = public_key.encrypt(\n message.encode(),\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None\n )\n )\n return ciphertext\n# additional context region\n# additional context region", 119 | "filePath": "springfield-nuclear-power-plant/core-reactor.py", 120 | "lineNumbers": [ 121 | 28, 122 | 29, 123 | 30, 124 | 31, 125 | 32, 126 | 33, 127 | 34, 128 | 35, 129 | 36, 130 | 37, 131 | 38, 132 | 39, 133 | 40, 134 | 41, 135 | 42, 136 | 43, 137 | 44, 138 | 45, 139 | 46, 140 | 47, 141 | 48, 142 | 49, 143 | 50, 144 | 51, 145 | 52, 146 | 53, 147 | 54, 148 | 55, 149 | 56, 150 | 57, 151 | 58, 152 | 59, 153 | 60, 154 | 61, 155 | 62, 156 | 63, 157 | 64 158 | ] 159 | } 160 | ] 161 | }, 162 | "name": "DSA-2048-OAEP", 163 | "type": "crypto-asset" 164 | }, 165 | { 166 | "bom-ref": "cryptography:algorithm:4c003a38-2ab7-4bf3-810f-c0e473d3fff8", 167 | "cryptoProperties": { 168 | "algorithmProperties": { 169 | "cryptoFunctions": [ 170 | "encrypt", 171 | "generate", 172 | "sign" 173 | ], 174 | "padding": "oaep", 175 | "primitive": "pke", 176 | "variant": "RSA-2048" 177 | }, 178 | "assetType": "algorithm", 179 | "detectionContext": [ 180 | { 181 | "additionalContext": "# additional context region\n# additional context region\ndef encrypt(message):\n private_key = rsa.generate_private_key(\n public_exponent=65537,\n key_size=2048\n )\n\n subject = issuer = x509.Name([\n x509.NameAttribute(NameOID.COUNTRY_NAME, 'US'),\n x509.NameAttribute(NameOID.LOCALITY_NAME, 'Springfield'),\n x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'Springfield Nuclear Power Plant'),\n x509.NameAttribute(NameOID.COMMON_NAME, \"springfield-nuclear.com\")\n ])\n\n certificate = (\n x509.CertificateBuilder()\n .subject_name(subject)\n .issuer_name(issuer)\n .public_key(private_key.public_key())\n .serial_number(x509.random_serial_number())\n .not_valid_before(datetime.datetime.now(datetime.timezone.utc))\n .not_valid_after(datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=10))\n .add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]), critical=False)\n ).sign(private_key, hashes.SHA256())\n\n public_key = certificate.public_key()\n ciphertext = public_key.encrypt(\n message.encode(),\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None\n )\n )\n return ciphertext\n# additional context region\n# additional context region", 182 | "filePath": "springfield-nuclear-power-plant/core-reactor.py", 183 | "lineNumbers": [ 184 | 28, 185 | 29, 186 | 30, 187 | 31, 188 | 32, 189 | 33, 190 | 34, 191 | 35, 192 | 36, 193 | 37, 194 | 38, 195 | 39, 196 | 40, 197 | 41, 198 | 42, 199 | 43, 200 | 44, 201 | 45, 202 | 46, 203 | 47, 204 | 48, 205 | 49, 206 | 50, 207 | 51, 208 | 52, 209 | 53, 210 | 54, 211 | 55, 212 | 56, 213 | 57, 214 | 58, 215 | 59, 216 | 60, 217 | 61, 218 | 62, 219 | 63, 220 | 64, 221 | 65 222 | ] 223 | } 224 | ] 225 | }, 226 | "name": "RSA-2048-OAEP", 227 | "type": "crypto-asset" 228 | }, 229 | { 230 | "bom-ref": "cryptography:certificate:bff25a20-7c0a-490e-959c-85295f4c145b", 231 | "cryptoProperties": { 232 | "assetType": "certificate", 233 | "certificateProperties": { 234 | "certificateAlgorithm": "RSA", 235 | "certificateFormat": "X.509", 236 | "certificateSignatureAlgorithm": "SHA256", 237 | "issuerName": "C=US, L=Springfield, O=Springfield Nuclear Power Plant, CN=springfield-nuclear.com", 238 | "subjectName": "C=US, L=Springfield, O=Springfield Nuclear Power Plant, CN=springfield-nuclear.com" 239 | }, 240 | "detectionContext": [ 241 | { 242 | "additionalContext": "# additional context region\n# additional context region\ndef encrypt(message):\n private_key = rsa.generate_private_key(\n public_exponent=65537,\n key_size=2048\n )\n\n subject = issuer = x509.Name([\n x509.NameAttribute(NameOID.COUNTRY_NAME, 'US'),\n x509.NameAttribute(NameOID.LOCALITY_NAME, 'Springfield'),\n x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'Springfield Nuclear Power Plant'),\n x509.NameAttribute(NameOID.COMMON_NAME, \"springfield-nuclear.com\")\n ])\n\n certificate = (\n x509.CertificateBuilder()\n .subject_name(subject)\n .issuer_name(issuer)\n .public_key(private_key.public_key())\n .serial_number(x509.random_serial_number())\n .not_valid_before(datetime.datetime.now(datetime.timezone.utc))\n .not_valid_after(datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=10))\n .add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]), critical=False)\n ).sign(private_key, hashes.SHA256())\n\n public_key = certificate.public_key()\n ciphertext = public_key.encrypt(\n message.encode(),\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None\n )\n )\n return ciphertext\n# additional context region\n# additional context region", 243 | "filePath": "springfield-nuclear-power-plant/core-reactor.py", 244 | "lineNumbers": [ 245 | 28, 246 | 29, 247 | 30, 248 | 31, 249 | 32, 250 | 33, 251 | 34, 252 | 35, 253 | 36, 254 | 37, 255 | 38, 256 | 39, 257 | 40, 258 | 41, 259 | 42, 260 | 43, 261 | 44, 262 | 45, 263 | 46, 264 | 47, 265 | 48, 266 | 49, 267 | 50, 268 | 51, 269 | 52, 270 | 53, 271 | 54, 272 | 55, 273 | 56, 274 | 57, 275 | 58, 276 | 59, 277 | 60, 278 | 61, 279 | 62, 280 | 63, 281 | 64, 282 | 65 283 | ] 284 | } 285 | ] 286 | }, 287 | "name": "bff25a20-7c0a-490e-959c-85295f4c145b", 288 | "type": "crypto-asset" 289 | } 290 | ], 291 | "dependencies": [ 292 | { 293 | "dependsOn": [ 294 | "cryptography:algorithm:1b80c552-5c11-48ac-a0f6-edc470a8aa40", 295 | "cryptography:algorithm:496f1dcb-ccbc-434e-8918-ff19da3e0819", 296 | "cryptography:algorithm:4c003a38-2ab7-4bf3-810f-c0e473d3fff8", 297 | "cryptography:algorithm:f959178c-6674-4041-bcd0-be09ca56c772" 298 | ], 299 | "ref": "58e8d784-8745-4666-964e-7f1ce44446eb" 300 | }, 301 | { 302 | "ref": "cryptography:algorithm:1b80c552-5c11-48ac-a0f6-edc470a8aa40" 303 | }, 304 | { 305 | "ref": "cryptography:algorithm:496f1dcb-ccbc-434e-8918-ff19da3e0819" 306 | }, 307 | { 308 | "dependsOn": [ 309 | "cryptography:certificate:bff25a20-7c0a-490e-959c-85295f4c145b", 310 | "cryptography:private_key:90d480d3-42b2-4342-b319-7c5df8856064" 311 | ], 312 | "ref": "cryptography:algorithm:4c003a38-2ab7-4bf3-810f-c0e473d3fff8" 313 | }, 314 | { 315 | "ref": "cryptography:algorithm:f959178c-6674-4041-bcd0-be09ca56c772" 316 | }, 317 | { 318 | "ref": "cryptography:certificate:bff25a20-7c0a-490e-959c-85295f4c145b" 319 | }, 320 | { 321 | "ref": "cryptography:private_key:90d480d3-42b2-4342-b319-7c5df8856064" 322 | } 323 | ], 324 | "metadata": { 325 | "component": { 326 | "bom-ref": "58e8d784-8745-4666-964e-7f1ce44446eb", 327 | "name": "root", 328 | "type": "application" 329 | }, 330 | "timestamp": "2024-01-04T09:54:58.428646+00:00", 331 | "tools": [ 332 | { 333 | "externalReferences": [ 334 | { 335 | "type": "build-system", 336 | "url": "https://github.com/CycloneDX/cyclonedx-python-lib/actions" 337 | }, 338 | { 339 | "type": "distribution", 340 | "url": "https://pypi.org/project/cyclonedx-python-lib/" 341 | }, 342 | { 343 | "type": "documentation", 344 | "url": "https://cyclonedx.github.io/cyclonedx-python-lib/" 345 | }, 346 | { 347 | "type": "issue-tracker", 348 | "url": "https://github.com/CycloneDX/cyclonedx-python-lib/issues" 349 | }, 350 | { 351 | "type": "license", 352 | "url": "https://github.com/CycloneDX/cyclonedx-python-lib/blob/main/LICENSE" 353 | }, 354 | { 355 | "type": "release-notes", 356 | "url": "https://github.com/CycloneDX/cyclonedx-python-lib/blob/main/CHANGELOG.md" 357 | }, 358 | { 359 | "type": "vcs", 360 | "url": "https://github.com/CycloneDX/cyclonedx-python-lib" 361 | }, 362 | { 363 | "type": "website", 364 | "url": "https://cyclonedx.org" 365 | } 366 | ], 367 | "name": "cyclonedx-python-lib", 368 | "vendor": "CycloneDX", 369 | "version": "4.2.2" 370 | }, 371 | { 372 | "name": "CodeQL", 373 | "vendor": "GitHub", 374 | "version": "2.15.4" 375 | } 376 | ] 377 | }, 378 | "serialNumber": "urn:uuid:6b990ba4-1d57-41f0-b995-11006eb91239", 379 | "version": 1, 380 | "$schema": "https://raw.githubusercontent.com/IBM/CBOM/main/bom-1.4-cbom-1.0.schema.json", 381 | "bomFormat": "CBOM", 382 | "specVersion": "1.4-cbom-1.0" 383 | } -------------------------------------------------------------------------------- /tests/integration_tests/data/cbom/cbom_full.json: -------------------------------------------------------------------------------- 1 | { 2 | "components": [ 3 | { 4 | "bom-ref": "cryptography:private_key:90d480d3-42b2-4342-b319-7c5df8856064", 5 | "cryptoProperties": { 6 | "assetType": "relatedCryptoMaterial", 7 | "detectionContext": [ 8 | { 9 | "additionalContext": "# additional context region\n# additional context region\ndef encrypt(message):\n private_key = rsa.generate_private_key(\n public_exponent=65537,\n key_size=2048\n )\n\n subject = issuer = x509.Name([\n x509.NameAttribute(NameOID.COUNTRY_NAME, 'US'),\n x509.NameAttribute(NameOID.LOCALITY_NAME, 'Springfield'),\n x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'Springfield Nuclear Power Plant'),\n x509.NameAttribute(NameOID.COMMON_NAME, \"springfield-nuclear.com\")\n ])\n\n certificate = (\n x509.CertificateBuilder()\n .subject_name(subject)\n .issuer_name(issuer)\n .public_key(private_key.public_key())\n .serial_number(x509.random_serial_number())\n .not_valid_before(datetime.datetime.now(datetime.timezone.utc))\n .not_valid_after(datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=10))\n .add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]), critical=False)\n ).sign(private_key, hashes.SHA256())\n\n public_key = certificate.public_key()\n ciphertext = public_key.encrypt(\n message.encode(),\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None\n )\n )\n return ciphertext\n# additional context region\n# additional context region", 10 | "filePath": "springfield-nuclear-power-plant/core-reactor.py", 11 | "lineNumbers": [ 12 | 28, 13 | 29, 14 | 30, 15 | 31, 16 | 32, 17 | 33, 18 | 34, 19 | 35, 20 | 36, 21 | 37, 22 | 38, 23 | 39, 24 | 40, 25 | 41, 26 | 42, 27 | 43, 28 | 44, 29 | 45, 30 | 46, 31 | 47, 32 | 48, 33 | 49, 34 | 50, 35 | 51, 36 | 52, 37 | 53, 38 | 54, 39 | 55, 40 | 56, 41 | 57, 42 | 58, 43 | 59, 44 | 60, 45 | 61, 46 | 62, 47 | 63, 48 | 64, 49 | 65 50 | ] 51 | } 52 | ], 53 | "relatedCryptoMaterialProperties": { 54 | "relatedCryptoMaterialType": "privateKey", 55 | "size": 2048 56 | } 57 | }, 58 | "name": "90d480d3-42b2-4342-b319-7c5df8856064", 59 | "type": "crypto-asset" 60 | }, 61 | { 62 | "bom-ref": "cryptography:algorithm:1b80c552-5c11-48ac-a0f6-edc470a8aa40", 63 | "cryptoProperties": { 64 | "algorithmProperties": { 65 | "cryptoFunctions": [ 66 | "encrypt", 67 | "generate" 68 | ], 69 | "mode": "cbc", 70 | "padding": "unknown", 71 | "primitive": "blockcipher", 72 | "variant": "AES-128-CBC" 73 | }, 74 | "assetType": "algorithm", 75 | "detectionContext": [ 76 | { 77 | "additionalContext": "# additional context region\n# additional context region\ndef encrypt(message):\n encryptor = Fernet(Fernet.generate_key())\n ciphertext = encryptor.encrypt(message.encode())\n return ciphertext\n# additional context region\n# additional context region", 78 | "filePath": "springfield-nuclear-power-plant/tests/core-reactor.py", 79 | "lineNumbers": [ 80 | 28, 81 | 29, 82 | 30, 83 | 31, 84 | 32, 85 | 33, 86 | 34, 87 | 35 88 | ] 89 | } 90 | ] 91 | }, 92 | "name": "AES-128-CBC", 93 | "type": "crypto-asset" 94 | }, 95 | { 96 | "bom-ref": "cryptography:algorithm:f959178c-6674-4041-bcd0-be09ca56c772", 97 | "cryptoProperties": { 98 | "algorithmProperties": { 99 | "cryptoFunctions": [ 100 | "encrypt" 101 | ], 102 | "mode": "ecb", 103 | "padding": "pkcs7", 104 | "primitive": "blockcipher", 105 | "variant": "AES-128-ECB" 106 | }, 107 | "assetType": "algorithm", 108 | "detectionContext": [ 109 | { 110 | "additionalContext": "# additional context region\n# additional context region\ndef encrypt(message):\n padder = padding.PKCS7(128).padder()\n message = padder.update(message.encode()) + padder.finalize()\n\n key = os.urandom(32)\n encryptor = Cipher(\n algorithms.AES(key),\n modes.ECB(initialization_vector=os.urandom(16))\n ).encryptor()\n\n ciphertext = encryptor.update(message) + encryptor.finalize()\n return ciphertext\n# additional context region\n# additional context region", 111 | "filePath": "springfield-nuclear-power-plant/core-reactor.py", 112 | "lineNumbers": [ 113 | 28, 114 | 29, 115 | 30, 116 | 31, 117 | 32, 118 | 33, 119 | 34, 120 | 35, 121 | 36, 122 | 37, 123 | 38, 124 | 39, 125 | 40, 126 | 41, 127 | 42, 128 | 43 129 | ] 130 | } 131 | ] 132 | }, 133 | "name": "AES-128-ECB-PKCS7", 134 | "type": "crypto-asset" 135 | }, 136 | { 137 | "bom-ref": "cryptography:algorithm:496f1dcb-ccbc-434e-8918-ff19da3e0819", 138 | "cryptoProperties": { 139 | "algorithmProperties": { 140 | "cryptoFunctions": [ 141 | "encrypt", 142 | "generate", 143 | "sign" 144 | ], 145 | "padding": "oaep", 146 | "primitive": "signature", 147 | "variant": "DSA-2048" 148 | }, 149 | "assetType": "algorithm", 150 | "detectionContext": [ 151 | { 152 | "additionalContext": "# additional context region\n# additional context region\ndef encrypt(message):\n private_key = dsa.generate_private_key(\n key_size=2048\n )\n\n subject = issuer = x509.Name([\n x509.NameAttribute(NameOID.COUNTRY_NAME, 'US'),\n x509.NameAttribute(NameOID.LOCALITY_NAME, 'Springfield'),\n x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'Springfield Nuclear Power Plant'),\n x509.NameAttribute(NameOID.COMMON_NAME, \"springfield-nuclear.com\")\n ])\n\n certificate = (\n x509.CertificateBuilder()\n .subject_name(subject)\n .issuer_name(issuer)\n .public_key(private_key.public_key())\n .serial_number(x509.random_serial_number())\n .not_valid_before(datetime.datetime.now(datetime.timezone.utc))\n .not_valid_after(datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=10))\n .add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]), critical=False)\n ).sign(private_key, hashes.SHA256())\n\n public_key = certificate.public_key()\n ciphertext = public_key.encrypt(\n message.encode(),\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None\n )\n )\n return ciphertext\n# additional context region\n# additional context region", 153 | "filePath": "springfield-nuclear-power-plant/core-reactor.py", 154 | "lineNumbers": [ 155 | 28, 156 | 29, 157 | 30, 158 | 31, 159 | 32, 160 | 33, 161 | 34, 162 | 35, 163 | 36, 164 | 37, 165 | 38, 166 | 39, 167 | 40, 168 | 41, 169 | 42, 170 | 43, 171 | 44, 172 | 45, 173 | 46, 174 | 47, 175 | 48, 176 | 49, 177 | 50, 178 | 51, 179 | 52, 180 | 53, 181 | 54, 182 | 55, 183 | 56, 184 | 57, 185 | 58, 186 | 59, 187 | 60, 188 | 61, 189 | 62, 190 | 63, 191 | 64 192 | ] 193 | } 194 | ] 195 | }, 196 | "name": "DSA-2048-OAEP", 197 | "type": "crypto-asset" 198 | }, 199 | { 200 | "bom-ref": "cryptography:algorithm:4c003a38-2ab7-4bf3-810f-c0e473d3fff8", 201 | "cryptoProperties": { 202 | "algorithmProperties": { 203 | "cryptoFunctions": [ 204 | "encrypt", 205 | "generate", 206 | "sign" 207 | ], 208 | "padding": "oaep", 209 | "primitive": "pke", 210 | "variant": "RSA-2048" 211 | }, 212 | "assetType": "algorithm", 213 | "detectionContext": [ 214 | { 215 | "additionalContext": "# additional context region\n# additional context region\ndef encrypt(message):\n private_key = rsa.generate_private_key(\n public_exponent=65537,\n key_size=2048\n )\n\n subject = issuer = x509.Name([\n x509.NameAttribute(NameOID.COUNTRY_NAME, 'US'),\n x509.NameAttribute(NameOID.LOCALITY_NAME, 'Springfield'),\n x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'Springfield Nuclear Power Plant'),\n x509.NameAttribute(NameOID.COMMON_NAME, \"springfield-nuclear.com\")\n ])\n\n certificate = (\n x509.CertificateBuilder()\n .subject_name(subject)\n .issuer_name(issuer)\n .public_key(private_key.public_key())\n .serial_number(x509.random_serial_number())\n .not_valid_before(datetime.datetime.now(datetime.timezone.utc))\n .not_valid_after(datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=10))\n .add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]), critical=False)\n ).sign(private_key, hashes.SHA256())\n\n public_key = certificate.public_key()\n ciphertext = public_key.encrypt(\n message.encode(),\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None\n )\n )\n return ciphertext\n# additional context region\n# additional context region", 216 | "filePath": "springfield-nuclear-power-plant/core-reactor.py", 217 | "lineNumbers": [ 218 | 28, 219 | 29, 220 | 30, 221 | 31, 222 | 32, 223 | 33, 224 | 34, 225 | 35, 226 | 36, 227 | 37, 228 | 38, 229 | 39, 230 | 40, 231 | 41, 232 | 42, 233 | 43, 234 | 44, 235 | 45, 236 | 46, 237 | 47, 238 | 48, 239 | 49, 240 | 50, 241 | 51, 242 | 52, 243 | 53, 244 | 54, 245 | 55, 246 | 56, 247 | 57, 248 | 58, 249 | 59, 250 | 60, 251 | 61, 252 | 62, 253 | 63, 254 | 64, 255 | 65 256 | ] 257 | } 258 | ] 259 | }, 260 | "name": "RSA-2048-OAEP", 261 | "type": "crypto-asset" 262 | }, 263 | { 264 | "bom-ref": "cryptography:certificate:bff25a20-7c0a-490e-959c-85295f4c145b", 265 | "cryptoProperties": { 266 | "assetType": "certificate", 267 | "certificateProperties": { 268 | "certificateAlgorithm": "RSA", 269 | "certificateFormat": "X.509", 270 | "certificateSignatureAlgorithm": "SHA256", 271 | "issuerName": "C=US, L=Springfield, O=Springfield Nuclear Power Plant, CN=springfield-nuclear.com", 272 | "subjectName": "C=US, L=Springfield, O=Springfield Nuclear Power Plant, CN=springfield-nuclear.com" 273 | }, 274 | "detectionContext": [ 275 | { 276 | "additionalContext": "# additional context region\n# additional context region\ndef encrypt(message):\n private_key = rsa.generate_private_key(\n public_exponent=65537,\n key_size=2048\n )\n\n subject = issuer = x509.Name([\n x509.NameAttribute(NameOID.COUNTRY_NAME, 'US'),\n x509.NameAttribute(NameOID.LOCALITY_NAME, 'Springfield'),\n x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'Springfield Nuclear Power Plant'),\n x509.NameAttribute(NameOID.COMMON_NAME, \"springfield-nuclear.com\")\n ])\n\n certificate = (\n x509.CertificateBuilder()\n .subject_name(subject)\n .issuer_name(issuer)\n .public_key(private_key.public_key())\n .serial_number(x509.random_serial_number())\n .not_valid_before(datetime.datetime.now(datetime.timezone.utc))\n .not_valid_after(datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=10))\n .add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]), critical=False)\n ).sign(private_key, hashes.SHA256())\n\n public_key = certificate.public_key()\n ciphertext = public_key.encrypt(\n message.encode(),\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None\n )\n )\n return ciphertext\n# additional context region\n# additional context region", 277 | "filePath": "springfield-nuclear-power-plant/core-reactor.py", 278 | "lineNumbers": [ 279 | 28, 280 | 29, 281 | 30, 282 | 31, 283 | 32, 284 | 33, 285 | 34, 286 | 35, 287 | 36, 288 | 37, 289 | 38, 290 | 39, 291 | 40, 292 | 41, 293 | 42, 294 | 43, 295 | 44, 296 | 45, 297 | 46, 298 | 47, 299 | 48, 300 | 49, 301 | 50, 302 | 51, 303 | 52, 304 | 53, 305 | 54, 306 | 55, 307 | 56, 308 | 57, 309 | 58, 310 | 59, 311 | 60, 312 | 61, 313 | 62, 314 | 63, 315 | 64, 316 | 65 317 | ] 318 | } 319 | ] 320 | }, 321 | "name": "bff25a20-7c0a-490e-959c-85295f4c145b", 322 | "type": "crypto-asset" 323 | } 324 | ], 325 | "dependencies": [ 326 | { 327 | "dependsOn": [ 328 | "cryptography:algorithm:1b80c552-5c11-48ac-a0f6-edc470a8aa40", 329 | "cryptography:algorithm:496f1dcb-ccbc-434e-8918-ff19da3e0819", 330 | "cryptography:algorithm:4c003a38-2ab7-4bf3-810f-c0e473d3fff8", 331 | "cryptography:algorithm:f959178c-6674-4041-bcd0-be09ca56c772" 332 | ], 333 | "ref": "58e8d784-8745-4666-964e-7f1ce44446eb" 334 | }, 335 | { 336 | "ref": "cryptography:algorithm:1b80c552-5c11-48ac-a0f6-edc470a8aa40" 337 | }, 338 | { 339 | "ref": "cryptography:algorithm:496f1dcb-ccbc-434e-8918-ff19da3e0819" 340 | }, 341 | { 342 | "dependsOn": [ 343 | "cryptography:certificate:bff25a20-7c0a-490e-959c-85295f4c145b", 344 | "cryptography:private_key:90d480d3-42b2-4342-b319-7c5df8856064" 345 | ], 346 | "ref": "cryptography:algorithm:4c003a38-2ab7-4bf3-810f-c0e473d3fff8" 347 | }, 348 | { 349 | "ref": "cryptography:algorithm:f959178c-6674-4041-bcd0-be09ca56c772" 350 | }, 351 | { 352 | "ref": "cryptography:certificate:bff25a20-7c0a-490e-959c-85295f4c145b" 353 | }, 354 | { 355 | "ref": "cryptography:private_key:90d480d3-42b2-4342-b319-7c5df8856064" 356 | } 357 | ], 358 | "metadata": { 359 | "component": { 360 | "bom-ref": "58e8d784-8745-4666-964e-7f1ce44446eb", 361 | "name": "root", 362 | "type": "application" 363 | }, 364 | "timestamp": "2024-01-04T09:54:58.428646+00:00", 365 | "tools": [ 366 | { 367 | "externalReferences": [ 368 | { 369 | "type": "build-system", 370 | "url": "https://github.com/CycloneDX/cyclonedx-python-lib/actions" 371 | }, 372 | { 373 | "type": "distribution", 374 | "url": "https://pypi.org/project/cyclonedx-python-lib/" 375 | }, 376 | { 377 | "type": "documentation", 378 | "url": "https://cyclonedx.github.io/cyclonedx-python-lib/" 379 | }, 380 | { 381 | "type": "issue-tracker", 382 | "url": "https://github.com/CycloneDX/cyclonedx-python-lib/issues" 383 | }, 384 | { 385 | "type": "license", 386 | "url": "https://github.com/CycloneDX/cyclonedx-python-lib/blob/main/LICENSE" 387 | }, 388 | { 389 | "type": "release-notes", 390 | "url": "https://github.com/CycloneDX/cyclonedx-python-lib/blob/main/CHANGELOG.md" 391 | }, 392 | { 393 | "type": "vcs", 394 | "url": "https://github.com/CycloneDX/cyclonedx-python-lib" 395 | }, 396 | { 397 | "type": "website", 398 | "url": "https://cyclonedx.org" 399 | } 400 | ], 401 | "name": "cyclonedx-python-lib", 402 | "vendor": "CycloneDX", 403 | "version": "4.2.2" 404 | }, 405 | { 406 | "name": "CodeQL", 407 | "vendor": "GitHub", 408 | "version": "2.15.4" 409 | } 410 | ] 411 | }, 412 | "serialNumber": "urn:uuid:6b990ba4-1d57-41f0-b995-11006eb91239", 413 | "version": 1, 414 | "$schema": "https://raw.githubusercontent.com/IBM/CBOM/main/bom-1.4-cbom-1.0.schema.json", 415 | "bomFormat": "CBOM", 416 | "specVersion": "1.4-cbom-1.0" 417 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------