Skip to content

Instantly share code, notes, and snippets.

@salrashid123
Last active August 29, 2023 00:40
Show Gist options
  • Save salrashid123/865ea715881cb7c020da987b08c3881a to your computer and use it in GitHub Desktop.
Save salrashid123/865ea715881cb7c020da987b08c3881a to your computer and use it in GitHub Desktop.
Trusted Platform Module (TPM) based GCP Service Account Key

snippet demonstrating how to create an RSA key on a TPM, then assocaite that with a GCP service account.

Finally, use that embedded service account key to access GCP resources


export PROJECT_ID=core-eso

## create service account 

gcloud iam service-accounts create tpm-sa

gcloud projects add-iam-policy-binding core-eso \
     --member="serviceAccount:tpm-sa@$PROJECT_ID.iam.gserviceaccount.com"  \
     --role=roles/storage.admin

### create key on tpm and generate a self-signed certificate

git clone https://github.com/salrashid123/go_tpm_https_embed

cd go_tpm_https_embed
go run src/selfsigned/main.go --cn [email protected] -persistentHandle=0x81008000

0x81008000         <<< tpm persisted 
x509cert.pem         <<< public cert for tpm-based key


### associate the x509 with the service account, (as allowed by constraints/iam.disableServiceAccountKeyUpload )

$ gcloud iam service-accounts keys upload x509cert.pem --iam-account="[email protected]"
        keyAlgorithm: KEY_ALG_RSA_2048
        keyOrigin: USER_PROVIDED
        keyType: USER_MANAGED
        name: projects/core-eso/serviceAccounts/[email protected]/keys/4ac60d72244e0447e26da7882cd38b0e87fbcd9c
        validAfterTime: '2023-08-18T18:12:06Z'
        validBeforeTime: '2024-08-17T18:12:06Z'


## note the keyid 4ac60d72244e0447e26da7882cd38b0e87fbcd9c

edit the go file and add in the projectid, svcaccountemail and keyid

var (
	projectId           = "core-eso"
	bucketName          = "core-eso-bucket"
	serviceAccountEmail = "[email protected]"
	keyId               = "4ac60d72244e0447e26da7882cd38b0e87fbcd9c"
)

func main() 
	rwc, err := tpm2.OpenTPM(*tpmPath)
        defer rwc.Close()  // remember to close 

        //*persistentHandle = 0x81008000
	k, err := client.LoadCachedKey(rwc, tpmutil.Handle(*persistentHandle), nil) 

	ts, err := sal.TpmTokenSource(&sal.TpmTokenConfig{
		TPMDevice: rwc,
		Key:       k,
		Email:     *serviceAccountEmail,
		//KeyId:         *keyId,
		UseOauthToken: true,
	})

run

$ sudo go run main.go 
2023/08/18 14:57:14 Token: ya29.c.b0Aaekm1Kz4axIzYhtFU7hjV3sOSEaz68_....


2023/08/18 14:57:15 core-eso-bucket
2023/08/18 14:57:15 core-eso_cloudbuild

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment