Debian Codegraph @

verifier/rest/rest.go

raw
1 // Package rest contains the code to use the REST-based Google API
2 package rest
3
4 import (
5 "context"
6 "encoding/base64"
7 "fmt"
8 "log"
9 "time"
10
11 sabi "github.com/google/go-sev-guest/abi"
12 spb "github.com/google/go-sev-guest/proto/sevsnp"
13 tabi "github.com/google/go-tdx-guest/abi"
14 tpb "github.com/google/go-tdx-guest/proto/tdx"
15 "github.com/google/go-tpm-tools/verifier"
16 "github.com/google/go-tpm-tools/verifier/models"
17 "github.com/googleapis/gax-go/v2"
18
19 v1 "cloud.google.com/go/confidentialcomputing/apiv1"
20 ccpb "cloud.google.com/go/confidentialcomputing/apiv1/confidentialcomputingpb"
21 "google.golang.org/api/iterator"
22 "google.golang.org/api/option"
23 locationpb "google.golang.org/genproto/googleapis/cloud/location"
24 "google.golang.org/grpc/codes"
25 )
26
27 /*
28 confComputeCallOptions retries as follows for all confidential computing APIs:
29
30 Timeout = 1000 milliseconds
31 Initial interval = 500 milliseconds
32 Maximum interval = 1000 milliseconds
33 Maximum retries = 2
34 */
35 func confComputeCallOptions() *v1.CallOptions {
36 callOption := []gax.CallOption{
37 gax.WithTimeout(1000 * time.Millisecond),
38 gax.WithRetry(func() gax.Retryer {
39 return gax.OnCodes([]codes.Code{
40 codes.Unavailable,
41 codes.Internal,
42 }, gax.Backoff{
43 Initial: 500 * time.Millisecond,
44 Max: 1000 * time.Millisecond,
45 Multiplier: 2.0,
46 })
47 }),
48 }
49 return &v1.CallOptions{
50 CreateChallenge: callOption,
51 VerifyAttestation: callOption,
52 GetLocation: callOption,
53 ListLocations: callOption,
54 }
55 }
56
57 // NewClient creates a new REST client which is configured to perform
58 // attestations in a particular project and region. Returns a *BadRegionError
59 // if the requested project is valid, but the region is invalid.
60 func NewClient(ctx context.Context, projectID string, region string, opts ...option.ClientOption) (verifier.Client, error) {
61 client, err := v1.NewRESTClient(ctx, opts...)
62 if err != nil {
63 return nil, fmt.Errorf("can't create ConfidentialComputing v1 API client: %w", err)
64 }
65
66 // Override the default retry CallOptions with specific retry policies.
67 client.CallOptions = confComputeCallOptions()
68
69 projectName := fmt.Sprintf("projects/%s", projectID)
70 locationName := fmt.Sprintf("%s/locations/%v", projectName, region)
71
72 getReq := &locationpb.GetLocationRequest{
73 Name: locationName,
74 }
75 location, getErr := client.GetLocation(ctx, getReq)
76 if getErr == nil {
77 return &restClient{client, location}, nil
78 }
79
80 // If we can't get the location, try to list the locations. This handles
81 // situations where the projectID is invalid.
82 listReq := &locationpb.ListLocationsRequest{
83 Name: projectName,
84 }
85 listIter := client.ListLocations(ctx, listReq)
86
87 // The project is valid, but can't get the desired region.
88 var regions []string
89 for {
90 resp, err := listIter.Next()
91 if err == iterator.Done {
92 break
93 }
94 if err != nil {
95 return nil, fmt.Errorf("listing regions in project %q: %w", projectID, err)
96 }
97 regions = append(regions, resp.LocationId)
98 }
99 return nil, &BadRegionError{
100 RequestedRegion: region,
101 AvailableRegions: regions,
102 err: getErr,
103 }
104 }
105
106 type restClient struct {
107 v1Client *v1.Client
108 location *locationpb.Location
109 }
110
111 // CreateChallenge implements verifier.Client
112 func (c *restClient) CreateChallenge(ctx context.Context) (*verifier.Challenge, error) {
113 // Pass an empty Challenge for the input (all params are output-only)
114 req := &ccpb.CreateChallengeRequest{
115 Parent: c.location.Name,
116 Challenge: &ccpb.Challenge{},
117 }
118 chal, err := c.v1Client.CreateChallenge(ctx, req)
119 if err != nil {
120 return nil, fmt.Errorf("calling v1.CreateChallenge in %v: %w", c.location.LocationId, err)
121 }
122 return convertChallengeFromREST(chal)
123 }
124
125 // VerifyAttestation implements verifier.Client
126 func (c *restClient) VerifyAttestation(ctx context.Context, request verifier.VerifyAttestationRequest) (*verifier.VerifyAttestationResponse, error) {
127 if request.Challenge == nil {
128 return nil, fmt.Errorf("nil value provided in challenge")
129 }
130
131 if request.Attestation == nil && request.TDCCELAttestation == nil {
132 return nil, fmt.Errorf("neither TPM nor TDX attestation is present")
133 }
134
135 req := convertRequestToREST(request)
136 req.Challenge = request.Challenge.Name
137
138 response, err := c.v1Client.VerifyAttestation(ctx, req)
139 if err != nil {
140 return nil, fmt.Errorf("calling v1.VerifyAttestation in %v: %w", c.location.LocationId, err)
141 }
142 return convertResponseFromREST(response)
143 }
144
145 func (c *restClient) VerifyConfidentialSpace(ctx context.Context, request verifier.VerifyAttestationRequest) (*verifier.VerifyAttestationResponse, error) {
146 if request.Challenge == nil {
147 return nil, fmt.Errorf("nil value provided in challenge")
148 }
149
150 if request.Attestation == nil && request.TDCCELAttestation == nil {
151 return nil, fmt.Errorf("neither TPM nor TDX attestation is present")
152 }
153
154 csReq := convertCSRequestToREST(request)
155 csReq.Challenge = request.Challenge.Name
156
157 response, err := c.v1Client.VerifyConfidentialSpace(ctx, csReq)
158 if err != nil {
159 return nil, fmt.Errorf("calling v1.VerifyConfidentialSpace in %v: %w", c.location.LocationId, err)
160 }
161
162 return convertCSResponseFromREST(response), nil
163 }
164
165 var encoding = base64.StdEncoding
166
167 func convertChallengeFromREST(chal *ccpb.Challenge) (*verifier.Challenge, error) {
168 nonce, err := encoding.DecodeString(chal.TpmNonce)
169 if err != nil {
170 return nil, fmt.Errorf("failed to decode Challenge.Nonce: %w", err)
171 }
172 return &verifier.Challenge{
173 Name: chal.Name,
174 Nonce: nonce,
175 }, nil
176 }
177
178 func convertTokenOptionsToREST(tokenOpts *models.TokenOptions) *ccpb.TokenOptions {
179 if tokenOpts == nil {
180 return nil
181 }
182
183 optsPb := &ccpb.TokenOptions{
184 Audience: tokenOpts.Audience,
185 Nonce: tokenOpts.Nonces,
186 }
187
188 switch tokenOpts.TokenType {
189 case "OIDC":
190 optsPb.TokenType = ccpb.TokenType_TOKEN_TYPE_OIDC
191 case "PKI":
192 optsPb.TokenType = ccpb.TokenType_TOKEN_TYPE_PKI
193 case "LIMITED_AWS":
194 optsPb.TokenType = ccpb.TokenType_TOKEN_TYPE_LIMITED_AWS
195 case "AWS_PRINCIPALTAGS":
196 optsPb.TokenType = ccpb.TokenType_TOKEN_TYPE_AWS_PRINCIPALTAGS
197 optsPb.TokenTypeOptions = setAwsPrincipalTagOptions(tokenOpts)
198 default:
199 optsPb.TokenType = ccpb.TokenType_TOKEN_TYPE_UNSPECIFIED
200 }
201
202 return optsPb
203 }
204
205 func convertRequestToREST(request verifier.VerifyAttestationRequest) *ccpb.VerifyAttestationRequest {
206 idTokens := make([]string, len(request.GcpCredentials))
207 for i, token := range request.GcpCredentials {
208 idTokens[i] = string(token)
209 }
210
211 signatures := make([]*ccpb.ContainerImageSignature, len(request.ContainerImageSignatures))
212 for i, sig := range request.ContainerImageSignatures {
213 signatures[i] = &ccpb.ContainerImageSignature{
214 Payload: sig.Payload,
215 Signature: sig.Signature,
216 }
217 }
218
219 verifyReq := &ccpb.VerifyAttestationRequest{
220 GcpCredentials: &ccpb.GcpCredentials{
221 ServiceAccountIdTokens: idTokens,
222 },
223 ConfidentialSpaceInfo: &ccpb.ConfidentialSpaceInfo{
224 SignedEntities: []*ccpb.SignedEntity{{ContainerImageSignatures: signatures}},
225 },
226 TokenOptions: convertTokenOptionsToREST(request.TokenOptions),
227 }
228
229 if request.Attestation != nil {
230 // TPM attestation route
231 quotes := make([]*ccpb.TpmAttestation_Quote, len(request.Attestation.GetQuotes()))
232 for i, quote := range request.Attestation.GetQuotes() {
233 pcrVals := map[int32][]byte{}
234 for idx, val := range quote.GetPcrs().GetPcrs() {
235 pcrVals[int32(idx)] = val
236 }
237
238 quotes[i] = &ccpb.TpmAttestation_Quote{
239 RawQuote: quote.GetQuote(),
240 RawSignature: quote.GetRawSig(),
241 HashAlgo: int32(quote.GetPcrs().GetHash()),
242 PcrValues: pcrVals,
243 }
244 }
245
246 certs := make([][]byte, len(request.Attestation.GetIntermediateCerts()))
247 for i, cert := range request.Attestation.GetIntermediateCerts() {
248 certs[i] = cert
249 }
250
251 verifyReq.TpmAttestation = &ccpb.TpmAttestation{
252 Quotes: quotes,
253 TcgEventLog: request.Attestation.GetEventLog(),
254 CanonicalEventLog: request.Attestation.GetCanonicalEventLog(),
255 AkCert: request.Attestation.GetAkCert(),
256 CertChain: certs,
257 }
258
259 if request.Attestation.GetSevSnpAttestation() != nil {
260 sevsnp, err := convertSEVSNPProtoToREST(request.Attestation.GetSevSnpAttestation())
261 if err != nil {
262 log.Fatalf("Failed to convert SEVSNP proto to API proto: %v", err)
263 }
264 verifyReq.TeeAttestation = sevsnp
265 }
266
267 if request.Attestation.GetTdxAttestation() != nil {
268 tdx, err := convertTDXProtoToREST(request.Attestation.GetTdxAttestation())
269 if err != nil {
270 log.Fatalf("Failed to convert TD quote proto to API proto: %v", err)
271 }
272 verifyReq.TeeAttestation = tdx
273 }
274 } else if request.TDCCELAttestation != nil {
275 // TDX attestation route
276 // still need AK for GCE info!
277 verifyReq.TpmAttestation = &ccpb.TpmAttestation{
278 AkCert: request.TDCCELAttestation.AkCert,
279 CertChain: request.TDCCELAttestation.IntermediateCerts,
280 }
281
282 verifyReq.TeeAttestation = &ccpb.VerifyAttestationRequest_TdCcel{
283 TdCcel: &ccpb.TdxCcelAttestation{
284 TdQuote: request.TDCCELAttestation.TdQuote,
285 CcelAcpiTable: request.TDCCELAttestation.CcelAcpiTable,
286 CcelData: request.TDCCELAttestation.CcelData,
287 CanonicalEventLog: request.TDCCELAttestation.CanonicalEventLog,
288 },
289 }
290 }
291
292 return verifyReq
293 }
294
295 func convertResponseFromREST(resp *ccpb.VerifyAttestationResponse) (*verifier.VerifyAttestationResponse, error) {
296 token := []byte(resp.GetOidcClaimsToken())
297 return &verifier.VerifyAttestationResponse{
298 ClaimsToken: token,
299 PartialErrs: resp.PartialErrors,
300 }, nil
301 }
302
303 func convertSEVSNPProtoToREST(att *spb.Attestation) (*ccpb.VerifyAttestationRequest_SevSnpAttestation, error) {
304 auxBlob := sabi.CertsFromProto(att.GetCertificateChain()).Marshal()
305 rawReport, err := sabi.ReportToAbiBytes(att.GetReport())
306 if err != nil {
307 return nil, err
308 }
309 return &ccpb.VerifyAttestationRequest_SevSnpAttestation{
310 SevSnpAttestation: &ccpb.SevSnpAttestation{
311 AuxBlob: auxBlob,
312 Report: rawReport,
313 },
314 }, nil
315 }
316
317 func convertTDXProtoToREST(att *tpb.QuoteV4) (*ccpb.VerifyAttestationRequest_TdCcel, error) {
318 rawQuote, err := tabi.QuoteToAbiBytes(att)
319 if err != nil {
320 return nil, err
321 }
322 return &ccpb.VerifyAttestationRequest_TdCcel{
323 TdCcel: &ccpb.TdxCcelAttestation{
324 TdQuote: rawQuote,
325 },
326 }, nil
327 }
328
329 func setAwsPrincipalTagOptions(requestTokenOptions *models.TokenOptions) *ccpb.TokenOptions_AwsPrincipalTagsOptions {
330 if requestTokenOptions.PrincipalTagOptions == nil {
331 return nil
332 }
333 options := &ccpb.TokenOptions_AwsPrincipalTagsOptions{
334 AwsPrincipalTagsOptions: &ccpb.AwsPrincipalTagsOptions{},
335 }
336
337 if requestTokenOptions.PrincipalTagOptions.AllowedPrincipalTags == nil {
338 return options
339 }
340 options.AwsPrincipalTagsOptions.AllowedPrincipalTags = &ccpb.AwsPrincipalTagsOptions_AllowedPrincipalTags{}
341
342 if requestTokenOptions.PrincipalTagOptions.AllowedPrincipalTags.ContainerImageSignatures == nil {
343 return options
344 }
345
346 options.AwsPrincipalTagsOptions.GetAllowedPrincipalTags().ContainerImageSignatures = &ccpb.AwsPrincipalTagsOptions_AllowedPrincipalTags_ContainerImageSignatures{
347 KeyIds: requestTokenOptions.PrincipalTagOptions.AllowedPrincipalTags.ContainerImageSignatures.KeyIDs,
348 }
349
350 return options
351 }
352
353 func convertCSRequestToREST(request verifier.VerifyAttestationRequest) *ccpb.VerifyConfidentialSpaceRequest {
354 // Use convertRequestToREST to avoid duplicating conversion logic.
355 verifyAttRequest := convertRequestToREST(request)
356
357 csReq := &ccpb.VerifyConfidentialSpaceRequest{
358 Challenge: verifyAttRequest.Challenge,
359 GcpCredentials: verifyAttRequest.GcpCredentials,
360 SignedEntities: verifyAttRequest.ConfidentialSpaceInfo.SignedEntities,
361 }
362
363 if request.TDCCELAttestation != nil { // TDX Attestation.
364 csReq.TeeAttestation = &ccpb.VerifyConfidentialSpaceRequest_TdCcel{
365 TdCcel: verifyAttRequest.GetTdCcel(),
366 }
367
368 // Set AK cert info.
369 csReq.GceShieldedIdentity = &ccpb.GceShieldedIdentity{
370 AkCert: verifyAttRequest.TpmAttestation.AkCert,
371 AkCertChain: verifyAttRequest.TpmAttestation.CertChain,
372 }
373 } else { // TPM Attestation.
374 csReq.TeeAttestation = &ccpb.VerifyConfidentialSpaceRequest_TpmAttestation{
375 TpmAttestation: verifyAttRequest.TpmAttestation,
376 }
377 }
378
379 csReq.Options = convertToCSOpts(verifyAttRequest.TokenOptions)
380
381 return csReq
382 }
383
384 func convertToCSOpts(tokenOpts *ccpb.TokenOptions) *ccpb.VerifyConfidentialSpaceRequest_ConfidentialSpaceOptions {
385 if tokenOpts == nil {
386 return &ccpb.VerifyConfidentialSpaceRequest_ConfidentialSpaceOptions{
387 TokenProfile: ccpb.TokenProfile_TOKEN_PROFILE_DEFAULT_EAT,
388 }
389 }
390
391 csOpts := &ccpb.VerifyConfidentialSpaceRequest_ConfidentialSpaceOptions{
392 Audience: tokenOpts.Audience,
393 Nonce: tokenOpts.Nonce,
394 }
395
396 switch tokenOpts.TokenType {
397 case ccpb.TokenType_TOKEN_TYPE_OIDC:
398 csOpts.SignatureType = ccpb.SignatureType_SIGNATURE_TYPE_OIDC
399 csOpts.TokenProfile = ccpb.TokenProfile_TOKEN_PROFILE_DEFAULT_EAT
400
401 case ccpb.TokenType_TOKEN_TYPE_PKI:
402 csOpts.SignatureType = ccpb.SignatureType_SIGNATURE_TYPE_PKI
403 csOpts.TokenProfile = ccpb.TokenProfile_TOKEN_PROFILE_DEFAULT_EAT
404
405 case ccpb.TokenType_TOKEN_TYPE_AWS_PRINCIPALTAGS, ccpb.TokenType_TOKEN_TYPE_LIMITED_AWS:
406 csOpts.SignatureType = ccpb.SignatureType_SIGNATURE_TYPE_OIDC
407 csOpts.TokenProfile = ccpb.TokenProfile_TOKEN_PROFILE_AWS
408
409 if tokenOpts.TokenTypeOptions != nil {
410 csOpts.TokenProfileOptions = &ccpb.VerifyConfidentialSpaceRequest_ConfidentialSpaceOptions_AwsPrincipalTagsOptions{
411 AwsPrincipalTagsOptions: tokenOpts.GetAwsPrincipalTagsOptions(),
412 }
413 }
414 default:
415 // TokenProfile must be specified.
416 csOpts.TokenProfile = ccpb.TokenProfile_TOKEN_PROFILE_DEFAULT_EAT
417 }
418
419 return csOpts
420 }
421
422 func convertCSResponseFromREST(resp *ccpb.VerifyConfidentialSpaceResponse) *verifier.VerifyAttestationResponse {
423 token := []byte(resp.GetAttestationToken())
424 return &verifier.VerifyAttestationResponse{
425 ClaimsToken: token,
426 PartialErrs: resp.PartialErrors,
427 }
428 }