Skip to content

Commit

Permalink
upgrade tpm signer; use tpm policy callback function
Browse files Browse the repository at this point in the history
  • Loading branch information
salrashid123 committed Jun 7, 2024
1 parent 7d138e4 commit 3f91f36
Show file tree
Hide file tree
Showing 7 changed files with 60 additions and 72 deletions.
15 changes: 6 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -424,20 +424,17 @@ openssl rsa -in /tmp/f.json -out /tmp/key_rsa.pem
### the specific primary here happens to be the h2 template described later on but you are free to define any template and policy

printf '\x00\x00' > unique.dat
tpm2_createprimary -C o -G ecc -g sha256 \
-c primary.ctx -a "fixedtpm|fixedparent|sensitivedataorigin|userwithauth|noda|restricted|decrypt" -u unique.dat

# import

tpm2_createprimary -C o -G ecc -g sha256 -c primary.ctx -a "fixedtpm|fixedparent|sensitivedataorigin|userwithauth|noda|restricted|decrypt" -u unique.dat
# tpm2_createprimary -C o -G ecc -g sha256 -c primary.ctx -a "fixedtpm|fixedparent|sensitivedataorigin|userwithauth|noda|restricted|decrypt"
tpm2_import -C primary.ctx -G rsa2048:rsassa:null -g sha256 -i /tmp/key_rsa.pem -u key.pub -r key.prv
tpm2_load -C primary.ctx -u key.pub -r key.prv -c key.ctx

## save to a persistent handle
tpm2_flushcontext -t
tpm2_load -C primary.ctx -u key.pub -r key.prv -c key.ctx
tpm2_flushcontext -t

tpm2_evictcontrol -C o -c key.ctx 0x81010002

# if you have tpm2-tss-engine installed, you can save as encrypted PEM
tpm2tss-genkey -u key.pub -r key.prv private.pem
# tpm2tss-genkey -u key.pub -r key.prv private.pem

## which formats it as TPM-encrypted PEM:
cat private.pem
Expand Down
5 changes: 3 additions & 2 deletions cmd/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,12 @@ go_library(
"@com_github_google_go_tpm//tpm2:go_default_library",
"@com_github_google_go_tpm//tpm2/transport:go_default_library",
"@com_github_google_go_tpm_tools//simulator:go_default_library",
"@com_github_foxboron_go_tpm_keyfiles//:go_default_library",
"@com_github_foxboron_go_tpm_keyfiles//:go_default_library",
"@com_github_golang_glog//:go_default_library",
"@com_github_google_go_tpm//tpmutil:go_default_library",
"@com_github_salrashid123_oauth2_tpm//:go_default_library",
"@com_github_fsnotify_fsnotify//:go_default_library",
"@com_github_salrashid123_golang_jwt_tpm//:go_default_library",
"@com_github_fsnotify_fsnotify//:go_default_library",
],
)

Expand Down
74 changes: 30 additions & 44 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"github.com/google/go-tpm/tpm2/transport"
"github.com/google/go-tpm/tpmutil"
mds "github.com/salrashid123/gce_metadata_server"
tpmjwt "github.com/salrashid123/golang-jwt-tpm"
saltpm "github.com/salrashid123/oauth2/tpm"

"golang.org/x/oauth2"
Expand Down Expand Up @@ -91,7 +92,8 @@ func main() {
// if using TPMs
var creds *google.Credentials
var rwc io.ReadWriteCloser
var authHandle tpm2.AuthHandle
var namedHandle tpm2.NamedHandle
var authSession tpmjwt.Session
// parse TPM PCR values (if set)
var pcrList = []int{}
if *pcrs != "" && *useTPM {
Expand Down Expand Up @@ -194,9 +196,6 @@ func main() {
}

// configure a session

var sess tpm2.Session

if *pcrs != "" {
strpcrs := strings.Split(*pcrs, ",")
var pcrList = []uint{}
Expand All @@ -210,41 +209,23 @@ func main() {
pcrList = append(pcrList, uint(j))
}

var cleanup func() error
sess, cleanup, err = tpm2.PolicySession(rwr, tpm2.TPMAlgSHA256, 16)
if err != nil {
glog.Error(os.Stderr, "ERROR: could not get PolicySession: %v", err)
os.Exit(1)
}
defer cleanup()

selection := tpm2.TPMLPCRSelection{
PCRSelections: []tpm2.TPMSPCRSelection{
{
Hash: tpm2.TPMAlgSHA256,
PCRSelect: tpm2.PCClientCompatible.PCRs(pcrList...),
},
authSession, err = tpmjwt.NewPCRSession(rwr, []tpm2.TPMSPCRSelection{
{
Hash: tpm2.TPMAlgSHA256,
PCRSelect: tpm2.PCClientCompatible.PCRs(pcrList...),
},
}

expectedDigest, err := mds.GetExpectedPCRDigest(rwr, selection, tpm2.TPMAlgSHA256)
})
if err != nil {
glog.Error(os.Stderr, "ERROR: could not get PolicySession: %v", err)
glog.Error(os.Stderr, "error creating tpm pcrsession %v\n", err)
os.Exit(1)
}
_, err = tpm2.PolicyPCR{
PolicySession: sess.Handle(),
Pcrs: selection,
PcrDigest: tpm2.TPM2BDigest{
Buffer: expectedDigest,
},
}.Execute(rwr)

} else if *keyPass != "" {
authSession, err = tpmjwt.NewPasswordSession(rwr, []byte(*keyPass))
if err != nil {
glog.Error(os.Stderr, "Unable to create policyPCR: %v", err)
glog.Error(os.Stderr, "error creating tpm passwordsession%v\n", err)
os.Exit(1)
}
} else {
sess = tpm2.PasswordAuth([]byte(*keyPass))
}

var ts oauth2.TokenSource
Expand Down Expand Up @@ -283,7 +264,7 @@ func main() {
ParentHandle: tpm2.AuthHandle{
Handle: primaryKey.ObjectHandle,
Name: tpm2.TPM2BName(primaryKey.Name),
Auth: sess,
Auth: tpm2.PasswordAuth([]byte(*parentPass)),
},
InPublic: key.Pubkey,
InPrivate: key.Privkey,
Expand All @@ -301,20 +282,24 @@ func main() {
_, _ = flushContextCmd.Execute(rwr)
}()

authHandle = tpm2.AuthHandle{
namedHandle = tpm2.NamedHandle{
Handle: rsaKey.ObjectHandle,
Name: rsaKey.Name,
Auth: tpm2.PasswordAuth([]byte(*keyPass)),
}
ts, err = saltpm.TpmTokenSource(&saltpm.TpmTokenConfig{
TPMDevice: rwc,
AuthHandle: &authHandle,
NamedHandle: namedHandle,
AuthSession: authSession,
Email: claims.ComputeMetadata.V1.Instance.ServiceAccounts["default"].Email,
Scopes: claims.ComputeMetadata.V1.Instance.ServiceAccounts["default"].Scopes,
UseOauthToken: true,
EncryptionHandle: encryptionSessionHandle,
EncryptionPub: encryptionPub,
})
if err != nil {
glog.Error(os.Stderr, "error creating tpm tokensource%v\n", err)
os.Exit(1)
}

} else if *persistentHandle > 0 {
glog.V(20).Infof("TPM credentials using using persistent handle")
Expand All @@ -325,29 +310,29 @@ func main() {
glog.Error(os.Stderr, "error executing tpm2.ReadPublic %v", err)
os.Exit(1)
}
authHandle = tpm2.AuthHandle{
namedHandle = tpm2.NamedHandle{
Handle: tpm2.TPMHandle(*persistentHandle), // persistent handle
Name: pub.Name,
Auth: sess,
}
ts, err = saltpm.TpmTokenSource(&saltpm.TpmTokenConfig{
TPMDevice: rwc,
AuthHandle: &authHandle,
NamedHandle: namedHandle,
AuthSession: authSession,
Email: claims.ComputeMetadata.V1.Instance.ServiceAccounts["default"].Email,
Scopes: claims.ComputeMetadata.V1.Instance.ServiceAccounts["default"].Scopes,
UseOauthToken: true,
EncryptionHandle: encryptionSessionHandle,
EncryptionPub: encryptionPub,
})
if err != nil {
glog.Error(os.Stderr, "error creating tpm tokensource%v\n", err)
os.Exit(1)
}
} else {
glog.Error("Must specify either a persistent handle or a keyfile for use with at TPM")
os.Exit(1)
}

if err != nil {
glog.Error(os.Stderr, "error creating tpm tokensource%v\n", err)
os.Exit(1)
}
creds = &google.Credentials{
ProjectID: claims.ComputeMetadata.V1.Project.ProjectID,
TokenSource: ts,
Expand Down Expand Up @@ -395,7 +380,8 @@ func main() {
DomainSocket: *useDomainSocket,
UseTPM: *useTPM,
TPMDevice: rwc,
AuthHandle: &authHandle,
NamedHandle: namedHandle,
AuthSession: authSession,
MetricsEnabled: *metricsEnabled,
MetricsInterface: *metricsInterface,
MetricsPort: *metricsPort,
Expand Down
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ require (
github.com/google/go-tpm v0.9.1-0.20240514145214-58e3e47cd434
github.com/google/go-tpm-tools v0.4.4
github.com/gorilla/mux v1.8.1
github.com/salrashid123/golang-jwt-tpm v1.7.1-0.20240604211341-f01b73a33d43
github.com/salrashid123/oauth2/tpm v0.0.0-20240605124728-abefe62a0bc5
github.com/salrashid123/golang-jwt-tpm v1.8.1-0.20240606202535-4a9cc73e10e7
github.com/salrashid123/oauth2/tpm v0.0.0-20240607190353-7c8d56da8695
golang.org/x/net v0.26.0
golang.org/x/oauth2 v0.21.0
google.golang.org/api v0.183.0
Expand Down
10 changes: 6 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,12 @@ github.com/prometheus/common v0.54.0 h1:ZlZy0BgJhTwVZUn7dLOkwCZHUkrAqd3WYtcFCWnM
github.com/prometheus/common v0.54.0/go.mod h1:/TQgMJP5CuVYveyT7n/0Ix8yLNNXy9yRSkhnLTHPDIQ=
github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc=
github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=
github.com/salrashid123/golang-jwt-tpm v1.7.1-0.20240604211341-f01b73a33d43 h1:4/sE+pplrAGwFJSUdyABaFD9nwoGw150wgppiVh12Y0=
github.com/salrashid123/golang-jwt-tpm v1.7.1-0.20240604211341-f01b73a33d43/go.mod h1:j09G3lbE4f1xA8b/iJylp+vjM9zjbXU56+OS70eifTg=
github.com/salrashid123/oauth2/tpm v0.0.0-20240605124728-abefe62a0bc5 h1:Z9e9fWwtXr6XW99qEV5fVU8IiLXqkcLGh52M+hE9MqI=
github.com/salrashid123/oauth2/tpm v0.0.0-20240605124728-abefe62a0bc5/go.mod h1:AUnV6Mqi0G40oMRvK3yfTYWY6gT1sg5qOkUAjECjL1g=
github.com/salrashid123/golang-jwt-tpm v1.8.1-0.20240606202535-4a9cc73e10e7 h1:Pf1R4jEDRNICUvVh3dILCNpJMAXSOTbJf+gsXzNl4kw=
github.com/salrashid123/golang-jwt-tpm v1.8.1-0.20240606202535-4a9cc73e10e7/go.mod h1:j09G3lbE4f1xA8b/iJylp+vjM9zjbXU56+OS70eifTg=
github.com/salrashid123/oauth2/tpm v0.0.0-20240607173538-b627228b5c65 h1:o9SQjmccJAGmktGpPFEARcsqD6rNXYlawDX/Q/oPzAY=
github.com/salrashid123/oauth2/tpm v0.0.0-20240607173538-b627228b5c65/go.mod h1:r/i6uqpS4UEttsF1cfMFA6d36E7hK9AewpEXjTq0/SA=
github.com/salrashid123/oauth2/tpm v0.0.0-20240607190353-7c8d56da8695 h1:+XNYNHaB/S+7+1FoP1/IVDAKspp52l93G+h6CqhmcBc=
github.com/salrashid123/oauth2/tpm v0.0.0-20240607190353-7c8d56da8695/go.mod h1:r/i6uqpS4UEttsF1cfMFA6d36E7hK9AewpEXjTq0/SA=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
Expand Down
14 changes: 7 additions & 7 deletions repositories.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -341,20 +341,20 @@ def go_repositories():
go_repository(
name = "com_github_salrashid123_golang_jwt_tpm",
importpath = "github.com/salrashid123/golang-jwt-tpm",
sum = "h1:4/sE+pplrAGwFJSUdyABaFD9nwoGw150wgppiVh12Y0=",
version = "v1.7.1-0.20240604211341-f01b73a33d43",
sum = "h1:Pf1R4jEDRNICUvVh3dILCNpJMAXSOTbJf+gsXzNl4kw=",
version = "v1.8.1-0.20240606202535-4a9cc73e10e7",
)
go_repository(
name = "com_github_salrashid123_oauth2_tpm",
importpath = "github.com/salrashid123/oauth2/tpm",
sum = "h1:Z9e9fWwtXr6XW99qEV5fVU8IiLXqkcLGh52M+hE9MqI=",
version = "v0.0.0-20240605124728-abefe62a0bc5",
sum = "h1:+XNYNHaB/S+7+1FoP1/IVDAKspp52l93G+h6CqhmcBc=",
version = "v0.0.0-20240607190353-7c8d56da8695",
)
go_repository(
name = "com_github_salrashid123_signer_tpm",
importpath = "github.com/salrashid123/signer/tpm",
sum = "h1:ADJfp739VgQe3iI6/abqk2R4c8r+QXJZ/3xNIXPUa1Y=",
version = "v0.0.0-20240604023456-fad3918e0a31",
sum = "h1:w+/chwzi8SuGwuMRin5iJGYHbPO8B+gS0edqMxkylvU=",
version = "v0.0.0-20240607132035-0e96f7d4c37c",
)
go_repository(
name = "com_github_stretchr_objx",
Expand Down Expand Up @@ -607,4 +607,4 @@ def go_repositories():
importpath = "go.uber.org/multierr",
sum = "h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=",
version = "v1.11.0",
)
)
10 changes: 6 additions & 4 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,8 @@ type ServerConfig struct {

UseTPM bool // toggle if TPM should be used for credentials (default: false)
TPMDevice io.ReadWriteCloser // initialized transport for the TPM
AuthHandle *tpm2.AuthHandle // initialized authorization handle to the key
NamedHandle tpm2.NamedHandle // initialized handle to the key
AuthSession tpmjwt.Session // auth session to use
EncryptionHandle tpm2.TPMHandle // (optional) handle to use for transit encryption
EncryptionPub *tpm2.TPMTPublic // (optional) public key to use for transit encryption
}
Expand Down Expand Up @@ -694,7 +695,8 @@ func (h *MetadataServer) getIDToken(targetAudience string) (string, error) {
ctx := context.Background()
config := &tpmjwt.TPMConfig{
TPMDevice: h.ServerConfig.TPMDevice,
AuthHandle: h.ServerConfig.AuthHandle,
NamedHandle: h.ServerConfig.NamedHandle,
AuthSession: h.ServerConfig.AuthSession,
EncryptionHandle: h.ServerConfig.EncryptionHandle,
EncryptionPub: h.ServerConfig.EncryptionPub,
}
Expand Down Expand Up @@ -1202,8 +1204,8 @@ func NewMetadataServer(ctx context.Context, serverConfig *ServerConfig, creds *g
return nil, errors.New("serverConfig, credential and claims cannot be nil")
}

if serverConfig.UseTPM && serverConfig.AuthHandle == nil {
return nil, errors.New("AuthHandle must be set if useTPM is enabled")
if serverConfig.UseTPM && &serverConfig.NamedHandle == nil {
return nil, errors.New("NamedHandle must be set if useTPM is enabled")
}

h := &MetadataServer{
Expand Down

0 comments on commit 3f91f36

Please sign in to comment.