From e71c33c88dc87b88346a78dd121e5e8e15d714d7 Mon Sep 17 00:00:00 2001 From: Moritz Sanft <58110325+msanft@users.noreply.github.com> Date: Mon, 3 Apr 2023 15:06:27 +0200 Subject: [PATCH] cli: print attestation document with constellation verify (#1577) * wip: verification output * wip: Azure cert parsing * wip: print actual PCRs * wip: use string builder for output formatting * compare PCR expected with actual * tests * change naming * update cli reference * update bazel buildfile * bazel update * change loop signature --- cli/internal/cmd/verify.go | 227 +++++++++++++++++++++++++++----- cli/internal/cmd/verify_test.go | 145 +++++++++++++++++++- docs/docs/reference/cli.md | 5 +- 3 files changed, 336 insertions(+), 41 deletions(-) diff --git a/cli/internal/cmd/verify.go b/cli/internal/cmd/verify.go index c6812be8e..221e8d260 100644 --- a/cli/internal/cmd/verify.go +++ b/cli/internal/cmd/verify.go @@ -9,6 +9,10 @@ package cmd import ( "bytes" "context" + "crypto/x509" + "encoding/base64" + "encoding/json" + "encoding/pem" "errors" "fmt" "net" @@ -18,6 +22,7 @@ import ( "github.com/edgelesssys/constellation/v2/cli/internal/cloudcmd" "github.com/edgelesssys/constellation/v2/cli/internal/clusterid" "github.com/edgelesssys/constellation/v2/internal/atls" + "github.com/edgelesssys/constellation/v2/internal/attestation/measurements" "github.com/edgelesssys/constellation/v2/internal/config" "github.com/edgelesssys/constellation/v2/internal/constants" "github.com/edgelesssys/constellation/v2/internal/crypto" @@ -34,13 +39,13 @@ func NewVerifyCmd() *cobra.Command { cmd := &cobra.Command{ Use: "verify", Short: "Verify the confidential properties of a Constellation cluster", - Long: `Verify the confidential properties of a Constellation cluster. - -If arguments aren't specified, values are read from ` + "`" + constants.ClusterIDsFileName + "`.", + Long: `Verify the confidential properties of a Constellation cluster.\n` + + `If arguments aren't specified, values are read from ` + "`" + constants.ClusterIDsFileName + "`.", Args: cobra.ExactArgs(0), RunE: runVerify, } cmd.Flags().String("cluster-id", "", "expected cluster identifier") + cmd.Flags().Bool("raw", false, "print raw attestation document") cmd.Flags().StringP("node-endpoint", "e", "", "endpoint of the node to verify, passed as HOST[:PORT]") return cmd } @@ -61,85 +66,102 @@ func runVerify(cmd *cobra.Command, _ []string) error { dialer: dialer.New(nil, nil, &net.Dialer{}), log: log, } + formatter := &attestationDocFormatterImpl{ + log: log, + } v := &verifyCmd{log: log} - return v.verify(cmd, fileHandler, verifyClient) + return v.verify(cmd, fileHandler, verifyClient, formatter) } -func (v *verifyCmd) verify(cmd *cobra.Command, fileHandler file.Handler, verifyClient verifyClient) error { - flags, err := v.parseVerifyFlags(cmd, fileHandler) +func (c *verifyCmd) verify(cmd *cobra.Command, fileHandler file.Handler, verifyClient verifyClient, formatter attestationDocFormatter) error { + flags, err := c.parseVerifyFlags(cmd, fileHandler) if err != nil { - return err + return fmt.Errorf("parsing flags: %w", err) } - v.log.Debugf("Using flags: %+v", flags) + c.log.Debugf("Using flags: %+v", flags) - v.log.Debugf("Loading configuration file from %q", flags.configPath) + c.log.Debugf("Loading configuration file from %q", flags.configPath) conf, err := config.New(fileHandler, flags.configPath, flags.force) var configValidationErr *config.ValidationError if errors.As(err, &configValidationErr) { cmd.PrintErrln(configValidationErr.LongMessage()) } if err != nil { - return err + return fmt.Errorf("loading config file: %w", err) } - v.log.Debugf("Creating aTLS Validator for %s", conf.AttestationVariant) - validators, err := cloudcmd.NewValidator(conf, flags.maaURL, v.log) + c.log.Debugf("Creating aTLS Validator for %s", conf.AttestationVariant) + validators, err := cloudcmd.NewValidator(conf, flags.maaURL, c.log) if err != nil { - return err + return fmt.Errorf("creating aTLS validator: %w", err) } - v.log.Debugf("Updating expected PCRs") + c.log.Debugf("Updating expected PCRs") if err := validators.UpdateInitPCRs(flags.ownerID, flags.clusterID); err != nil { - return err + return fmt.Errorf("updating expected PCRs: %w", err) } nonce, err := crypto.GenerateRandomBytes(32) if err != nil { - return err + return fmt.Errorf("generating random nonce: %w", err) } - v.log.Debugf("Generated random nonce: %x", nonce) + c.log.Debugf("Generated random nonce: %x", nonce) - if err := verifyClient.Verify( + rawAttestationDoc, err := verifyClient.Verify( cmd.Context(), flags.endpoint, &verifyproto.GetAttestationRequest{ Nonce: nonce, }, validators.V(cmd), - ); err != nil { - return err + ) + if err != nil { + return fmt.Errorf("verifying: %w", err) } - cmd.Println("OK") + // certificates are only available for Azure + attDocOutput, err := formatter.format(rawAttestationDoc, conf.Provider.Azure == nil, flags.rawOutput, validators.PCRS()) + if err != nil { + return fmt.Errorf("printing attestation document: %w", err) + } + cmd.Println(attDocOutput) + cmd.Println("Verification OK") + return nil } -func (v *verifyCmd) parseVerifyFlags(cmd *cobra.Command, fileHandler file.Handler) (verifyFlags, error) { +func (c *verifyCmd) parseVerifyFlags(cmd *cobra.Command, fileHandler file.Handler) (verifyFlags, error) { configPath, err := cmd.Flags().GetString("config") if err != nil { return verifyFlags{}, fmt.Errorf("parsing config path argument: %w", err) } - v.log.Debugf("Flag 'config' set to %q", configPath) + c.log.Debugf("Flag 'config' set to %q", configPath) ownerID := "" clusterID, err := cmd.Flags().GetString("cluster-id") if err != nil { return verifyFlags{}, fmt.Errorf("parsing cluster-id argument: %w", err) } - v.log.Debugf("Flag 'cluster-id' set to %q", clusterID) + c.log.Debugf("Flag 'cluster-id' set to %q", clusterID) endpoint, err := cmd.Flags().GetString("node-endpoint") if err != nil { return verifyFlags{}, fmt.Errorf("parsing node-endpoint argument: %w", err) } - v.log.Debugf("Flag 'node-endpoint' set to %q", endpoint) + c.log.Debugf("Flag 'node-endpoint' set to %q", endpoint) force, err := cmd.Flags().GetBool("force") if err != nil { return verifyFlags{}, fmt.Errorf("parsing force argument: %w", err) } - v.log.Debugf("Flag 'force' set to %t", force) + c.log.Debugf("Flag 'force' set to %t", force) + + raw, err := cmd.Flags().GetBool("raw") + if err != nil { + return verifyFlags{}, fmt.Errorf("parsing raw argument: %w", err) + } + c.log.Debugf("Flag 'raw' set to %t", force) var idFile clusterid.File if err := fileHandler.ReadJSON(constants.ClusterIDsFileName, &idFile); err != nil && !errors.Is(err, afero.ErrFileNotFound) { @@ -150,7 +172,7 @@ func (v *verifyCmd) parseVerifyFlags(cmd *cobra.Command, fileHandler file.Handle emptyEndpoint := endpoint == "" emptyIDs := ownerID == "" && clusterID == "" if emptyEndpoint || emptyIDs { - v.log.Debugf("Trying to supplement empty flag values from %q", constants.ClusterIDsFileName) + c.log.Debugf("Trying to supplement empty flag values from %q", constants.ClusterIDsFileName) if emptyEndpoint { cmd.Printf("Using endpoint from %q. Specify --node-endpoint to override this.\n", constants.ClusterIDsFileName) endpoint = idFile.IP @@ -177,6 +199,7 @@ func (v *verifyCmd) parseVerifyFlags(cmd *cobra.Command, fileHandler file.Handle ownerID: ownerID, clusterID: clusterID, maaURL: idFile.AttestationURL, + rawOutput: raw, force: force, }, nil } @@ -187,6 +210,7 @@ type verifyFlags struct { clusterID string configPath string maaURL string + rawOutput bool force bool } @@ -207,6 +231,140 @@ func addPortIfMissing(endpoint string, defaultPort int) (string, error) { return "", err } +// an attestationDocFormatter formats the attestation document. +type attestationDocFormatter interface { + // format returns the raw or formatted attestation doc depending on the rawOutput argument. + format(docString string, PCRsOnly bool, rawOutput bool, expectedPCRs measurements.M) (string, error) +} + +type attestationDocFormatterImpl struct { + log debugLog +} + +// format returns the raw or formatted attestation doc depending on the rawOutput argument. +func (f *attestationDocFormatterImpl) format(docString string, PCRsOnly bool, rawOutput bool, expectedPCRs measurements.M) (string, error) { + b := &strings.Builder{} + b.WriteString("Attestation Document:\n") + if rawOutput { + b.WriteString(fmt.Sprintf("%s\n", docString)) + return b.String(), nil + } + + var doc attestationDoc + if err := json.Unmarshal([]byte(docString), &doc); err != nil { + return "", fmt.Errorf("unmarshal attestation document: %w", err) + } + + if err := f.parseQuotes(b, doc.Attestation.Quotes, expectedPCRs); err != nil { + return "", fmt.Errorf("parse quote: %w", err) + } + if PCRsOnly { + return b.String(), nil + } + + instanceInfoString, err := base64.StdEncoding.DecodeString(doc.InstanceInfo) + if err != nil { + return "", fmt.Errorf("decode instance info: %w", err) + } + + var instanceInfo azureInstanceInfo + if err := json.Unmarshal(instanceInfoString, &instanceInfo); err != nil { + return "", fmt.Errorf("unmarshal instance info: %w", err) + } + + if err := f.parseCerts(b, "VCEK certificate", instanceInfo.Vcek); err != nil { + return "", fmt.Errorf("print VCEK certificate: %w", err) + } + if err := f.parseCerts(b, "Certificate chain", instanceInfo.CertChain); err != nil { + return "", fmt.Errorf("print certificate chain: %w", err) + } + + return b.String(), nil +} + +// parseCerts parses the base64-encoded PEM certificates and writes their details to the output builder. +func (f *attestationDocFormatterImpl) parseCerts(b *strings.Builder, certTypeName string, encCertString string) error { + certBytes, err := base64.StdEncoding.DecodeString(encCertString) + if err != nil { + return fmt.Errorf("decode %s: %w", certTypeName, err) + } + formattedCert := strings.ReplaceAll(string(certBytes[:len(certBytes)-1]), "\n", "\n\t\t") + "\n" + b.WriteString(fmt.Sprintf("\tRaw %s:\n\t\t%s", certTypeName, formattedCert)) + + f.log.Debugf("Decoding PEM certificate: %s", certTypeName) + i := 1 + for block, rest := pem.Decode(certBytes); block != nil; block, rest = pem.Decode(rest) { + f.log.Debugf("Parsing PEM block: %d", i) + if block.Type != "CERTIFICATE" { + return fmt.Errorf("parse %s: expected PEM block type 'CERTIFICATE', got '%s'", certTypeName, block.Type) + } + + cert, err := x509.ParseCertificate(block.Bytes) + if err != nil { + return fmt.Errorf("parse %s: %w", certTypeName, err) + } + + b.WriteString(fmt.Sprintf("\t%s (%d):\n", certTypeName, i)) + b.WriteString(fmt.Sprintf("\t\tSerial Number: %s\n", cert.SerialNumber)) + b.WriteString(fmt.Sprintf("\t\tSubject: %s\n", cert.Subject)) + b.WriteString(fmt.Sprintf("\t\tIssuer: %s\n", cert.Issuer)) + b.WriteString(fmt.Sprintf("\t\tNot Before: %s\n", cert.NotBefore)) + b.WriteString(fmt.Sprintf("\t\tNot After: %s\n", cert.NotAfter)) + b.WriteString(fmt.Sprintf("\t\tSignature Algorithm: %s\n", cert.SignatureAlgorithm)) + b.WriteString(fmt.Sprintf("\t\tPublic Key Algorithm: %s\n", cert.PublicKeyAlgorithm)) + + i++ + } + + return nil +} + +// parseQuotes parses the base64-encoded quotes and writes their details to the output builder. +func (f *attestationDocFormatterImpl) parseQuotes(b *strings.Builder, quotes []quote, expectedPCRs measurements.M) error { + b.WriteString("\tQuote:\n") + for pcrNum, expectedPCR := range expectedPCRs { + encPCR := quotes[1].Pcrs.Pcrs[fmt.Sprintf("%d", pcrNum)] + actualPCR, err := base64.StdEncoding.DecodeString(encPCR) + if err != nil { + return fmt.Errorf("decode PCR %d: %w", pcrNum, err) + } + b.WriteString(fmt.Sprintf("\t\tPCR %d (Strict: %t):\n", pcrNum, !expectedPCR.ValidationOpt)) + b.WriteString(fmt.Sprintf("\t\t\tExpected:\t%x\n", expectedPCR.Expected)) + b.WriteString(fmt.Sprintf("\t\t\tActual:\t\t%x\n", actualPCR)) + } + return nil +} + +// attestationDoc is the attestation document returned by the verifier. +type attestationDoc struct { + Attestation struct { + AkPub string `json:"ak_pub"` + Quotes []quote `json:"quotes"` + EventLog string `json:"event_log"` + TeeAttestation interface{} `json:"TeeAttestation"` + } `json:"Attestation"` + InstanceInfo string `json:"InstanceInfo"` + UserData string `json:"UserData"` +} + +type quote struct { + Quote string `json:"quote"` + RawSig string `json:"raw_sig"` + Pcrs struct { + Hash int `json:"hash"` + Pcrs map[string]string `json:"pcrs"` + } `json:"pcrs"` +} + +// azureInstanceInfo is the b64-decoded InstanceInfo field of the attestation document. +// as of now (2023-04-03), it only contains interesting data on Azure. +type azureInstanceInfo struct { + Vcek string `json:"Vcek"` + CertChain string `json:"CertChain"` + AttestationReport string `json:"AttestationReport"` + RuntimeData string `json:"RuntimeData"` +} + type constellationVerifier struct { dialer grpcInsecureDialer log debugLog @@ -215,11 +373,11 @@ type constellationVerifier struct { // Verify retrieves an attestation statement from the Constellation and verifies it using the validator. func (v *constellationVerifier) Verify( ctx context.Context, endpoint string, req *verifyproto.GetAttestationRequest, validator atls.Validator, -) error { +) (string, error) { v.log.Debugf("Dialing endpoint: %q", endpoint) conn, err := v.dialer.DialInsecure(ctx, endpoint) if err != nil { - return fmt.Errorf("dialing init server: %w", err) + return "", fmt.Errorf("dialing init server: %w", err) } defer conn.Close() @@ -228,23 +386,24 @@ func (v *constellationVerifier) Verify( v.log.Debugf("Sending attestation request") resp, err := client.GetAttestation(ctx, req) if err != nil { - return fmt.Errorf("getting attestation: %w", err) + return "", fmt.Errorf("getting attestation: %w", err) } v.log.Debugf("Verifying attestation") signedData, err := validator.Validate(ctx, resp.Attestation, req.Nonce) if err != nil { - return fmt.Errorf("validating attestation: %w", err) + return "", fmt.Errorf("validating attestation: %w", err) } if !bytes.Equal(signedData, []byte(constants.ConstellationVerifyServiceUserData)) { - return errors.New("signed data in attestation does not match expected user data") + return "", errors.New("signed data in attestation does not match expected user data") } - return nil + + return string(resp.Attestation), nil } type verifyClient interface { - Verify(ctx context.Context, endpoint string, req *verifyproto.GetAttestationRequest, validator atls.Validator) error + Verify(ctx context.Context, endpoint string, req *verifyproto.GetAttestationRequest, validator atls.Validator) (string, error) } type grpcInsecureDialer interface { diff --git a/cli/internal/cmd/verify_test.go b/cli/internal/cmd/verify_test.go index 72189658b..1126fd666 100644 --- a/cli/internal/cmd/verify_test.go +++ b/cli/internal/cmd/verify_test.go @@ -14,10 +14,12 @@ import ( "errors" "net" "strconv" + "strings" "testing" "github.com/edgelesssys/constellation/v2/cli/internal/clusterid" "github.com/edgelesssys/constellation/v2/internal/atls" + "github.com/edgelesssys/constellation/v2/internal/attestation/measurements" "github.com/edgelesssys/constellation/v2/internal/cloud/cloudprovider" "github.com/edgelesssys/constellation/v2/internal/config" "github.com/edgelesssys/constellation/v2/internal/constants" @@ -42,6 +44,7 @@ func TestVerify(t *testing.T) { testCases := map[string]struct { provider cloudprovider.Provider protoClient *stubVerifyClient + formatter *stubAttDocFormatter nodeEndpointFlag string configFlag string ownerIDFlag string @@ -56,6 +59,7 @@ func TestVerify(t *testing.T) { clusterIDFlag: zeroBase64, protoClient: &stubVerifyClient{}, wantEndpoint: "192.0.2.1:1234", + formatter: &stubAttDocFormatter{}, }, "azure": { provider: cloudprovider.Azure, @@ -63,6 +67,7 @@ func TestVerify(t *testing.T) { clusterIDFlag: zeroBase64, protoClient: &stubVerifyClient{}, wantEndpoint: "192.0.2.1:1234", + formatter: &stubAttDocFormatter{}, }, "default port": { provider: cloudprovider.GCP, @@ -70,11 +75,13 @@ func TestVerify(t *testing.T) { clusterIDFlag: zeroBase64, protoClient: &stubVerifyClient{}, wantEndpoint: "192.0.2.1:" + strconv.Itoa(constants.VerifyServiceNodePortGRPC), + formatter: &stubAttDocFormatter{}, }, "endpoint not set": { provider: cloudprovider.GCP, clusterIDFlag: zeroBase64, protoClient: &stubVerifyClient{}, + formatter: &stubAttDocFormatter{}, wantErr: true, }, "endpoint from id file": { @@ -83,6 +90,7 @@ func TestVerify(t *testing.T) { protoClient: &stubVerifyClient{}, idFile: &clusterid.File{IP: "192.0.2.1"}, wantEndpoint: "192.0.2.1:" + strconv.Itoa(constants.VerifyServiceNodePortGRPC), + formatter: &stubAttDocFormatter{}, }, "override endpoint from details file": { provider: cloudprovider.GCP, @@ -91,17 +99,20 @@ func TestVerify(t *testing.T) { protoClient: &stubVerifyClient{}, idFile: &clusterid.File{IP: "192.0.2.1"}, wantEndpoint: "192.0.2.2:1234", + formatter: &stubAttDocFormatter{}, }, "invalid endpoint": { provider: cloudprovider.GCP, nodeEndpointFlag: ":::::", clusterIDFlag: zeroBase64, protoClient: &stubVerifyClient{}, + formatter: &stubAttDocFormatter{}, wantErr: true, }, "neither owner id nor cluster id set": { provider: cloudprovider.GCP, nodeEndpointFlag: "192.0.2.1:1234", + formatter: &stubAttDocFormatter{}, wantErr: true, }, "use owner id from id file": { @@ -110,12 +121,14 @@ func TestVerify(t *testing.T) { protoClient: &stubVerifyClient{}, idFile: &clusterid.File{OwnerID: zeroBase64}, wantEndpoint: "192.0.2.1:1234", + formatter: &stubAttDocFormatter{}, }, "config file not existing": { provider: cloudprovider.GCP, clusterIDFlag: zeroBase64, nodeEndpointFlag: "192.0.2.1:1234", configFlag: "./file", + formatter: &stubAttDocFormatter{}, wantErr: true, }, "error protoClient GetState": { @@ -123,6 +136,7 @@ func TestVerify(t *testing.T) { nodeEndpointFlag: "192.0.2.1:1234", clusterIDFlag: zeroBase64, protoClient: &stubVerifyClient{verifyErr: rpcStatus.Error(codes.Internal, "failed")}, + formatter: &stubAttDocFormatter{}, wantErr: true, }, "error protoClient GetState not rpc": { @@ -130,6 +144,16 @@ func TestVerify(t *testing.T) { nodeEndpointFlag: "192.0.2.1:1234", clusterIDFlag: zeroBase64, protoClient: &stubVerifyClient{verifyErr: someErr}, + formatter: &stubAttDocFormatter{}, + wantErr: true, + }, + "format error": { + provider: cloudprovider.Azure, + nodeEndpointFlag: "192.0.2.1:1234", + clusterIDFlag: zeroBase64, + protoClient: &stubVerifyClient{}, + wantEndpoint: "192.0.2.1:1234", + formatter: &stubAttDocFormatter{formatErr: someErr}, wantErr: true, }, } @@ -166,7 +190,7 @@ func TestVerify(t *testing.T) { } v := &verifyCmd{log: logger.NewTest(t)} - err := v.verify(cmd, fileHandler, tc.protoClient) + err := v.verify(cmd, fileHandler, tc.protoClient, tc.formatter) if tc.wantErr { assert.Error(err) @@ -179,6 +203,119 @@ func TestVerify(t *testing.T) { } } +type stubAttDocFormatter struct { + formatErr error +} + +func (f *stubAttDocFormatter) format(_ string, _ bool, _ bool, _ measurements.M) (string, error) { + return "", f.formatErr +} + +func TestFormat(t *testing.T) { + formatter := func() *attestationDocFormatterImpl { + return &attestationDocFormatterImpl{ + log: logger.NewTest(t), + } + } + + testCases := map[string]struct { + formatter *attestationDocFormatterImpl + doc string + wantErr bool + }{ + "invalid doc": { + formatter: formatter(), + doc: "invalid", + wantErr: true, + }, + } + + for name, tc := range testCases { + t.Run(name, func(t *testing.T) { + _, err := tc.formatter.format(tc.doc, false, false, nil) + if tc.wantErr { + assert.Error(t, err) + } else { + assert.NoError(t, err) + } + }) + } +} + +func TestParseCerts(t *testing.T) { + formatter := func() *attestationDocFormatterImpl { + return &attestationDocFormatterImpl{ + log: logger.NewTest(t), + } + } + validCert := `-----BEGIN CERTIFICATE----- +MIIFTDCCAvugAwIBAgIBADBGBgkqhkiG9w0BAQowOaAPMA0GCWCGSAFlAwQCAgUA +oRwwGgYJKoZIhvcNAQEIMA0GCWCGSAFlAwQCAgUAogMCATCjAwIBATB7MRQwEgYD +VQQLDAtFbmdpbmVlcmluZzELMAkGA1UEBhMCVVMxFDASBgNVBAcMC1NhbnRhIENs +YXJhMQswCQYDVQQIDAJDQTEfMB0GA1UECgwWQWR2YW5jZWQgTWljcm8gRGV2aWNl +czESMBAGA1UEAwwJU0VWLU1pbGFuMB4XDTIyMTEyMzIyMzM0N1oXDTI5MTEyMzIy +MzM0N1owejEUMBIGA1UECwwLRW5naW5lZXJpbmcxCzAJBgNVBAYTAlVTMRQwEgYD +VQQHDAtTYW50YSBDbGFyYTELMAkGA1UECAwCQ0ExHzAdBgNVBAoMFkFkdmFuY2Vk +IE1pY3JvIERldmljZXMxETAPBgNVBAMMCFNFVi1WQ0VLMHYwEAYHKoZIzj0CAQYF +K4EEACIDYgAEVGm4GomfpkiziqEYP61nfKaz5OjDLr8Y0POrv4iAnFVHAmBT81Ms +gfSLKL5r3V3mNzl1Zh7jwSBft14uhGdwpARoK0YNQc4OvptqVIiv2RprV53DMzge +rtwiumIargiCo4IBFjCCARIwEAYJKwYBBAGceAEBBAMCAQAwFwYJKwYBBAGceAEC +BAoWCE1pbGFuLUIwMBEGCisGAQQBnHgBAwEEAwIBAzARBgorBgEEAZx4AQMCBAMC +AQAwEQYKKwYBBAGceAEDBAQDAgEAMBEGCisGAQQBnHgBAwUEAwIBADARBgorBgEE +AZx4AQMGBAMCAQAwEQYKKwYBBAGceAEDBwQDAgEAMBEGCisGAQQBnHgBAwMEAwIB +CDARBgorBgEEAZx4AQMIBAMCAXMwTQYJKwYBBAGceAEEBEB80kCZ1oAyCjWC6w3m +xOz+i4t6dFjk/Bqhm7+Jscf8D62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QCN1qBYOywoZWGnQvk6u0Oh\n\t\t5zkEKykXU6sK8hA6L65rQcqWUjEHDa9AZUpx3UuCmpPc24dx6DTHc58M7TxcyKry\n\t\t8s4CvruBKFbQ6B8MHnH6k07MzsmiBnsiIhAscZ0ipGm6h8e/VM/6ULrAcVSxZ+Mh\n\t\tD/IogZAuCQARsGQ4QYXBT8Qc5mLnTkx30m1rZVlp1VcN4ngOo/1tz1jj1mfpG2zv\n\t\twNcQa9LwAzRLnnmLpxXA2OMbl7AaTWQenpL9rzBON2sg4OBl6lVhaSU0uBbFyCmR\n\t\tRvBqKC0iDD6TvyIikkMq05v5YwIKFYw++ICndz+fKcLEULZbziAsZ52qjM8iPVHC\n\t\tpN0yhVOr2g22F9zxlGH3WxTl9ymUytuv3vJL/aJiQM+n/Ri90Sc05EK4oIJ3+BS8\n\t\tyu5cVy9o2cQcOcQ8rhQh+Kv1sR9xrs25EXZF8KEETfhoJnN6KY1RwG7HsOfAQ3dV\n\t\tLWInQRaC/8JPyVS2zbd0+NRBJOnq4/quv/P3C4SBP98/ZuGrqN59uifyqC3Kodkl\n\t\tWkG/2UdhiLlCmOtsU+BYDZrSiYK1R9FNnlQCOGrkuVxpDwa2TbbvEEzQP7RXxotA\n\t\tKlxejvrY4VuK8agNqvffVofbdIIperK65K4+0mYIb+A6fU8QQHlCbti4ERSZ6UYD\n\t\tF/SjRih31+SAtWb42jueAA==\n\t\t-----END CERTIFICATE-----\n\tSome Cert (1):\n\t\tSerial Number: 0\n\t\tSubject: CN=SEV-VCEK,OU=Engineering,O=Advanced Micro Devices,L=Santa Clara,ST=CA,C=US\n\t\tIssuer: CN=SEV-Milan,OU=Engineering,O=Advanced Micro Devices,L=Santa Clara,ST=CA,C=US\n\t\tNot Before: 2022-11-23 22:33:47 +0000 UTC\n\t\tNot After: 2029-11-23 22:33:47 +0000 UTC\n\t\tSignature Algorithm: SHA384-RSAPSS\n\t\tPublic Key Algorithm: ECDSA\n" + + testCases := map[string]struct { + formatter *attestationDocFormatterImpl + encodedCert string + expected string + wantErr bool + }{ + "one cert": { + formatter: formatter(), + encodedCert: base64.StdEncoding.EncodeToString([]byte(validCert)), + expected: validCertExpected, + }, + "invalid cert": { + formatter: formatter(), + encodedCert: "invalid", + wantErr: true, + }, + } + + for name, tc := range testCases { + t.Run(name, func(t *testing.T) { + assert := assert.New(t) + + b := &strings.Builder{} + err := tc.formatter.parseCerts(b, "Some Cert", tc.encodedCert) + if tc.wantErr { + assert.Error(err) + } else { + assert.NoError(err) + assert.Equal(tc.expected, b.String()) + } + }) + } +} + func TestVerifyClient(t *testing.T) { testCases := map[string]struct { attestationDoc atls.FakeAttestationDoc @@ -247,7 +384,7 @@ func TestVerifyClient(t *testing.T) { Nonce: tc.nonce, } - err = verifier.Verify(context.Background(), addr, request, atls.NewFakeValidator(variant.Dummy{})) + _, err = verifier.Verify(context.Background(), addr, request, atls.NewFakeValidator(variant.Dummy{})) if tc.wantErr { assert.Error(err) @@ -263,9 +400,9 @@ type stubVerifyClient struct { endpoint string } -func (c *stubVerifyClient) Verify(_ context.Context, endpoint string, _ *verifyproto.GetAttestationRequest, _ atls.Validator) error { +func (c *stubVerifyClient) Verify(_ context.Context, endpoint string, _ *verifyproto.GetAttestationRequest, _ atls.Validator) (string, error) { c.endpoint = endpoint - return c.verifyErr + return "", c.verifyErr } type stubVerifyAPI struct { diff --git a/docs/docs/reference/cli.md b/docs/docs/reference/cli.md index 42a52d274..d39f9191f 100644 --- a/docs/docs/reference/cli.md +++ b/docs/docs/reference/cli.md @@ -312,9 +312,7 @@ Verify the confidential properties of a Constellation cluster ### Synopsis -Verify the confidential properties of a Constellation cluster. - -If arguments aren't specified, values are read from `constellation-id.json`. +Verify the confidential properties of a Constellation cluster.\nIf arguments aren't specified, values are read from `constellation-id.json`. ``` constellation verify [flags] @@ -326,6 +324,7 @@ constellation verify [flags] --cluster-id string expected cluster identifier -h, --help help for verify -e, --node-endpoint string endpoint of the node to verify, passed as HOST[:PORT] + --raw print raw attestation document ``` ### Options inherited from parent commands