|
| 1 | +package nitro |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/ecdsa" |
| 5 | + "crypto/sha256" |
| 6 | + "crypto/sha512" |
| 7 | + "crypto/x509" |
| 8 | + "errors" |
| 9 | + "fmt" |
| 10 | + "math/big" |
| 11 | + "time" |
| 12 | + |
| 13 | + "github.com/fxamacker/cbor/v2" |
| 14 | +) |
| 15 | + |
| 16 | +var ( |
| 17 | + errBadCOSESign1Structure = errors.New("data is not a COSE Sign1 array") |
| 18 | + errEmptyProtectedSection = errors.New("COSE Sign1 protected section is nil or empty") |
| 19 | + errEmptyPayloadSection = errors.New("COSE Sign1 payload section is nil or empty") |
| 20 | + errEmptySignatureSection = errors.New("COSE Sign1 signature section is nil or empty") |
| 21 | + errUnsupportedSignatureAlgorithm = errors.New("COSE Sign1 algorithm is not ECDSA P-384") |
| 22 | + errBadAttestationDocument = errors.New("bad attestation document") |
| 23 | + errMandatoryFieldsMissing = errors.New("attestation document is missing mandatory fields") |
| 24 | + errBadDigest = errors.New("attestation digest is not SHA384") |
| 25 | + errBadTimestamp = errors.New("attestation timestamp is 0") |
| 26 | + errBadPCRs = errors.New("attestation pcrs is less than 1 or more than 32") |
| 27 | + errBadPCRIndex = errors.New("attestation pcr index is not in [0, 32)") |
| 28 | + errBadPCRValue = errors.New("attestation pcr value length is invalid") |
| 29 | + errBadCABundle = errors.New("attestation cabundle is empty") |
| 30 | + errBadCABundleItem = errors.New("attestation cabundle item is empty or too large") |
| 31 | + errBadPublicKey = errors.New("attestation public_key length is invalid") |
| 32 | + errBadUserData = errors.New("attestation user_data length is invalid") |
| 33 | + errBadNonce = errors.New("attestation nonce length is invalid") |
| 34 | + errBadCertificatePublicKeyAlgo = errors.New("attestation certificate public key algorithm is not ECDSA") |
| 35 | + errBadCertificateSigningAlgo = errors.New("attestation certificate signature algorithm is not ECDSAWithSHA384") |
| 36 | + errBadSignature = errors.New("attestation signature does not match certificate") |
| 37 | +) |
| 38 | + |
| 39 | +type verifyResult struct { |
| 40 | + document *attestationDocument |
| 41 | + signatureOK bool |
| 42 | +} |
| 43 | + |
| 44 | +type attestationDocument struct { |
| 45 | + ModuleID string `cbor:"module_id"` |
| 46 | + Timestamp uint64 `cbor:"timestamp"` |
| 47 | + Digest string `cbor:"digest"` |
| 48 | + PCRs map[uint][]byte `cbor:"pcrs"` |
| 49 | + Certificate []byte `cbor:"certificate"` |
| 50 | + CABundle [][]byte `cbor:"cabundle"` |
| 51 | + PublicKey []byte `cbor:"public_key,omitempty"` |
| 52 | + UserData []byte `cbor:"user_data,omitempty"` |
| 53 | + Nonce []byte `cbor:"nonce,omitempty"` |
| 54 | +} |
| 55 | + |
| 56 | +type coseProtectedHeader struct { |
| 57 | + Alg any `cbor:"1,keyasint,omitempty"` |
| 58 | +} |
| 59 | + |
| 60 | +type coseSign1 struct { |
| 61 | + _ struct{} `cbor:",toarray"` //nolint:revive // idiomatic CBOR array encoding |
| 62 | + Protected []byte |
| 63 | + Unprotected cbor.RawMessage |
| 64 | + Payload []byte |
| 65 | + Signature []byte |
| 66 | +} |
| 67 | + |
| 68 | +type coseSignatureInput struct { |
| 69 | + _ struct{} `cbor:",toarray"` //nolint:revive // idiomatic CBOR array encoding |
| 70 | + Context string |
| 71 | + Protected []byte |
| 72 | + ExternalAAD []byte |
| 73 | + Payload []byte |
| 74 | +} |
| 75 | + |
| 76 | +func verifyAttestationDocument(data []byte, roots *x509.CertPool, currentTime time.Time) (*verifyResult, error) { |
| 77 | + var sign1 coseSign1 |
| 78 | + if err := cbor.Unmarshal(data, &sign1); err != nil { |
| 79 | + return nil, errBadCOSESign1Structure |
| 80 | + } |
| 81 | + if len(sign1.Protected) == 0 { |
| 82 | + return nil, errEmptyProtectedSection |
| 83 | + } |
| 84 | + if len(sign1.Payload) == 0 { |
| 85 | + return nil, errEmptyPayloadSection |
| 86 | + } |
| 87 | + if len(sign1.Signature) == 0 { |
| 88 | + return nil, errEmptySignatureSection |
| 89 | + } |
| 90 | + |
| 91 | + var protected coseProtectedHeader |
| 92 | + if err := cbor.Unmarshal(sign1.Protected, &protected); err != nil { |
| 93 | + return nil, errBadCOSESign1Structure |
| 94 | + } |
| 95 | + if err := validateProtectedAlgorithm(protected.Alg); err != nil { |
| 96 | + return nil, err |
| 97 | + } |
| 98 | + |
| 99 | + var doc attestationDocument |
| 100 | + if err := cbor.Unmarshal(sign1.Payload, &doc); err != nil { |
| 101 | + return nil, errBadAttestationDocument |
| 102 | + } |
| 103 | + if err := validateAttestationPayload(&doc); err != nil { |
| 104 | + return nil, err |
| 105 | + } |
| 106 | + |
| 107 | + leafCert, intermediates, err := parseCertificateChain(&doc) |
| 108 | + if err != nil { |
| 109 | + return nil, err |
| 110 | + } |
| 111 | + if currentTime.IsZero() { |
| 112 | + currentTime = time.Now() |
| 113 | + } |
| 114 | + if _, err := leafCert.Verify(x509.VerifyOptions{ |
| 115 | + Intermediates: intermediates, |
| 116 | + Roots: roots, |
| 117 | + CurrentTime: currentTime, |
| 118 | + KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny}, |
| 119 | + }); err != nil { |
| 120 | + return nil, err |
| 121 | + } |
| 122 | + |
| 123 | + sigStructure, err := cbor.Marshal(&coseSignatureInput{ |
| 124 | + Context: "Signature1", |
| 125 | + Protected: sign1.Protected, |
| 126 | + ExternalAAD: []byte{}, |
| 127 | + Payload: sign1.Payload, |
| 128 | + }) |
| 129 | + if err != nil { |
| 130 | + return nil, fmt.Errorf("build signature structure: %w", err) |
| 131 | + } |
| 132 | + |
| 133 | + pubKey, ok := leafCert.PublicKey.(*ecdsa.PublicKey) |
| 134 | + if !ok { |
| 135 | + return nil, errBadCertificatePublicKeyAlgo |
| 136 | + } |
| 137 | + signatureOK := verifyECDSASignature(pubKey, sigStructure, sign1.Signature) |
| 138 | + if !signatureOK { |
| 139 | + return &verifyResult{document: &doc, signatureOK: false}, errBadSignature |
| 140 | + } |
| 141 | + |
| 142 | + return &verifyResult{document: &doc, signatureOK: true}, nil |
| 143 | +} |
| 144 | + |
| 145 | +func validateProtectedAlgorithm(alg any) error { |
| 146 | + switch v := alg.(type) { |
| 147 | + case int64: |
| 148 | + if v == -35 { |
| 149 | + return nil |
| 150 | + } |
| 151 | + case string: |
| 152 | + if v == "ES384" { |
| 153 | + return nil |
| 154 | + } |
| 155 | + } |
| 156 | + return errUnsupportedSignatureAlgorithm |
| 157 | +} |
| 158 | + |
| 159 | +func validateAttestationPayload(doc *attestationDocument) error { |
| 160 | + if doc.ModuleID == "" || doc.Digest == "" || doc.Timestamp == 0 || doc.PCRs == nil || doc.Certificate == nil || doc.CABundle == nil { |
| 161 | + return errMandatoryFieldsMissing |
| 162 | + } |
| 163 | + if doc.Digest != "SHA384" { |
| 164 | + return errBadDigest |
| 165 | + } |
| 166 | + if doc.Timestamp < 1 { |
| 167 | + return errBadTimestamp |
| 168 | + } |
| 169 | + if len(doc.PCRs) < 1 || len(doc.PCRs) > 32 { |
| 170 | + return errBadPCRs |
| 171 | + } |
| 172 | + for idx, value := range doc.PCRs { |
| 173 | + if idx > 31 { |
| 174 | + return errBadPCRIndex |
| 175 | + } |
| 176 | + if value == nil || (len(value) != 32 && len(value) != 48 && len(value) != 64) { |
| 177 | + return errBadPCRValue |
| 178 | + } |
| 179 | + } |
| 180 | + if len(doc.CABundle) < 1 { |
| 181 | + return errBadCABundle |
| 182 | + } |
| 183 | + for _, item := range doc.CABundle { |
| 184 | + if item == nil || len(item) < 1 || len(item) > 1024 { |
| 185 | + return errBadCABundleItem |
| 186 | + } |
| 187 | + } |
| 188 | + if doc.PublicKey != nil && len(doc.PublicKey) > 1024 { |
| 189 | + return errBadPublicKey |
| 190 | + } |
| 191 | + if doc.UserData != nil && len(doc.UserData) > 1024 { |
| 192 | + return errBadUserData |
| 193 | + } |
| 194 | + if doc.Nonce != nil && len(doc.Nonce) > 1024 { |
| 195 | + return errBadNonce |
| 196 | + } |
| 197 | + return nil |
| 198 | +} |
| 199 | + |
| 200 | +func parseCertificateChain(doc *attestationDocument) (*x509.Certificate, *x509.CertPool, error) { |
| 201 | + leafCert, err := x509.ParseCertificate(doc.Certificate) |
| 202 | + if err != nil { |
| 203 | + return nil, nil, err |
| 204 | + } |
| 205 | + if leafCert.PublicKeyAlgorithm != x509.ECDSA { |
| 206 | + return nil, nil, errBadCertificatePublicKeyAlgo |
| 207 | + } |
| 208 | + if leafCert.SignatureAlgorithm != x509.ECDSAWithSHA384 { |
| 209 | + return nil, nil, errBadCertificateSigningAlgo |
| 210 | + } |
| 211 | + |
| 212 | + intermediates := x509.NewCertPool() |
| 213 | + for _, der := range doc.CABundle { |
| 214 | + cert, err := x509.ParseCertificate(der) |
| 215 | + if err != nil { |
| 216 | + return nil, nil, err |
| 217 | + } |
| 218 | + intermediates.AddCert(cert) |
| 219 | + } |
| 220 | + return leafCert, intermediates, nil |
| 221 | +} |
| 222 | + |
| 223 | +func verifyECDSASignature(publicKey *ecdsa.PublicKey, sigStructure, signature []byte) bool { |
| 224 | + hash, ok := hashForCurve(publicKey, sigStructure) |
| 225 | + if !ok || len(signature) != 2*len(hash) { |
| 226 | + return false |
| 227 | + } |
| 228 | + |
| 229 | + r := new(big.Int).SetBytes(signature[:len(hash)]) |
| 230 | + s := new(big.Int).SetBytes(signature[len(hash):]) |
| 231 | + return ecdsa.Verify(publicKey, hash, r, s) |
| 232 | +} |
| 233 | + |
| 234 | +func hashForCurve(publicKey *ecdsa.PublicKey, sigStructure []byte) ([]byte, bool) { |
| 235 | + switch publicKey.Curve.Params().Name { |
| 236 | + case "P-224": |
| 237 | + sum := sha256.Sum224(sigStructure) |
| 238 | + return sum[:], true |
| 239 | + case "P-256": |
| 240 | + sum := sha256.Sum256(sigStructure) |
| 241 | + return sum[:], true |
| 242 | + case "P-384": |
| 243 | + sum := sha512.Sum384(sigStructure) |
| 244 | + return sum[:], true |
| 245 | + case "P-512": |
| 246 | + sum := sha512.Sum512(sigStructure) |
| 247 | + return sum[:], true |
| 248 | + default: |
| 249 | + return nil, false |
| 250 | + } |
| 251 | +} |
0 commit comments