ias.go 14.6 KB
Newer Older
1
package ias // import "github.com/opencontainers/runc/libenclave/attestation/sgx/ias"
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

import (
	"bytes"
	"crypto/tls"
	"crypto/x509"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"encoding/pem"
	"fmt"
	attest "github.com/opencontainers/runc/libenclave/attestation"
	pb "github.com/opencontainers/runc/libenclave/attestation/proto"
	"github.com/opencontainers/runc/libenclave/intelsgx"
	"github.com/sirupsen/logrus"
	"io"
	"math/rand"
	"net/http"
	"net/http/httputil"
	"net/url"
	"strconv"
	"unsafe"
)

const (
	spidLength            = 16
	subscriptionKeyLength = 16
)

type reportStatus struct {
	requestId   string
	reportId    string
	timestamp   string
	quoteStatus string
}

type iasRegistry struct {
}

type iasService struct {
	attest.Service
	reportApiUrl    string
	spid            [spidLength]byte
	subscriptionKey [subscriptionKeyLength]byte
}

func (reg *iasRegistry) Create(p map[string]string) (*attest.Service, error) {
	isProduct := false
	v := attest.GetParameter("service-class", p)
	if v != "" && v == "product" {
		isProduct = true
	}

	spid := attest.GetParameter("spid", p)
	if spid == "" {
		return nil, fmt.Errorf("Missing parameter spid")
	}

	if len(spid) != spidLength*2 {
		return nil, fmt.Errorf("The length of spid must be %d-character",
			spidLength*2)
	}

	subKey := attest.GetParameter("subscription-key", p)
	if subKey == "" {
		return nil, fmt.Errorf("Missing parameter subscription-key")
	}

	if len(subKey) != subscriptionKeyLength*2 {
		return nil, fmt.Errorf("The length of subscription key must be %d-character",
			subscriptionKeyLength*2)
	}

	var rawSubKey []byte
	var err error
	if rawSubKey, err = hex.DecodeString(subKey); err != nil {
		return nil, fmt.Errorf("Failed to decode subscription key: %s", err)
	}

	var rawSpid []byte
	if rawSpid, err = hex.DecodeString(spid); err != nil {
		return nil, fmt.Errorf("Failed to decode spid: %s", err)
	}

	url := "https://api.trustedservices.intel.com/sgx"
	if !isProduct {
		url += "/dev"
	}
Y
YiLin.Li 已提交
89 90 91 92 93 94 95 96 97 98 99

	apiVer := attest.GetParameter("apiVer", p)
	if apiVer != "" {
		apiVersion, err = strconv.ParseUint(apiVer, 10, 32)
		if err != nil {
			return nil, fmt.Errorf("Invalid IAS API Version: %s", err)
		} else if apiVersion != apiV3 && apiVersion != apiV4 {
			return nil, fmt.Errorf("Unsupported IAS API Version: %s", apiVer)
		}
	}
	url += fmt.Sprintf("/attestation/v%d/report", apiVersion)
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

	ias := &iasService{
		reportApiUrl: url,
	}
	copy(ias.subscriptionKey[:], rawSubKey)
	copy(ias.spid[:], rawSpid)

	ias.Attester = ias

	return &ias.Service, nil
}

func (ias *iasService) PrepareChallenge() (*pb.AttestChallenge, error) {
	return &pb.AttestChallenge{
		Nonce: ias.NonceForChallenge.Generate(),
	}, nil
}

func (ias *iasService) HandleChallengeResponse(r *pb.AttestResponse) (*attest.Quote, error) {
	quote := r.GetQuote()

	if len(quote) <= intelsgx.QuoteLength {
		return nil, fmt.Errorf("Invalid length of quote returned: %d-byte", len(quote))
	}

	return &attest.Quote{Evidence: quote}, nil
}

// TODO: check target enclave report
func (ias *iasService) Check(q []byte) error {
	quote := (*intelsgx.Quote)(unsafe.Pointer(&q[0]))

	if ias.IsVerbose() {
		logrus.Infof("Target Platform's Quote")
		logrus.Infof("  Quote Body")
		logrus.Infof("    QUOTE Structure Version:                               %d",
			quote.Version)
		logrus.Infof("    EPID Signature Type:                                   %d",
			quote.SignatureType)
		logrus.Infof("    Platform's EPID Group ID:                              %#08x",
			quote.Gid)
		logrus.Infof("    Quoting Enclave's ISV assigned SVN:                    %#04x",
			quote.ISVSvnQe)
		logrus.Infof("    Provisioning Certification Enclave's ISV assigned SVN: %#04x",
			quote.ISVSvnPce)
		logrus.Infof("    EPID Basename:                                         0x%v",
			hex.EncodeToString(quote.Basename[:]))
		logrus.Infof("  Report Body")
		logrus.Infof("    Target CPU SVN:                                        0x%v",
			hex.EncodeToString(quote.CpuSvn[:]))
		logrus.Infof("    Enclave Misc Select:                                   %#08x",
			quote.MiscSelect)
		logrus.Infof("    Enclave Attributes:                                    0x%v",
			hex.EncodeToString(quote.Attributes[:]))
		logrus.Infof("    Enclave Hash:                                          0x%v",
			hex.EncodeToString(quote.MrEnclave[:]))
		logrus.Infof("    Enclave Signer:                                        0x%v",
			hex.EncodeToString(quote.MrSigner[:]))
		logrus.Infof("    ISV assigned Product ID:                               %#04x",
			quote.IsvProdId)
		logrus.Infof("    ISV assigned SVN:                                      %#04x",
			quote.IsvSvn)
		logrus.Infof("    Report Data:                                           0x%v...",
			hex.EncodeToString(quote.ReportData[:32]))
		logrus.Infof("  Encrypted EPID Signature")
		logrus.Infof("    Length:                                                %d",
			quote.SigLen)
		logrus.Infof("    Signature:                                             0x%v...",
			hex.EncodeToString(q[intelsgx.QuoteLength:intelsgx.QuoteLength+32]))
	}

	if quote.Version != intelsgx.QuoteVersion {
		return fmt.Errorf("Invalid quote version: %d", quote.Version)
	}

	if quote.SignatureType != intelsgx.QuoteSignatureTypeUnlinkable &&
		quote.SignatureType != intelsgx.QuoteSignatureTypeLinkable {
		return fmt.Errorf("Invalid signature type: %#04x", quote.SignatureType)
	}

	spid := [spidLength]byte{}
	copy(spid[:], quote.Basename[:spidLength])
	if spid != ias.spid {
		return fmt.Errorf("Invalid spid in quote body: 0x%v",
			hex.EncodeToString(quote.Basename[:]))
	}

	return nil
}

190
func (ias *iasService) getIasReport(quote []byte) (*attest.Status, map[string]string, error) {
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
	nonce := strconv.FormatUint(rand.Uint64(), 16) + strconv.FormatUint(rand.Uint64(), 16)
	p := &evidencePayload{
		IsvEnclaveQuote: base64.StdEncoding.EncodeToString(quote),
		PseManifest:     "",
		Nonce:           nonce,
	}

	status := &attest.Status{
		StatusCode:   attest.StatusSgxBit,
		ErrorMessage: "",
	}

	var resp *http.Response
	var err error
	if resp, err = ias.reportAttestationEvidence(p); err != nil {
		status.ErrorMessage = fmt.Sprintf("%s", err)
207
		return status, nil, err
208 209 210 211
	}
	defer resp.Body.Close()

	var reportStatus *reportStatus
212 213
	reportStatus, rawReport, err := checkVerificationReport(resp, quote, nonce)
	if err != nil {
214
		status.ErrorMessage = fmt.Sprintf("%s", err)
215
		return status, nil, err
216 217
	}

218 219
	iasReport := formatIasReport(resp, rawReport)

220
	status.SpecificStatus = reportStatus
221 222 223 224 225 226 227 228 229
	return status, iasReport, nil
}

func (ias *iasService) Verify(quote []byte) *attest.Status {
	status, _, err := ias.getIasReport(quote)
	if err != nil {
		return nil
	}

230 231 232
	return status
}

233 234 235 236
func (ias *iasService) GetVerifiedReport(quote []byte) (*attest.Status, map[string]string, error) {
	return ias.getIasReport(quote)
}

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
func (ias *iasService) ShowStatus(status *attest.Status) {
	s, ok := status.SpecificStatus.(*reportStatus)
	if ok {
		logrus.Infof("Request ID: %s\n", s.requestId)
		logrus.Infof("Report ID: %s\n", s.reportId)
		logrus.Infof("Timestamp: %s\n", s.timestamp)
		logrus.Infof("IsvEnclaveQuoteStatus: %s\n", s.quoteStatus)
	}
}

func (ias *iasService) reportAttestationEvidence(p *evidencePayload) (*http.Response, error) {
	var jp []byte
	var err error

	if jp, err = json.Marshal(p); err != nil {
		return nil, fmt.Errorf("Failed to marshal evidence payload: %s", err)
	}

	bjp := bytes.NewBuffer(jp)
	var req *http.Request
	if req, err = http.NewRequest(http.MethodPost, ias.reportApiUrl, bjp); err != nil {
		return nil, fmt.Errorf("Failed to create http.Request: %s", err)
	}

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Ocp-Apim-Subscription-Key", hex.EncodeToString(ias.subscriptionKey[:]))

	if ias.IsVerbose() {
		logrus.Infof("Initializing attestation evidence report ...")

		if dump, err := httputil.DumpRequestOut(req, true); err == nil {
			logrus.Infof("--- start of request ---")
			logrus.Infof("%s\n", dump)
			logrus.Infof("--- end of request ---")
		}
	}

	client := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		},
	}

	var resp *http.Response
	if resp, err = client.Do(req); err != nil {
		return nil, fmt.Errorf("Failed to send http request and receive http response: %s", err)
	}

	if ias.IsVerbose() {
		logrus.Infof("Attestation evidence response retrieved ...")

		if dump, err := httputil.DumpResponse(resp, true); err == nil {
			logrus.Infof("--- start of response ---")
			logrus.Infof("%s\n", dump)
			logrus.Infof("--- end of response ---")
		}
	}

	return resp, nil
}

298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
func formatIasReport(resp *http.Response, rawReport string) map[string]string {
	iasReport := make(map[string]string)

	iasReport["Body"] = rawReport
	iasReport["StatusCode"] = strconv.FormatUint(uint64(resp.StatusCode), 10)
	iasReport["Request-ID"] = resp.Header.Get("Request-ID")
	iasReport["X-Iasreport-Signature"] = resp.Header.Get("X-Iasreport-Signature")
	iasReport["X-Iasreport-Signing-Certificate"] = resp.Header.Get("X-Iasreport-Signing-Certificate")
	iasReport["ContentLength"] = strconv.FormatUint(uint64(resp.ContentLength), 10)
	iasReport["Content-Type"] = resp.Header.Get("Content-Type")

	return iasReport
}

func checkVerificationReport(resp *http.Response, quote []byte, nonce string) (*reportStatus, string, error) {
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
	status := &reportStatus{
		requestId:   "",
		reportId:    "",
		quoteStatus: "",
	}

	if resp.StatusCode != 200 {
		errMsg := "Unexpected status"

		switch resp.StatusCode {
		case 400:
			errMsg = "Invalid Attestation Evidence Payload. The client should not repeat the request without modifications."
		case 401:
			errMsg = "Failed to authenticate or authorize request."
		case 500:
			errMsg = "Internal error occurred."
		case 503:
			errMsg = "IAS is currently not able to process the request due to a temporary overloading or maintenance. This is a temporary state and the same request can be repeated after some time."
		default:
		}

334
		return status, "", fmt.Errorf("%s: %s", resp.Status, errMsg)
335 336 337 338
	}

	reqId := resp.Header.Get("Request-ID")
	if reqId == "" {
339
		return status, "", fmt.Errorf("No Request-ID in response header")
340 341 342 343 344
	}

	status.requestId = reqId

	if resp.Header.Get("X-Iasreport-Signature") == "" {
345
		return status, "", fmt.Errorf("No X-Iasreport-Signature in response header")
346 347 348
	}

	if resp.Header.Get("X-Iasreport-Signing-Certificate") == "" {
349
		return status, "", fmt.Errorf("No X-Iasreport-Signing-Certificate in response header")
350 351 352
	}

	if resp.ContentLength == -1 {
353
		return status, "", fmt.Errorf("Unknown length of response body")
354 355 356
	}

	if resp.Header.Get("Content-Type") != "application/json" {
357
		return status, "", fmt.Errorf("Invalid content type (%s) in response",
358 359 360 361 362 363
			resp.Header.Get("Content-Type"))
	}

	var err error
	rawReport := make([]byte, resp.ContentLength)
	if _, err = io.ReadFull(resp.Body, rawReport); err != nil {
364
		return status, "", fmt.Errorf("Failed to read reponse body (%d-byte): %s",
365 366 367 368 369
			resp.ContentLength, err)
	}

	var report verificationReport
	if err = json.Unmarshal(rawReport, &report); err != nil {
370
		return status, "", fmt.Errorf("Failed to unmarshal attestation verification report: %s: %s",
371 372 373 374 375 376 377
			rawReport, err)
	}

	status.reportId = report.Id
	status.timestamp = report.Timestamp
	status.quoteStatus = report.IsvEnclaveQuoteStatus

Y
YiLin.Li 已提交
378
	if report.Version != (uint32)(apiVersion) {
379
		return status, "", fmt.Errorf("Unsupported attestation API version %d in attesation verification report",
380 381 382 383
			report.Version)
	}

	if report.Nonce != nonce {
384
		return status, "", fmt.Errorf("Invalid nonce in attestation verification report: %s",
385 386 387 388 389 390
			report.Nonce)
	}

	if report.Id == "" || report.Timestamp == "" ||
		report.IsvEnclaveQuoteStatus == "" ||
		report.IsvEnclaveQuoteBody == "" {
391
		return status, "", fmt.Errorf("Required fields in attestation verification report is not present: %s",
392 393 394 395 396
			string(rawReport))
	}

	if report.IsvEnclaveQuoteStatus == "GROUP_OUT_OF_DATE" ||
		report.IsvEnclaveQuoteStatus == "CONFIGURATION_NEEDED" {
Y
YiLin.Li 已提交
397 398
		if report.Version == apiV3 {
			if resp.Header.Get("Advisory-Ids") == "" || resp.Header.Get("Advisory-Url") == "" {
399
				return status, "", fmt.Errorf("Advisory-Ids or Advisory-Url is not present in response header")
Y
YiLin.Li 已提交
400 401
			}
		} else if report.Version == apiV4 && (report.AdvisoryIds == "" || report.AdvisoryUrl == nil) {
402
			return status, "", fmt.Errorf("Advisory-Ids or Advisory-Url is not present in attestation verification report")
403 404 405 406 407
		}
	}

	var quoteBody []byte
	if quoteBody, err = base64.StdEncoding.DecodeString(report.IsvEnclaveQuoteBody); err != nil {
408
		return status, "", fmt.Errorf("Invalid isvEnclaveQuoteBody: %s",
409 410 411 412
			report.IsvEnclaveQuoteBody)
	}

	if len(quoteBody) != intelsgx.QuoteBodyLength+intelsgx.ReportBodyLength {
413
		return status, "", fmt.Errorf("Invalid length of isvEnclaveQuoteBody: %d-byte",
414 415 416 417 418
			len(quoteBody))
	}

	for i, v := range quoteBody {
		if v != quote[i] {
419
			return status, "", fmt.Errorf("Unexpected isvEnclaveQuoteBody: %s",
420 421 422 423 424 425 426
				report.IsvEnclaveQuoteBody)
		}
	}

	var sig []byte
	if sig, err = base64.StdEncoding.DecodeString(
		resp.Header.Get("X-Iasreport-Signature")); err != nil {
427
		return status, "", fmt.Errorf("Invalid X-Iasreport-Signature in response header: %s",
428 429 430 431 432 433
			resp.Header.Get("X-Iasreport-Signature"))
	}

	var pemCerts string
	if pemCerts, err = url.QueryUnescape(
		resp.Header.Get("X-Iasreport-Signing-Certificate")); err != nil {
434
		return status, "", fmt.Errorf("Failed to unescape X-Iasreport-Signing-Certificate in response header: %s: %s",
435 436 437 438 439 440 441 442 443 444 445
			resp.Header.Get("X-Iasreport-Signing-Certificate"), err)
	}

	rawPemCerts := []byte(pemCerts)
	rawPemCerts = append(rawPemCerts, caCert...)

	var derCerts []byte
	for true {
		var b *pem.Block

		if b, rawPemCerts = pem.Decode(rawPemCerts); err != nil {
446
			return status, "", fmt.Errorf("Failed to convert PEM certificate to DER format: %s: %s",
447 448 449 450 451 452 453 454
				pemCerts, err)
		}

		if b == nil {
			break
		}

		if b.Type != "CERTIFICATE" {
455
			return status, "", fmt.Errorf("Returned content is not PEM certificate: %s",
456 457 458 459 460 461 462 463
				b.Type)
		}

		derCerts = append(derCerts, b.Bytes...)
	}

	var x509Certs []*x509.Certificate
	if x509Certs, err = x509.ParseCertificates(derCerts); err != nil {
464
		return status, "", fmt.Errorf("Failed to parse certificates: %s", err)
465 466 467 468
	}

	cert := x509Certs[0]
	if err = cert.CheckSignature(x509.SHA256WithRSA, rawReport, sig); err != nil {
469
		return status, "", fmt.Errorf("Failed to verify the attestation verification report: %s",
470 471 472 473 474
			err)
	}

	for _, parentCert := range x509Certs[1:] {
		if err = cert.CheckSignatureFrom(parentCert); err != nil {
475
			return status, "", fmt.Errorf("Failed to verify the certificate (%s) with parent certificate (%s): %s",
476 477 478 479 480 481
				cert.Subject.String(), parentCert.Subject.String(), err)
		}

		cert = parentCert
	}

482
	return status, string(rawReport), nil
483 484 485 486 487 488 489
}

func init() {
	if err := attest.RegisterAttestation(&iasRegistry{}); err != nil {
		fmt.Print(err)
	}
}