diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000..1d36346 --- /dev/null +++ b/.flake8 @@ -0,0 +1,2 @@ +[flake8] +max-line-length = 88 \ No newline at end of file diff --git a/.github/workflows/tox.yml b/.github/workflows/tox.yml new file mode 100644 index 0000000..f68e652 --- /dev/null +++ b/.github/workflows/tox.yml @@ -0,0 +1,34 @@ +name: Run Tox on PR + +on: + pull_request: + branches: + - main + - '**' # Run on all branches for PRs + +jobs: + tox-tests: + runs-on: ubuntu-latest + + strategy: + matrix: + python-version: [3.9, 3.11] # Test against multiple Python versions + + steps: + # Checkout the code + - name: Checkout code + uses: actions/checkout@v3 + + # Setup Python + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + + # Install tox + - name: Install tox + run: pip install tox + + # Run tox + - name: Run tox + run: tox \ No newline at end of file diff --git a/.pylintrc b/.pylintrc index ee29c99..ce00b4d 100644 --- a/.pylintrc +++ b/.pylintrc @@ -1,8 +1,9 @@ [MESSAGES CONTROL] -disable = C0114, C0115, C0116 ; Disable missing module/class/function docstring warnings +disable = C0114, C0115, C0116, redefined-outer-name, duplicate-code [FORMAT] max-line-length = 88 ; Match Black's default line length +max-attributes=10 [MASTER] ignore = venv ; Ignore virtual environment folder diff --git a/README.md b/README.md index 537468d..1407903 100644 --- a/README.md +++ b/README.md @@ -1,26 +1,68 @@ -# python-ear +# **python-ear** -A python implementation of [draft-fv-rats-ear](https://datatracker.ietf.org/doc/draft-fv-rats-ear/). +A Python library that implements the EAT Attestation Result (EAR) data format, as specified in [draft-fv-rats-ear](https://datatracker.ietf.org/doc/draft-fv-rats-ear/). This library provides implementations for both CBOR-based and JSON-based serialisations. -# Proposal +--- -Following are the tools that will be used in the development of this library +## **Overview** -## CWT and JWT creation +The goal of this project is to standardize attestation results by defining a shared information and data model, enabling seamless integration with other components of the RATS architecture. This focuses specifically on harmonizing attestation results to facilitate interoperability between various verifiers and relying parties. -1. [python-cwt](https://python-cwt.readthedocs.io/en/stable/) -2. [python-jwt](https://pypi.org/project/python-jose/) +This implementation was initiated as part of the **Veraison Mentorship** under the Linux Foundation Mentorship Program (**LFX Mentorship**), focusing on the following capabilities: -## Code formatting and styling +- **Populating EAR Claims-Sets:** Define and populate claims that represent evidence and attestation results. +- **Signing EAR Claims-Sets:** Support signing using private keys, ensuring data integrity and authenticity. +- **Encoding and Decoding:** + - Encode signed EAR claims as **CWT** (Concise Binary Object Representation Web Tokens) or **JWT** (JSON Web Tokens). + - Decode signed EARs from CWT or JWT formats, enabling interoperability between different systems. +- **Signature Verification:** Verify signatures using public keys to ensure the authenticity of claims. +- **Accessing Claims:** Provide interfaces to access and manage EAR claims efficiently. -1. [black](https://pypi.org/project/black/) -2. [isort](https://pypi.org/project/isort/) +This library is developed in Python and makes use of existing packages for CWT and JWT management, static code analysis, and testing. -## Linting and static analysis +--- -1. [flake8](https://pypi.org/project/flake8/) -2. [mypy](https://pypi.org/project/mypy/) +## **Key Features** -## Testing +1. **Standards Compliance:** + Implements draft-fv-rats-ear as per IETF specifications to ensure compatibility with the RATS architecture. -1. [pytest](https://pypi.org/project/pytest/) \ No newline at end of file +2. **Token Management:** + - **CWT Support:** Utilizes [python-cwt](https://python-cwt.readthedocs.io/en/stable/) for handling CBOR Web Tokens. + - **JWT Support:** Uses [python-jose](https://pypi.org/project/python-jose/) for JSON Web Tokens management. + +3. **Security:** + - Supports signing of EAR claims with private keys and verification with public keys. + - Adopts secure cryptographic practices for token creation and verification. + +4. **Static Analysis and Code Quality:** + - Ensures code quality using linters and static analysis tools. + - Maintains type safety and code consistency. + +5. **Testing:** + - Comprehensive unit tests using `pytest` to validate all functionalities. + +--- + +## **Technical Stack** + +### **Token Creation and Management** + +- **CWT:** [python-cwt](https://python-cwt.readthedocs.io/en/stable/) +- **JWT:** [python-jose](https://pypi.org/project/python-jose/) + +### **Code Formatting and Styling** + +- **black:** Ensures consistent code formatting. +- **isort:** Manages import statements. + +### **Linting and Static Analysis** + +- **flake8:** For PEP 8 compliance and linting. +- **mypy:** Static type checking. +- **pyright:** Advanced type checking for Python. +- **pylint:** Code analysis for error detection and enforcing coding standards. + +### **Testing** + +- **pytest:** Framework for writing and executing tests. \ No newline at end of file diff --git a/src/base.py b/src/base.py new file mode 100644 index 0000000..ae506f1 --- /dev/null +++ b/src/base.py @@ -0,0 +1,99 @@ +import json +from abc import ABC +from collections import namedtuple +from typing import Any, ClassVar, Dict, Tuple, Type, TypeVar, Union, get_args + +T = TypeVar("T", bound="BaseJCSerializable") + +KeyMapping = namedtuple("KeyMapping", ["int_key", "str_key"]) + + +def to_data(value: Any, keys_as_int=False) -> Any: + if hasattr(value, "to_data"): + return value.to_data(keys_as_int) + if hasattr(value, "items"): # dict-like + return { + to_data(k, keys_as_int): to_data(v, keys_as_int) for k, v in value.items() + } + if hasattr(value, "__iter__") and not isinstance(value, str): # list-like + return [to_data(v, keys_as_int) for v in value] + + if hasattr( + value, "value" + ): # custom classes that have value attr but don't have 'to_data' + return value.value # type: ignore[attr-defined] + # scalar and no to_data(), so assume serializable as-is + return value + + +class BaseJCSerializable(ABC): + jc_map: ClassVar[Dict[str, Tuple[int, str]]] + + def to_data(self, keys_as_int=False) -> Dict[Union[str, int], Any]: + return { + (int_key if keys_as_int else str_key): to_data( + getattr(self, attr), keys_as_int + ) + for attr, (int_key, str_key) in self.jc_map.items() + } + + @classmethod + def from_data(cls: Type[T], data: dict, keys_as_int=False) -> T: + key_attr = "int_key" if keys_as_int else "str_key" + init_kwargs = {} + reverse_map = { + getattr(mapping, key_attr): attr for attr, mapping in cls.jc_map.items() + } + + for key, value in data.items(): + if key not in reverse_map: + continue + + attr = reverse_map[key] + field_type = getattr(cls, "__annotations__", {}).get(attr) + if field_type is None: + continue + + args = get_args(field_type) + + if hasattr(field_type, "from_data"): + # Direct object + init_kwargs[attr] = field_type.from_data(value, keys_as_int=keys_as_int) + + elif hasattr(field_type, "items") and hasattr(args[1], "from_data"): + # Dict[str | int, CustomClass] + init_kwargs[attr] = { + k: args[1].from_data(v, keys_as_int=keys_as_int) + for k, v in value.items() + } + + elif args: + # custom classes that dont have 'from_data' + init_kwargs[attr] = args[0](value) + + else: + init_kwargs[attr] = field_type(value) + + return cls(**init_kwargs) + + def to_dict(self) -> Dict[str, Any]: + # default str_keys + return self.to_data() # type: ignore[return-value] # pyright: ignore[reportGeneralTypeIssues] # noqa: E501 # pylint: disable=line-too-long + + def to_int_keys(self) -> Dict[Union[str, int], Any]: + return self.to_data(keys_as_int=True) + + @classmethod + def from_dict(cls: Type[T], data: Dict[str, Any]) -> T: + return cls.from_data(data) + + @classmethod + def from_int_keys(cls: Type[T], data: Dict[int, Any]) -> T: + return cls.from_data(data, keys_as_int=True) + + @classmethod + def from_json(cls, json_str: str): + return cls.from_dict(json.loads(json_str)) + + def to_json(self): + return json.dumps(self.to_data()) diff --git a/src/claims.py b/src/claims.py index 8e69c4d..e5416fb 100644 --- a/src/claims.py +++ b/src/claims.py @@ -1,35 +1,76 @@ -import json from dataclasses import dataclass, field -from typing import Any, Dict +from datetime import datetime, timedelta +from typing import Dict +from jose import jwt # type: ignore # pylint: disable=import-error +from src.base import BaseJCSerializable, KeyMapping +from src.errors import EARValidationError +from src.jwt_config import DEFAULT_ALGORITHM, DEFAULT_EXPIRATION_MINUTES +from src.submod import Submod +from src.verifier_id import VerifierID + + +# https://datatracker.ietf.org/doc/draft-fv-rats-ear/ @dataclass -class EARClaims: +class AttestationResult(BaseJCSerializable): profile: str issued_at: int - verifier_id: Dict[str, str] = field(default_factory=dict) - submods: Dict[str, Any] = field(default_factory=dict) + verifier_id: VerifierID + submods: Dict[str, Submod] = field(default_factory=dict) - def to_dict(self) -> Dict[str, Any]: - return { - "eat_profile": self.profile, - "iat": self.issued_at, - "ear.verifier-id": self.verifier_id, - "submods": self.submods, - } + # https://www.ietf.org/archive/id/draft-ietf-rats-eat-31.html#section-7.2.4 + jc_map = { + "profile": KeyMapping(265, "eat_profile"), + "issued_at": KeyMapping(6, "iat"), + "verifier_id": KeyMapping(1004, "ear.verifier-id"), + "submods": KeyMapping(266, "submods"), + } - @classmethod - def from_dict(cls, data: Dict[str, Any]): - return cls( - profile=data.get("eat_profile", ""), - issued_at=data.get("iat", 0), - verifier_id=data.get("ear.verifier-id", {}), - submods=data.get("submods", {}), - ) + def validate(self): + # Validates an AttestationResult object + if not isinstance(self.profile, str) or not self.profile: + raise EARValidationError( + "AttestationResult profile must be a non-empty string" + ) + if not isinstance(self.issued_at, int) or self.issued_at <= 0: + raise EARValidationError( + "AttestationResult issued_at must be a positive integer" + ) - def to_json(self) -> str: - return json.dumps(self.to_dict()) + self.verifier_id.validate() + + for submod, details in self.submods.items(): + if not isinstance(details, Submod): + raise EARValidationError( + f"Submodule {submod} must contain a valid trust_vector and status" + ) + + trust_vector = details.trust_vector + trust_vector.validate() + + def encode_jwt( + self, + secret_key: str, + algorithm: str = DEFAULT_ALGORITHM, + expiration_minutes: int = DEFAULT_EXPIRATION_MINUTES, + ) -> str: + # Signs an AttestationResult object and returns a JWT + payload = self.to_dict() + payload["exp"] = int( + datetime.timestamp(datetime.now() + timedelta(minutes=expiration_minutes)) + ) + return jwt.encode( + payload, secret_key, algorithm=algorithm + ) # pyright: ignore[reportGeneralTypeIssues] @classmethod - def from_json(cls, json_str: str): - return cls.from_dict(json.loads(json_str)) + def decode_jwt( + cls, token: str, secret_key: str, algorithm: str = DEFAULT_ALGORITHM + ): + # Verifies a JWT and returns the decoded AttestationResult object. + try: + payload = jwt.decode(token, secret_key, algorithms=[algorithm]) + return cls.from_dict(payload) + except Exception as exc: + raise ValueError(f"JWT decoding failed: {exc}") from exc diff --git a/src/errors.py b/src/errors.py new file mode 100644 index 0000000..cd5747e --- /dev/null +++ b/src/errors.py @@ -0,0 +1,3 @@ +class EARValidationError(Exception): + # Custom exception for validation errors in AttestationResult + pass diff --git a/src/example/__init__.py b/src/example/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/example/jwt_example.py b/src/example/jwt_example.py new file mode 100644 index 0000000..8a8dde3 --- /dev/null +++ b/src/example/jwt_example.py @@ -0,0 +1,42 @@ +from datetime import datetime + +from src.claims import AttestationResult +from src.jwt_config import generate_secret_key +from src.submod import Submod +from src.trust_claims import TRUSTWORTHY_INSTANCE_CLAIM, UNRECOGNIZED_INSTANCE_CLAIM +from src.trust_tier import TRUST_TIER_AFFIRMING, TRUST_TIER_CONTRAINDICATED +from src.trust_vector import TrustVector +from src.verifier_id import VerifierID + +# import json + +# Generate a secret key for signing +secret_key = generate_secret_key() + +# Create an AttestationResult object +attestation_result = AttestationResult( + profile="test_profile", + issued_at=int(datetime.timestamp(datetime.now())), + verifier_id=VerifierID(developer="Acme Inc.", build="v1"), + submods={ + "submod1": Submod( + trust_vector=TrustVector(instance_identity=UNRECOGNIZED_INSTANCE_CLAIM), + status=TRUST_TIER_AFFIRMING, + ), + "submod2": Submod( + trust_vector=TrustVector(instance_identity=TRUSTWORTHY_INSTANCE_CLAIM), + status=TRUST_TIER_CONTRAINDICATED, + ), + }, +) + +# payload = attestation_result.encode_jwt(secret_key=secret_key) +# print(payload) + +# decoded = AttestationResult.decode_jwt(token=payload, secret_key=secret_key) +# output_data = decoded.to_dict() + +# with open("jwt_output.json", "w", encoding="utf-8") as f: +# json.dump(output_data, f, indent=4) + +# print("Output successfully written to output.json") diff --git a/src/example/jwt_output.json b/src/example/jwt_output.json new file mode 100644 index 0000000..c87caea --- /dev/null +++ b/src/example/jwt_output.json @@ -0,0 +1,36 @@ +{ + "profile": "test_profile", + "issued_at": 1744932192, + "verifier_id": { + "developer": "Acme Inc.", + "build": "v1" + }, + "submods": { + "submod1": { + "status": 2, + "trust_vector": { + "instance_identity": 97, + "configuration": null, + "executables": null, + "file_system": null, + "hardware": null, + "runtime_opaque": null, + "storage_opaque": null, + "sourced_data": null + } + }, + "submod2": { + "status": 96, + "trust_vector": { + "instance_identity": 2, + "configuration": null, + "executables": null, + "file_system": null, + "hardware": null, + "runtime_opaque": null, + "storage_opaque": null, + "sourced_data": null + } + } + } +} \ No newline at end of file diff --git a/src/jwt_config.py b/src/jwt_config.py new file mode 100644 index 0000000..af17f0e --- /dev/null +++ b/src/jwt_config.py @@ -0,0 +1,10 @@ +import secrets + +# Default cryptographic settings for JWT +DEFAULT_ALGORITHM = "HS256" +DEFAULT_EXPIRATION_MINUTES = 60 + + +def generate_secret_key() -> str: + # Generates a secure random secret key for JWT signing. + return secrets.token_hex(32) diff --git a/src/submod.py b/src/submod.py new file mode 100644 index 0000000..7ba1608 --- /dev/null +++ b/src/submod.py @@ -0,0 +1,16 @@ +from dataclasses import dataclass + +from src.base import BaseJCSerializable, KeyMapping +from src.trust_tier import TrustTier +from src.trust_vector import TrustVector + + +@dataclass +class Submod(BaseJCSerializable): + trust_vector: TrustVector + status: TrustTier + + jc_map = { + "status": KeyMapping(1000, "ear.status"), + "trust_vector": KeyMapping(1001, "ear.trustworthiness-vector"), + } diff --git a/src/trust_claims.py b/src/trust_claims.py new file mode 100644 index 0000000..9ac7fa6 --- /dev/null +++ b/src/trust_claims.py @@ -0,0 +1,274 @@ +from dataclasses import asdict, dataclass +from typing import Any, Dict + +from src.errors import EARValidationError + + +# https://www.ietf.org/archive/id/draft-ietf-rats-ar4si-08.html#section-2.3 +@dataclass +class TrustClaim: + # every trustclaim will be transported in form of its value only + value: int # must be in range -128 to 127, + tag: str = "" + short: str = "" + long: str = "" + + def to_dict(self) -> Dict[str, Any]: + return asdict(self) + + def validate(self): + # Validates a TrustClaim object + if not isinstance(self.value, int) or not -128 <= self.value <= 127: + raise EARValidationError( + f"""Invalid value in TrustClaim: {self.value}. + Must be in range [-128, 127]""" + ) + if not isinstance(self.tag, str): + raise EARValidationError("TrustClaim tag must be a string") + if not isinstance(self.short, str): + raise EARValidationError("TrustClaim short description must be a string") + if not isinstance(self.long, str): + raise EARValidationError("TrustClaim long description must be a string") + + +# Mapping value to TrustClaim types +# General +VERIFIER_MALFUNCTION_CLAIM = TrustClaim( + value=-1, + tag="verifier_malfunction", + short="verifier malfunction", + long="A verifier malfunction occurred during the Verifier's appraisal processing.", # noqa: E501 # pylint: disable=line-too-long +) + +NO_CLAIM = TrustClaim( + value=0, + tag="no_claim", + short="no claim being made", + long="The Evidence received is insufficient to make a conclusion.", +) + +UNEXPECTED_EVIDENCE_CLAIM = TrustClaim( + value=1, + tag="unexected_evidence", + short="unexpected evidence", + long="The Evidence received contains unexpected elements which the Verifier is unable to parse.", # noqa: E501 # pylint: disable=line-too-long +) + +CRYPTO_VALIDATION_FAILED_CLAIM = TrustClaim( + value=99, + tag="crypto_failed", + short="cryptographic validation failed", + long="Cryptographic validation of the Evidence has failed.", +) + + +# Instance Identity +TRUSTWORTHY_INSTANCE_CLAIM = TrustClaim( + value=2, + tag="recognized_instance", + short="recognized and not compromised", + long="The Attesting Environment is recognized, and the associated instance of the Attester is not known to be compromised.", # noqa: E501 # pylint: disable=line-too-long +) + +UNTRUSTWORTHY_INSTANCE_CLAIM = TrustClaim( + value=96, + tag="untrustworthy_instance", + short="recognized but not trustworthy", + long="The Attesting Environment is recognized, but its unique private key indicates a device which is not trustworthy.", # noqa: E501 # pylint: disable=line-too-long +) + +UNRECOGNIZED_INSTANCE_CLAIM = TrustClaim( + value=97, + tag="unrecognized_instance", + short="not recognized", + long="The Attesting Environment is not recognized; however the Verifier believes it should be.", # noqa: E501 # pylint: disable=line-too-long +) + + +# Config +APPROVED_CONFIG_CLAIM = TrustClaim( + value=2, + tag="approved_config", + short="all recognized and approved", + long="The configuration is a known and approved config.", +) + +NO_CONFIG_VULNS_CLAIM = TrustClaim( + value=3, + tag="safe_config", + short="no known vulnerabilities", + long="The configuration includes or exposes no known vulnerabilities", # noqa: E501 # pylint: disable=line-too-long +) + +UNSAFE_CONFIG_CLAIM = TrustClaim( + value=32, + tag="unsafe_config", + short="known vulnerabilities", + long="The configuration includes or exposes known vulnerabilities.", +) + +UNSUPPORTABLE_CONFIG_CLAIM = TrustClaim( + value=96, + tag="unsupportable_config", + short="unacceptable security vulnerabilities", + long="The configuration is unsupportable as it exposes unacceptable security vulnerabilities", # noqa: E501 # pylint: disable=line-too-long +) + + +# Executables & Runtime +APPROVED_RUNTIME_CLAIM = TrustClaim( + value=2, + tag="approved_rt", + short="recognized and approved boot- and run-time", + long="Only a recognized genuine set of approved executables, scripts, files, and/or objects have been loaded during and after the boot process.", # noqa: E501 # pylint: disable=line-too-long +) + +APPROVED_BOOT_CLAIM = TrustClaim( + value=3, + tag="approved_boot", + short="recognized and approved boot-time", + long="Only a recognized genuine set of approved executables have been loaded during the boot process.", # noqa: E501 # pylint: disable=line-too-long +) + +UNSAFE_RUNTIME_CLAIM = TrustClaim( + value=32, + tag="unsafe_rt", + short="recognized but known bugs or vulnerabilities", + long="Only a recognized genuine set of executables, scripts, files, and/or objects have been loaded. However the Verifier cannot vouch for a subset of these due to known bugs or other known vulnerabilities.", # noqa: E501 # pylint: disable=line-too-long +) + +UNRECOGNIZED_RUNTIME_CLAIM = TrustClaim( + value=33, + tag="unrecognized_rt", + short="unrecognized run-time", + long="Runtime memory includes executables, scripts, files, and/or objects which are not recognized.", # noqa: E501 # pylint: disable=line-too-long +) + +CONTRAINDICATED_RUNTIME_CLAIM = TrustClaim( + value=96, + tag="contraindicated_rt", + short="contraindicated run-time", + long="Runtime memory includes executables, scripts, files, and/or object which are contraindicated.", # noqa: E501 # pylint: disable=line-too-long +) + + +# File System +APPROVED_FILES_CLAIM = TrustClaim( + value=2, + tag="approved_fs", + short="all recognized and approved", + long="Only a recognized set of approved files are found.", +) + +UNRECOGNIZED_FILES_CLAIM = TrustClaim( + value=32, + tag="unrecognized_fs", + short="unrecognized item(s) found", + long="The file system includes unrecognized executables, scripts, or files.", # noqa: E501 # pylint: disable=line-too-long +) + +CONTRAINDICATED_FILES_CLAIM = TrustClaim( + value=96, + tag="contraindicated_fs", + short="contraindicated item(s) found", + long="The file system includes contraindicated executables, scripts, or files.", # noqa: E501 # pylint: disable=line-too-long +) + + +# Hardware +GENUINE_HARDWARE_CLAIM = TrustClaim( + value=2, + tag="genuine_hw", + short="genuine", + long="An Attester has passed its hardware and/or firmware verifications needed to demonstrate that these are genuine/supported.", # noqa: E501 # pylint: disable=line-too-long +) + +UNSAFE_HARDWARE_CLAIM = TrustClaim( + value=32, + tag="unsafe_hw", + short="genuine but known bugs or vulnerabilities", + long="An Attester contains only genuine/supported hardware and/or firmware, but there are known security vulnerabilities.", # noqa: E501 # pylint: disable=line-too-long +) + +CONTRAINDICATED_HARDWARE_CLAIM = TrustClaim( + value=96, + tag="contraindicated_hw", + short="genuine but contraindicated", + long="Attester hardware and/or firmware is recognized, but its trustworthiness is contraindicated.", # noqa: E501 # pylint: disable=line-too-long +) + +UNRECOGNIZED_HARDWARE_CLAIM = TrustClaim( + value=97, + tag="unrecognized_hw", + short="unrecognized", + long="A Verifier does not recognize an Attester's hardware or firmware, but it should be recognized.", # noqa: E501 # pylint: disable=line-too-long +) + + +# Opaque Runtime +ENCRYPTED_MEMORY_RUNTIME_CLAIM = TrustClaim( + value=2, + tag="encrypted_rt", + short="memory encryption", + long="the Attester's executing Target Environment and Attesting Environments are encrypted and within Trusted Execution Environment(s) opaque to the operating system, virtual machine manager, and peer applications.", # noqa: E501 # pylint: disable=line-too-long +) + +ISOLATED_MEMORY_RUNTIME_CLAIM = TrustClaim( + value=32, + tag="isolated_rt", + short="memory isolation", + long="the Attester's executing Target Environment and Attesting Environments are inaccessible from any other parallel application or Guest VM running on the Attester's physical device.", # noqa: E501 # pylint: disable=line-too-long +) + +VISIBLE_MEMORY_RUNTIME_CLAIM = TrustClaim( + value=96, + tag="visible_rt", + short="visible", + long="The Verifier has concluded that in memory objects are unacceptably visible within the physical host that supports the Attester.", # noqa: E501 # pylint: disable=line-too-long +) + + +# Opaque Storage +HW_KEYS_ENCRYPTED_SECRETS_CLAIM = TrustClaim( + value=2, + tag="hw_encrypted_secrets", + short="encrypted secrets with HW-backed keys", + long="the Attester encrypts all secrets in persistent storage via using keys which are never visible outside an HSM or the Trusted Execution Environment hardware.", # noqa: E501 # pylint: disable=line-too-long +) + +SW_KEYS_ENCRYPTED_SECRETS_CLAIM = TrustClaim( + value=32, + tag="sw_encrypted_secrets", + short="encrypted secrets with non HW-backed keys", + long="the Attester encrypts all persistently stored secrets, but without using hardware backed keys.", # noqa: E501 # pylint: disable=line-too-long +) + +UNENCRYPTED_SECRETS_CLAIM = TrustClaim( + value=96, + tag="unencrypted_secrets", + short="unencrypted secrets", + long="There are persistent secrets which are stored unencrypted in an Attester.", +) + + +# Sourced Data +TRUSTED_SOURCES_CLAIM = TrustClaim( + value=2, + tag="trusted_sources", + short="from attesters in the affirming tier", + long='All essential Attester source data objects have been provided by other Attester(s) whose most recent appraisal(s) had both no Trustworthiness Claims of "0" where the current Trustworthiness Claim is "Affirming", as well as no "Warning" or "Contraindicated" Trustworthiness Claims.', # noqa: E501 # pylint: disable=line-too-long +) + +UNTRUSTED_SOURCES_CLAIM = TrustClaim( + value=32, + tag="untrusted_sources", + short="from unattested sources or attesters in the warning tier", + long='Attester source data objects come from unattested sources, or attested sources with "Warning" type Trustworthiness Claims', # noqa: E501 # pylint: disable=line-too-long +) + +CONTRAINDICATED_SOURCES_CLAIM = TrustClaim( + value=96, + tag="contraindicated_sources", + short="from attesters in the contraindicated tier", + long="Attester source data objects come from contraindicated sources.", +) diff --git a/src/trust_tier.py b/src/trust_tier.py new file mode 100644 index 0000000..2f186f7 --- /dev/null +++ b/src/trust_tier.py @@ -0,0 +1,46 @@ +from dataclasses import dataclass +from typing import Any, Dict + + +# https://www.ietf.org/archive/id/draft-ietf-rats-ar4si-08.html#section-3.2 +@dataclass(frozen=True) +class TrustTier: + value: int + + +def to_trust_tier(value: Any) -> TrustTier: + # Converts an integer or string to a TrustTier instance, + # defaulting to TrustTierNone on failure + if isinstance(value, int): + return INT_TO_TRUST_TIER.get(value, TRUST_TIER_NONE) + if isinstance(value, str): + return STRING_TO_TRUST_TIER.get(value, TRUST_TIER_NONE) + raise ValueError(f"Cannot convert {value} (type {type(value)}) to TrustTier") + + +# Defining trust tiers +TRUST_TIER_NONE: TrustTier = TrustTier(0) +TRUST_TIER_AFFIRMING: TrustTier = TrustTier(2) +TRUST_TIER_WARNING: TrustTier = TrustTier(32) +TRUST_TIER_CONTRAINDICATED: TrustTier = TrustTier(96) + +# Mapping from TrustTier to string representation +TRUST_TIER_TO_STRING: Dict[TrustTier, str] = { + TRUST_TIER_NONE: "none", + TRUST_TIER_AFFIRMING: "affirming", + TRUST_TIER_WARNING: "warning", + TRUST_TIER_CONTRAINDICATED: "contraindicated", +} + +# Reverse mapping from string to TrustTier +STRING_TO_TRUST_TIER: Dict[str, TrustTier] = { + v: k for k, v in TRUST_TIER_TO_STRING.items() +} + +# Mapping from integer value to TrustTier +INT_TO_TRUST_TIER: Dict[int, TrustTier] = { + TRUST_TIER_NONE.value: TRUST_TIER_NONE, + TRUST_TIER_AFFIRMING.value: TRUST_TIER_AFFIRMING, + TRUST_TIER_WARNING.value: TRUST_TIER_WARNING, + TRUST_TIER_CONTRAINDICATED.value: TRUST_TIER_CONTRAINDICATED, +} diff --git a/src/trust_vector.py b/src/trust_vector.py new file mode 100644 index 0000000..a55f1a8 --- /dev/null +++ b/src/trust_vector.py @@ -0,0 +1,37 @@ +from dataclasses import dataclass +from typing import Optional + +from src.base import BaseJCSerializable, KeyMapping +from src.trust_claims import TrustClaim + + +# https://www.ietf.org/archive/id/draft-ietf-rats-ar4si-08.html#section-3.1 +# TrustVector class to represent the trustworthiness vector +@dataclass +class TrustVector(BaseJCSerializable): + instance_identity: Optional[TrustClaim] = None + configuration: Optional[TrustClaim] = None + executables: Optional[TrustClaim] = None + file_system: Optional[TrustClaim] = None + hardware: Optional[TrustClaim] = None + runtime_opaque: Optional[TrustClaim] = None + storage_opaque: Optional[TrustClaim] = None + sourced_data: Optional[TrustClaim] = None + + jc_map = { + "instance_identity": KeyMapping(0, "instance-identity"), + "configuration": KeyMapping(1, "configuration"), + "executables": KeyMapping(2, "executables"), + "file_system": KeyMapping(3, "file-system"), + "hardware": KeyMapping(4, "hardware"), + "runtime_opaque": KeyMapping(5, "runtime-opaque"), + "storage_opaque": KeyMapping(6, "storage-opaque"), + "sourced_data": KeyMapping(7, "sourced-data"), + } + + def validate(self): + # Validates a TrustVector object + + for claim in self.__dict__.values(): + if claim is not None: + claim.validate() diff --git a/src/verifier_id.py b/src/verifier_id.py new file mode 100644 index 0000000..f450f01 --- /dev/null +++ b/src/verifier_id.py @@ -0,0 +1,22 @@ +from dataclasses import dataclass + +from src.base import BaseJCSerializable, KeyMapping +from src.errors import EARValidationError + + +# https://www.ietf.org/archive/id/draft-ietf-rats-ar4si-08.html#section-3.3 +@dataclass +class VerifierID(BaseJCSerializable): + developer: str + build: str + jc_map = { + "developer": KeyMapping(0, "developer"), # JC<"developer", 0> + "build": KeyMapping(1, "build"), # JC<"build", 1> + } + + def validate(self): + # Validates a VerifierID object + if not self.developer or not isinstance(self.developer, str): + raise EARValidationError("VerifierID developer must be a non-empty string") + if not self.build or not isinstance(self.build, str): + raise EARValidationError("VerifierID build must be a non-empty string") diff --git a/tests/test_claims.py b/tests/test_claims.py index 06fac4b..15b6737 100644 --- a/tests/test_claims.py +++ b/tests/test_claims.py @@ -1,13 +1,166 @@ -from src.claims import EARClaims +import json +import pytest -def test_ear_claims(): - claims = EARClaims( - "test_profile", - 1234567890, - {"build": "v1"}, - {"submods1": {"status": "affirming"}}, +from src.claims import AttestationResult +from src.errors import EARValidationError +from src.submod import Submod +from src.trust_claims import ( + APPROVED_CONFIG_CLAIM, + APPROVED_FILES_CLAIM, + APPROVED_RUNTIME_CLAIM, + ENCRYPTED_MEMORY_RUNTIME_CLAIM, + GENUINE_HARDWARE_CLAIM, + HW_KEYS_ENCRYPTED_SECRETS_CLAIM, + TRUSTED_SOURCES_CLAIM, + TRUSTWORTHY_INSTANCE_CLAIM, + TrustClaim, +) +from src.trust_tier import TRUST_TIER_AFFIRMING +from src.trust_vector import TrustVector +from src.verifier_id import VerifierID + + +@pytest.fixture +def sample_attestation_result(): + return AttestationResult( + profile="test_profile", + issued_at=1234567890, + verifier_id=VerifierID(developer="Acme Inc.", build="v1"), + submods={ + "submod1": Submod( + trust_vector=TrustVector( + instance_identity=TrustClaim(2), + configuration=TrustClaim(2), + executables=TrustClaim(2), + file_system=TrustClaim(2), + hardware=TrustClaim(2), + runtime_opaque=TrustClaim(2), + storage_opaque=TrustClaim(2), + sourced_data=TrustClaim(2), + ), + status=TRUST_TIER_AFFIRMING, + ), + }, + ) + + +def test_attestation_result_to_dict(sample_attestation_result): + expected = { + "eat_profile": "test_profile", + "iat": 1234567890, + "ear.verifier-id": {"developer": "Acme Inc.", "build": "v1"}, + "submods": { + "submod1": { + "ear.trustworthiness-vector": { + "instance-identity": TRUSTWORTHY_INSTANCE_CLAIM.value, + "configuration": APPROVED_CONFIG_CLAIM.value, + "executables": APPROVED_RUNTIME_CLAIM.value, + "file-system": APPROVED_FILES_CLAIM.value, + "hardware": GENUINE_HARDWARE_CLAIM.value, + "runtime-opaque": ENCRYPTED_MEMORY_RUNTIME_CLAIM.value, + "storage-opaque": HW_KEYS_ENCRYPTED_SECRETS_CLAIM.value, + "sourced-data": TRUSTED_SOURCES_CLAIM.value, + }, + "ear.status": TRUST_TIER_AFFIRMING.value, + } + }, + } + assert sample_attestation_result.to_dict() == expected + + +def test_attestation_result_to_json(sample_attestation_result): + json_str = sample_attestation_result.to_json() + parsed_claims = AttestationResult.from_json(json_str=json_str) + assert parsed_claims.to_dict() == sample_attestation_result.to_dict() + + +def test_attestation_result_from_dict(): + data = { + "eat_profile": "test_profile", + "iat": 1234567890, + "ear.verifier-id": {"developer": "Acme Inc.", "build": "v1"}, + "submods": { + "submod1": { + "ear.trustworthiness-vector": { + "instance-identity": TRUSTWORTHY_INSTANCE_CLAIM.value, + "configuration": APPROVED_CONFIG_CLAIM.value, + "executables": APPROVED_RUNTIME_CLAIM.value, + "file-system": APPROVED_FILES_CLAIM.value, + "hardware": GENUINE_HARDWARE_CLAIM.value, + "runtime-opaque": ENCRYPTED_MEMORY_RUNTIME_CLAIM.value, + "storage-opaque": HW_KEYS_ENCRYPTED_SECRETS_CLAIM.value, + "sourced-data": TRUSTED_SOURCES_CLAIM.value, + }, + "ear.status": TRUST_TIER_AFFIRMING.value, + } + }, + } + parsed_claims = AttestationResult.from_dict(data) + assert parsed_claims.to_dict() == data + + +def test_attestation_result_to_int_keys(sample_attestation_result): + int_keys_data = sample_attestation_result.to_int_keys() + expected_int_keys = { + 265: "test_profile", + 6: 1234567890, + 1004: {0: "Acme Inc.", 1: "v1"}, + 266: { + "submod1": { + 1001: { + 0: TRUSTWORTHY_INSTANCE_CLAIM.value, + 1: APPROVED_CONFIG_CLAIM.value, + 2: APPROVED_RUNTIME_CLAIM.value, + 3: APPROVED_FILES_CLAIM.value, + 4: GENUINE_HARDWARE_CLAIM.value, + 5: ENCRYPTED_MEMORY_RUNTIME_CLAIM.value, + 6: HW_KEYS_ENCRYPTED_SECRETS_CLAIM.value, + 7: TRUSTED_SOURCES_CLAIM.value, + }, + 1000: TRUST_TIER_AFFIRMING.value, + } + }, + } + assert int_keys_data == expected_int_keys + + +def test_attestation_result_from_int_keys(): + int_keys_data = { + 265: "test_profile", + 6: 1234567890, + 1004: {0: "Acme Inc.", 1: "v1"}, + 266: { + "submod1": { + 1001: { + 0: TRUSTWORTHY_INSTANCE_CLAIM.value, + 1: APPROVED_CONFIG_CLAIM.value, + 2: APPROVED_RUNTIME_CLAIM.value, + 3: APPROVED_FILES_CLAIM.value, + 4: GENUINE_HARDWARE_CLAIM.value, + 5: ENCRYPTED_MEMORY_RUNTIME_CLAIM.value, + 6: HW_KEYS_ENCRYPTED_SECRETS_CLAIM.value, + 7: TRUSTED_SOURCES_CLAIM.value, + }, + 1000: TRUST_TIER_AFFIRMING.value, + } + }, + } + + parsed_claims = AttestationResult.from_int_keys(int_keys_data) + assert json.dumps(parsed_claims.to_int_keys(), sort_keys=True) == json.dumps( + int_keys_data, sort_keys=True ) - json_str = claims.to_json() - parsed_claims = EARClaims.from_json(json_str) - assert parsed_claims.to_dict() == claims.to_dict() + + +def test_validate_ear_claims(sample_attestation_result): + # Should not raise an error + sample_attestation_result.validate() + + +def test_validate_ear_claims_invalid(): + with pytest.raises(EARValidationError): + invalid_attestation_result = AttestationResult( + profile="", issued_at=-1, verifier_id=VerifierID(developer="", build="") + ) + invalid_attestation_result.validate() diff --git a/tests/test_trust_claims.py b/tests/test_trust_claims.py new file mode 100644 index 0000000..1c477b7 --- /dev/null +++ b/tests/test_trust_claims.py @@ -0,0 +1,31 @@ +import pytest + +from src.errors import EARValidationError +from src.trust_claims import TRUSTWORTHY_INSTANCE_CLAIM, TrustClaim + + +@pytest.fixture +def trust_claim(): + # Sample TrustClaim object for testing + return TRUSTWORTHY_INSTANCE_CLAIM + + +def test_to_dict(trust_claim): + expected = { + "value": 2, + "tag": "recognized_instance", + "short": "recognized and not compromised", + "long": "The Attesting Environment is recognized, and the associated instance of the Attester is not known to be compromised.", # noqa: E501 # pylint: disable=line-too-long + } + assert trust_claim.to_dict() == expected + + +def test_validate_trust_claim_valid(trust_claim): + # Should not raise an error + trust_claim.validate() + + +def test_validate_trust_claim_invalid(): + with pytest.raises(EARValidationError): + invalid_trust_claim = TrustClaim(value=200, tag="invalid", short="", long="") + invalid_trust_claim.validate() diff --git a/tests/test_trust_tier.py b/tests/test_trust_tier.py new file mode 100644 index 0000000..69287e3 --- /dev/null +++ b/tests/test_trust_tier.py @@ -0,0 +1,39 @@ +import pytest + +from src.trust_tier import ( + TRUST_TIER_AFFIRMING, + TRUST_TIER_CONTRAINDICATED, + TRUST_TIER_NONE, + TRUST_TIER_WARNING, + to_trust_tier, +) + + +def test_to_trust_tier_valid_int(): + assert to_trust_tier(0) == TRUST_TIER_NONE + assert to_trust_tier(2) == TRUST_TIER_AFFIRMING + assert to_trust_tier(32) == TRUST_TIER_WARNING + assert to_trust_tier(96) == TRUST_TIER_CONTRAINDICATED + + +def test_to_trust_tier_valid_str(): + assert to_trust_tier("none") == TRUST_TIER_NONE + assert to_trust_tier("affirming") == TRUST_TIER_AFFIRMING + assert to_trust_tier("warning") == TRUST_TIER_WARNING + assert to_trust_tier("contraindicated") == TRUST_TIER_CONTRAINDICATED + + +def test_to_trust_tier_invalid_int(): + assert to_trust_tier(100) == TRUST_TIER_NONE # Default fallback + + +def test_to_trust_tier_invalid_str(): + assert to_trust_tier("invalid_string") == TRUST_TIER_NONE # Default fallback + + +def test_to_trust_tier_invalid_type(): + with pytest.raises(ValueError): + to_trust_tier([1, 2, 3]) + + with pytest.raises(ValueError): + to_trust_tier({"tier": "affirming"}) diff --git a/tests/test_trust_vector.py b/tests/test_trust_vector.py new file mode 100644 index 0000000..890a261 --- /dev/null +++ b/tests/test_trust_vector.py @@ -0,0 +1,110 @@ +import json + +import pytest + +from src.errors import EARValidationError +from src.trust_claims import ( + APPROVED_FILES_CLAIM, + APPROVED_RUNTIME_CLAIM, + ENCRYPTED_MEMORY_RUNTIME_CLAIM, + GENUINE_HARDWARE_CLAIM, + HW_KEYS_ENCRYPTED_SECRETS_CLAIM, + TRUSTED_SOURCES_CLAIM, + TRUSTWORTHY_INSTANCE_CLAIM, + UNSAFE_CONFIG_CLAIM, + TrustClaim, +) +from src.trust_vector import TrustVector + + +@pytest.fixture +def sample_trust_vector(): + return TrustVector( + instance_identity=TRUSTWORTHY_INSTANCE_CLAIM, + configuration=UNSAFE_CONFIG_CLAIM, + executables=APPROVED_RUNTIME_CLAIM, + file_system=APPROVED_FILES_CLAIM, + hardware=GENUINE_HARDWARE_CLAIM, + runtime_opaque=ENCRYPTED_MEMORY_RUNTIME_CLAIM, + storage_opaque=HW_KEYS_ENCRYPTED_SECRETS_CLAIM, + sourced_data=TRUSTED_SOURCES_CLAIM, + ) + + +def test_trust_vector_to_dict(sample_trust_vector): + expected = { + "instance-identity": TRUSTWORTHY_INSTANCE_CLAIM.value, + "configuration": UNSAFE_CONFIG_CLAIM.value, + "executables": APPROVED_RUNTIME_CLAIM.value, + "file-system": APPROVED_FILES_CLAIM.value, + "hardware": GENUINE_HARDWARE_CLAIM.value, + "runtime-opaque": ENCRYPTED_MEMORY_RUNTIME_CLAIM.value, + "storage-opaque": HW_KEYS_ENCRYPTED_SECRETS_CLAIM.value, + "sourced-data": TRUSTED_SOURCES_CLAIM.value, + } + assert sample_trust_vector.to_dict() == expected + + +def test_trust_vector_to_json(sample_trust_vector): + json_str = sample_trust_vector.to_json() + parsed_vector = TrustVector.from_dict(json.loads(json_str)) + assert parsed_vector.to_dict() == sample_trust_vector.to_dict() + + +def test_trust_vector_to_int_keys(sample_trust_vector): + expected = { + 0: TRUSTWORTHY_INSTANCE_CLAIM.value, + 1: UNSAFE_CONFIG_CLAIM.value, + 2: APPROVED_RUNTIME_CLAIM.value, + 3: APPROVED_FILES_CLAIM.value, + 4: GENUINE_HARDWARE_CLAIM.value, + 5: ENCRYPTED_MEMORY_RUNTIME_CLAIM.value, + 6: HW_KEYS_ENCRYPTED_SECRETS_CLAIM.value, + 7: TRUSTED_SOURCES_CLAIM.value, + } + assert sample_trust_vector.to_int_keys() == expected + + +def test_trust_vector_from_dict(): + data = { + "instance-identity": TRUSTWORTHY_INSTANCE_CLAIM.value, + "configuration": UNSAFE_CONFIG_CLAIM.value, + "executables": APPROVED_RUNTIME_CLAIM.value, + "file-system": APPROVED_FILES_CLAIM.value, + "hardware": GENUINE_HARDWARE_CLAIM.value, + "runtime-opaque": ENCRYPTED_MEMORY_RUNTIME_CLAIM.value, + "storage-opaque": HW_KEYS_ENCRYPTED_SECRETS_CLAIM.value, + "sourced-data": TRUSTED_SOURCES_CLAIM.value, + } + parsed_vector = TrustVector.from_dict(data) + assert parsed_vector.to_dict() == data + + +def test_trust_vector_from_int_keys(): + int_keys_data = { + 0: TRUSTWORTHY_INSTANCE_CLAIM.to_dict(), + 1: UNSAFE_CONFIG_CLAIM.to_dict(), + 2: APPROVED_RUNTIME_CLAIM.to_dict(), + 3: APPROVED_FILES_CLAIM.to_dict(), + 4: GENUINE_HARDWARE_CLAIM.to_dict(), + 5: ENCRYPTED_MEMORY_RUNTIME_CLAIM.to_dict(), + 6: HW_KEYS_ENCRYPTED_SECRETS_CLAIM.to_dict(), + 7: TRUSTED_SOURCES_CLAIM.to_dict(), + } + parsed_vector = TrustVector.from_int_keys(int_keys_data) + assert ( + parsed_vector.to_dict() == TrustVector.from_int_keys(int_keys_data).to_dict() + ) # noqa: E501 + + +def test_validate_trust_vector(sample_trust_vector): + # Should not raise an error + sample_trust_vector.validate() + + +def test_validate_trust_vector_invalid(): + with pytest.raises(EARValidationError): + invalid_vector = TrustVector( + configuration=TrustClaim(value=200, tag="invalid", short="", long="") + ) + invalid_vector.validate() diff --git a/tests/test_verifier_id.py b/tests/test_verifier_id.py new file mode 100644 index 0000000..5476203 --- /dev/null +++ b/tests/test_verifier_id.py @@ -0,0 +1,52 @@ +import json + +import pytest + +from src.errors import EARValidationError +from src.verifier_id import VerifierID + + +@pytest.fixture +def verifier(): + # Sample VerifierID object for testing + return VerifierID(developer="Acme Inc.", build="v1.0.0") + + +def test_to_dict(verifier): # pylint: disable=redefined-outer-name + expected = {"developer": "Acme Inc.", "build": "v1.0.0"} + assert verifier.to_dict() == expected + + +def test_to_json(verifier): # pylint: disable=redefined-outer-name + expected = json.dumps({"developer": "Acme Inc.", "build": "v1.0.0"}) + assert verifier.to_json() == expected + + +def test_to_int_keys(verifier): # pylint: disable=redefined-outer-name + expected = {0: "Acme Inc.", 1: "v1.0.0"} + assert verifier.to_int_keys() == expected + + +def test_from_dict(): + data = {"developer": "Acme Inc.", "build": "v1.0.0"} + sample_verifier = VerifierID.from_dict(data) + assert sample_verifier.developer == "Acme Inc." + assert sample_verifier.build == "v1.0.0" + + +def test_from_int_keys(): + int_keys_data = {0: "Acme Inc.", 1: "v1.0.0"} + sample_verifier = VerifierID.from_int_keys(int_keys_data) + assert sample_verifier.developer == "Acme Inc." + assert sample_verifier.build == "v1.0.0" + + +def test_validate_verifier_id(verifier): + # Should not raise an error + verifier.validate() + + +def test_validate_verifier_id_invalid(): + with pytest.raises(EARValidationError): + invalid_verifier_id = VerifierID(developer="", build="") # Invalid empty fields + invalid_verifier_id.validate() diff --git a/tox.ini b/tox.ini index 2a75fe9..4f4f283 100644 --- a/tox.ini +++ b/tox.ini @@ -9,8 +9,10 @@ deps = mypy==1.5.1 pylint==2.17.5 pyright==1.1.325 + pytest==7.4.2 + python-jose==3.4.0 commands = - isort . --check --diff + isort . --profile=black black . --check --diff flake8 . mypy . @@ -20,4 +22,5 @@ commands = [testenv:test] deps = pytest==7.4.2 + python-jose==3.4.0 commands = pytest