From 78d80001f11d4ea7945bb4a48d633630f2d2bd90 Mon Sep 17 00:00:00 2001 From: WillJiang1 Date: Thu, 23 Jan 2025 16:36:12 +0000 Subject: [PATCH 1/2] Add tee plugin --- plugins/tee/README.md | 42 +++++++++ plugins/tee/pyproject.toml | 36 ++++++++ plugins/tee/tee_plugin_gamesdk/tee_plugin.py | 93 ++++++++++++++++++++ plugins/tee/test_tee.py | 13 +++ 4 files changed, 184 insertions(+) create mode 100644 plugins/tee/README.md create mode 100644 plugins/tee/pyproject.toml create mode 100644 plugins/tee/tee_plugin_gamesdk/tee_plugin.py create mode 100644 plugins/tee/test_tee.py diff --git a/plugins/tee/README.md b/plugins/tee/README.md new file mode 100644 index 00000000..8ceb6986 --- /dev/null +++ b/plugins/tee/README.md @@ -0,0 +1,42 @@ +# TEE Plugin for GAME SDK + +The TEE Plugin is a plugin designed to obtain an attestation report in a Trusted Execution Environment (TEE). + +An attestation report is a document generated by a Trusted Execution Environment (TEE) that serves as cryptographic proof of the environment's integrity and trustworthiness. It is primarily used to assure external parties that: + +- The TEE environment is secure: It proves that the execution environment is isolated from other processes and protected from unauthorized access or tampering. + +- The code running inside the TEE is legitimate: It verifies that the code or application executed inside the TEE has not been altered and is authentic. + +- The environment has not been compromised: It includes evidence that the hardware and software configurations are intact and match a known, trusted state. + + +## Installation +From this directory (`tee`), run the installation: +```bash +pip install -e . +``` + +## Usage +This TEE plugin currently supports retrieving attestation reports exclusively from [Google Confidential Space](https://cloud.google.com/docs/security/confidential-space). It is actively under development, and support for attestation reports from AMD SEV-SNP Confidential VMs will be released soon. + +1. You should deploy the AI Agent on Google Confidential Space to safeguard sensitive information, such as wallet secrets. +2. Use this plugin to generate an attestation report for Google Confidential Space, demonstrating that the agent is enhanced by TEE and operating in a secure environment. The attestation report also includes the agent's Docker image to verify that it matches the expected configuration. +3. Import and initialize the plugin to use in your worker: +```python +from tee_plugin_gamesdk.tee_plugin import TeePlugin +options = { + "id": "test_tee_worker", + "name": "Test TEE Worker", + "description": "An example TEE Plugin for testing.", + "type": "GCS" +} +# Initialize the TeePlugin with your options +tee_plugin = TeePlugin(options) + +# Generate Attestation report +get_attestation_report_fn = tee_plugin.get_function('get_attestation_report') +get_attestation_report_fn("Hello world!") # The input is a nonce releated to the report +``` + +You can refer to `test_tee.py` for more examples on how to call the twitter functions. diff --git a/plugins/tee/pyproject.toml b/plugins/tee/pyproject.toml new file mode 100644 index 00000000..aea01eb8 --- /dev/null +++ b/plugins/tee/pyproject.toml @@ -0,0 +1,36 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "tee_plugin_gamesdk" +version = "0.1.0" +authors = [ + { name = "Will Jiang", email = "jianliiin96@gmail.com" }, +] +description = "TEE Plugin for Python SDK for GAME by Virtuals" +requires-python = ">=3.8" +classifiers = [ + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "License :: OSI Approved :: MIT License", + "Operating System :: OS Independent", + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "Topic :: Software Development :: Libraries :: Python Modules", +] +dependencies = [ + "requests>=2.31.0", + "requests_unixsocket2>=0.4.2", + "pyjwt>=2.10" +] + +[tool.hatch.build.targets.wheel] +packages = ["tee_plugin_gamesdk"] + +[project.urls] +"Homepage" = "https://github.com/game-by-virtuals/game-python" +"Bug Tracker" = "https://github.com/game-by-virtuals/game-python" \ No newline at end of file diff --git a/plugins/tee/tee_plugin_gamesdk/tee_plugin.py b/plugins/tee/tee_plugin_gamesdk/tee_plugin.py new file mode 100644 index 00000000..7a42c3bd --- /dev/null +++ b/plugins/tee/tee_plugin_gamesdk/tee_plugin.py @@ -0,0 +1,93 @@ +import json +import requests_unixsocket +from requests import HTTPError +import hashlib +import jwt +import logging +from typing import Dict, Callable, Any, Optional, List, Callable + +Audience = "http://aizel.com" + +class CustomToken: + def __init__(self, audience, nonce, token_type="OIDC"): + self.audience = audience + self.nonces = [nonce] + self.token_type = token_type + +class GcpConfidentialSpace: + def __init__(self, audience: str): + self.audience = audience + + def attestation_report(self, nonce: str) -> str: + try: + hashed_nonce = hashlib.sha256(nonce.encode('utf-8')).hexdigest() + request = CustomToken(self.audience, hashed_nonce) + session = requests_unixsocket.Session() + url = 'http+unix://%2Frun%2Fcontainer_launcher%2Fteeserver.sock/v1/token' + headers = {'Content-Type': 'application/json'} + custom_json = json.dumps(request.__dict__) + response = session.post(url, headers=headers, data=custom_json) + response.raise_for_status() + return response.content.decode('utf-8') + except Exception as err: + raise RuntimeError(f"{err}") + + +class TeePlugin: + def __init__(self, options: Dict[str, Any]) -> None: + self.id: str = options.get("id", "tee_plugin") + self.name: str = options.get("name", "TEE Plugin") + self.description: str = options.get( + "description", + "A plugin that obtains the attestation report in the Trusted Execution Environment.", + ) + # tee plugin type, current only support Google Confidential Space + self.type: str = options.get("tee_type", "GCS") + + # Define internal function mappings + self._functions: Dict[str, Callable[..., Any]] = { + "get_attestation_report": self._get_attestation_report, + } + + # Configure logging + logging.basicConfig(level=logging.INFO) + self.logger: logging.Logger = logging.getLogger(__name__) + + def get_function(self, fn_name: str) -> Callable: + """ + Get a specific function by name. + + Args: + fn_name: Name of the function to retrieve + + Raises: + ValueError: If function name is not found + + Returns: + Function object + """ + if fn_name not in self._functions: + raise ValueError( + f"Function '{fn_name}' not found. Available functions: {', '.join(self.available_functions)}" + ) + return self._functions[fn_name] + + def _get_attestation_report(self, nonce: str) -> str: + if self.type == "GCS": + try: + gcp = GcpConfidentialSpace(Audience) + gcp.attestation_report(nonce) + except RuntimeError as e: + self.logger.error(f"Failed to get attestation report for Google confidential space: {e}") + return "" + else: + raise ValueError( + f"Unsupport tee backend type '{self.type}'. Available type: GCS" + ) + +def decode_gcp_attestation_report(report: str) -> dict: + try: + decoded_report = jwt.decode(report, options={"verify_signature": False}) + return decoded_report + except jwt.InvalidTokenError: + raise ValueError("Invalid token") \ No newline at end of file diff --git a/plugins/tee/test_tee.py b/plugins/tee/test_tee.py new file mode 100644 index 00000000..db24eea0 --- /dev/null +++ b/plugins/tee/test_tee.py @@ -0,0 +1,13 @@ +from tee_plugin_gamesdk.tee_plugin import TeePlugin +options = { + "id": "test_tee_worker", + "name": "Test TEE Worker", + "description": "An example TEE Plugin for testing.", + "type": "GCS" +} +# Initialize the TeePlugin with your options +tee_plugin = TeePlugin(options) + +# Generate Attestation report +get_attestation_report_fn = tee_plugin.get_function('get_attestation_report') +get_attestation_report_fn("Hello world!") \ No newline at end of file From aad42959ecfee980b100a96ec7adda298f8b8e41 Mon Sep 17 00:00:00 2001 From: WillJiang1 Date: Wed, 16 Apr 2025 14:22:31 +0000 Subject: [PATCH 2/2] add plugin meta data --- plugins/tee/plugin_metadata.yml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 plugins/tee/plugin_metadata.yml diff --git a/plugins/tee/plugin_metadata.yml b/plugins/tee/plugin_metadata.yml new file mode 100644 index 00000000..8db4eae2 --- /dev/null +++ b/plugins/tee/plugin_metadata.yml @@ -0,0 +1,14 @@ +# General Information +plugin_name: "tee_plugin_gamesdk" +author: "Will Jiang" +logo_url: "https://pbs.twimg.com/profile_images/1883754196991942657/BoC1g-Cj_400x400.jpg" +release_date: "2025-04" + +# Description +short_description: "TEE (trusted execution environment) Plugin for GAME SDK" +detailed_description: "The TEE Plugin is a plugin designed to obtain an attestation report in a Trusted Execution Environment (TEE). An attestation report is a document generated by a Trusted Execution Environment (TEE) that serves as cryptographic proof of the environment's integrity and trustworthiness." + +# Contact & Support +x_account_handle: "@aizel_network" +support_contact: "contact@aizelnetwork.com" +community_link: "https://linktr.ee/AizelNetwork"