| 1 |
package server |
| 2 |
|
| 3 |
import ( |
| 4 |
"crypto" |
| 5 |
"crypto/x509" |
| 6 |
"crypto/x509/pkix" |
| 7 |
"encoding/asn1" |
| 8 |
"errors" |
| 9 |
"fmt" |
| 10 |
"slices" |
| 11 |
|
| 12 |
"github.com/google/go-tpm-tools/internal" |
| 13 |
pb "github.com/google/go-tpm-tools/proto/attest" |
| 14 |
tpmpb "github.com/google/go-tpm-tools/proto/tpm" |
| 15 |
"github.com/google/go-tpm/legacy/tpm2" |
| 16 |
"google.golang.org/protobuf/proto" |
| 17 |
) |
| 18 |
|
| 19 |
var ( |
| 20 |
errSHA1NotAllowed = fmt.Errorf("SHA-1 is not allowed for verification (set VerifyOpts.AllowSHA1 to true to allow)") |
| 21 |
errNoSupportedQuote = fmt.Errorf("attestation does not contain a supported quote") |
| 22 |
) |
| 23 |
|
| 24 |
// We conditionally support SHA-1 for PCR hashes, but at the lowest priority. |
| 25 |
var pcrHashAlgs = append(internal.SignatureHashAlgs, tpm2.AlgSHA1) |
| 26 |
|
| 27 |
var oidExtensionSubjectAltName = []int{2, 5, 29, 17} |
| 28 |
|
| 29 |
var cloudComputeInstanceIdentifierOID asn1.ObjectIdentifier = []int{1, 3, 6, 1, 4, 1, 11129, 2, 1, 21} |
| 30 |
|
| 31 |
// VerifyOpts allows for customizing the functionality of VerifyAttestation. |
| 32 |
type VerifyOpts struct { |
| 33 |
// The nonce used when calling client.Attest |
| 34 |
Nonce []byte |
| 35 |
// Trusted public keys that can be used to directly verify the key used for |
| 36 |
// attestation. This option should be used if you already know the AK, as |
| 37 |
// it provides the highest level of assurance. |
| 38 |
TrustedAKs []crypto.PublicKey |
| 39 |
// Allow using SHA-1 PCRs to verify attestations. This defaults to false |
| 40 |
// because SHA-1 is a weak hash algorithm with known collision attacks. |
| 41 |
// However, setting this to true may be necessary if the client only |
| 42 |
// supports the legacy event log format. This is the case on older Linux |
| 43 |
// distributions (such as Debian 10). Note that this will NOT allow |
| 44 |
// SHA-1 signatures to be used, just SHA-1 PCRs. |
| 45 |
AllowSHA1 bool |
| 46 |
// A collection of trusted root CAs that are used to sign AK certificates. |
| 47 |
// The TrustedAKs are used first, followed by TrustRootCerts and |
| 48 |
// IntermediateCerts. |
| 49 |
// Adding a specific TPM manufacturer's root and intermediate CAs means all |
| 50 |
// TPMs signed by that CA will be trusted. |
| 51 |
// To trust the MachineState's GCE instance_info, the caller MUST use |
| 52 |
// authentic Google-signed certificates provided in server/ca-certs |
| 53 |
// OR fetched via |
| 54 |
// https://privateca-content-62d71773-0000-21da-852e-f4f5e80d7778.storage.googleapis.com/032bf9d39db4fa06aade/ca.crt |
| 55 |
// https://pki.goog/cloud_integrity/tpm_ek_root_1.crt. |
| 56 |
TrustedRootCerts []*x509.Certificate |
| 57 |
IntermediateCerts []*x509.Certificate |
| 58 |
// Which bootloader the instance uses. Pick UNSUPPORTED to skip this |
| 59 |
// parsing or for unsupported bootloaders (e.g., systemd). |
| 60 |
Loader Bootloader |
| 61 |
// TEEOpts allows customizing the functionality of VerifyTEEAttestation. |
| 62 |
// Its type can be *VerifySnpOpts if the TEEAttestation is a SevSnpAttestation |
| 63 |
// or can be *VerifyTdxOpts if the TEEAttestation is a TdxAttestation |
| 64 |
// If nil, uses Nonce for ReportData and the TEE's verification library's |
| 65 |
// embedded root certs for its roots of trust. |
| 66 |
// |
| 67 |
// Deprecated: go-tpm-tools no longer verifies SNP or TDX attestation. |
| 68 |
// Please use go-sev-guest and go-tdx-guest. |
| 69 |
TEEOpts interface{} |
| 70 |
// AllowEFIAppBeforeCallingEvent skips a check that requires |
| 71 |
// EV_EFI_BOOT_SERVICES_APPLICATION to occur after a |
| 72 |
// "Calling EFI Application from Boot Option". This option is useful when |
| 73 |
// the host platform loads EFI Applications unrelated to OS boot. |
| 74 |
AllowEFIAppBeforeCallingEvent bool |
| 75 |
// AllowEmptySBVar allows the SecureBoot variable to be empty in addition |
| 76 |
// to length 1 (0 or 1) during eventlog parsing. |
| 77 |
// This can be used when the SecureBoot variable is not initialized. |
| 78 |
AllowEmptySBVar bool |
| 79 |
// The TPM hash algorithm to use to verify attestations. |
| 80 |
// SHA512, SHA384, SHA256, and SHA1 are supported. To use SHA1, also set |
| 81 |
// AllowSHA1. |
| 82 |
// If HashAlgo is the zero value (tpm2.AlgUnknown), VerifyAttestation will |
| 83 |
// try all supported hashes in the order [SHA512 SHA384 SHA256 SHA1] until |
| 84 |
// one quote and eventlog is successfully verified. |
| 85 |
HashAlgo tpm2.Algorithm |
| 86 |
} |
| 87 |
|
| 88 |
// Bootloader refers to the second-stage bootloader that loads and transfers |
| 89 |
// execution to the OS kernel. |
| 90 |
type Bootloader int |
| 91 |
|
| 92 |
const ( |
| 93 |
// UnsupportedLoader refers to a second-stage bootloader that is of an |
| 94 |
// unsupported type. VerifyAttestation will not parse the PCClient Event Log |
| 95 |
// for bootloader events. |
| 96 |
UnsupportedLoader Bootloader = iota |
| 97 |
// GRUB (https://www.gnu.org/software/grub/). |
| 98 |
GRUB |
| 99 |
) |
| 100 |
|
| 101 |
// TODO: Change int64 fields to uint64 when compatible with ASN1 parsing. |
| 102 |
type gceSecurityProperties struct { |
| 103 |
SecurityVersion int64 `asn1:"explicit,tag:0,optional"` |
| 104 |
IsProduction bool `asn1:"explicit,tag:1,optional"` |
| 105 |
} |
| 106 |
|
| 107 |
type gceInstanceInfo struct { |
| 108 |
Zone string `asn1:"utf8"` |
| 109 |
ProjectNumber int64 |
| 110 |
ProjectID string `asn1:"utf8"` |
| 111 |
InstanceID int64 |
| 112 |
InstanceName string `asn1:"utf8"` |
| 113 |
SecurityProperties gceSecurityProperties `asn1:"explicit,optional"` |
| 114 |
} |
| 115 |
|
| 116 |
// VerifyAttestation performs the following checks on an Attestation: |
| 117 |
// - the AK used to generate the attestation is trusted (based on VerifyOpts) |
| 118 |
// - the provided signature is generated by the trusted AK public key |
| 119 |
// - the signature signs the provided quote data |
| 120 |
// - the quote data starts with TPM_GENERATED_VALUE |
| 121 |
// - the quote data is a valid TPMS_QUOTE_INFO |
| 122 |
// - the quote data was taken over the provided PCRs |
| 123 |
// - the provided PCR values match the quote data internal digest |
| 124 |
// - the provided opts.Nonce matches that in the quote data |
| 125 |
// - the provided eventlog matches the provided PCR values |
| 126 |
// |
| 127 |
// After this, the eventlog is parsed and the corresponding MachineState is |
| 128 |
// returned. This design prevents unverified MachineStates from being used. |
| 129 |
func VerifyAttestation(attestation *pb.Attestation, opts VerifyOpts) (*pb.MachineState, error) { |
| 130 |
if err := validateOpts(opts); err != nil { |
| 131 |
return nil, fmt.Errorf("bad options: %w", err) |
| 132 |
} |
| 133 |
|
| 134 |
machineState, akPubKey, err := validateAK(attestation, opts) |
| 135 |
if err != nil { |
| 136 |
return nil, fmt.Errorf("failed to parse and validate AK: %w", err) |
| 137 |
} |
| 138 |
|
| 139 |
var algos []tpm2.Algorithm |
| 140 |
if opts.HashAlgo != tpm2.AlgUnknown { |
| 141 |
if err := supportedAlgo(opts.HashAlgo); err != nil { |
| 142 |
return nil, err |
| 143 |
} |
| 144 |
algos = append(algos, opts.HashAlgo) |
| 145 |
} else { |
| 146 |
algos = pcrHashAlgs |
| 147 |
} |
| 148 |
|
| 149 |
// Attempt to replay the log against our PCRs in order of hash preference |
| 150 |
var lastErr error |
| 151 |
for _, quote := range supportedQuotes(attestation.GetQuotes(), algos) { |
| 152 |
// Verify the Quote |
| 153 |
if err := internal.VerifyQuote(quote, akPubKey, opts.Nonce); err != nil { |
| 154 |
lastErr = fmt.Errorf("failed to verify quote: %w", err) |
| 155 |
continue |
| 156 |
} |
| 157 |
|
| 158 |
// Parse event logs and replay the events against the provided PCRs |
| 159 |
pcrs := quote.GetPcrs() |
| 160 |
tpmMachineState, err := parseMachineStateFromTPM(attestation, pcrs, opts) |
| 161 |
if err != nil { |
| 162 |
lastErr = fmt.Errorf("failed to parse machine state from TCG event log: %w", err) |
| 163 |
continue |
| 164 |
} |
| 165 |
|
| 166 |
// Verify the PCR hash algorithm. We have this check here (instead of at |
| 167 |
// the start of the loop) so that the user gets a "SHA-1 not supported" |
| 168 |
// error only if allowing SHA-1 support would actually allow the log |
| 169 |
// to be verified. This makes debugging failed verifications easier. |
| 170 |
if !opts.AllowSHA1 && tpm2.Algorithm(pcrs.GetHash()) == tpm2.AlgSHA1 { |
| 171 |
lastErr = errSHA1NotAllowed |
| 172 |
continue |
| 173 |
} |
| 174 |
|
| 175 |
proto.Merge(machineState, tpmMachineState) |
| 176 |
|
| 177 |
return machineState, nil |
| 178 |
} |
| 179 |
|
| 180 |
if lastErr != nil { |
| 181 |
return nil, lastErr |
| 182 |
} |
| 183 |
return nil, errNoSupportedQuote |
| 184 |
} |
| 185 |
|
| 186 |
// validateAK validates AK cert in the attestation, and returns AK cert (if exists) and public key. |
| 187 |
// It also pulls out the GCE Instance Info if it exists. |
| 188 |
func validateAK(attestation *pb.Attestation, opts VerifyOpts) (*pb.MachineState, crypto.PublicKey, error) { |
| 189 |
if len(attestation.GetAkCert()) == 0 || len(opts.TrustedRootCerts) == 0 { |
| 190 |
// If the AK Cert is not in the attestation, use the AK Public Area. |
| 191 |
akPubArea, err := tpm2.DecodePublic(attestation.GetAkPub()) |
| 192 |
if err != nil { |
| 193 |
return nil, nil, fmt.Errorf("failed to decode AK public area: %w", err) |
| 194 |
} |
| 195 |
akPubKey, err := akPubArea.Key() |
| 196 |
if err != nil { |
| 197 |
return nil, nil, fmt.Errorf("failed to get AK public key: %w", err) |
| 198 |
} |
| 199 |
if err := validateAKPub(akPubKey, opts); err != nil { |
| 200 |
return nil, nil, fmt.Errorf("failed to validate AK public key: %w", err) |
| 201 |
} |
| 202 |
return &pb.MachineState{}, akPubKey, nil |
| 203 |
} |
| 204 |
|
| 205 |
// If AK Cert is presented, ignore the AK Public Area. |
| 206 |
akCert, err := x509.ParseCertificate(attestation.GetAkCert()) |
| 207 |
if err != nil { |
| 208 |
return nil, nil, fmt.Errorf("failed to parse AK certificate: %w", err) |
| 209 |
} |
| 210 |
// Use intermediate certs from the attestation if they exist. |
| 211 |
certs, err := parseCerts(attestation.IntermediateCerts) |
| 212 |
if err != nil { |
| 213 |
return nil, nil, fmt.Errorf("attestation intermediates: %w", err) |
| 214 |
} |
| 215 |
opts.IntermediateCerts = append(opts.IntermediateCerts, certs...) |
| 216 |
|
| 217 |
if err := VerifyAKCert(akCert, opts.TrustedRootCerts, opts.IntermediateCerts); err != nil { |
| 218 |
return nil, nil, fmt.Errorf("failed to validate AK certificate: %w", err) |
| 219 |
} |
| 220 |
instanceInfo, err := getInstanceInfoFromExtensions(akCert.Extensions) |
| 221 |
if err != nil { |
| 222 |
return nil, nil, fmt.Errorf("error getting instance info: %v", err) |
| 223 |
} |
| 224 |
|
| 225 |
return &pb.MachineState{Platform: &pb.PlatformState{InstanceInfo: instanceInfo}}, akCert.PublicKey, nil |
| 226 |
} |
| 227 |
|
| 228 |
// GetGCEInstanceInfo takes a GCE-issued x509 EK/AK certificate and tries to |
| 229 |
// extract its GCE instance information. It returns an error if the cert is nil |
| 230 |
// or malformed, but it does not return an error if the cert does not contain |
| 231 |
// the GCE Instance OID. |
| 232 |
// The caller must first `ValidateAKCert` using a GCE EK Certificate root CA. |
| 233 |
func GetGCEInstanceInfo(cert *x509.Certificate) (*pb.GCEInstanceInfo, error) { |
| 234 |
if cert == nil { |
| 235 |
return nil, errors.New("cannot extract GCEInstanceInfo from a nil cert") |
| 236 |
} |
| 237 |
return getInstanceInfoFromExtensions(cert.Extensions) |
| 238 |
} |
| 239 |
|
| 240 |
func getInstanceInfoFromExtensions(extensions []pkix.Extension) (*pb.GCEInstanceInfo, error) { |
| 241 |
var rawInfo []byte |
| 242 |
for _, ext := range extensions { |
| 243 |
if ext.Id.Equal(cloudComputeInstanceIdentifierOID) { |
| 244 |
rawInfo = ext.Value |
| 245 |
break |
| 246 |
} |
| 247 |
} |
| 248 |
|
| 249 |
// If GCE Instance Info extension is not found. |
| 250 |
if len(rawInfo) == 0 { |
| 251 |
return nil, nil |
| 252 |
} |
| 253 |
|
| 254 |
info := gceInstanceInfo{} |
| 255 |
if _, err := asn1.Unmarshal(rawInfo, &info); err != nil { |
| 256 |
return nil, fmt.Errorf("failed to parse GCE Instance Information Extension: %w", err) |
| 257 |
} |
| 258 |
|
| 259 |
// TODO: Remove when fields are changed to uint64. |
| 260 |
if info.ProjectNumber < 0 || info.InstanceID < 0 || info.SecurityProperties.SecurityVersion < 0 { |
| 261 |
return nil, fmt.Errorf("negative integer fields found in GCE Instance Information Extension") |
| 262 |
} |
| 263 |
|
| 264 |
// Check production. |
| 265 |
if !info.SecurityProperties.IsProduction { |
| 266 |
return nil, nil |
| 267 |
} |
| 268 |
|
| 269 |
return &pb.GCEInstanceInfo{ |
| 270 |
Zone: info.Zone, |
| 271 |
ProjectId: info.ProjectID, |
| 272 |
ProjectNumber: uint64(info.ProjectNumber), |
| 273 |
InstanceName: info.InstanceName, |
| 274 |
InstanceId: uint64(info.InstanceID), |
| 275 |
}, nil |
| 276 |
} |
| 277 |
|
| 278 |
// Check that we are passing in a valid VerifyOpts structure |
| 279 |
func validateOpts(opts VerifyOpts) error { |
| 280 |
checkPub := len(opts.TrustedAKs) > 0 |
| 281 |
checkCert := len(opts.TrustedRootCerts) > 0 |
| 282 |
if !checkPub && !checkCert { |
| 283 |
return fmt.Errorf("no trust mechanism provided, either use TrustedAKs or TrustedRootCerts") |
| 284 |
} |
| 285 |
if checkPub && checkCert { |
| 286 |
return fmt.Errorf("multiple trust mechanisms provided, only use one of TrustedAKs or TrustedRootCerts") |
| 287 |
} |
| 288 |
return nil |
| 289 |
} |
| 290 |
|
| 291 |
func validateAKPub(ak crypto.PublicKey, opts VerifyOpts) error { |
| 292 |
for _, trusted := range opts.TrustedAKs { |
| 293 |
if internal.PubKeysEqual(ak, trusted) { |
| 294 |
return nil |
| 295 |
} |
| 296 |
} |
| 297 |
return fmt.Errorf("key not trusted") |
| 298 |
} |
| 299 |
|
| 300 |
// VerifyAKCert checks a given Attestation Key certificate against the provided |
| 301 |
// root and intermediate CAs. |
| 302 |
func VerifyAKCert(akCert *x509.Certificate, trustedRootCerts []*x509.Certificate, intermediateCerts []*x509.Certificate) error { |
| 303 |
if akCert == nil { |
| 304 |
return errors.New("failed to validate AK Cert: received nil cert") |
| 305 |
} |
| 306 |
if len(trustedRootCerts) == 0 { |
| 307 |
return errors.New("failed to validate AK Cert: received no trusted root certs") |
| 308 |
} |
| 309 |
|
| 310 |
// We manually handle the SAN extension because x509 marks it unhandled if |
| 311 |
// SAN does not parse any of DNSNames, EmailAddresses, IPAddresses, or URIs. |
| 312 |
// https://cs.opensource.google/go/go/+/master:src/crypto/x509/parser.go;l=668-678 |
| 313 |
var exts []asn1.ObjectIdentifier |
| 314 |
for _, ext := range akCert.UnhandledCriticalExtensions { |
| 315 |
if ext.Equal(oidExtensionSubjectAltName) { |
| 316 |
continue |
| 317 |
} |
| 318 |
exts = append(exts, ext) |
| 319 |
} |
| 320 |
akCert.UnhandledCriticalExtensions = exts |
| 321 |
|
| 322 |
x509Opts := x509.VerifyOptions{ |
| 323 |
Roots: makePool(trustedRootCerts), |
| 324 |
Intermediates: makePool(intermediateCerts), |
| 325 |
// The default key usage (ExtKeyUsageServerAuth) is not appropriate for |
| 326 |
// an Attestation Key: ExtKeyUsage of |
| 327 |
// - https://oidref.com/2.23.133.8.1 |
| 328 |
// - https://oidref.com/2.23.133.8.3 |
| 329 |
// https://pkg.go.dev/crypto/x509#VerifyOptions |
| 330 |
KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsage(x509.ExtKeyUsageAny)}, |
| 331 |
} |
| 332 |
if _, err := akCert.Verify(x509Opts); err != nil { |
| 333 |
return fmt.Errorf("certificate did not chain to a trusted root: %v", err) |
| 334 |
} |
| 335 |
|
| 336 |
return nil |
| 337 |
} |
| 338 |
|
| 339 |
func supportedAlgo(algo tpm2.Algorithm) error { |
| 340 |
if slices.Contains(pcrHashAlgs, algo) { |
| 341 |
return nil |
| 342 |
} |
| 343 |
return fmt.Errorf("hash algorithm %s is not supported, use one of %s", algo, pcrHashAlgs) |
| 344 |
} |
| 345 |
|
| 346 |
// Retrieve the supported quotes in order of preference based on supportedAlgos. |
| 347 |
func supportedQuotes(quotes []*tpmpb.Quote, supportedAlgos []tpm2.Algorithm) []*tpmpb.Quote { |
| 348 |
out := make([]*tpmpb.Quote, 0, len(quotes)) |
| 349 |
for _, alg := range supportedAlgos { |
| 350 |
for _, quote := range quotes { |
| 351 |
if tpm2.Algorithm(quote.GetPcrs().GetHash()) == alg { |
| 352 |
out = append(out, quote) |
| 353 |
break |
| 354 |
} |
| 355 |
} |
| 356 |
} |
| 357 |
return out |
| 358 |
} |
| 359 |
|
| 360 |
func makePool(certs []*x509.Certificate) *x509.CertPool { |
| 361 |
pool := x509.NewCertPool() |
| 362 |
for _, cert := range certs { |
| 363 |
pool.AddCert(cert) |
| 364 |
} |
| 365 |
return pool |
| 366 |
} |
| 367 |
|
| 368 |
// parseMachineStateFromTPM is a wrapper function around `parsePCClientEventLog` method to: |
| 369 |
// 1. parse partial machine state from TPM TCG event logs. |
| 370 |
// 2. verify GceTechnology since the GCE Technology event is directly related to the TPM. |
| 371 |
// 3. populate the machineState TeeAttestatation field with the verified TDX/SNP attestation data. |
| 372 |
func parseMachineStateFromTPM(attestation *pb.Attestation, pcrs *tpmpb.PCRs, opts VerifyOpts) (*pb.MachineState, error) { |
| 373 |
ms, err := parsePCClientEventLog(attestation.GetEventLog(), pcrs, opts) |
| 374 |
if err != nil { |
| 375 |
return nil, fmt.Errorf("failed to validate the PCClient event log: %w", err) |
| 376 |
} |
| 377 |
return ms, nil |
| 378 |
} |