Debian Codegraph @

launcher/image/testworkloads/keymanager/workload.py

raw
1 import requests
2 import requests_unixsocket
3 import json
4 import base64
5 from urllib.parse import quote
6
7 # Configure the session to use the UDS adapter
8 session = requests_unixsocket.Session()
9
10 # Define the socket path
11 # Note: requests_unixsocket requires URL-encoding the path slashes
12 # The KMS and AS are mounted at /run/container_launcher in the workload VM.
13 kms_socket_path = "/run/container_launcher/kmaserver.sock"
14 kms_encoded_path = quote(kms_socket_path, safe='')
15 kms_base_url = f"http+unix://{kms_encoded_path}"
16 as_socket_path = "/run/container_launcher/teeserver.sock"
17 as_encoded_path = quote(as_socket_path, safe='')
18 as_base_url = f"http+unix://{as_encoded_path}"
19
20 def get_capabilities():
21 """Check supported algorithms."""
22 resp = session.get(f"{kms_base_url}/v1/capabilities")
23 resp.raise_for_status()
24 print("Capabilities:", json.dumps(resp.json(), indent=2))
25
26 def generate_key():
27 """Generate a new KEM key."""
28 payload = {
29 "algorithm": {
30 "type": "kem",
31 "params": {
32 "kem_id": "DHKEM_X25519_HKDF_SHA256",
33 }
34 },
35 "lifespan": 3600
36 }
37 resp = session.post(f"{kms_base_url}/v1/keys:generate_key", json=payload)
38 resp.raise_for_status()
39 key_handle = resp.json()["key_handle"]
40 print(f"Generated Key: {key_handle['handle']}")
41 return key_handle
42
43 def get_key_endorsement(challenge, key_handle):
44 """Generates a fresh key endorsement."""
45 challange_base64 = base64.b64encode(challenge).decode('utf-8')
46 payload = {
47 "challenge": challange_base64,
48 "key_handle": key_handle
49 }
50 resp = session.post(f"{as_base_url}/v1/keys:getEndorsement", json=payload)
51 print(f"resp: {resp}")
52 resp.raise_for_status()
53 return resp.json()
54
55
56 def decapsulate_secret(key_handle, encapsulated_key):
57 """Simulate decapsulation."""
58 # In a real scenario, 'encapsulated_key' is the result of a DHKEM
59 # encapsulation operation against the KPS public key, typically
60 # received from the trusted proxy.
61
62 encoded_encap_key = base64.b64encode(encapsulated_key).decode('utf-8')
63
64 payload = {
65 "key_handle": key_handle,
66 "ciphertext": {
67 "algorithm": "DHKEM_X25519_HKDF_SHA256",
68 "ciphertext": encoded_encap_key
69 }
70 }
71
72 resp = session.post(f"{kms_base_url}/v1/keys:decap", json=payload)
73 resp.raise_for_status()
74
75 secret_b64 = resp.json()["shared_secret"]["secret"]
76 secret = base64.b64decode(secret_b64)
77 print(f"Decapsulated Secret (hex): {secret.hex()}")
78
79 def destroy_key(key_handle):
80 """Cleanup the key."""
81 payload = {"key_handle": key_handle}
82 resp = session.post(f"{kms_base_url}/v1/keys:destroy", json=payload)
83 resp.raise_for_status()
84 print(f"Key {key_handle['handle']} destroyed successfully.")
85
86 if __name__ == "__main__":
87 try:
88 print("--- 1. Checking Capabilities ---")
89 get_capabilities()
90 print("\n--- 2. Generating Key ---")
91 handle = generate_key()
92 # Simulate some encapsulated key (32 bytes for X25519)
93 dummy_ciphertext = b'\x00' * 32
94 print("\n--- 3. Generating Key Endorsement ---")
95 challenge = b'\x00' * 32
96
97 print(get_key_endorsement(challenge, handle))
98 print("\n--- 4. Decapsulating ---")
99 decapsulate_secret(handle, dummy_ciphertext.decode('utf-8'))
100 print("\n--- 5. Destroying Key ---")
101 destroy_key(handle)
102
103 except requests.exceptions.ConnectionError:
104 print(f"Error: Could not connect to socket at {kms_socket_path}.")
105 print("Ensure the Workload Services Daemon is running.")
106 except Exception as e:
107 print(f"An error occurred: {e}")