| 1 |
// Package fake is a fake implementation of the Client interface for testing. |
| 2 |
package fake |
| 3 |
|
| 4 |
import ( |
| 5 |
"context" |
| 6 |
"crypto" |
| 7 |
"encoding/base64" |
| 8 |
"encoding/binary" |
| 9 |
"errors" |
| 10 |
"fmt" |
| 11 |
"strings" |
| 12 |
"time" |
| 13 |
|
| 14 |
"github.com/golang-jwt/jwt/v4" |
| 15 |
"github.com/google/go-eventlog/proto/state" |
| 16 |
"github.com/google/go-eventlog/register" |
| 17 |
tabi "github.com/google/go-tdx-guest/abi" |
| 18 |
tdxpb "github.com/google/go-tdx-guest/proto/tdx" |
| 19 |
"github.com/google/go-tdx-guest/rtmr" |
| 20 |
"github.com/google/go-tpm-tools/proto/attest" |
| 21 |
"github.com/google/go-tpm-tools/proto/tpm" |
| 22 |
"github.com/google/go-tpm-tools/server" |
| 23 |
"github.com/google/go-tpm-tools/verifier" |
| 24 |
"github.com/google/go-tpm-tools/verifier/oci" |
| 25 |
"github.com/google/go-tpm/legacy/tpm2" |
| 26 |
"google.golang.org/genproto/googleapis/rpc/code" |
| 27 |
"google.golang.org/genproto/googleapis/rpc/status" |
| 28 |
"google.golang.org/protobuf/encoding/protojson" |
| 29 |
) |
| 30 |
|
| 31 |
type fakeClient struct { |
| 32 |
signer crypto.Signer |
| 33 |
nonce []byte |
| 34 |
} |
| 35 |
|
| 36 |
// NewClient constructs a new fake client given a crypto.Signer. |
| 37 |
func NewClient(signer crypto.Signer) verifier.Client { |
| 38 |
nonce := make([]byte, 2) |
| 39 |
binary.LittleEndian.PutUint16(nonce, 15) |
| 40 |
|
| 41 |
// If signer is nil, test keys found in verifier/fake/ will be used. |
| 42 |
if signer == nil { |
| 43 |
signer = TestPrivateKey() |
| 44 |
} |
| 45 |
|
| 46 |
return &fakeClient{signer, nonce} |
| 47 |
} |
| 48 |
|
| 49 |
// CreateChallenge returns a hard coded, basic challenge. |
| 50 |
// |
| 51 |
// If you have found this method is insufficient for your tests, this class must be updated to |
| 52 |
// allow for better testing. |
| 53 |
func (fc *fakeClient) CreateChallenge(_ context.Context) (*verifier.Challenge, error) { |
| 54 |
return &verifier.Challenge{ |
| 55 |
Name: "projects/fakeProject/locations/fakeRegion/challenges/d882c62f-452f-4709-9335-0cccaf64eee1", |
| 56 |
Nonce: fc.nonce, |
| 57 |
}, nil |
| 58 |
} |
| 59 |
|
| 60 |
func verifyTDX(req verifier.VerifyAttestationRequest, nonce []byte) (*attest.MachineState, error) { |
| 61 |
tdQuote, err := tabi.QuoteToProto(req.TDCCELAttestation.TdQuote) |
| 62 |
if err != nil { |
| 63 |
return nil, fmt.Errorf("failed to marshal TdQuote: %v", err) |
| 64 |
} |
| 65 |
quoteV4, ok := tdQuote.(*tdxpb.QuoteV4) |
| 66 |
if !ok { |
| 67 |
return nil, errors.New("failed to convert TdQuote: not of type QuoteV4") |
| 68 |
} |
| 69 |
rtmrbank, err := rtmr.GetRtmrsFromTdQuote(quoteV4) |
| 70 |
if err != nil { |
| 71 |
return nil, err |
| 72 |
} |
| 73 |
cosState, err := server.ParseCosCELRTMR(req.TDCCELAttestation.CanonicalEventLog, *rtmrbank) |
| 74 |
if err != nil { |
| 75 |
return nil, fmt.Errorf("failed to validate the Canonical event log: %w", err) |
| 76 |
} |
| 77 |
opts := rtmr.TdxDefaultOpts(nonce) |
| 78 |
fls, err := rtmr.ParseCcelWithTdQuote(req.TDCCELAttestation.CcelData, req.TDCCELAttestation.CcelAcpiTable, quoteV4, &opts) |
| 79 |
if err != nil { |
| 80 |
return nil, fmt.Errorf("failed to parse CCEL: %w", err) |
| 81 |
} |
| 82 |
ms, err := server.ConvertToMachineState(fls) |
| 83 |
if err != nil { |
| 84 |
return nil, fmt.Errorf("failed to convert to MachineState: %w", err) |
| 85 |
} |
| 86 |
ms.Cos = cosState |
| 87 |
return ms, nil |
| 88 |
} |
| 89 |
|
| 90 |
func verifyTPM(req verifier.VerifyAttestationRequest, nonce []byte) (*attest.MachineState, error) { |
| 91 |
akPub, err := tpm2.DecodePublic(req.Attestation.GetAkPub()) |
| 92 |
if err != nil { |
| 93 |
return nil, fmt.Errorf("failed to decode AKPub as TPMT_PUBLIC: %v", err) |
| 94 |
} |
| 95 |
akCrypto, err := akPub.Key() |
| 96 |
if err != nil { |
| 97 |
return nil, fmt.Errorf("failed to convert TPMT_PUBLIC to crypto.PublicKey: %v", err) |
| 98 |
} |
| 99 |
ms, err := server.VerifyAttestation(req.Attestation, server.VerifyOpts{Nonce: nonce, TrustedAKs: []crypto.PublicKey{akCrypto}}) |
| 100 |
if err != nil { |
| 101 |
return nil, fmt.Errorf("failed to verify attestation: %v", err) |
| 102 |
} |
| 103 |
|
| 104 |
pcrBank, err := extractPCRBank(req.Attestation, ms.GetHash()) |
| 105 |
if err != nil { |
| 106 |
return nil, fmt.Errorf("failed to extract PCR bank: %w", err) |
| 107 |
} |
| 108 |
|
| 109 |
cosState, err := server.ParseCosCELPCR(req.Attestation.GetCanonicalEventLog(), *pcrBank) |
| 110 |
if err != nil { |
| 111 |
return nil, fmt.Errorf("failed to validate the Canonical event log: %w", err) |
| 112 |
} |
| 113 |
ms.Cos = cosState |
| 114 |
return ms, nil |
| 115 |
} |
| 116 |
|
| 117 |
// VerifyAttestation calls server.VerifyAttestation against the request's public key. |
| 118 |
// It returns the marshaled MachineState as a claim. |
| 119 |
func (fc *fakeClient) VerifyAttestation(_ context.Context, req verifier.VerifyAttestationRequest) (*verifier.VerifyAttestationResponse, error) { |
| 120 |
// Determine signing algorithm. |
| 121 |
signingMethod := jwt.SigningMethodRS256 |
| 122 |
now := jwt.TimeFunc() |
| 123 |
var ms *attest.MachineState |
| 124 |
var err error |
| 125 |
|
| 126 |
if req.TDCCELAttestation != nil { |
| 127 |
ms, err = verifyTDX(req, fc.nonce) |
| 128 |
if err != nil { |
| 129 |
return nil, err |
| 130 |
} |
| 131 |
} else if req.Attestation != nil { |
| 132 |
ms, err = verifyTPM(req, fc.nonce) |
| 133 |
if err != nil { |
| 134 |
return nil, err |
| 135 |
} |
| 136 |
} else { |
| 137 |
return nil, errors.New("contains no attestation in the request") |
| 138 |
} |
| 139 |
|
| 140 |
msJSON, err := protojson.Marshal(ms) |
| 141 |
if err != nil { |
| 142 |
return nil, fmt.Errorf("failed to convert proto object to JSON: %v", err) |
| 143 |
} |
| 144 |
|
| 145 |
audience := "https://sts.googleapis.com/" |
| 146 |
if req.TokenOptions != nil && req.TokenOptions.Audience != "" { |
| 147 |
audience = req.TokenOptions.Audience |
| 148 |
} |
| 149 |
|
| 150 |
claims := Claims{ |
| 151 |
RegisteredClaims: jwt.RegisteredClaims{ |
| 152 |
IssuedAt: &jwt.NumericDate{Time: now}, |
| 153 |
NotBefore: &jwt.NumericDate{Time: now}, |
| 154 |
ExpiresAt: &jwt.NumericDate{Time: now.Add(time.Hour)}, |
| 155 |
Audience: []string{audience}, |
| 156 |
Issuer: "fake-issuer-for-testing", |
| 157 |
Subject: "https://www.googleapis.com/compute/v1/projects/fakeProject/zones/fakeZone/instances/fakeInstance", |
| 158 |
}, |
| 159 |
MachineStateMarshaled: string(msJSON), |
| 160 |
OEMID: "fake-oem-id", |
| 161 |
HWModel: "fake-hw-model", |
| 162 |
SecBoot: true, |
| 163 |
SWName: "fake-sw-name", |
| 164 |
} |
| 165 |
|
| 166 |
var signatureClaims []ContainerImageSignatureClaims |
| 167 |
var partialErrs []*status.Status |
| 168 |
for _, signature := range req.ContainerImageSignatures { |
| 169 |
claims, err := extractClaims(signature) |
| 170 |
if err != nil { |
| 171 |
partialErrs = append(partialErrs, &status.Status{Code: int32(code.Code_INVALID_ARGUMENT), Message: err.Error()}) |
| 172 |
} else { |
| 173 |
signatureClaims = append(signatureClaims, claims) |
| 174 |
} |
| 175 |
} |
| 176 |
claims.ContainerImageSignatures = signatureClaims |
| 177 |
|
| 178 |
token := jwt.NewWithClaims(signingMethod, claims) |
| 179 |
|
| 180 |
// Instead of a private key, provide the signer. |
| 181 |
signed, err := token.SignedString(fc.signer) |
| 182 |
if err != nil { |
| 183 |
return nil, err |
| 184 |
} |
| 185 |
|
| 186 |
response := verifier.VerifyAttestationResponse{ |
| 187 |
ClaimsToken: []byte(signed), |
| 188 |
PartialErrs: partialErrs, |
| 189 |
} |
| 190 |
|
| 191 |
return &response, nil |
| 192 |
} |
| 193 |
|
| 194 |
// VerifyConfidentialSpace is identical in behavior to VerifyAttestation, necessary for implementing verifier.Client. |
| 195 |
func (fc *fakeClient) VerifyConfidentialSpace(ctx context.Context, req verifier.VerifyAttestationRequest) (*verifier.VerifyAttestationResponse, error) { |
| 196 |
return fc.VerifyAttestation(ctx, req) |
| 197 |
} |
| 198 |
|
| 199 |
type payload struct { |
| 200 |
Optional map[string]any `json:"optional"` // Optional represents optional metadata about the image, and its value shouldn't contain any "=" signs. |
| 201 |
} |
| 202 |
|
| 203 |
func isValid(alg string) bool { |
| 204 |
switch alg { |
| 205 |
case string(oci.ECDSAP256SHA256), string(oci.RSASSAPKCS1V152048SHA256), string(oci.RSASSAPSS2048SHA256): |
| 206 |
return true |
| 207 |
default: |
| 208 |
return false |
| 209 |
} |
| 210 |
} |
| 211 |
|
| 212 |
// Note: this is only compatible with the fake signature implementation. |
| 213 |
func extractClaims(signature *verifier.ContainerSignature) (ContainerImageSignatureClaims, error) { |
| 214 |
payloadStr := string(signature.Payload) |
| 215 |
|
| 216 |
// Fake payload consists of the expected pubkey and sigalg separated by a comma. |
| 217 |
separatorIndex := strings.LastIndex(payloadStr, ",") |
| 218 |
|
| 219 |
sigAlg := payloadStr[separatorIndex+1:] |
| 220 |
if !isValid(sigAlg) { |
| 221 |
return ContainerImageSignatureClaims{}, fmt.Errorf("unsupported algorithm %v", sigAlg) |
| 222 |
} |
| 223 |
|
| 224 |
return ContainerImageSignatureClaims{ |
| 225 |
Payload: payloadStr, |
| 226 |
Signature: base64.StdEncoding.EncodeToString(signature.Signature), |
| 227 |
PubKey: payloadStr[:separatorIndex], |
| 228 |
SigAlg: sigAlg, |
| 229 |
}, nil |
| 230 |
} |
| 231 |
|
| 232 |
// extractPCRBank finds the quote matching the given hash algorithm and returns the PCR bank. |
| 233 |
func extractPCRBank(attestation *attest.Attestation, hashAlgo tpm.HashAlgo) (*register.PCRBank, error) { |
| 234 |
for _, quote := range attestation.GetQuotes() { |
| 235 |
pcrs := quote.GetPcrs() |
| 236 |
if pcrs.GetHash() == hashAlgo { |
| 237 |
pcrBank := ®ister.PCRBank{TCGHashAlgo: state.HashAlgo(pcrs.Hash)} |
| 238 |
digestAlg, err := pcrBank.TCGHashAlgo.CryptoHash() |
| 239 |
if err != nil { |
| 240 |
return nil, fmt.Errorf("invalid digest algorithm: %w", err) |
| 241 |
} |
| 242 |
|
| 243 |
for pcrIndex, digest := range pcrs.GetPcrs() { |
| 244 |
pcrBank.PCRs = append(pcrBank.PCRs, register.PCR{ |
| 245 |
Index: int(pcrIndex), |
| 246 |
Digest: digest, |
| 247 |
DigestAlg: digestAlg}) |
| 248 |
} |
| 249 |
return pcrBank, nil |
| 250 |
} |
| 251 |
} |
| 252 |
return nil, fmt.Errorf("no PCRs found matching hash %s", hashAlgo.String()) |
| 253 |
} |