Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement example to generate a fake EK certificate. #94

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
132 changes: 132 additions & 0 deletions examples/tpm-fakeekcert/tpm-fakeekcert.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
// Copyright (c) 2014, Google LLC All rights reserved.
twitchy-jsonp marked this conversation as resolved.
Show resolved Hide resolved
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
"crypto/x509/pkix"
"encoding/binary"
"flag"
"fmt"
"io"
"math/big"
"os"
"time"

"github.com/google/go-tpm/tpm"
)

var (
ownerAuthEnvVar = "TPM_OWNER_AUTH"

tpmPath = flag.String("tpm", "/dev/tpm0", "The path to the TPM device to use")
certPath = flag.String("cert", "ek.der", "The path to write the EK out to")
certOrg = flag.String("cert_org", "Acme Co", "The organization string to use in the EKCert")
twitchy-jsonp marked this conversation as resolved.
Show resolved Hide resolved
)

func generateCertificate(pub *rsa.PublicKey) ([]byte, error) {
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, err
}

serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, err
}

template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{*certOrg},
},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(1, 0, 0),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
BasicConstraintsValid: true,
}

return x509.CreateCertificate(rand.Reader, &template, &template, pub, priv)
}

func writePCCert(f io.Writer, der []byte) error {
// Write the header as documented in: TCG PC Specific Implementation
// Specification, section 7.3.2.
if _, err := f.Write([]byte{0x10, 0x01, 0x00}); err != nil {
return err
}
certLength := make([]byte, 2)
binary.BigEndian.PutUint16(certLength, uint16(len(der)))
if _, err := f.Write(certLength); err != nil {
return err
}

_, err := f.Write(der)
return err
}

func main() {
flag.Parse()

var ownerAuth [20]byte
ownerInput := os.Getenv(ownerAuthEnvVar)
if ownerInput != "" {
oa := sha1.Sum([]byte(ownerInput))
copy(ownerAuth[:], oa[:])
}

rwc, err := tpm.OpenTPM(*tpmPath)
if err != nil {
fmt.Fprintf(os.Stderr, "Couldn't open the TPM at %q: %v\n", *tpmPath, err)
return
}

pubEK, err := tpm.OwnerReadPubEK(rwc, ownerAuth)
if err != nil {
fmt.Fprintf(os.Stderr, "Couldn't read the endorsement key: %v\n", err)
return
}
pub, err := tpm.DecodePublic(pubEK)
if err != nil {
fmt.Fprintf(os.Stderr, "Couldn't decode the endorsement key: %v\n", err)
return
}

der, err := generateCertificate(pub.(*rsa.PublicKey))
if err != nil {
fmt.Fprintf(os.Stderr, "Couldn't generate a certificate: %v\n", err)
return
}

f, err := os.OpenFile(*certPath, os.O_RDWR|os.O_TRUNC|os.O_CREATE, 0744)
if err != nil {
fmt.Fprintf(os.Stderr, "Could open certificate path %q: %v\n", *certPath, err)
return
}
defer func() {
if err := f.Close(); err != nil {
fmt.Fprintf(os.Stderr, "Failed to close %q: %v\n", *certPath, err)
}
}()

if err := writePCCert(f, der); err != nil {
fmt.Fprintf(os.Stderr, "Failed to write certificate: %v\n", err)
return
}
}
25 changes: 25 additions & 0 deletions tpm/structures.go
Original file line number Diff line number Diff line change
Expand Up @@ -359,3 +359,28 @@ func convertPubKey(pk crypto.PublicKey) (*pubKey, error) {

return &pubKey, nil
}

// DecodePublic consumes bytes representing a TPM_PUBKEY, and returns a
// crypto.PublicKey representing the encoded public key. Currently, this
// function only supports 2048-bit RSA keys.
func DecodePublic(b []byte) (crypto.PublicKey, error) {
var pk pubKey
if _, err := tpmutil.Unpack(b, &pk); err != nil {
return nil, err
}
if pk.AlgorithmParams.AlgID != algRSA {
return nil, fmt.Errorf("expected RSA algorithm, got %v", pk.AlgorithmParams.AlgID)
}
var kp rsaKeyParams
if _, err := tpmutil.Unpack(pk.AlgorithmParams.Params, &kp); err != nil {
return nil, fmt.Errorf("unpacking rsaKeyParams: %v", err)
}
if kp.KeyLength != 2048 {
return nil, fmt.Errorf("only 2048-bit keys supported, got %d-bit", kp.KeyLength)
}

return &rsa.PublicKey{
E: int(big.NewInt(0).SetBytes(kp.Exponent).Int64()),
N: big.NewInt(0).SetBytes(pk.Key),
}, nil
}
31 changes: 31 additions & 0 deletions tpm/tpm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package tpm
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
"io/ioutil"
Expand Down Expand Up @@ -554,3 +555,33 @@ func TestForceClear(t *testing.T) {
t.Fatal("Couldn't clear the TPM without owner auth in physical presence mode:", err)
}
}

func TestEncodePubkey(t *testing.T) {
k, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
pk, err := convertPubKey(k.Public())
if err != nil {
t.Fatalf("convertPubKey() failed: %v", err)
}

packed, err := tpmutil.Pack(&pk)
if err != nil {
t.Fatalf("tpmutil.Pack(&pk) failed: %v", err)
}
pk2, err := DecodePublic(packed)
if err != nil {
t.Fatalf("DecodePublic() failed: %v", err)
}
decodedPK := pk2.(*rsa.PublicKey)

if k.N.Cmp(decodedPK.N) != 0 {
t.Errorf("k.N != decodedPK.N")
t.Logf("Got: %v", k.N)
t.Logf("Want: %v", decodedPK.N)
}
if k.E != decodedPK.E {
t.Errorf("decodedPK.E = %v, want %v", decodedPK.E, k.E)
}
}