| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
package configtls |
| 5 |
|
| 6 |
import ( |
| 7 |
"crypto/tls" |
| 8 |
"crypto/x509" |
| 9 |
"encoding/pem" |
| 10 |
"fmt" |
| 11 |
|
| 12 |
tpmkeyfile "github.com/foxboron/go-tpm-keyfiles" |
| 13 |
"github.com/google/go-tpm/tpm2/transport" |
| 14 |
) |
| 15 |
|
| 16 |
|
| 17 |
type TPMConfig struct { |
| 18 |
Enabled bool `mapstructure:"enabled"` |
| 19 |
|
| 20 |
|
| 21 |
Path string `mapstructure:"path"` |
| 22 |
OwnerAuth string `mapstructure:"owner_auth"` |
| 23 |
Auth string `mapstructure:"auth"` |
| 24 |
|
| 25 |
_ struct{} |
| 26 |
} |
| 27 |
|
| 28 |
func (c TPMConfig) tpmCertificate(keyPem, certPem []byte, openTPM func() (transport.TPMCloser, error)) (tls.Certificate, error) { |
| 29 |
tpm, err := openTPM() |
| 30 |
if err != nil { |
| 31 |
return tls.Certificate{}, err |
| 32 |
} |
| 33 |
|
| 34 |
tpmKey, err := tpmkeyfile.Decode(keyPem) |
| 35 |
if err != nil { |
| 36 |
return tls.Certificate{}, fmt.Errorf("failed to load TPM key: %w", err) |
| 37 |
} |
| 38 |
|
| 39 |
tpmSigner, err := tpmKey.Signer(tpm, []byte(c.OwnerAuth), []byte(c.Auth)) |
| 40 |
if err != nil { |
| 41 |
return tls.Certificate{}, fmt.Errorf("failed to load TPM signer: %w", err) |
| 42 |
} |
| 43 |
|
| 44 |
certDER, _ := pem.Decode(certPem) |
| 45 |
x509Cert, err := x509.ParseCertificate(certDER.Bytes) |
| 46 |
if err != nil { |
| 47 |
return tls.Certificate{}, fmt.Errorf("failed to parse certificate: %w", err) |
| 48 |
} |
| 49 |
return tls.Certificate{ |
| 50 |
Certificate: [][]byte{ |
| 51 |
x509Cert.Raw, |
| 52 |
}, |
| 53 |
Leaf: x509Cert, |
| 54 |
PrivateKey: tpmSigner, |
| 55 |
}, nil |
| 56 |
} |