Debian Codegraph @

verifier/ita/client.go

raw
1 package ita
2
3 import (
4 "bytes"
5 "context"
6 "crypto/sha512"
7 "crypto/tls"
8 "encoding/json"
9 "errors"
10 "fmt"
11 "io"
12 "net/http"
13 "strings"
14
15 "github.com/google/go-tpm-tools/verifier"
16 )
17
18 const (
19 nonceEndpoint = "/appraisal/v2/nonce"
20 tokenEndpoint = "/appraisal/v2/attest/gcp/confidentialspace"
21
22 apiKeyHeader = "x-api-key"
23 acceptHeader = "Accept"
24 contentTypeHeader = "Content-Type"
25 applicationJSON = "application/json"
26
27 challengeNamePrefix = "ita://"
28 )
29
30 var regionalURLs map[string]string = map[string]string{
31 "US": "https://api.trustauthority.intel.com",
32 "EU": "https://api.eu.trustauthority.intel.com",
33 }
34
35 type client struct {
36 inner *http.Client
37 apiURL string
38 apiKey string
39 }
40
41 func urlFromRegion(region string) (string, error) {
42 if region == "" {
43 return "", errors.New("API region required to initialize ITA client")
44 }
45 url, ok := regionalURLs[strings.ToUpper(region)]
46 if !ok {
47 // Create list of allowed regions.
48 keys := []string{}
49 for k := range regionalURLs {
50 keys = append(keys, k)
51 }
52 return "", fmt.Errorf("unsupported region %v, expect one of %v", region, keys)
53 }
54
55 return url, nil
56 }
57
58 // Confirm that client implements verifier.Client interface.
59 var _ verifier.Client = (*client)(nil)
60
61 type itaNonce struct {
62 Val []byte `json:"val"`
63 Iat []byte `json:"iat"`
64 Signature []byte `json:"signature"`
65 }
66
67 // The ITA evidence nonce is a concatenation+hash of Val and Iat. See references below:
68 // https://github.com/intel/trustauthority-client-for-go/blob/main/go-connector/attest.go#L22
69 // https://github.com/intel/trustauthority-client-for-go/blob/main/go-tdx/tdx_adapter.go#L37
70 func createHashedNonce(nonce *itaNonce) ([]byte, error) {
71 hash := sha512.New()
72 _, err := hash.Write(append(nonce.Val, nonce.Iat...))
73 if err != nil {
74 return nil, fmt.Errorf("error hashing ITA nonce: %v", err)
75 }
76
77 return hash.Sum(nil), err
78 }
79
80 func NewClient(itaConfig verifier.ITAConfig) (verifier.Client, error) { //region string, key string) (verifier.Client, error) {
81 url, err := urlFromRegion(itaConfig.ITARegion)
82 if err != nil {
83 return nil, err
84 }
85
86 return &client{
87 inner: &http.Client{
88 Transport: &http.Transport{
89 // https://github.com/intel/trustauthority-client-for-go/blob/main/go-connector/token.go#L130.
90 TLSClientConfig: &tls.Config{
91 CipherSuites: []uint16{
92 tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
93 tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
94 },
95 InsecureSkipVerify: false,
96 MinVersion: tls.VersionTLS12,
97 },
98 Proxy: http.ProxyFromEnvironment,
99 },
100 },
101 apiURL: url,
102 apiKey: itaConfig.ITAKey,
103 }, nil
104 }
105
106 func (c *client) CreateChallenge(_ context.Context) (*verifier.Challenge, error) {
107 url := c.apiURL + nonceEndpoint
108
109 headers := map[string]string{
110 acceptHeader: applicationJSON,
111 }
112
113 resp := &itaNonce{}
114 if err := c.doHTTPRequest(http.MethodGet, url, nil, headers, &resp); err != nil {
115 return nil, err
116 }
117
118 nonce, err := createHashedNonce(resp)
119 if err != nil {
120 return nil, err
121 }
122
123 return &verifier.Challenge{
124 Name: challengeNamePrefix + string(resp.Val),
125 Nonce: nonce,
126 Val: resp.Val,
127 Iat: resp.Iat,
128 Signature: resp.Signature,
129 }, nil
130 }
131
132 func (c *client) VerifyAttestation(_ context.Context, request verifier.VerifyAttestationRequest) (*verifier.VerifyAttestationResponse, error) {
133 if request.TDCCELAttestation == nil {
134 return nil, errors.New("TDX required for ITA attestation")
135 }
136
137 tokenReq := convertRequestToTokenRequest(request)
138
139 url := c.apiURL + tokenEndpoint
140 headers := map[string]string{
141 apiKeyHeader: c.apiKey,
142 acceptHeader: applicationJSON,
143 contentTypeHeader: applicationJSON,
144 }
145
146 resp := &tokenResponse{}
147 if err := c.doHTTPRequest(http.MethodPost, url, tokenReq, headers, &resp); err != nil {
148 return nil, err
149 }
150
151 return &verifier.VerifyAttestationResponse{
152 ClaimsToken: []byte(resp.Token),
153 }, nil
154 }
155
156 func (c *client) doHTTPRequest(method string, url string, reqStruct any, headers map[string]string, respStruct any) error {
157 // Create HTTP request.
158 var req *http.Request
159 var err error
160 if reqStruct != nil {
161 body, err := json.Marshal(reqStruct)
162 if err != nil {
163 return fmt.Errorf("error marshaling request: %v", err)
164 }
165
166 req, err = http.NewRequest(method, url, bytes.NewReader(body))
167 if err != nil {
168 return fmt.Errorf("error creating HTTP request: %v", err)
169 }
170 } else {
171 req, err = http.NewRequest(method, url, nil)
172 if err != nil {
173 return fmt.Errorf("error creating HTTP request: %v", err)
174 }
175 }
176
177 // Add headers to request.
178 headers[apiKeyHeader] = string(c.apiKey)
179 for key, val := range headers {
180 req.Header.Add(key, val)
181 }
182
183 resp, err := c.inner.Do(req)
184 if err != nil {
185 return fmt.Errorf("HTTP request error: %v", err)
186 }
187 defer resp.Body.Close()
188
189 // Read and unmarshal response body.
190 respBody, err := io.ReadAll(resp.Body)
191 if err != nil {
192 return fmt.Errorf("error reading response body: %v", err)
193 }
194 if resp.StatusCode != http.StatusOK {
195 return fmt.Errorf("HTTP request failed with status code %d, response body %s", resp.StatusCode, string(respBody))
196 }
197
198 if err := json.Unmarshal(respBody, respStruct); err != nil {
199 return fmt.Errorf("error unmarshaling response: %v", err)
200 }
201
202 return nil
203 }
204
205 func convertRequestToTokenRequest(request verifier.VerifyAttestationRequest) tokenRequest {
206 // Trim trailing 0xFF bytes from CCEL Data.
207 data := request.TDCCELAttestation.CcelData
208 trimIndex := len(data)
209
210 for ; trimIndex >= 0; trimIndex-- {
211 c := data[trimIndex-1]
212 // Proceed until 0xFF padding ends.
213 if c != byte(255) {
214 break
215 }
216 }
217
218 tokenReq := tokenRequest{
219 PolicyMatch: true,
220 TDX: tdxEvidence{
221 EventLog: data[:trimIndex],
222 CanonicalEventLog: request.TDCCELAttestation.CanonicalEventLog,
223 Quote: request.TDCCELAttestation.TdQuote,
224 VerifierNonce: nonce{
225 Val: request.Challenge.Val,
226 Iat: request.Challenge.Iat,
227 Signature: request.Challenge.Signature,
228 },
229 },
230 SigAlg: "RS256", // Figure out what this should be.
231 GCP: gcpData{
232 AKCert: request.TDCCELAttestation.AkCert,
233 IntermediateCerts: request.TDCCELAttestation.IntermediateCerts,
234 CSInfo: confidentialSpaceInfo{
235 TokenOpts: tokenOptions{},
236 },
237 },
238 }
239
240 if request.TokenOptions != nil {
241 tokenReq.GCP.CSInfo.TokenOpts = tokenOptions{
242 Audience: request.TokenOptions.Audience,
243 Nonces: request.TokenOptions.Nonces,
244 TokenType: request.TokenOptions.TokenType,
245 TokenTypeOpts: tokenTypeOptions{},
246 }
247 }
248
249 for _, token := range request.GcpCredentials {
250 tokenReq.GCP.GcpCredentials = append(tokenReq.GCP.GcpCredentials, string(token))
251 }
252
253 for _, sig := range request.ContainerImageSignatures {
254 itaSig := containerSignature{
255 Payload: sig.Payload,
256 Signature: sig.Signature,
257 }
258 tokenReq.GCP.CSInfo.SignedEntities = append(tokenReq.GCP.CSInfo.SignedEntities, itaSig)
259 }
260
261 return tokenReq
262 }
263
264 func (c *client) VerifyConfidentialSpace(ctx context.Context, request verifier.VerifyAttestationRequest) (*verifier.VerifyAttestationResponse, error) {
265 return c.VerifyAttestation(ctx, request)
266 }