|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto/rand" |
| 6 | + "crypto/rsa" |
| 7 | + "crypto/x509" |
| 8 | + "encoding/hex" |
| 9 | + "encoding/json" |
| 10 | + "fmt" |
| 11 | + "time" |
| 12 | + |
| 13 | + "github.com/distributed-lab/enclave-extras/attestation/kmshelpers" |
| 14 | + "github.com/distributed-lab/enclave-extras/nsm" |
| 15 | + |
| 16 | + "github.com/aws/aws-sdk-go-v2/aws" |
| 17 | + "github.com/aws/aws-sdk-go-v2/aws/arn" |
| 18 | + "github.com/aws/aws-sdk-go-v2/config" |
| 19 | + "github.com/aws/aws-sdk-go-v2/credentials" |
| 20 | + "github.com/aws/aws-sdk-go-v2/service/iam" |
| 21 | + "github.com/aws/aws-sdk-go-v2/service/kms" |
| 22 | + kmstypes "github.com/aws/aws-sdk-go-v2/service/kms/types" |
| 23 | + "github.com/ethereum/go-ethereum/common/hexutil" |
| 24 | + "github.com/ethereum/go-ethereum/log" |
| 25 | +) |
| 26 | + |
| 27 | +const ( |
| 28 | + region = "you_region" |
| 29 | + accessKey = "iam_access_key" |
| 30 | + secretKey = "iam_secret_key" |
| 31 | +) |
| 32 | + |
| 33 | +func main() { |
| 34 | + time.Sleep(15 * time.Second) |
| 35 | + |
| 36 | + awsConfig, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion(region), config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKey, secretKey, ""))) |
| 37 | + if err != nil { |
| 38 | + panic(fmt.Errorf("failed to load default aws config: %w", err)) |
| 39 | + } |
| 40 | + |
| 41 | + fmt.Println("All pcrs values: should be zeros at start") |
| 42 | + for i := 0; i < 32; i++ { |
| 43 | + _, pcrData, err := nsm.DescribePCR(i) |
| 44 | + if err != nil { |
| 45 | + panic(fmt.Errorf("failed to get pcr0 data: %w", err)) |
| 46 | + } |
| 47 | + fmt.Printf("PCR%d data: %s\n", i, hexutil.Encode(pcrData)) |
| 48 | + } |
| 49 | + |
| 50 | + _, pcr0Data, err := nsm.DescribePCR(0) |
| 51 | + if err != nil { |
| 52 | + panic(fmt.Errorf("failed to get pcr0 data: %w", err)) |
| 53 | + } |
| 54 | + |
| 55 | + keyID, err := CreateKMSEnclaveKey(awsConfig, map[string]string{ |
| 56 | + "kms:RecipientAttestation:PCR0": hex.EncodeToString(pcr0Data), |
| 57 | + }) |
| 58 | + if err != nil { |
| 59 | + panic(fmt.Errorf("failed to create kms key: %w", err)) |
| 60 | + } |
| 61 | + fmt.Printf("KeyID: %s\n", keyID) |
| 62 | + |
| 63 | + rsaPrivateKey, err := rsa.GenerateKey(rand.Reader, 4096) |
| 64 | + if err != nil { |
| 65 | + panic(fmt.Errorf("failed to generate rsa 4096 private key: %w", err)) |
| 66 | + } |
| 67 | + fmt.Printf("PrivateKey: %s\n", hexutil.Encode(x509.MarshalPKCS1PrivateKey(rsaPrivateKey))) |
| 68 | + fmt.Printf("PublicKey: %s\n", hexutil.Encode(x509.MarshalPKCS1PublicKey(&rsaPrivateKey.PublicKey))) |
| 69 | + |
| 70 | + derEncodedPublicKey, err := x509.MarshalPKIXPublicKey(&rsaPrivateKey.PublicKey) |
| 71 | + if err != nil { |
| 72 | + panic(fmt.Errorf("faield to encode public key in DER format: %w", err)) |
| 73 | + } |
| 74 | + fmt.Printf("DEREncodedPublicKey: %s\n", hexutil.Encode(derEncodedPublicKey)) |
| 75 | + |
| 76 | + attestationDoc, err := nsm.GetAttestationDoc(nil, nil, derEncodedPublicKey) |
| 77 | + if err != nil { |
| 78 | + panic(fmt.Errorf("faield to get attestatiokn doc: %w", err)) |
| 79 | + } |
| 80 | + fmt.Printf("AttestationDoc: %s\n", hexutil.Encode(attestationDoc)) |
| 81 | + |
| 82 | + awsKMSEnclaveClient := kmshelpers.NewFromConfig(awsConfig) |
| 83 | + |
| 84 | + encryptResp, err := awsKMSEnclaveClient.Encrypt(context.TODO(), &kms.EncryptInput{ |
| 85 | + KeyId: aws.String(keyID), |
| 86 | + Plaintext: []byte("Hello world"), |
| 87 | + }) |
| 88 | + if err != nil { |
| 89 | + panic(fmt.Errorf("failed to encrypt plaintext: %w", err)) |
| 90 | + } |
| 91 | + fmt.Printf("Ciphertext: %s\n", hexutil.Encode(encryptResp.CiphertextBlob)) |
| 92 | + |
| 93 | + decryptResp, err := awsKMSEnclaveClient.Decrypt(context.TODO(), &kms.DecryptInput{ |
| 94 | + KeyId: aws.String(keyID), |
| 95 | + CiphertextBlob: encryptResp.CiphertextBlob, |
| 96 | + Recipient: &kmstypes.RecipientInfo{ |
| 97 | + AttestationDocument: attestationDoc, |
| 98 | + KeyEncryptionAlgorithm: kmstypes.KeyEncryptionMechanismRsaesOaepSha256, |
| 99 | + }, |
| 100 | + }, rsaPrivateKey) |
| 101 | + if err != nil { |
| 102 | + panic(fmt.Errorf("failed to decrypt ciphertext on KMS: %w", err)) |
| 103 | + } |
| 104 | + fmt.Printf("Plaintext(decrypt): %s\n", string(decryptResp.Plaintext)) |
| 105 | + |
| 106 | + generateDataKeyResp, err := awsKMSEnclaveClient.GenerateDataKey(context.TODO(), &kms.GenerateDataKeyInput{ |
| 107 | + KeyId: aws.String(keyID), |
| 108 | + KeySpec: kmstypes.DataKeySpecAes256, |
| 109 | + Recipient: &kmstypes.RecipientInfo{ |
| 110 | + AttestationDocument: attestationDoc, |
| 111 | + KeyEncryptionAlgorithm: kmstypes.KeyEncryptionMechanismRsaesOaepSha256, |
| 112 | + }, |
| 113 | + }, rsaPrivateKey) |
| 114 | + if err != nil { |
| 115 | + panic(fmt.Errorf("failed to generate data key on KMS: %w", err)) |
| 116 | + } |
| 117 | + fmt.Printf("Plaintext(generate-data-key): %s\n", hexutil.Encode(generateDataKeyResp.Plaintext)) |
| 118 | + |
| 119 | + generateDataKeyPairResp, err := awsKMSEnclaveClient.GenerateDataKeyPair(context.TODO(), &kms.GenerateDataKeyPairInput{ |
| 120 | + KeyId: aws.String(keyID), |
| 121 | + KeyPairSpec: kmstypes.DataKeyPairSpecEccNistP521, |
| 122 | + Recipient: &kmstypes.RecipientInfo{ |
| 123 | + AttestationDocument: attestationDoc, |
| 124 | + KeyEncryptionAlgorithm: kmstypes.KeyEncryptionMechanismRsaesOaepSha256, |
| 125 | + }, |
| 126 | + }, rsaPrivateKey) |
| 127 | + if err != nil { |
| 128 | + panic(fmt.Errorf("failed to generate data key pair on KMS: %w", err)) |
| 129 | + } |
| 130 | + fmt.Printf("PrivateKeyPlaintext(generate-data-key-pair): %s\n", hexutil.Encode(generateDataKeyPairResp.PrivateKeyPlaintext)) |
| 131 | + fmt.Printf("PublicKey: %s\n", hexutil.Encode(generateDataKeyPairResp.PublicKey)) |
| 132 | + |
| 133 | + generateRandomResp, err := awsKMSEnclaveClient.GenerateRandom(context.TODO(), &kms.GenerateRandomInput{ |
| 134 | + NumberOfBytes: aws.Int32(128), |
| 135 | + Recipient: &kmstypes.RecipientInfo{ |
| 136 | + AttestationDocument: attestationDoc, |
| 137 | + KeyEncryptionAlgorithm: kmstypes.KeyEncryptionMechanismRsaesOaepSha256, |
| 138 | + }, |
| 139 | + }, rsaPrivateKey) |
| 140 | + if err != nil { |
| 141 | + panic(fmt.Errorf("failed to genearate random on KMS: %w", err)) |
| 142 | + } |
| 143 | + fmt.Printf("Plaintext(generate-random): %s\n", hexutil.Encode(generateRandomResp.Plaintext)) |
| 144 | +} |
| 145 | + |
| 146 | +func CreateKMSEnclaveKey(cfg aws.Config, pcrs map[string]string) (string, error) { |
| 147 | + callerARN, err := getCallerARN(cfg) |
| 148 | + if err != nil { |
| 149 | + return "", fmt.Errorf("failed to get arn of active user: %w", err) |
| 150 | + } |
| 151 | + |
| 152 | + log.Debug("Create KMS Restricted key: Caller ARN", callerARN) |
| 153 | + |
| 154 | + rootARN, err := arn.Parse(callerARN) |
| 155 | + if err != nil { |
| 156 | + return "", fmt.Errorf("failed to parse arn: %w", err) |
| 157 | + } |
| 158 | + rootARN.Resource = "root" |
| 159 | + |
| 160 | + log.Debug("Create KMS Restricted key: Root ARN", rootARN.String()) |
| 161 | + |
| 162 | + keyPolicy := map[string]interface{}{ |
| 163 | + "Version": "2012-10-17", |
| 164 | + "Id": "key-default-1", |
| 165 | + "Statement": []map[string]interface{}{ |
| 166 | + { |
| 167 | + "Sid": "Allow access for Key Administrators", |
| 168 | + "Effect": "Allow", |
| 169 | + "Principal": map[string]interface{}{ |
| 170 | + "AWS": rootARN.String(), |
| 171 | + }, |
| 172 | + "Action": []string{ |
| 173 | + "kms:CancelKeyDeletion", |
| 174 | + "kms:DescribeKey", |
| 175 | + "kms:DisableKey", |
| 176 | + "kms:EnableKey", |
| 177 | + "kms:GetKeyPolicy", |
| 178 | + "kms:ScheduleKeyDeletion", |
| 179 | + }, |
| 180 | + "Resource": "*", |
| 181 | + }, |
| 182 | + // should be removed if you want to |
| 183 | + // trust private key generated in enclave |
| 184 | + { |
| 185 | + "Sid": "Enable encrypt from instance", |
| 186 | + "Effect": "Allow", |
| 187 | + "Principal": map[string]interface{}{ |
| 188 | + "AWS": callerARN, |
| 189 | + }, |
| 190 | + "Action": "kms:Encrypt", |
| 191 | + "Resource": "*", |
| 192 | + }, |
| 193 | + { |
| 194 | + "Sid": "Enable decrypt from enclave", |
| 195 | + "Effect": "Allow", |
| 196 | + "Principal": map[string]interface{}{ |
| 197 | + "AWS": callerARN, |
| 198 | + }, |
| 199 | + "Action": []string{ |
| 200 | + "kms:Decrypt", |
| 201 | + "kms:GenerateRandom", |
| 202 | + "kms:GenerateDataKey", |
| 203 | + "kms:GenerateDataKeyPair", |
| 204 | + }, |
| 205 | + "Resource": "*", |
| 206 | + "Condition": map[string]interface{}{ |
| 207 | + "StringEqualsIgnoreCase": pcrs, |
| 208 | + }, |
| 209 | + }, |
| 210 | + }, |
| 211 | + } |
| 212 | + |
| 213 | + policyBytes, err := json.Marshal(keyPolicy) |
| 214 | + if err != nil { |
| 215 | + return "", fmt.Errorf("failed to marshal policy: %w", err) |
| 216 | + } |
| 217 | + |
| 218 | + log.Debug("Create KMS Restricted key: Key policy", string(policyBytes)) |
| 219 | + |
| 220 | + awsKMSClient := kms.NewFromConfig(cfg) |
| 221 | + resp, err := awsKMSClient.CreateKey(context.TODO(), &kms.CreateKeyInput{ |
| 222 | + // DANGER: The key may become unmanageable |
| 223 | + BypassPolicyLockoutSafetyCheck: true, |
| 224 | + Description: aws.String("Nitro Enclave Key"), |
| 225 | + Policy: aws.String(string(policyBytes)), |
| 226 | + }) |
| 227 | + if err != nil { |
| 228 | + return "", fmt.Errorf("failed to create kms key") |
| 229 | + } |
| 230 | + |
| 231 | + // Should never be nil |
| 232 | + return *resp.KeyMetadata.KeyId, nil |
| 233 | +} |
| 234 | + |
| 235 | +func getCallerARN(cfg aws.Config) (string, error) { |
| 236 | + awsIAMClient := iam.NewFromConfig(cfg) |
| 237 | + resp, err := awsIAMClient.GetUser(context.TODO(), &iam.GetUserInput{}) |
| 238 | + if err != nil { |
| 239 | + return "", err |
| 240 | + } |
| 241 | + |
| 242 | + // Should never be nil |
| 243 | + return *resp.User.Arn, nil |
| 244 | +} |
0 commit comments