github.com/jlmucb/cloudproxy@v0.0.0-20170830161738-b5aa0b619bc4/go/tpm2/support_test.go (about)

     1  // Copyright (c) 2014, Google Inc. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package tpm2
    16  
    17  import (
    18  	"bytes"
    19  	"crypto/rand"
    20  	"crypto/rsa"
    21  	"crypto/sha1"
    22  	"crypto/x509"
    23  	"fmt"
    24  	"io/ioutil"
    25  	"math/big"
    26  	"testing"
    27  	"time"
    28  
    29  	"github.com/golang/protobuf/proto"
    30  )
    31  
    32  func TestStringUtils(t *testing.T) {
    33  	in := "1, 3, 2"
    34  	out, err := StringToIntList(in)
    35  	if err != nil {
    36  		fmt.Printf("err: %s\n", err)
    37  		t.Fatal("Can't parse list\n")
    38  	}
    39  	for _, v := range out {
    40  		fmt.Printf("%d ", v)
    41  	}
    42  	fmt.Printf("\n")
    43  }
    44  
    45  func TestSerializeDeserialize(t *testing.T) {
    46  	key, err := rsa.GenerateKey(rand.Reader, 2048)
    47  	if err != nil {
    48  		t.Fatal("Cant generate rsa key\n")
    49  	}
    50  	ser, err := SerializeRsaPrivateKey(key)
    51  	if err != nil {
    52  		t.Fatal("Cant serialize rsa key\n")
    53  	}
    54  	newKey, err := DeserializeRsaKey(ser)
    55  	if err != nil {
    56  		t.Fatal("Can't deserialize rsa key\n")
    57  	}
    58  	if bytes.Compare(key.D.Bytes(), newKey.D.Bytes()) != 0 {
    59  		t.Fatal("D is wrong\n")
    60  	}
    61  	if bytes.Compare(key.PublicKey.N.Bytes(), newKey.PublicKey.N.Bytes()) != 0 {
    62  		t.Fatal("N is wrong\n")
    63  	}
    64  	ioutil.WriteFile("./tmptest/ser.buf", ser, 0644)
    65  	buf, _ := ioutil.ReadFile("./tmptest/ser.buf")
    66  	newerKey, err := DeserializeRsaKey(buf)
    67  	if err != nil {
    68  		t.Fatal("Can't deserialize rsa key\n")
    69  	}
    70  	if bytes.Compare(key.D.Bytes(), newerKey.D.Bytes()) != 0 {
    71  		t.Fatal("D is wrong\n")
    72  	}
    73  	if bytes.Compare(key.PublicKey.N.Bytes(), newerKey.PublicKey.N.Bytes()) != 0 {
    74  		t.Fatal("N is wrong\n")
    75  	}
    76  }
    77  
    78  func TestDer(t *testing.T) {
    79  	fileName := "./tmptest/endorsement_cert"
    80  	der, err := ioutil.ReadFile(fileName)
    81  	if der == nil || err != nil {
    82  		t.Fatal("Can't retrieve endorsement cert\n")
    83  	}
    84  	key, err := GetPublicKeyFromDerCert(der)
    85  	if der == nil {
    86  		t.Fatal("Can't get public key from endorsement cert\n")
    87  	}
    88  	fmt.Printf("key: %x\n", key)
    89  }
    90  
    91  // Test GenerateCert from Keys
    92  func TestGenerateCertFromKeys(t *testing.T) {
    93  	var notBefore time.Time
    94  	notBefore = time.Now()
    95  	validFor := 365 * 24 * time.Hour
    96  	notAfter := notBefore.Add(validFor)
    97  
    98  	signingKey, err := rsa.GenerateKey(rand.Reader, 2048)
    99  	if err != nil {
   100  		t.Fatal("Can't generate signing key\n")
   101  	}
   102  	derSignerCert, err := GenerateSelfSignedCertFromKey(signingKey, "Cloudproxy Authority",
   103  		"Application Policy Key", GetSerialNumber(), notBefore, notAfter)
   104  	if err != nil {
   105  		t.Fatal("Can't generate signer key\n")
   106  	}
   107  	fmt.Printf("SigningKey: %x\n", signingKey)
   108  
   109  	signedKey, err := rsa.GenerateKey(rand.Reader, 2048)
   110  	if err != nil {
   111  		t.Fatal("Can't generate privatekey\n")
   112  	}
   113  	newPublic := PublicKeyFromPrivate(signedKey)
   114  	if newPublic == nil {
   115  		t.Fatal("Can't generate privatekey\n")
   116  	}
   117  	cert, err := GenerateCertFromKeys(signingKey, derSignerCert, newPublic,
   118  		"TestKey", "CommonTestKey", GetSerialNumber(),
   119  		notBefore, notAfter)
   120  	if err != nil {
   121  		t.Fatal("Can't generate cert\n")
   122  	}
   123  	fmt.Printf("cert: %x\n", cert)
   124  }
   125  
   126  func TestEndorseCertificate(t *testing.T) {
   127  	fileName := "./tmptest/endorsement_cert.ext"
   128  	out, err := ioutil.ReadFile(fileName)
   129  	if out == nil || err != nil {
   130  		t.Fatal("Can't retrieve endorsement cert\n")
   131  	}
   132  	endorse_cert, err := x509.ParseCertificate(out)
   133  	if err != nil {
   134  		t.Fatal("Can't parse test endorse certificate ", err, "\n")
   135  	}
   136  	fmt.Printf("endorse_cert: %x\n", endorse_cert)
   137  }
   138  
   139  func TestSignCertificate(t *testing.T) {
   140  	var notBefore time.Time
   141  	notBefore = time.Now()
   142  	validFor := 365 * 24 * time.Hour
   143  	notAfter := notBefore.Add(validFor)
   144  
   145  	// Generate Policy Key.
   146  	privatePolicyKey, err := rsa.GenerateKey(rand.Reader, 2048)
   147  	if err != nil {
   148  		t.Fatal("Can't generate privatekey\n")
   149  	}
   150  
   151  	derPolicyCert, err := GenerateSelfSignedCertFromKey(privatePolicyKey, "PolicyKey",
   152  		"PolicyKey", GetSerialNumber(), notBefore, notAfter)
   153  	if err != nil {
   154  		t.Fatal("Can't parse program certificate ", err, "\n")
   155  	}
   156  
   157  	// Generate Program Key.
   158  	privateProgramKey, err := rsa.GenerateKey(rand.Reader, 2048)
   159  	if err != nil {
   160  		t.Fatal("Can't generate program privatekey\n")
   161  	}
   162  	derProgramCert, err := GenerateCertFromKeys(privatePolicyKey,
   163  		derPolicyCert, &privateProgramKey.PublicKey,
   164  		"JLM", "Test-program", GetSerialNumber(), notBefore, notAfter)
   165  	if err != nil {
   166  		t.Fatal("Can't generate cert\n")
   167  	}
   168  	ok, err := VerifyDerCert(derProgramCert, derPolicyCert)
   169  	if !ok || err != nil {
   170  		t.Fatal("Can't verify certificate ", err, "\n")
   171  	}
   172  }
   173  
   174  func TestRsaEncryptDataWithCredential(t *testing.T) {
   175  	unmarshaled_credential := []byte{0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8,
   176  		0x9, 0xa, 0xb, 0xc, 0xd, 0xf, 0x10}
   177  	var inData [64]byte
   178  	for i := 0; i < int(64); i++ {
   179  		inData[i] = byte(i)
   180  	}
   181  	fmt.Printf("Credential: %x\n", unmarshaled_credential)
   182  	fmt.Printf("inData: %x\n", inData)
   183  
   184  	var inHmac []byte
   185  	calcHmac, outData, err := EncryptDataWithCredential(true,
   186  		AlgTPM_ALG_SHA1, unmarshaled_credential,
   187  		inData[0:64], inHmac)
   188  	if err != nil {
   189  		t.Fatal("Could not encrypt data\n")
   190  	}
   191  	fmt.Printf("calcHmac: %x\n", calcHmac)
   192  	fmt.Printf("outData: %x\n", outData)
   193  	_, checkData, err := EncryptDataWithCredential(false,
   194  		AlgTPM_ALG_SHA1, unmarshaled_credential,
   195  		outData, calcHmac)
   196  	if err != nil {
   197  		t.Fatal("Could not encrypt data\n")
   198  	}
   199  	fmt.Printf("checkData: %x\n", checkData)
   200  	if bytes.Compare(inData[0:64], checkData) != 0 {
   201  		t.Fatal("input data and decrypt of encrypt don't match\n")
   202  	}
   203  }
   204  
   205  func TestRsaTranslate(t *testing.T) {
   206  	key, err := rsa.GenerateKey(rand.Reader, 2048)
   207  	if err != nil || key == nil {
   208  		t.Fatal("Can't gen private key %s\n", err)
   209  	}
   210  	msg, err := MarshalRsaPrivateToProto(key)
   211  	if err != nil {
   212  		t.Fatal("Can't marshal key to proto\n")
   213  	}
   214  	newKey, err := UnmarshalRsaPrivateFromProto(msg)
   215  	if err != nil {
   216  		t.Fatal("Can't unmarshal key to proto\n")
   217  	}
   218  	// values equal?
   219  	if key.D.Cmp(newKey.D) != 0 {
   220  		t.Fatal("Keys are unequal\n")
   221  	}
   222  	fmt.Printf("TestRsaTranslate succeeds\n")
   223  }
   224  
   225  func TestRsaPrivateKeyParse(t *testing.T) {
   226  
   227  	// use SerializeRsaPrivateKey(key *rsa.PrivateKey) ([]byte, error)
   228  	// and DeserializeRsaKey(in []byte) (*rsa.PrivateKey, error)
   229  	fileName := "./tmptest/cloudproxy_key_file.proto"
   230  	out, err := ioutil.ReadFile(fileName)
   231  	if out == nil || err != nil {
   232  		t.Fatal("Can't retrieve file\n")
   233  	}
   234  	msg := new(RsaPrivateKeyMessage)
   235  	err = proto.Unmarshal(out, msg)
   236  	key, err := UnmarshalRsaPrivateFromProto(msg)
   237  	if err != nil {
   238  		t.Fatal("Can't unmarshal key to proto\n")
   239  	}
   240  	fmt.Printf("key: %x\n", key)
   241  }
   242  
   243  func TestAttributes(t *testing.T) {
   244  	sealedObj := uint32(FlagFixedTPM | FlagFixedParent)
   245  	if sealedObj != 0x12 {
   246  		t.Fatal("sealed object flags wrong\n")
   247  	}
   248  	storageObj := uint32(FlagRestricted | FlagDecrypt | FlagUserWithAuth |
   249  		FlagSensitiveDataOrigin | FlagFixedTPM | FlagFixedParent)
   250  	if storageObj != 0x30072 {
   251  		t.Fatal("storage object flags wrong\n")
   252  	}
   253  	signObj := uint32(FlagRestricted | FlagSign | FlagUserWithAuth |
   254  		FlagSensitiveDataOrigin | FlagFixedTPM | FlagFixedParent)
   255  	if signObj != 0x50072 {
   256  		t.Fatal("storage object flags wrong\n")
   257  	}
   258  }
   259  
   260  func TestSetShortPcrs(t *testing.T) {
   261  	pcr_nums := []int{7, 8}
   262  	pcr, err := SetShortPcrs(pcr_nums)
   263  	if err != nil {
   264  		t.Fatal("Test SetShortPcrs fails\n")
   265  	}
   266  	test_pcr := []byte{0x03, 0x80, 0x01, 0x00}
   267  	if !bytes.Equal(test_pcr, pcr) {
   268  		t.Fatal("Wrong pcr value\n")
   269  	}
   270  }
   271  
   272  func TestSetHandle(t *testing.T) {
   273  	hand := SetHandle(Handle(OrdTPM_RH_OWNER))
   274  	if hand == nil {
   275  		t.Fatal("Test SetHandle fails\n")
   276  	}
   277  	test_out := []byte{0x40, 0, 0, 1}
   278  	if !bytes.Equal(test_out, hand) {
   279  		t.Fatal("Test SetHandle bad output\n")
   280  	}
   281  }
   282  
   283  func TestSetPasswordData(t *testing.T) {
   284  	pw1 := SetPasswordData("01020304")
   285  	test1 := []byte{0, 4, 1, 2, 3, 4}
   286  	if pw1 == nil || !bytes.Equal(test1, pw1) {
   287  		t.Fatal("Test Password 1 fails\n")
   288  	}
   289  	pw2 := SetPasswordData("0102030405")
   290  	test2 := []byte{0, 5, 1, 2, 3, 4, 5}
   291  	if pw2 == nil || !bytes.Equal(test2, pw2) {
   292  		t.Fatal("Test Password 2 fails\n")
   293  	}
   294  }
   295  
   296  func TestCreatePasswordAuthArea(t *testing.T) {
   297  	pw_auth1 := CreatePasswordAuthArea("01020304", Handle(OrdTPM_RS_PW))
   298  	test1 := []byte{0, 0xd, 0x40, 0, 0, 9, 0, 0, 1, 0, 4, 1, 2, 3, 4}
   299  	if test1 == nil || !bytes.Equal(test1, pw_auth1) {
   300  		t.Fatal("Test PasswordAuthArea 1 fails\n")
   301  	}
   302  
   303  	pw_auth2 := CreatePasswordAuthArea("", Handle(OrdTPM_RS_PW))
   304  	test2 := []byte{0, 0x9, 0x40, 0, 0, 9, 0, 0, 1, 0, 0}
   305  	if test2 == nil || !bytes.Equal(test1, pw_auth1) {
   306  		t.Fatal("Test PasswordAuthArea 2 fails\n")
   307  	}
   308  	fmt.Printf("TestCreatePasswordAuthArea: %x\n", pw_auth1)
   309  	fmt.Printf("TestCreatePasswordAuthArea: %x\n", pw_auth2)
   310  }
   311  
   312  func TestCreateSensitiveArea(t *testing.T) {
   313  	a1 := []byte{1, 2, 3, 4}
   314  	var a2 []byte
   315  	s := CreateSensitiveArea(a1, a2)
   316  	if s == nil {
   317  		t.Fatal("CreateSensitiveArea fails")
   318  	}
   319  	test := []byte{0, 8, 0, 4, 1, 2, 3, 4, 0, 0}
   320  	if !bytes.Equal(test, s) {
   321  		t.Fatal("CreateSensitiveArea fails")
   322  	}
   323  	fmt.Printf("Sensitive area: %x\n", s)
   324  }
   325  
   326  func TestCreateRsaParams(t *testing.T) {
   327  	var empty []byte
   328  	parms := RsaParams{uint16(AlgTPM_ALG_RSA), uint16(AlgTPM_ALG_SHA1),
   329  		uint32(0x00030072), empty, uint16(AlgTPM_ALG_AES), uint16(128),
   330  		uint16(AlgTPM_ALG_CFB), uint16(AlgTPM_ALG_NULL), uint16(0),
   331  		uint16(1024), uint32(0x00010001), empty}
   332  
   333  	s := CreateRsaParams(parms)
   334  	if s == nil {
   335  		t.Fatal("CreateRsaParams fails")
   336  	}
   337  	fmt.Printf("RsaParams area: %x\n", s)
   338  	/*
   339  		test := []byte{0,6,0,0x80,0,0x43, 0, 0x10, 4,0,0,1,0,1,0,0}
   340  		if !bytes.Equal(test, s) {
   341  			t.Fatal("CreateRsaParams fails")
   342  		}
   343  	*/
   344  }
   345  
   346  func TestCreateLongPcr(t *testing.T) {
   347  	s := CreateLongPcr(uint32(1), []int{7})
   348  	test := []byte{0, 0, 0, 1, 0, 4, 3, 0x80, 0, 0}
   349  	if !bytes.Equal(test, s) {
   350  		t.Fatal("CreateRsaParams fails")
   351  	}
   352  }
   353  
   354  func TestKDFa(t *testing.T) {
   355  	key := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 23, 14, 15}
   356  	out, err := KDFA(uint16(AlgTPM_ALG_SHA1), key, "IDENTITY", nil, nil, 256)
   357  	if err != nil {
   358  		t.Fatal("KDFa fails")
   359  	}
   360  	fmt.Printf("KDFA: %x\n", out)
   361  }
   362  
   363  func TestReadRsaBlob(t *testing.T) {
   364  }
   365  
   366  func TestCertificateParse(t *testing.T) {
   367  	out, err := ioutil.ReadFile("./tmptest/endorsement_cert")
   368  	if out == nil || err != nil {
   369  		t.Fatal("Can't retrieve file\n")
   370  	}
   371  
   372  	cert, err := x509.ParseCertificate(out)
   373  	if cert == nil || err != nil {
   374  		fmt.Printf("Error: %s\n", err)
   375  		t.Fatal("Can't parse retrieved cert\n")
   376  	}
   377  }
   378  
   379  func TestPad(t *testing.T) {
   380  	private, err := rsa.GenerateKey(rand.Reader, 2048)
   381  	if err != nil || private == nil {
   382  		t.Fatal("Can't gen private key %s\n", err)
   383  	}
   384  	public := &private.PublicKey
   385  	var a [9]byte
   386  	copy(a[0:8], "IDENTITY")
   387  
   388  	seed := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
   389  	encrypted_secret, err := rsa.EncryptOAEP(sha1.New(), rand.Reader,
   390  		public, seed, a[0:9])
   391  	if err != nil {
   392  		t.Fatal("Can't encrypt ", err)
   393  	}
   394  	fmt.Printf("encrypted_secret: %x\n", encrypted_secret)
   395  	decrypted_secret, err := rsa.DecryptOAEP(sha1.New(), rand.Reader,
   396  		private, encrypted_secret, a[0:9])
   397  	if err != nil {
   398  		t.Fatal("Can't decrypt ", err)
   399  	}
   400  	fmt.Printf("decrypted_secret: %x\n", decrypted_secret)
   401  	var N *big.Int
   402  	var D *big.Int
   403  	var x *big.Int
   404  	var z *big.Int
   405  	N = public.N
   406  	D = private.D
   407  	x = new(big.Int)
   408  	z = new(big.Int)
   409  	x.SetBytes(encrypted_secret)
   410  	z = z.Exp(x, D, N)
   411  	decrypted_pad := z.Bytes()
   412  	fmt.Printf("decrypted_pad   : %x\n", decrypted_pad)
   413  }