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 leave2async function generateSecureKeys() {3 // Hardware RNG generates entropy4 const entropy = await TEE.getRandomBytes(32);56 // Generate keypair in enclave7 const keypair = secp256k1.generateKeypair(entropy);89 // Seal private key to hardware10 const sealed = await TEE.seal(keypair.privateKey);1112 // Only public key and address are exposed13 return {14 address: keypair.address,15 publicKey: keypair.publicKey,16 // privateKey stays in TEE forever17 };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 interaction2async function verifyAgentAttestation(agentPublicKey: string) {3 // Request attestation quote from agent4 const quote = await agent.getAttestationQuote();56 // Verify with platform attestation service7 const verification = await attestationService.verify({8 quote: quote,9 publicKey: agentPublicKey,10 expectedMeasurement: TRUSTED_CODE_HASH11 });1213 if (!verification.isValid) {14 throw new Error('Agent attestation failed');15 }1617 // Check platform type (Intel SGX, AMD SEV, etc)18 console.log('Platform:', verification.platform);19 console.log('Security version:', verification.securityVersion);2021 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 TEE2async function signTransaction(recipient: string, amount: bigint) {3 // Transaction created in TEE4 const tx = {5 to: recipient,6 value: amount,7 nonce: await getNonce(),8 chainId: 42161, // Arbitrum One9 gasLimit: 21000n,10 maxFeePerGas: await getGasPrice()11 };1213 // Private key never leaves TEE14 const signedTx = await TEE.signTransaction(tx);1516 // Only signed transaction leaves enclave17 return signedTx;18}1920// Verify transaction before broadcasting21async 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 }2627 // Sign in TEE28 const signed = await signTransaction(recipient, amount);2930 // Broadcast31 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.
Marketplace Safety
When using the agent marketplace (Arbius, EACC), verify both the compute provider and the task results.
1// Safe marketplace interaction2async function requestCompute(task: ComputeTask) {3 // Find providers with valid attestation4 const providers = await marketplace.findProviders({5 minReputation: 0.8,6 requireAttestation: true,7 platform: ['sgx', 'sev']8 });910 // Submit task with result verification11 const result = await marketplace.submitTask({12 task: task,13 provider: providers[0],14 verifyAttestation: true,15 requireSignature: true,16 timeout: 300000 // 5 min17 });1819 // Verify result signature matches provider attestation20 if (!await verifyResultSignature(result, providers[0])) {21 throw new Error('Result verification failed');22 }2324 return result;25}
Secure Configuration
Agent configuration should be validated and sensitive settings should be encrypted at rest.
1// Example secure configuration2{3 "tee": {4 "platform": "sgx",5 "attestation": {6 "provider": "intel-dcap",7 "minimumSecurityVersion": 2,8 "allowDebugMode": false // NEVER enable in production9 }10 },11 "keys": {12 "autoGenerate": true,13 "sealToDisk": true, // Encrypted with platform key14 "backupEnabled": false // Keys cannot be exported15 },16 "network": {17 "encryption": "noise-xx",18 "requireAttestation": true,19 "trustedPeers": [], // Empty = trust on first use20 "denylist": []21 },22 "marketplace": {23 "maxTaskValue": "1000000000000000000", // 1 $AIUS max per task24 "requireProviderAttestation": true,25 "minProviderReputation": 0.726 }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.
| Port | Protocol | Purpose |
|---|---|---|
| 9100 | TCP | P2P agent networking (LibP2P) |
| 8080 | TCP | WebSocket bridge (local only) |
| 443 | TCP | HTTPS for attestation verification |
| * | UDP | QUIC transport (optional) |
1# UFW (Ubuntu) firewall configuration2# Allow P2P networking from specific peers3sudo ufw allow from 192.168.1.0/24 to any port 910045# NEVER expose bridge to public internet6sudo ufw deny 808078# Allow attestation service communication9sudo ufw allow out 443/tcp1011# Enable firewall12sudo ufw enable1314# iptables alternative15iptables -A INPUT -p tcp --dport 9100 -s 192.168.1.0/24 -j ACCEPT16iptables -A INPUT -p tcp --dport 8080 -s 127.0.0.1 -j ACCEPT17iptables -A INPUT -p tcp --dport 8080 -j DROP
1# Secure Docker port configuration2docker run -d \3 --name catgirl-agent \4 -p 127.0.0.1:8080:8080 \ # Bridge: local only5 -p 9100:9100 \ # P2P: exposed to network6 --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.
- • 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)
- • 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
1// Proper key lifecycle with hardware sealing2class SecureKeyManager {3 async initialize() {4 // Check if keys exist5 const hasKeys = await TEE.hasSealedKeys();67 if (!hasKeys) {8 // Generate new keys in TEE9 await this.generateKeys();10 } else {11 // Unseal existing keys12 await this.unsealKeys();13 }1415 // Verify key integrity16 await this.verifyKeyIntegrity();17 }1819 async generateKeys() {20 // Hardware RNG for entropy21 const entropy = await TEE.getRandomBytes(32);2223 // Generate signing key24 const signingKey = await TEE.generateSecp256k1Key(entropy);2526 // Generate encryption key (separate)27 const encryptionKey = await TEE.generateX25519Key();2829 // Seal both keys to hardware30 await TEE.seal('signing_key', signingKey);31 await TEE.seal('encryption_key', encryptionKey);3233 // 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 days39 });40 }4142 async rotateKeys() {43 // Generate new keys44 await this.generateKeys();4546 // Migrate to new keys (keep old for 30 days)47 await this.scheduleKeyDeprecation(30);4849 // Update DHT with new public keys50 await this.announceNewKeys();51 }5253 async verifyKeyIntegrity() {54 // Verify keys are sealed properly55 const attestation = await TEE.getAttestation();5657 if (!attestation.keysSealed) {58 throw new Error('Key sealing verification failed');59 }6061 // Check for key rotation62 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.
- • 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
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 anonymity2const agent = new UnifiedTEEAgent('AnonymousAgent', signer, 'production');34await agent.start({5 port: 9100,67 // Use I2P transport for anonymous networking8 transports: [9 {10 type: 'i2p',11 samHost: '127.0.0.1',12 samPort: 7656,1314 // Generate unique I2P destination15 destination: await I2P.generateDestination(),1617 // I2P tunnel configuration18 inbound: {19 length: 3, // 3-hop inbound tunnel20 quantity: 2 // 2 parallel tunnels21 },22 outbound: {23 length: 3, // 3-hop outbound tunnel24 quantity: 225 }26 }27 ],2829 // Disable clearnet transport for full anonymity30 disableClearnet: true,3132 // Use anonymous DHT33 dht: {34 mode: 'private',35 routeViaI2P: true36 }37});3839console.log('Agent running anonymously via I2P');40console.log('I2P destination:', agent.i2pDestination);
1# Run agent as Tor hidden service2# Install Tor3sudo apt install tor45# Configure torrc6cat >> /etc/tor/torrc <<EOF7HiddenServiceDir /var/lib/tor/catgirl-agent/8HiddenServicePort 9100 127.0.0.1:91009EOF1011# Restart Tor12sudo systemctl restart tor1314# Get your .onion address15sudo cat /var/lib/tor/catgirl-agent/hostname1617# Start agent bound to localhost only18AGENT_PORT=9100 BIND_ADDRESS=127.0.0.1 npm start
1{2 "privacy": {3 // Minimal information disclosure4 "agentName": "Agent-" + randomHex(8),5 "hideCapabilities": true,6 "randomizeVersionString": true,78 // Network privacy9 "useI2P": true,10 "useTor": false,11 "disableWebRTC": true, // Prevents IP leaks12 "disableUPnP": true, // No automatic port forwarding1314 // Timing attack mitigation15 "randomDelays": {16 "min": 100,17 "max": 500018 },1920 // DHT privacy21 "privateDHT": true,22 "onionRouting": true,23 "routeViaI2P": true24 },2526 "blockchain": {27 // Use privacy-preserving techniques28 "useProxyVault": true,29 "rotateAddresses": true,30 "addressRotationInterval": 86400000, // Daily3132 // Transaction privacy33 "useMixer": false, // Optional: use tornado.cash style mixer34 "batching": true // Batch multiple txs together35 },3637 "attestation": {38 // Selective disclosure39 "shareMinimalInfo": true,40 "hidePlatformDetails": true,41 "anonymousAttestation": true42 }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 system2class AgentAccessControl {3 constructor(private tee: TEESigner) {4 this.roles = new Map();5 this.sessions = new Map();6 }78 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 }1819 // 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 }2425 // 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 }3233 // Create session token34 const sessionToken = await this.createSession('admin', 3600);35 return sessionToken;36 }3738 async executePrivilegedOperation(39 sessionToken: string,40 operation: string,41 params: any42 ) {43 // Verify session44 const session = await this.verifySession(sessionToken);45 if (!session) {46 throw new Error('Invalid or expired session');47 }4849 // Check permissions50 const hasPermission = await this.checkPermission(51 session.role,52 operation53 );54 if (!hasPermission) {55 throw new Error('Insufficient permissions');56 }5758 // Rate limiting59 await this.checkRateLimit(session.userId, operation);6061 // Execute with audit logging62 const result = await this.executeWithAudit(63 operation,64 params,65 session.userId66 );6768 return result;69 }7071 async checkPermission(role: string, operation: string): Promise<boolean> {72 const permissions = {73 admin: ['*'],74 operator: ['start', 'stop', 'configure', 'view'],75 viewer: ['view']76 };7778 const rolePerms = permissions[role] || [];79 return rolePerms.includes('*') || rolePerms.includes(operation);80 }8182 async checkRateLimit(userId: string, operation: string): Promise<void> {83 // Implement sliding window rate limiting84 const key = `${userId}:${operation}`;85 const limit = this.rateLimits.get(operation) || 10;86 const window = 60000; // 1 minute8788 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 alerting2class SecurityMonitor {3 constructor() {4 this.alerts = [];5 this.metrics = new Map();6 }78 async monitorAgent(agent: UnifiedTEEAgent) {9 // Monitor attestation health10 setInterval(async () => {11 const attestation = await agent.getMyAttestation();1213 if (!attestation || attestation.trustScore < 0.7) {14 await this.alert('critical', 'Attestation compromised', {15 trustScore: attestation?.trustScore16 });17 }18 }, 60000); // Check every minute1920 // Monitor network activity21 agent.on('peer_connected', (peer) => {22 this.recordEvent('peer_connection', peer);2324 // Alert on connections from suspicious peers25 if (this.isSuspiciousPeer(peer)) {26 this.alert('warning', 'Suspicious peer connection', { peer });27 }28 });2930 // Monitor transaction activity31 agent.on('transaction_signed', (tx) => {32 this.recordTransaction(tx);3334 // Alert on large or unusual transactions35 if (this.isUnusualTransaction(tx)) {36 this.alert('warning', 'Unusual transaction detected', { tx });37 }38 });3940 // Monitor resource usage41 setInterval(() => {42 const usage = {43 cpu: process.cpuUsage(),44 memory: process.memoryUsage(),45 connections: agent.getPeerCount()46 };4748 if (usage.memory.heapUsed > 1e9) { // 1GB49 this.alert('warning', 'High memory usage', usage);50 }51 }, 30000);5253 // Monitor failed operations54 agent.on('operation_failed', (op) => {55 this.recordFailure(op);5657 // Alert on repeated failures (potential attack)58 if (this.getFailureCount(op.type) > 10) {59 this.alert('critical', 'Repeated operation failures', { op });60 }61 });62 }6364 async alert(severity: string, message: string, context: any) {65 const alert = {66 timestamp: Date.now(),67 severity,68 message,69 context70 };7172 // Log to secure audit log73 await this.auditLog(alert);7475 // Send notifications based on severity76 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 }8384 // Store for dashboard85 this.alerts.push(alert);86 }8788 async respondToIncident(incidentType: string) {89 // Automated incident response90 const responses = {91 'attestation_compromised': async () => {92 // Immediately stop agent93 await this.agent.stop();94 // Revoke keys95 await this.tee.revokeKeys();96 // Alert all peers97 await this.broadcastCompromise();98 },99100 'suspicious_peer': async (peer) => {101 // Disconnect and blacklist102 await this.agent.disconnectPeer(peer);103 await this.agent.addToBlacklist(peer);104 },105106 'rate_limit_exceeded': async (source) => {107 // Temporary ban108 await this.agent.rateLimitPeer(source, 300000); // 5 min109 }110 };111112 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
Learn about the overall security architecture
Deep dive into encryption schemes and key management
Platform-specific security features and requirements
Report security vulnerabilities responsibly
