Documentation Banner

Documentation

Security Best Practices

Key Management

  • Keys are generated and sealed within the hardware enclave
  • Never expose private keys outside the TEE
  • Use hardware-based attestation for trust verification
  • $AIUS transactions are signed within the enclave

Secure Key Generation Example

1// This happens inside the TEE - keys never leave
2async function generateSecureKeys() {
3 // Hardware RNG generates entropy
4 const entropy = await TEE.getRandomBytes(32);
5
6 // Generate keypair in enclave
7 const keypair = secp256k1.generateKeypair(entropy);
8
9 // Seal private key to hardware
10 const sealed = await TEE.seal(keypair.privateKey);
11
12 // Only public key and address are exposed
13 return {
14 address: keypair.address,
15 publicKey: keypair.publicKey,
16 // privateKey stays in TEE forever
17 };
18}

TEE Attestation Verification

Before trusting an agent, always verify its attestation to ensure it’s running in a genuine hardware TEE. The attestation process provides cryptographic proof that the code is running unmodified in a secure enclave.

1// Verify agent attestation before interaction
2async function verifyAgentAttestation(agentPublicKey: string) {
3 // Request attestation quote from agent
4 const quote = await agent.getAttestationQuote();
5
6 // Verify with platform attestation service
7 const verification = await attestationService.verify({
8 quote: quote,
9 publicKey: agentPublicKey,
10 expectedMeasurement: TRUSTED_CODE_HASH
11 });
12
13 if (!verification.isValid) {
14 throw new Error('Agent attestation failed');
15 }
16
17 // Check platform type (Intel SGX, AMD SEV, etc)
18 console.log('Platform:', verification.platform);
19 console.log('Security version:', verification.securityVersion);
20
21 return verification;
22}

Secure Transaction Signing

All blockchain transactions (including $AIUS transfers) must be signed within the TEE. This ensures the private key never leaves the secure enclave, even during transaction creation.

1// Sign $AIUS transaction inside TEE
2async function signTransaction(recipient: string, amount: bigint) {
3 // Transaction created in TEE
4 const tx = {
5 to: recipient,
6 value: amount,
7 nonce: await getNonce(),
8 chainId: 42161, // Arbitrum One
9 gasLimit: 21000n,
10 maxFeePerGas: await getGasPrice()
11 };
12
13 // Private key never leaves TEE
14 const signedTx = await TEE.signTransaction(tx);
15
16 // Only signed transaction leaves enclave
17 return signedTx;
18}
19
20// Verify transaction before broadcasting
21async function safeSendTransaction(recipient: string, amount: bigint) {
22 // User approval check (outside TEE)
23 if (!await userApproval(recipient, amount)) {
24 throw new Error('Transaction not approved');
25 }
26
27 // Sign in TEE
28 const signed = await signTransaction(recipient, amount);
29
30 // Broadcast
31 const txHash = await provider.sendTransaction(signed);
32 return txHash;
33}

Network Security

All P2P communication is encrypted end-to-end using noise protocol framework with X25519 key exchange. Agent identities are tied to their attestation, preventing impersonation attacks.

Transport Encryption
All messages use ChaCha20-Poly1305 authenticated encryption with perfect forward secrecy
Identity Binding
Agent public keys are bound to their attestation quotes, verified on first connection
DHT Security
Distributed hash table entries are signed, preventing unauthorized modifications

Marketplace Safety

When using the agent marketplace (Arbius, EACC), verify both the compute provider and the task results.

1// Safe marketplace interaction
2async function requestCompute(task: ComputeTask) {
3 // Find providers with valid attestation
4 const providers = await marketplace.findProviders({
5 minReputation: 0.8,
6 requireAttestation: true,
7 platform: ['sgx', 'sev']
8 });
9
10 // Submit task with result verification
11 const result = await marketplace.submitTask({
12 task: task,
13 provider: providers[0],
14 verifyAttestation: true,
15 requireSignature: true,
16 timeout: 300000 // 5 min
17 });
18
19 // Verify result signature matches provider attestation
20 if (!await verifyResultSignature(result, providers[0])) {
21 throw new Error('Result verification failed');
22 }
23
24 return result;
25}

Secure Configuration

Agent configuration should be validated and sensitive settings should be encrypted at rest.

1// Example secure configuration
2{
3 "tee": {
4 "platform": "sgx",
5 "attestation": {
6 "provider": "intel-dcap",
7 "minimumSecurityVersion": 2,
8 "allowDebugMode": false // NEVER enable in production
9 }
10 },
11 "keys": {
12 "autoGenerate": true,
13 "sealToDisk": true, // Encrypted with platform key
14 "backupEnabled": false // Keys cannot be exported
15 },
16 "network": {
17 "encryption": "noise-xx",
18 "requireAttestation": true,
19 "trustedPeers": [], // Empty = trust on first use
20 "denylist": []
21 },
22 "marketplace": {
23 "maxTaskValue": "1000000000000000000", // 1 $AIUS max per task
24 "requireProviderAttestation": true,
25 "minProviderReputation": 0.7
26 }
27}

Port Security and Firewall Configuration

Proper port management and firewall configuration are critical for securing your agent deployment. Expose only the minimum required ports and implement strict firewall rules.

Required Ports
PortProtocolPurpose
9100TCPP2P agent networking (LibP2P)
8080TCPWebSocket bridge (local only)
443TCPHTTPS for attestation verification
*UDPQUIC transport (optional)
Firewall Rules Example
1# UFW (Ubuntu) firewall configuration
2# Allow P2P networking from specific peers
3sudo ufw allow from 192.168.1.0/24 to any port 9100
4
5# NEVER expose bridge to public internet
6sudo ufw deny 8080
7
8# Allow attestation service communication
9sudo ufw allow out 443/tcp
10
11# Enable firewall
12sudo ufw enable
13
14# iptables alternative
15iptables -A INPUT -p tcp --dport 9100 -s 192.168.1.0/24 -j ACCEPT
16iptables -A INPUT -p tcp --dport 8080 -s 127.0.0.1 -j ACCEPT
17iptables -A INPUT -p tcp --dport 8080 -j DROP
Docker Port Binding
1# Secure Docker port configuration
2docker run -d \
3 --name catgirl-agent \
4 -p 127.0.0.1:8080:8080 \ # Bridge: local only
5 -p 9100:9100 \ # P2P: exposed to network
6 --security-opt no-new-privileges \
7 catgirl/agent:latest

Private Key Protection

Private keys are the most critical security component. They must never leave the TEE and should be protected at multiple layers using hardware sealing and access controls.

❌ Never Do This
  • • Export private keys to disk or environment variables
  • • Log private keys or mnemonic phrases
  • • Send keys over network (even encrypted)
  • • Store keys in configuration files or databases
  • • Share keys between multiple agents
  • • Use the same key for different purposes (signing + encryption)
✓ Best Practices
  • • Generate keys inside TEE using hardware RNG
  • • Seal keys to specific hardware using platform binding
  • • Implement key rotation policies (monthly or quarterly)
  • • Use separate keys for different operations
  • • Require attestation before allowing key operations
  • • Implement rate limiting on signing operations
Key Lifecycle Management
1// Proper key lifecycle with hardware sealing
2class SecureKeyManager {
3 async initialize() {
4 // Check if keys exist
5 const hasKeys = await TEE.hasSealedKeys();
6
7 if (!hasKeys) {
8 // Generate new keys in TEE
9 await this.generateKeys();
10 } else {
11 // Unseal existing keys
12 await this.unsealKeys();
13 }
14
15 // Verify key integrity
16 await this.verifyKeyIntegrity();
17 }
18
19 async generateKeys() {
20 // Hardware RNG for entropy
21 const entropy = await TEE.getRandomBytes(32);
22
23 // Generate signing key
24 const signingKey = await TEE.generateSecp256k1Key(entropy);
25
26 // Generate encryption key (separate)
27 const encryptionKey = await TEE.generateX25519Key();
28
29 // Seal both keys to hardware
30 await TEE.seal('signing_key', signingKey);
31 await TEE.seal('encryption_key', encryptionKey);
32
33 // Store metadata (NOT the keys)
34 await this.storeKeyMetadata({
35 signingAddress: signingKey.address,
36 encryptionPublicKey: encryptionKey.publicKey,
37 createdAt: Date.now(),
38 rotationDue: Date.now() + 90 * 24 * 60 * 60 * 1000 // 90 days
39 });
40 }
41
42 async rotateKeys() {
43 // Generate new keys
44 await this.generateKeys();
45
46 // Migrate to new keys (keep old for 30 days)
47 await this.scheduleKeyDeprecation(30);
48
49 // Update DHT with new public keys
50 await this.announceNewKeys();
51 }
52
53 async verifyKeyIntegrity() {
54 // Verify keys are sealed properly
55 const attestation = await TEE.getAttestation();
56
57 if (!attestation.keysSealed) {
58 throw new Error('Key sealing verification failed');
59 }
60
61 // Check for key rotation
62 const metadata = await this.getKeyMetadata();
63 if (Date.now() > metadata.rotationDue) {
64 console.warn('Key rotation overdue');
65 await this.rotateKeys();
66 }
67 }
68}

Anonymity and Privacy

While agents use pseudonymous Ethereum addresses, additional steps can be taken to enhance privacy and prevent correlation attacks. Consider network-level anonymity and metadata protection.

Privacy Considerations
  • • IP Address Exposure:P2P connections reveal your IP. Use VPN, Tor, or I2P for anonymity
  • • Timing Attacks:Message timing can correlate identities. Add random delays
  • • Blockchain Linkability:On-chain transactions are public. Use mixers or fresh addresses
  • • Metadata Leakage:Agent name, version, capabilities can identify you
  • • DHT Tracking:DHT queries are visible to network. Use private DHT routing
I2P Integration for Anonymity

Route agent traffic through I2P (Invisible Internet Project) for enhanced anonymity. I2P provides garlic routing and encrypted tunnels for all agent communication.

1// Configure agent to use I2P for anonymity
2const agent = new UnifiedTEEAgent('AnonymousAgent', signer, 'production');
3
4await agent.start({
5 port: 9100,
6
7 // Use I2P transport for anonymous networking
8 transports: [
9 {
10 type: 'i2p',
11 samHost: '127.0.0.1',
12 samPort: 7656,
13
14 // Generate unique I2P destination
15 destination: await I2P.generateDestination(),
16
17 // I2P tunnel configuration
18 inbound: {
19 length: 3, // 3-hop inbound tunnel
20 quantity: 2 // 2 parallel tunnels
21 },
22 outbound: {
23 length: 3, // 3-hop outbound tunnel
24 quantity: 2
25 }
26 }
27 ],
28
29 // Disable clearnet transport for full anonymity
30 disableClearnet: true,
31
32 // Use anonymous DHT
33 dht: {
34 mode: 'private',
35 routeViaI2P: true
36 }
37});
38
39console.log('Agent running anonymously via I2P');
40console.log('I2P destination:', agent.i2pDestination);
Tor Hidden Service (Alternative)
1# Run agent as Tor hidden service
2# Install Tor
3sudo apt install tor
4
5# Configure torrc
6cat >> /etc/tor/torrc <<EOF
7HiddenServiceDir /var/lib/tor/catgirl-agent/
8HiddenServicePort 9100 127.0.0.1:9100
9EOF
10
11# Restart Tor
12sudo systemctl restart tor
13
14# Get your .onion address
15sudo cat /var/lib/tor/catgirl-agent/hostname
16
17# Start agent bound to localhost only
18AGENT_PORT=9100 BIND_ADDRESS=127.0.0.1 npm start
Privacy-Preserving Configuration
1{
2 "privacy": {
3 // Minimal information disclosure
4 "agentName": "Agent-" + randomHex(8),
5 "hideCapabilities": true,
6 "randomizeVersionString": true,
7
8 // Network privacy
9 "useI2P": true,
10 "useTor": false,
11 "disableWebRTC": true, // Prevents IP leaks
12 "disableUPnP": true, // No automatic port forwarding
13
14 // Timing attack mitigation
15 "randomDelays": {
16 "min": 100,
17 "max": 5000
18 },
19
20 // DHT privacy
21 "privateDHT": true,
22 "onionRouting": true,
23 "routeViaI2P": true
24 },
25
26 "blockchain": {
27 // Use privacy-preserving techniques
28 "useProxyVault": true,
29 "rotateAddresses": true,
30 "addressRotationInterval": 86400000, // Daily
31
32 // Transaction privacy
33 "useMixer": false, // Optional: use tornado.cash style mixer
34 "batching": true // Batch multiple txs together
35 },
36
37 "attestation": {
38 // Selective disclosure
39 "shareMinimalInfo": true,
40 "hidePlatformDetails": true,
41 "anonymousAttestation": true
42 }
43}

Access Control and Authentication

Implement strict access controls for agent administration and sensitive operations. Use multi-factor authentication and role-based access control (RBAC).

1// Multi-layered access control system
2class AgentAccessControl {
3 constructor(private tee: TEESigner) {
4 this.roles = new Map();
5 this.sessions = new Map();
6 }
7
8 async authenticateAdmin(credentials: {
9 password: string;
10 totpCode: string;
11 hardwareKey?: string;
12 }): Promise<string> {
13 // Verify password (hashed)
14 const passwordHash = await this.hashPassword(credentials.password);
15 if (passwordHash !== this.adminPasswordHash) {
16 throw new Error('Invalid credentials');
17 }
18
19 // Verify TOTP (time-based one-time password)
20 const validTOTP = await this.verifyTOTP(credentials.totpCode);
21 if (!validTOTP) {
22 throw new Error('Invalid TOTP code');
23 }
24
25 // Optional: Verify hardware security key (YubiKey, etc)
26 if (this.requireHardwareKey && credentials.hardwareKey) {
27 const validKey = await this.verifyHardwareKey(credentials.hardwareKey);
28 if (!validKey) {
29 throw new Error('Invalid hardware key');
30 }
31 }
32
33 // Create session token
34 const sessionToken = await this.createSession('admin', 3600);
35 return sessionToken;
36 }
37
38 async executePrivilegedOperation(
39 sessionToken: string,
40 operation: string,
41 params: any
42 ) {
43 // Verify session
44 const session = await this.verifySession(sessionToken);
45 if (!session) {
46 throw new Error('Invalid or expired session');
47 }
48
49 // Check permissions
50 const hasPermission = await this.checkPermission(
51 session.role,
52 operation
53 );
54 if (!hasPermission) {
55 throw new Error('Insufficient permissions');
56 }
57
58 // Rate limiting
59 await this.checkRateLimit(session.userId, operation);
60
61 // Execute with audit logging
62 const result = await this.executeWithAudit(
63 operation,
64 params,
65 session.userId
66 );
67
68 return result;
69 }
70
71 async checkPermission(role: string, operation: string): Promise<boolean> {
72 const permissions = {
73 admin: ['*'],
74 operator: ['start', 'stop', 'configure', 'view'],
75 viewer: ['view']
76 };
77
78 const rolePerms = permissions[role] || [];
79 return rolePerms.includes('*') || rolePerms.includes(operation);
80 }
81
82 async checkRateLimit(userId: string, operation: string): Promise<void> {
83 // Implement sliding window rate limiting
84 const key = `${userId}:${operation}`;
85 const limit = this.rateLimits.get(operation) || 10;
86 const window = 60000; // 1 minute
87
88 const count = await this.incrementCounter(key, window);
89 if (count > limit) {
90 throw new Error('Rate limit exceeded');
91 }
92 }
93}

Security Monitoring and Incident Response

Implement comprehensive security monitoring to detect and respond to threats in real-time. Set up alerts for suspicious activity and maintain audit logs.

1// Security monitoring and alerting
2class SecurityMonitor {
3 constructor() {
4 this.alerts = [];
5 this.metrics = new Map();
6 }
7
8 async monitorAgent(agent: UnifiedTEEAgent) {
9 // Monitor attestation health
10 setInterval(async () => {
11 const attestation = await agent.getMyAttestation();
12
13 if (!attestation || attestation.trustScore < 0.7) {
14 await this.alert('critical', 'Attestation compromised', {
15 trustScore: attestation?.trustScore
16 });
17 }
18 }, 60000); // Check every minute
19
20 // Monitor network activity
21 agent.on('peer_connected', (peer) => {
22 this.recordEvent('peer_connection', peer);
23
24 // Alert on connections from suspicious peers
25 if (this.isSuspiciousPeer(peer)) {
26 this.alert('warning', 'Suspicious peer connection', { peer });
27 }
28 });
29
30 // Monitor transaction activity
31 agent.on('transaction_signed', (tx) => {
32 this.recordTransaction(tx);
33
34 // Alert on large or unusual transactions
35 if (this.isUnusualTransaction(tx)) {
36 this.alert('warning', 'Unusual transaction detected', { tx });
37 }
38 });
39
40 // Monitor resource usage
41 setInterval(() => {
42 const usage = {
43 cpu: process.cpuUsage(),
44 memory: process.memoryUsage(),
45 connections: agent.getPeerCount()
46 };
47
48 if (usage.memory.heapUsed > 1e9) { // 1GB
49 this.alert('warning', 'High memory usage', usage);
50 }
51 }, 30000);
52
53 // Monitor failed operations
54 agent.on('operation_failed', (op) => {
55 this.recordFailure(op);
56
57 // Alert on repeated failures (potential attack)
58 if (this.getFailureCount(op.type) > 10) {
59 this.alert('critical', 'Repeated operation failures', { op });
60 }
61 });
62 }
63
64 async alert(severity: string, message: string, context: any) {
65 const alert = {
66 timestamp: Date.now(),
67 severity,
68 message,
69 context
70 };
71
72 // Log to secure audit log
73 await this.auditLog(alert);
74
75 // Send notifications based on severity
76 if (severity === 'critical') {
77 await this.sendPagerDutyAlert(alert);
78 await this.sendTelegramAlert(alert);
79 await this.sendEmailAlert(alert);
80 } else if (severity === 'warning') {
81 await this.sendTelegramAlert(alert);
82 }
83
84 // Store for dashboard
85 this.alerts.push(alert);
86 }
87
88 async respondToIncident(incidentType: string) {
89 // Automated incident response
90 const responses = {
91 'attestation_compromised': async () => {
92 // Immediately stop agent
93 await this.agent.stop();
94 // Revoke keys
95 await this.tee.revokeKeys();
96 // Alert all peers
97 await this.broadcastCompromise();
98 },
99
100 'suspicious_peer': async (peer) => {
101 // Disconnect and blacklist
102 await this.agent.disconnectPeer(peer);
103 await this.agent.addToBlacklist(peer);
104 },
105
106 'rate_limit_exceeded': async (source) => {
107 // Temporary ban
108 await this.agent.rateLimitPeer(source, 300000); // 5 min
109 }
110 };
111
112 const response = responses[incidentType];
113 if (response) {
114 await response();
115 }
116 }
117}

Security Checklist

  • Verify agent attestation before first interaction
  • Never run agents in debug mode in production
  • Configure firewall rules to restrict port access
  • Never expose WebSocket bridge (port 8080) to public internet
  • Implement key rotation policies (90 days maximum)
  • Use I2P or Tor for anonymous agent operation
  • Enable multi-factor authentication for admin access
  • Keep agent software updated to latest security patches
  • Monitor agent transaction activity regularly
  • Set reasonable spending limits for autonomous transactions
  • Backup attestation certificates and agent configurations
  • Review marketplace provider reputations before submitting tasks
  • Implement security monitoring and alerting
  • Maintain audit logs of all security-relevant events
  • Test incident response procedures regularly

Additional Resources

Security Overview →

Learn about the overall security architecture

Cryptography Details →

Deep dive into encryption schemes and key management

TEE Platforms →

Platform-specific security features and requirements

Responsible Disclosure →

Report security vulnerabilities responsibly