Skip to content

Instantly share code, notes, and snippets.

@salrashid123
Last active May 21, 2024 17:57
Show Gist options
  • Save salrashid123/6372158f9a6b6af0772412394a2e6e21 to your computer and use it in GitHub Desktop.
Save salrashid123/6372158f9a6b6af0772412394a2e6e21 to your computer and use it in GitHub Desktop.
self-signed jwt access to google cloud iap
/*
self-signed jwt access to google cloud iap
https://cloud.google.com/iap/docs/authentication-howto#authenticating_with_a_self-signed_jwt
using google auth library
and service account bound inside Trusted Platform Module
*/
package main
import (
"context"
"flag"
"fmt"
"io"
"os"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"github.com/google/go-tpm-tools/client"
"github.com/google/go-tpm/legacy/tpm2"
"github.com/google/go-tpm/tpmutil"
sal "github.com/salrashid123/oauth2/tpm"
)
var ()
/*
cat svc-account.json | jq -r '.private_key' > /tmp/f.json
openssl rsa -out private.pem -traditional -in /tmp/f.json
tpm2_createprimary -C o -g sha256 -G rsa -c primary.ctx
tpm2_import -C primary.ctx -G rsa2048:rsassa:null -g sha256 -i private.pem -u key.pub -r key.prv
tpm2_load -C primary.ctx -u key.pub -r key.prv -c key.ctx
tpm2_evictcontrol -C o -c key.ctx 0x81010002
*/
func main() {
flag.Parse()
ctx := context.Background()
iapURL := "https://core-eso.uc.r.appspot.com"
// keyBytes, err := os.ReadFile("/home/srashid/gcp_misc/certs/core-eso-tpm-sa.json")
// if err != nil {
// panic(err)
// }
// s, err := google.JWTAccessTokenSourceFromJSON(keyBytes, iapURL)
// if err != nil {
// panic(err)
// }
rwc, err := tpm2.OpenTPM("/dev/tpm0")
if err != nil {
fmt.Fprintf(os.Stderr, "Can't open TPM : %v", err)
return
}
defer rwc.Close()
k, err := client.LoadCachedKey(rwc, tpmutil.Handle(0x81010002), nil)
if err != nil {
fmt.Fprintf(os.Stderr, "error closing tpm%v\n", err)
os.Exit(1)
}
fmt.Printf("using Key Handle %d\n", k.Handle())
s, err := sal.TpmTokenSource(&sal.TpmTokenConfig{
TPMDevice: rwc, // tpm is managed by the caller
Key: k,
Audience: iapURL,
Email: "tpm-sa@core-eso.iam.gserviceaccount.com",
UseOauthToken: false,
})
client := oauth2.NewClient(ctx, s)
resp, err := client.Get(iapURL)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Println(string(body))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment