|
| 1 | +""" |
| 2 | +Client for communicating with the Confidential Space vTPM attestation service. |
| 3 | +
|
| 4 | +This module provides a client to request attestation tokens from a local Unix domain |
| 5 | +socket endpoint. It extends HTTPConnection to handle Unix socket communication and |
| 6 | +implements token request functionality with nonce validation. |
| 7 | +
|
| 8 | +Classes: |
| 9 | + VtpmAttestationError: Exception for attestation service communication errors |
| 10 | + VtpmAttestation: Client for requesting attestation tokens |
| 11 | +""" |
| 12 | + |
| 13 | +import json |
| 14 | +import socket |
| 15 | +from http.client import HTTPConnection |
| 16 | +from pathlib import Path |
| 17 | + |
| 18 | +import structlog |
| 19 | + |
| 20 | +logger = structlog.get_logger(__name__) |
| 21 | + |
| 22 | + |
| 23 | +def get_simulated_token() -> str: |
| 24 | + """Reads the first line from a given file path.""" |
| 25 | + with (Path(__file__).parent / "simulated_token.txt").open("r") as f: |
| 26 | + return f.readline().strip() |
| 27 | + |
| 28 | + |
| 29 | +SIM_TOKEN = get_simulated_token() |
| 30 | + |
| 31 | + |
| 32 | +class VtpmAttestationError(Exception): |
| 33 | + """ |
| 34 | + Exception raised for attestation service communication errors. |
| 35 | +
|
| 36 | + This includes invalid nonce values, connection failures, and |
| 37 | + unexpected responses from the attestation service. |
| 38 | + """ |
| 39 | + |
| 40 | + |
| 41 | +class Vtpm: |
| 42 | + """ |
| 43 | + Client for requesting attestation tokens via Unix domain socket.""" |
| 44 | + |
| 45 | + def __init__( |
| 46 | + self, |
| 47 | + url: str = "http://localhost/v1/token", |
| 48 | + unix_socket_path: str = "/run/container_launcher/teeserver.sock", |
| 49 | + simulate: bool = False, # noqa: FBT001, FBT002 |
| 50 | + ) -> None: |
| 51 | + self.url = url |
| 52 | + self.unix_socket_path = unix_socket_path |
| 53 | + self.simulate = simulate |
| 54 | + self.attestation_requested: bool = False |
| 55 | + self.logger = logger.bind(router="vtpm") |
| 56 | + self.logger.debug( |
| 57 | + "vtpm", simulate=simulate, url=url, unix_socket_path=self.unix_socket_path |
| 58 | + ) |
| 59 | + |
| 60 | + def _check_nonce_length(self, nonces: list[str]) -> None: |
| 61 | + """ |
| 62 | + Validate the byte length of provided nonces. |
| 63 | +
|
| 64 | + Each nonce must be between 10 and 74 bytes when UTF-8 encoded. |
| 65 | +
|
| 66 | + Args: |
| 67 | + nonces: List of nonce strings to validate |
| 68 | +
|
| 69 | + Raises: |
| 70 | + VtpmAttestationError: If any nonce is outside the valid length range |
| 71 | + """ |
| 72 | + min_byte_len = 10 |
| 73 | + max_byte_len = 74 |
| 74 | + for nonce in nonces: |
| 75 | + byte_len = len(nonce.encode("utf-8")) |
| 76 | + self.logger.debug("nonce_length", byte_len=byte_len) |
| 77 | + if byte_len < min_byte_len or byte_len > max_byte_len: |
| 78 | + msg = f"Nonce '{nonce}' must be between {min_byte_len} bytes" |
| 79 | + f" and {max_byte_len} bytes" |
| 80 | + raise VtpmAttestationError(msg) |
| 81 | + |
| 82 | + def get_token( |
| 83 | + self, |
| 84 | + nonces: list[str], |
| 85 | + audience: str = "https://sts.google.com", |
| 86 | + token_type: str = "OIDC", # noqa: S107 |
| 87 | + ) -> str: |
| 88 | + """ |
| 89 | + Request an attestation token from the service. |
| 90 | +
|
| 91 | + Requests a token with specified nonces for replay protection, |
| 92 | + targeted at the specified audience. Supports both OIDC and PKI |
| 93 | + token types. |
| 94 | +
|
| 95 | + Args: |
| 96 | + nonces: List of random nonce strings for replay protection |
| 97 | + audience: Intended audience for the token (default: "https://sts.google.com") |
| 98 | + token_type: Type of token, either "OIDC" or "PKI" (default: "OIDC") |
| 99 | +
|
| 100 | + Returns: |
| 101 | + str: The attestation token in JWT format |
| 102 | +
|
| 103 | + Raises: |
| 104 | + VtpmAttestationError: If token request fails for any reason |
| 105 | + (invalid nonces, service unavailable, etc.) |
| 106 | +
|
| 107 | + Example: |
| 108 | + client = VtpmAttestation() |
| 109 | + token = client.get_token( |
| 110 | + nonces=["random_nonce"], |
| 111 | + audience="https://my-service.example.com", |
| 112 | + token_type="OIDC" |
| 113 | + ) |
| 114 | + """ |
| 115 | + self._check_nonce_length(nonces) |
| 116 | + if self.simulate: |
| 117 | + self.logger.debug("sim_token", token=SIM_TOKEN) |
| 118 | + return SIM_TOKEN |
| 119 | + |
| 120 | + # Connect to the socket |
| 121 | + client_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 122 | + client_socket.connect(self.unix_socket_path) |
| 123 | + |
| 124 | + # Create an HTTP connection object |
| 125 | + conn = HTTPConnection("localhost", timeout=10) |
| 126 | + conn.sock = client_socket |
| 127 | + |
| 128 | + # Send a POST request |
| 129 | + headers = {"Content-Type": "application/json"} |
| 130 | + body = json.dumps( |
| 131 | + {"audience": audience, "token_type": token_type, "nonces": nonces} |
| 132 | + ) |
| 133 | + conn.request("POST", self.url, body=body, headers=headers) |
| 134 | + |
| 135 | + # Get and decode the response |
| 136 | + res = conn.getresponse() |
| 137 | + success_status = 200 |
| 138 | + if res.status != success_status: |
| 139 | + msg = f"Failed to get attestation response: {res.status} {res.reason}" |
| 140 | + raise VtpmAttestationError(msg) |
| 141 | + token = res.read().decode() |
| 142 | + self.logger.debug("token", token_type=token_type, token=token) |
| 143 | + |
| 144 | + # Close the connection |
| 145 | + conn.close() |
| 146 | + return token |
0 commit comments