| 1 |
package cmd |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"encoding/json" |
| 6 |
"errors" |
| 7 |
"fmt" |
| 8 |
"log" |
| 9 |
"net/http" |
| 10 |
"time" |
| 11 |
|
| 12 |
"cloud.google.com/go/compute/metadata" |
| 13 |
"cloud.google.com/go/logging" |
| 14 |
"github.com/golang-jwt/jwt/v4" |
| 15 |
"github.com/google/go-tpm-tools/client" |
| 16 |
"github.com/google/go-tpm-tools/verifier" |
| 17 |
"github.com/google/go-tpm-tools/verifier/models" |
| 18 |
"github.com/google/go-tpm-tools/verifier/util" |
| 19 |
"github.com/google/go-tpm/legacy/tpm2" |
| 20 |
"github.com/spf13/cobra" |
| 21 |
"google.golang.org/api/option" |
| 22 |
"google.golang.org/grpc" |
| 23 |
"google.golang.org/grpc/credentials/insecure" |
| 24 |
) |
| 25 |
|
| 26 |
var mockCloudLoggingServerAddress string |
| 27 |
|
| 28 |
const toolName = "gotpm" |
| 29 |
|
| 30 |
// If hardware technology needs a variable length teenonce then please modify the flags description |
| 31 |
var tokenCmd = &cobra.Command{ |
| 32 |
Use: "token", |
| 33 |
Short: "Attest and fetch an OIDC token from Google Attestation Verification Service.", |
| 34 |
Long: `Gather attestation report and send it to Google Attestation Verification Service for an OIDC token. |
| 35 |
The OIDC token includes claims regarding the GCE VM, which is verified by Attestation Verification Service. Note that Confidential Computing API needs to be enabled for your account to access Google Attestation Verification Service https://console.cloud.google.com/apis/api/confidentialcomputing.googleapis.com. |
| 36 |
--algo flag overrides the public key algorithm for the GCE TPM attestation key. If not provided then by default rsa is used. |
| 37 |
`, |
| 38 |
Args: cobra.NoArgs, |
| 39 |
RunE: func(*cobra.Command, []string) error { |
| 40 |
rwc, err := openTpm() |
| 41 |
if err != nil { |
| 42 |
return err |
| 43 |
} |
| 44 |
defer rwc.Close() |
| 45 |
|
| 46 |
// Metadata Server (MDS). A GCP specific client. |
| 47 |
mdsClient := metadata.NewClient(nil) |
| 48 |
|
| 49 |
ctx := context.Background() |
| 50 |
|
| 51 |
fmt.Fprintf(debugOutput(), "Attestation Address is set to %s\n", asAddress) |
| 52 |
|
| 53 |
region, err := util.GetRegion(mdsClient) |
| 54 |
if err != nil { |
| 55 |
return fmt.Errorf("failed to fetch Region from MDS, the tool is probably not running in a GCE VM: %v", err) |
| 56 |
} |
| 57 |
|
| 58 |
projectID, err := mdsClient.ProjectIDWithContext(ctx) |
| 59 |
if err != nil { |
| 60 |
return fmt.Errorf("failed to retrieve ProjectID from MDS: %v", err) |
| 61 |
} |
| 62 |
|
| 63 |
verifierClient, err := util.NewRESTClient(ctx, asAddress, projectID, region) |
| 64 |
if err != nil { |
| 65 |
return fmt.Errorf("failed to create REST verifier client: %v", err) |
| 66 |
} |
| 67 |
|
| 68 |
// Supports GCE VM. Hard code the AK type. Set GCE AK (EK signing) cert |
| 69 |
var gceAK *client.Key |
| 70 |
var usedKeyAlgo string |
| 71 |
if keyAlgo == tpm2.AlgRSA { |
| 72 |
usedKeyAlgo = "RSA" |
| 73 |
gceAK, err = client.GceAttestationKeyRSA(rwc) |
| 74 |
} |
| 75 |
if keyAlgo == tpm2.AlgECC { |
| 76 |
usedKeyAlgo = "ECC" |
| 77 |
gceAK, err = client.GceAttestationKeyECC(rwc) |
| 78 |
} |
| 79 |
if err != nil { |
| 80 |
return err |
| 81 |
} |
| 82 |
if gceAK.Cert() == nil { |
| 83 |
return errors.New("failed to find GCE AK Certificate on this VM: try creating a new VM or verifying the VM has an EK cert using get-shielded-identity gcloud command. The used key algorithm is: " + usedKeyAlgo) |
| 84 |
} |
| 85 |
gceAK.Close() |
| 86 |
|
| 87 |
var cloudLogClient *logging.Client |
| 88 |
var cloudLogger *logging.Logger |
| 89 |
if cloudLog { |
| 90 |
if audience == "" { |
| 91 |
return errors.New("cloud logging requires the --audience flag") |
| 92 |
} |
| 93 |
if mockCloudLoggingServerAddress != "" { |
| 94 |
conn, err := grpc.NewClient(mockCloudLoggingServerAddress, grpc.WithTransportCredentials(insecure.NewCredentials())) |
| 95 |
if err != nil { |
| 96 |
log.Fatalf("dialing %q: %v", mockCloudLoggingServerAddress, err) |
| 97 |
} |
| 98 |
cloudLogClient, err = logging.NewClient(ctx, TestProjectID, option.WithGRPCConn(conn)) |
| 99 |
if err != nil { |
| 100 |
return fmt.Errorf("failed to create cloud logging client for mock cloud logging server: %w", err) |
| 101 |
} |
| 102 |
} else { |
| 103 |
cloudLogClient, err = logging.NewClient(ctx, projectID) |
| 104 |
if err != nil { |
| 105 |
return fmt.Errorf("failed to create cloud logging client: %w", err) |
| 106 |
} |
| 107 |
} |
| 108 |
|
| 109 |
cloudLogger = cloudLogClient.Logger(toolName) |
| 110 |
fmt.Fprintf(debugOutput(), "cloudLogger created for project: %s\n", projectID) |
| 111 |
} |
| 112 |
|
| 113 |
key = "gceAK" |
| 114 |
|
| 115 |
fmt.Fprint(debugOutput(), "Fetching attestation verifier OIDC token\n") |
| 116 |
|
| 117 |
challenge, err := verifierClient.CreateChallenge(ctx) |
| 118 |
if err != nil { |
| 119 |
return err |
| 120 |
} |
| 121 |
|
| 122 |
principalTokens, err := util.PrincipalFetcher(challenge.Name, mdsClient) |
| 123 |
if err != nil { |
| 124 |
return fmt.Errorf("failed to get principal tokens: %w", err) |
| 125 |
} |
| 126 |
|
| 127 |
ak, err := attestationKeys[key][keyAlgo](rwc) |
| 128 |
if err != nil { |
| 129 |
return fmt.Errorf("failed to get an AK: %w", err) |
| 130 |
} |
| 131 |
attestation, err := ak.Attest(client.AttestOpts{Nonce: challenge.Nonce, CertChainFetcher: http.DefaultClient}) |
| 132 |
if err != nil { |
| 133 |
return fmt.Errorf("failed to attest: %v", err) |
| 134 |
} |
| 135 |
ak.Close() |
| 136 |
|
| 137 |
req := verifier.VerifyAttestationRequest{ |
| 138 |
Challenge: challenge, |
| 139 |
GcpCredentials: principalTokens, |
| 140 |
Attestation: attestation, |
| 141 |
TokenOptions: &models.TokenOptions{Audience: audience, Nonces: customNonce, TokenType: "OIDC"}, |
| 142 |
} |
| 143 |
|
| 144 |
resp, err := verifierClient.VerifyAttestation(ctx, req) |
| 145 |
if err != nil { |
| 146 |
return err |
| 147 |
} |
| 148 |
if len(resp.PartialErrs) > 0 { |
| 149 |
fmt.Fprintf(debugOutput(), "partial errors from VerifyAttestation: %v", resp.PartialErrs) |
| 150 |
} |
| 151 |
|
| 152 |
token := resp.ClaimsToken |
| 153 |
|
| 154 |
// Get token expiration. |
| 155 |
claims := &jwt.RegisteredClaims{} |
| 156 |
_, _, err = jwt.NewParser().ParseUnverified(string(token), claims) |
| 157 |
if err != nil { |
| 158 |
return fmt.Errorf("failed to parse token: %w", err) |
| 159 |
} |
| 160 |
|
| 161 |
now := time.Now() |
| 162 |
if !now.Before(claims.ExpiresAt.Time) { |
| 163 |
return errors.New("token is expired") |
| 164 |
} |
| 165 |
|
| 166 |
// Print out the claims in the jwt payload |
| 167 |
mapClaims := jwt.MapClaims{} |
| 168 |
_, _, err = jwt.NewParser().ParseUnverified(string(token), mapClaims) |
| 169 |
if err != nil { |
| 170 |
return fmt.Errorf("failed to parse token: %w", err) |
| 171 |
} |
| 172 |
claimsString, err := json.MarshalIndent(mapClaims, "", " ") |
| 173 |
if err != nil { |
| 174 |
return fmt.Errorf("failed to format claims: %w", err) |
| 175 |
} |
| 176 |
|
| 177 |
if output == "" { |
| 178 |
fmt.Fprintf(messageOutput(), "%s\n", string(token)) |
| 179 |
} else { |
| 180 |
out := []byte(token) |
| 181 |
if _, err := dataOutput().Write(out); err != nil { |
| 182 |
return fmt.Errorf("failed to write the token: %v", err) |
| 183 |
} |
| 184 |
} |
| 185 |
|
| 186 |
if cloudLog { |
| 187 |
cloudLogger.Log(logging.Entry{Payload: challenge}) |
| 188 |
cloudLogger.Log(logging.Entry{Payload: attestation}) |
| 189 |
cloudLogger.Log(logging.Entry{Payload: map[string]string{"token": string(token)}}) |
| 190 |
cloudLogger.Log(logging.Entry{Payload: mapClaims}) |
| 191 |
cloudLogClient.Close() |
| 192 |
if err != nil { |
| 193 |
return fmt.Errorf("failed to close cloud logging client: %w", err) |
| 194 |
} |
| 195 |
} |
| 196 |
|
| 197 |
fmt.Fprintf(debugOutput(), "%s\nNote: these Claims are for debugging purpose and not verified\n", string(claimsString)) |
| 198 |
|
| 199 |
return nil |
| 200 |
}, |
| 201 |
} |
| 202 |
|
| 203 |
func init() { |
| 204 |
RootCmd.AddCommand(tokenCmd) |
| 205 |
addOutputFlag(tokenCmd) |
| 206 |
addPublicKeyAlgoFlag(tokenCmd) |
| 207 |
addAsAddressFlag(tokenCmd) |
| 208 |
addCloudLoggingFlag(tokenCmd) |
| 209 |
addAudienceFlag(tokenCmd) |
| 210 |
addEventLogFlag(tokenCmd) |
| 211 |
addCustomNonceFlag(tokenCmd) |
| 212 |
// TODO: Add TEE hardware OIDC token generation |
| 213 |
// addTeeNonceflag(tokenCmd) |
| 214 |
// addTeeTechnology(tokenCmd) |
| 215 |
} |