-
Notifications
You must be signed in to change notification settings - Fork 107
/
avr.go
576 lines (492 loc) · 17.1 KB
/
avr.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
// Package ias provides routines for interacting with the Intel Attestation
// Service.
package ias
import (
"crypto/x509"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"net/url"
"time"
"github.com/oasisprotocol/oasis-core/go/common/sgx"
)
// NonceMaxLen is the maximum length of the AVR nonce.
const NonceMaxLen = 32
var (
unsafeSkipVerify bool
unsafeAllowDebugEnclaves bool
)
// TimestampFormat is the format of the AVR timestamp, suitable for use with
// time.Parse.
//
// Workaround for https://github.com/golang/go/issues/21990
const TimestampFormat = "2006-01-02T15:04:05.999999999"
var (
attestationTypeFwdMap = map[string]AttestationType{
"": AttestationTypeFieldMissing,
"EPID": AttestationTypeEPID,
}
attestationTypeRevMap = make(map[AttestationType]string)
isvQuoteFwdMap = map[string]ISVEnclaveQuoteStatus{
"OK": QuoteOK,
"SIGNATURE_INVALID": QuoteSignatureInvalid,
"GROUP_REVOKED": QuoteGroupRevoked,
"SIGNATURE_REVOKED": QuoteSignatureRevoked,
"KEY_REVOKED": QuoteKeyRevoked,
"SIGRL_VERSION_MISMATCH": QuoteSigRLVersionMismatch,
"GROUP_OUT_OF_DATE": QuoteGroupOutOfDate,
"CONFIGURATION_NEEDED": QuoteConfigurationNeeded,
"SW_HARDENING_NEEDED": QuoteSwHardeningNeeded,
"CONFIGURATION_AND_SW_HARDENING_NEEDED": QuoteConfigurationAndSwHardeningNeeded,
}
isvQuoteRevMap = make(map[ISVEnclaveQuoteStatus]string)
pseManifFwdMap = map[string]PSEManifestStatus{
"OK": ManifestOK,
"UNKNOWN": ManifestUnknown,
"INVALID": ManifestInvalid,
"OUT_OF_DATE": ManifestOutOfDate,
"REVOKED": ManifestRevoked,
"RL_VERSION_MISMATCH": ManifestRLVersionMismatch,
}
pseManifRevMap = make(map[PSEManifestStatus]string)
crlReasonRevMap = map[CRLReason]string{
ReasonUnspecified: "unspecified",
ReasonKeyCompromise: "keyCompromise",
ReasonCACompromise: "cACompromise",
ReasonAffiliationChanged: "affiliationChanged",
ReasonSuperseded: "superseded",
ReasonCessationOfOperation: "cessationOfOperation",
ReasonCertificateHold: "certificateHold",
ReasonRemoveFromCRL: "removeFromCRL",
ReasonPrivilegeWithdrawn: "privilegeWithdrawn",
ReasonAACompromise: "aACompromise",
}
mrSignerBlacklist = make(map[sgx.MrSigner]bool)
)
// QuotePolicy is the quote validity policy.
type QuotePolicy struct {
// Disabled specifies whether IAS quotes are disabled and will always be rejected.
Disabled bool `json:"disabled,omitempty"`
// AllowedQuoteStatuses are the allowed quote statuses.
//
// Note: QuoteOK and QuoteSwHardeningNeeded are ALWAYS allowed, and do not need to be specified.
AllowedQuoteStatuses []ISVEnclaveQuoteStatus `json:"allowed_quote_statuses,omitempty"`
// GIDBlackList is a list of blocked platform EPID group IDs.
GIDBlacklist []uint32 `json:"gid_blacklist,omitempty"`
// MinTCBEvaluationDataNumber is the minimum acceptable TCB Evaluation Data number,
// as used in the attestation verification report structure.
MinTCBEvaluationDataNumber uint32 `json:"min_tcb_evaluation_data_number,omitempty"`
}
// AttestationType is the type of the SGX attestation.
type AttestationType int
// Predefined attestation types.
const (
AttestationTypeFieldMissing AttestationType = iota
AttestationTypeEPID
)
// UnmarshalText implements the encoding.TextUnmarshaler interface.
func (t *AttestationType) UnmarshalText(text []byte) error {
var ok bool
*t, ok = attestationTypeFwdMap[string(text)]
if !ok {
return fmt.Errorf("ias/avr: invalid attestation type: '%v'", string(text))
}
return nil
}
// MarshalText implements the encoding.TextMarshaler interface.
func (t *AttestationType) MarshalText() ([]byte, error) {
str, ok := attestationTypeRevMap[*t]
if !ok {
return nil, fmt.Errorf("ias/avr: invalid attestation type: %v", int(*t))
}
return []byte(str), nil
}
func (t AttestationType) String() string {
return attestationTypeRevMap[t]
}
// ISVEnclaveQuoteStatus is the status of an enclave quote.
type ISVEnclaveQuoteStatus int
// Predefined ISV enclave quote status codes.
const (
quoteFieldMissing ISVEnclaveQuoteStatus = iota
QuoteOK
QuoteSignatureInvalid
QuoteGroupRevoked
QuoteSignatureRevoked
QuoteKeyRevoked
QuoteSigRLVersionMismatch
QuoteGroupOutOfDate
QuoteConfigurationNeeded
QuoteSwHardeningNeeded
QuoteConfigurationAndSwHardeningNeeded
)
// UnmarshalText implements the encoding.TextUnmarshaler interface.
func (s *ISVEnclaveQuoteStatus) UnmarshalText(text []byte) error {
var ok bool
*s, ok = isvQuoteFwdMap[string(text)]
if !ok {
return fmt.Errorf("ias/avr: invalid quote status: '%v'", string(text))
}
return nil
}
// MarshalText implements the encoding.TextMarshaler interface.
func (s *ISVEnclaveQuoteStatus) MarshalText() ([]byte, error) {
str, ok := isvQuoteRevMap[*s]
if !ok {
return nil, fmt.Errorf("ias/avr: invalid quote status: '%v'", int(*s))
}
return []byte(str), nil
}
func (s ISVEnclaveQuoteStatus) String() string {
return isvQuoteRevMap[s]
}
// PSEManifestStatus is the status of a SGX Platform Service Security
// Property Descriptor.
type PSEManifestStatus int
// Predefined SGX Platform Service Security Property Descriptor status codes.
const (
ManifestOK PSEManifestStatus = iota
ManifestUnknown
ManifestInvalid
ManifestOutOfDate
ManifestRevoked
ManifestRLVersionMismatch
)
// UnmarshalText implements the encoding.TextUnmarshaler interface.
func (p *PSEManifestStatus) UnmarshalText(text []byte) error {
var ok bool
*p, ok = pseManifFwdMap[string(text)]
if !ok {
return fmt.Errorf("ias/avr: invalid PSE manifest status: '%v'", string(text))
}
return nil
}
// MarshalText implements the encoding.TextMarshaler interface.
func (p *PSEManifestStatus) MarshalText() ([]byte, error) {
str, ok := pseManifRevMap[*p]
if !ok {
return nil, fmt.Errorf("ias/avr: invalid PSE manifest status: '%v'", int(*p))
}
return []byte(str), nil
}
func (p PSEManifestStatus) String() string {
return pseManifRevMap[p]
}
// CRLReason is a certificate revocation reason code as specified in RFC 5280
// 5.3.1.
type CRLReason int
// Predefined CRL revocation reason codes.
const (
ReasonUnspecified CRLReason = 0
ReasonKeyCompromise CRLReason = 1
ReasonCACompromise CRLReason = 2
ReasonAffiliationChanged CRLReason = 3
ReasonSuperseded CRLReason = 4
ReasonCessationOfOperation CRLReason = 5
ReasonCertificateHold CRLReason = 6
ReasonRemoveFromCRL CRLReason = 8
ReasonPrivilegeWithdrawn CRLReason = 9
ReasonAACompromise CRLReason = 10
)
func (r CRLReason) String() string {
s, ok := crlReasonRevMap[r]
if !ok {
return fmt.Sprintf("[unknown reason (%d)]", int(r))
}
return s
}
// AVRBundle is a serialized Attestation Verification Report bundled
// with additional data required to allow offline verification.
type AVRBundle struct {
Body []byte `json:"body"`
CertificateChain []byte `json:"certificate_chain"`
Signature []byte `json:"signature"`
}
// Open decodes and validates the AVR contained in the bundle, and returns
// the Attestation Verification Report iff it is valid
func (b *AVRBundle) Open(policy *QuotePolicy, trustRoots *x509.CertPool, ts time.Time) (*AttestationVerificationReport, error) {
if policy != nil && policy.Disabled {
return nil, fmt.Errorf("IAS quotes are disabled by policy")
}
avr, err := DecodeAVR(b.Body, b.Signature, b.CertificateChain, trustRoots, ts)
if err != nil {
return nil, err
}
// Verify against policy.
if !avr.quoteStatusAllowed(policy) {
return nil, fmt.Errorf("quote status not allowed by policy")
}
// Check minimum TCB evaluation data number.
// If the report doesn't contain this number, it will be zeroed out in the structure.
if avr.TCBEvaluationDataNumber < policy.MinTCBEvaluationDataNumber {
return nil, fmt.Errorf("tcb evaluation data number not allowed by policy")
}
quote, err := avr.Quote()
if err != nil {
return nil, fmt.Errorf("quote open failure: %w", err)
}
// Validate EPID GID not blacklisted.
for _, blocked := range policy.GIDBlacklist {
if blocked == quote.Body.GID {
return nil, fmt.Errorf("blacklisted quote GID")
}
}
return avr, nil
}
// AttestationVerificationReport is a deserialized Attestation Verification
// Report (AVR).
type AttestationVerificationReport struct {
ID string `json:"id"`
Timestamp string `json:"timestamp"`
Version int `json:"version"`
AttestationType AttestationType `json:"attestationType,omitempty"`
ISVEnclaveQuoteStatus ISVEnclaveQuoteStatus `json:"isvEnclaveQuoteStatus"`
ISVEnclaveQuoteBody []byte `json:"isvEnclaveQuoteBody"`
RevocationReason *CRLReason `json:"revocationReason"`
PSEManifestStatus *PSEManifestStatus `json:"pseManifestStatus"`
PSEManifestHash string `json:"pseManifestHash"`
PlatformInfoBlob string `json:"platformInfoBlob"`
Nonce string `json:"nonce"`
EPIDPseudonym []byte `json:"epidPseudonym"`
AdvisoryURL string `json:"advisoryURL"`
AdvisoryIDs []string `json:"advisoryIDs"`
DocIDs []string `json:"docIDs"`
TCBEvaluationDataNumber uint32 `json:"tcbEvaluationDataNumber,omitempty"`
}
// Quote decodes and returns the enclave quote component of an Attestation
// Verification Report.
func (a *AttestationVerificationReport) Quote() (*Quote, error) {
var quote Quote
if err := quote.UnmarshalBinary(a.ISVEnclaveQuoteBody); err != nil {
return nil, err
}
return "e, nil
}
func (a *AttestationVerificationReport) quoteStatusAllowed(policy *QuotePolicy) bool {
status := a.ISVEnclaveQuoteStatus
// Always allow "OK" and "SW_HARDENING_NEEDED".
if status == QuoteOK || status == QuoteSwHardeningNeeded {
return true
}
if policy == nil {
return false
}
// Search through the constraints to see if the AVR quote status is
// explicitly allowed.
for _, v := range policy.AllowedQuoteStatuses {
if v == status {
return true
}
}
return false
}
func (a *AttestationVerificationReport) validate() error { // nolint: gocyclo
const (
pseManifestHashLen = 32
epidPseudonymLen = 64 + 64
)
if _, err := time.Parse(TimestampFormat, a.Timestamp); err != nil {
return fmt.Errorf("ias/avr: invalid timestamp: %w", err)
}
switch a.Version {
case 4:
if a.AttestationType != AttestationTypeFieldMissing {
return fmt.Errorf(
"ias/avr: phantom attestation type %d (%s) in report version 4",
a.AttestationType, a.AttestationType.String(),
)
}
case 5:
// This field is mandatory according to the v5 spec, but in practice doesn't always show up in AVR jsons.
if a.AttestationType != AttestationTypeFieldMissing && a.AttestationType != AttestationTypeEPID {
return fmt.Errorf(
"ias/avr: unexpected attestation type %d in report version 5, expected %d (%s)",
a.AttestationType, AttestationTypeEPID, AttestationTypeEPID.String(),
)
}
default:
return fmt.Errorf("ias/avr: invalid report version, got: %d, required 4 or 5", a.Version)
}
if a.ISVEnclaveQuoteStatus == quoteFieldMissing {
return fmt.Errorf("ias/avr: missing isvEnclaveQuoteStatus")
}
switch len(a.ISVEnclaveQuoteBody) {
case 0:
case quoteLen:
untrustedQuote, err := a.Quote()
if err != nil {
return fmt.Errorf("ias/avr: malformed quote: %w", err)
}
if err = untrustedQuote.Verify(); err != nil {
return fmt.Errorf("ias/avr: invalid quote: %w", err)
}
default:
return fmt.Errorf("ias/avr: invalid isvEnclaveQuoteBody length")
}
if a.ISVEnclaveQuoteStatus == QuoteGroupRevoked {
if a.RevocationReason == nil {
return fmt.Errorf("ias/avr: missing revocationReason")
}
} else if a.RevocationReason != nil {
return fmt.Errorf("ias/avr: invalid isvEnclaveStatus for revocationReason")
}
if a.PSEManifestStatus != nil {
switch a.ISVEnclaveQuoteStatus {
case QuoteOK, QuoteGroupOutOfDate, QuoteConfigurationNeeded, QuoteSwHardeningNeeded, QuoteConfigurationAndSwHardeningNeeded:
default:
return fmt.Errorf("ias/avr: unexpected pseManifestStatus")
}
}
pseHash, err := hex.DecodeString(a.PSEManifestHash)
if err != nil {
return fmt.Errorf("ias/avr: failed to decode pseManifestHash: %w", err)
}
switch len(pseHash) {
case 0, pseManifestHashLen:
default:
return fmt.Errorf("ias/avr: invalid pseManifestHash length")
}
piBlob, err := hex.DecodeString(a.PlatformInfoBlob)
if err != nil {
return fmt.Errorf("ias/avr: failed to decode platformInfoBlob: %w", err)
}
if len(piBlob) > 0 {
var canHas bool
switch a.ISVEnclaveQuoteStatus {
case QuoteGroupRevoked, QuoteGroupOutOfDate, QuoteConfigurationNeeded, QuoteSwHardeningNeeded, QuoteConfigurationAndSwHardeningNeeded:
canHas = true
default:
}
if a.PSEManifestStatus != nil && !canHas { // "one of the following"
switch *a.PSEManifestStatus {
case ManifestOutOfDate, ManifestRevoked, ManifestRLVersionMismatch:
canHas = true
default:
}
}
if !canHas {
return fmt.Errorf("ias/avr: unexpected platformInfoBlob")
}
// Could validate the Platform Info Blob (4.2.4), but it's also
// described as "opaque".
}
if len(a.Nonce) > NonceMaxLen {
return fmt.Errorf("ias/avr: invalid nonce length")
}
switch len(a.EPIDPseudonym) {
case 0, epidPseudonymLen:
default:
return fmt.Errorf("ias/avr: invalid epidPseudonym length")
}
return nil
}
// DecodeAVR decodes and validates an Attestation Verification Report.
func DecodeAVR(data, encodedSignature, encodedCertChain []byte, trustRoots *x509.CertPool, ts time.Time) (*AttestationVerificationReport, error) {
if !unsafeSkipVerify {
if err := validateAVRSignature(data, encodedSignature, encodedCertChain, trustRoots, ts); err != nil {
return nil, err
}
}
return UnsafeDecodeAVR(data)
}
// UnsafeDecodeAVR decodes and validates an Attestation Verification Report,
// but does not validate the signature.
//
// WARNING: This MUST only be used for diagnostic purposes.
func UnsafeDecodeAVR(data []byte) (*AttestationVerificationReport, error) {
// Set the ISVEnclaveQuoteStatus to a sentinel value so that it is
// possible to detect it being missing from the JSON.
a := &AttestationVerificationReport{
AttestationType: AttestationTypeFieldMissing,
ISVEnclaveQuoteStatus: quoteFieldMissing,
}
if err := json.Unmarshal(data, a); err != nil {
return nil, fmt.Errorf("ias/avr: failed to parse JSON: %w", err)
}
if err := a.validate(); err != nil {
return nil, err
}
return a, nil
}
func validateAVRSignature(data, encodedSignature, encodedCertChain []byte, trustRoots *x509.CertPool, ts time.Time) error {
decoded, err := url.QueryUnescape(string(encodedCertChain))
if err != nil {
return fmt.Errorf("ias/avr: failed to decode certificate chain: %w", err)
}
pemCerts := []byte(decoded)
var certs []*x509.Certificate
for {
var cert *x509.Certificate
cert, pemCerts, err = CertFromPEM(pemCerts)
if err != nil {
return err
}
if cert == nil {
break
}
certs = append(certs, cert)
}
if len(certs) != 2 {
return fmt.Errorf("ias/avr: unexpected certificate chain length: %d", len(certs))
}
signingCert, rootCert := certs[0], certs[1]
certChains, err := signingCert.Verify(x509.VerifyOptions{
Roots: trustRoots,
CurrentTime: ts,
})
if err != nil {
return fmt.Errorf("ias/avr: failed to verify certificate chain: %w", err)
}
if !certRootsAChain(rootCert, certChains) {
return fmt.Errorf("ias/avr: unexpected root in certificate chain")
}
signature, err := base64.StdEncoding.DecodeString(string(encodedSignature))
if err != nil {
return fmt.Errorf("ias/avr: failed to decode signature: %w", err)
}
if err = signingCert.CheckSignature(x509.SHA256WithRSA, data, signature); err != nil {
return fmt.Errorf("ias/avr: failed to verify AVR signature: %w", err)
}
return nil
}
// SetSkipVerify will disable AVR signature verification for the remainder
// of the process' lifetime.
func SetSkipVerify() {
unsafeSkipVerify = true
}
// SetAllowDebugEnclaves will enable running and communicating with enclaves
// with debug flag enabled in AVR for the remainder of the process' lifetime.
func SetAllowDebugEnclaves() {
unsafeAllowDebugEnclaves = true
}
// UnsetAllowDebugEnclaves will disable running and communicating with enclaves
// with debug flag enabled in AVR for the remainder of the process' lifetime.
func UnsetAllowDebugEnclaves() {
unsafeAllowDebugEnclaves = false
}
// BuildMrSignerBlacklist builds the MRSIGNER blacklist.
func BuildMrSignerBlacklist(allowTestKeys bool) {
if !allowTestKeys {
for _, v := range []string{
sgx.FortanixDummyMrSigner.String(),
} {
var signer sgx.MrSigner
if err := signer.UnmarshalHex(v); err != nil {
panic("ias/avr: failed to decode MRSIGNER: " + v)
}
mrSignerBlacklist[signer] = true
}
}
}
func init() {
for k, v := range attestationTypeFwdMap {
attestationTypeRevMap[v] = k
}
for k, v := range isvQuoteFwdMap {
isvQuoteRevMap[v] = k
}
for k, v := range pseManifFwdMap {
pseManifRevMap[v] = k
}
}