github.com/jlmucb/cloudproxy@v0.0.0-20170830161738-b5aa0b619bc4/go/tao/tao_key_management_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 tao
    16  
    17  import (
    18  	"bytes"
    19  	"crypto/rand"
    20  	"crypto/x509"
    21  	"fmt"
    22  	"io/ioutil"
    23  	"os"
    24  	"testing"
    25  
    26  	"github.com/golang/protobuf/proto"
    27  )
    28  
    29  func TestNewTemporaryKeys(t *testing.T) {
    30  	TaoCryptoSuite = "sign:ecdsap256,crypt:aes128-ctr-hmacsha256,derive:hdkf-sha256"
    31  	k, err := NewTemporaryKeys(Signing | Crypting | Deriving)
    32  	if err != nil {
    33  		t.Fatal("Couldn't initialize temporary keys:", err)
    34  	}
    35  
    36  	if k.SigningKey == nil || k.CryptingKey == nil || k.DerivingKey == nil {
    37  		t.Fatal("Couldn't generate the right keys")
    38  	}
    39  
    40  	_, err = proto.Marshal(k.SigningKey.Header)
    41  	if err != nil {
    42  		t.Fatal("Couldn't marshal signing key")
    43  	}
    44  	_, err = proto.Marshal(k.CryptingKey.Header)
    45  	if err != nil {
    46  		t.Fatal("Couldn't marshal crypting key")
    47  	}
    48  	_, err = proto.Marshal(k.DerivingKey.Header)
    49  	if err != nil {
    50  		t.Fatal("Couldn't marshal deriving key")
    51  	}
    52  }
    53  
    54  func TestSelfSignedX509(t *testing.T) {
    55  	keyName := "Temporary_Keys_signer"
    56  	keyType := SignerTypeFromSuiteName(TaoCryptoSuite)
    57  	if keyType == nil {
    58  		t.Fatal("BAD KEYTYPE")
    59  	}
    60  	keyPurpose := "signing"
    61  	keyStatus := "active"
    62  	keyEpoch := int32(1)
    63  	s, err := InitializeSigner(nil, *keyType, &keyName, &keyEpoch, &keyPurpose, &keyStatus)
    64  	if err != nil {
    65  		t.Fatal("BAD KEYTYPE" + TaoCryptoSuite)
    66  	}
    67  
    68  	details := &X509Details{
    69  		CommonName:   proto.String("test"),
    70  		Country:      proto.String("US"),
    71  		State:        proto.String("WA"),
    72  		Organization: proto.String("Google"),
    73  	}
    74  
    75  	pkInt := PublicKeyAlgFromSignerAlg(*keyType)
    76  	sigInt := SignatureAlgFromSignerAlg(*keyType)
    77  	if pkInt < 0 || sigInt < 0 {
    78  		t.Fatal("Unknown Algorithm identifiers")
    79  	}
    80  	_, nil := s.CreateSelfSignedX509(pkInt, sigInt, int64(1), NewX509Name(details))
    81  	if err != nil {
    82  		t.Fatal(err.Error())
    83  	}
    84  }
    85  
    86  func TestNewOnDiskPBEKeys(t *testing.T) {
    87  	tempDir, err := ioutil.TempDir("", "TestNewOnDiskPBEKeys")
    88  	if err != nil {
    89  		t.Fatal("Couldn't create a temporary directory:", err)
    90  	}
    91  	defer os.RemoveAll(tempDir)
    92  	password := []byte(`don't use this password`)
    93  	k, err := NewOnDiskPBEKeys(Signing|Crypting|Deriving, password, tempDir, nil)
    94  	if err != nil {
    95  		t.Fatal("Couldn't create on-disk PBE keys:", err)
    96  	}
    97  	if k.SigningKey == nil || k.CryptingKey == nil || k.DerivingKey == nil {
    98  		t.Fatal("Couldn't generate the right keys")
    99  	}
   100  
   101  	_, err = NewOnDiskPBEKeys(Signing|Crypting|Deriving, password, tempDir, nil)
   102  	if err != nil {
   103  		t.Fatal("Couldn't recover the serialized keys:", err)
   104  	}
   105  }
   106  
   107  func TestVerifierFromX509(t *testing.T) {
   108  	keyName := "Temporary_Keys_signer"
   109  	keyType := SignerTypeFromSuiteName(TaoCryptoSuite)
   110  	keyPurpose := "signing"
   111  	keyStatus := "active"
   112  	keyEpoch := int32(1)
   113  	s, err := InitializeSigner(nil, *keyType, &keyName, &keyEpoch, &keyPurpose, &keyStatus)
   114  	if err != nil {
   115  		t.Fatal(err.Error())
   116  	}
   117  
   118  	details := &X509Details{
   119  		CommonName:   proto.String("test"),
   120  		Country:      proto.String("US"),
   121  		State:        proto.String("WA"),
   122  		Organization: proto.String("Google"),
   123  	}
   124  
   125  	pkInt := PublicKeyAlgFromSignerAlg(*keyType)
   126  	sigInt := SignatureAlgFromSignerAlg(*keyType)
   127  	if pkInt < 0 || sigInt < 0 {
   128  		t.Fatal("Unknown Algorithm identifiers")
   129  	}
   130  	cert, nil := s.CreateSelfSignedX509(pkInt, sigInt, int64(1), NewX509Name(details))
   131  	if err != nil {
   132  		t.Fatal(err.Error())
   133  	}
   134  	roots := x509.NewCertPool()
   135  	roots.AddCert(cert)
   136  
   137  	opts := x509.VerifyOptions{
   138  		Roots: roots,
   139  	}
   140  
   141  	_, err = cert.Verify(opts)
   142  	if err != nil {
   143  		t.Fatal("Failed to verify certificate: ", err, "\n")
   144  	}
   145  }
   146  
   147  func TestNewOnDiskPBESigner(t *testing.T) {
   148  	tempDir, err := ioutil.TempDir("", "TestNewOnDiskPBESigner")
   149  	if err != nil {
   150  		t.Fatal("Couldn't create a temporary directory:", err)
   151  	}
   152  	defer os.RemoveAll(tempDir)
   153  
   154  	password := []byte(`don't use this password`)
   155  	k, err := NewOnDiskPBEKeys(Signing, password, tempDir, nil)
   156  	if k == nil || err != nil {
   157  		t.Fatal("Couldn't create on-disk PBE keys:", err)
   158  	}
   159  
   160  	_, err = NewOnDiskPBEKeys(Signing, password, tempDir, nil)
   161  	if err != nil {
   162  		t.Fatal("Couldn't recover the serialized keys:", err)
   163  	}
   164  }
   165  
   166  func TestMarshalKeys(t *testing.T) {
   167  	k, err := NewTemporaryKeys(Signing | Crypting | Deriving)
   168  	if err != nil {
   169  		t.Fatal("NewTemporaryKeys fails")
   170  	}
   171  	fmt.Printf("\nGenerated keys\n")
   172  	PrintKeys(k)
   173  	pkInt := PublicKeyAlgFromSignerAlg(*k.SigningKey.Header.KeyType)
   174  	sigInt := SignatureAlgFromSignerAlg(*k.SigningKey.Header.KeyType)
   175  	if pkInt < 0 || sigInt < 0 {
   176  		t.Fatal("Bad sig algs")
   177  	}
   178  	details := &X509Details{
   179  		CommonName:   proto.String("test"),
   180  		Country:      proto.String("US"),
   181  		State:        proto.String("WA"),
   182  		Organization: proto.String("Google"),
   183  	}
   184  	cert, err := k.SigningKey.CreateSelfSignedX509(pkInt, sigInt, int64(10), NewX509Name(details))
   185  	if err != nil {
   186  		t.Fatal("k.SigningKey.CreateSelfSignedX509 failed")
   187  	}
   188  	k.Cert = cert
   189  	cks, err := CryptoKeysetFromKeys(k)
   190  	if err != nil {
   191  		t.Fatal("CryptoKeysetFromKeys failed")
   192  	}
   193  	_, err = KeysFromCryptoKeyset(cks)
   194  	if err != nil {
   195  		t.Fatal("CryptoKeysetFromKeys failed")
   196  	}
   197  	b, err := MarshalKeyset(cks)
   198  	var newCks CryptoKeyset
   199  	err = UnmarshalKeyset(b, &newCks)
   200  	if err != nil {
   201  		t.Fatal("UnmarshalKeyset failed")
   202  	}
   203  	nb, err := MarshalKeys(k)
   204  	if err != nil {
   205  		t.Fatal("MarshalKey failed")
   206  	}
   207  	newKeys, err := UnmarshalKeys(nb)
   208  	if err != nil {
   209  		t.Fatal("UnmarshalKeys failed")
   210  	}
   211  	fmt.Printf("\nNewkeys\n")
   212  	PrintKeys(newKeys)
   213  	newCert, err := newKeys.SigningKey.CreateSelfSignedX509(pkInt, sigInt, int64(10), NewX509Name(details))
   214  	if err != nil {
   215  		t.Fatal("newKeys.SigningKey.CreateSelfSignedX509 failed")
   216  	}
   217  	fmt.Printf("newCert: %x\n", newCert)
   218  }
   219  
   220  func TestPBEEncryptDecrypt(t *testing.T) {
   221  	pt := []byte("I am plaintext")
   222  	pw := []byte("I am a password")
   223  	ct, err := PBEEncrypt(pt, pw)
   224  	if err != nil {
   225  		t.Fatal("Can't PBEEncrypt")
   226  	}
   227  	dpt, err := PBEDecrypt(ct, pw)
   228  	if err != nil {
   229  		t.Fatal("Can't PBEDecrypt")
   230  	}
   231  	if !bytes.Equal(pt, dpt) {
   232  		t.Fatal("Plain and decrypted cipher don't match")
   233  	}
   234  }
   235  
   236  func TestTaoDelegatedKeys(t *testing.T) {
   237  	ft, err := NewSoftTao("", nil)
   238  	if err != nil {
   239  		t.Fatal("Couldn't initialize a SoftTao:", err)
   240  	}
   241  
   242  	_, err = NewTemporaryTaoDelegatedKeys(Signing|Crypting|Deriving, ft)
   243  	if err != nil {
   244  		t.Fatal("Couldn't initialize a temporary hosted keyset:", err)
   245  	}
   246  }
   247  
   248  func TestNewOnDiskTaoSealedKeys(t *testing.T) {
   249  	tempDir, err := ioutil.TempDir("", "TestInitHosted")
   250  	if err != nil {
   251  		t.Fatal(err.Error())
   252  	}
   253  	defer os.RemoveAll(tempDir)
   254  
   255  	ft, err := NewSoftTao("", nil)
   256  	if err != nil {
   257  		t.Fatal("Couldn't initialize a SoftTao:", err)
   258  	}
   259  
   260  	_, err = NewOnDiskTaoSealedKeys(Signing|Crypting|Deriving, ft, tempDir, SealPolicyDefault)
   261  	if err != nil {
   262  		t.Fatal("Couldn't initialize a hosted keyset:", err)
   263  	}
   264  
   265  	_, err = NewOnDiskTaoSealedKeys(Signing|Crypting|Deriving, ft, tempDir, SealPolicyDefault)
   266  	if err != nil {
   267  		t.Fatal("Couldn't read back a sealed, hosted keyset:", err)
   268  	}
   269  }
   270  
   271  // Test generating a new set of keys and saving/loading them to/from the disk unsealed.
   272  func TestUnsealedDelegatedKeysSaveLoad(t *testing.T) {
   273  	tempDir, err := ioutil.TempDir("", "TestInitHosted")
   274  	if err != nil {
   275  		t.Fatal(err.Error())
   276  	}
   277  	defer os.RemoveAll(tempDir)
   278  
   279  	ft, err := NewSoftTao("", nil)
   280  	if err != nil {
   281  		t.Error("Couldn't initialize a SoftTao:", err)
   282  		return
   283  	}
   284  
   285  	k, err := NewTemporaryTaoDelegatedKeys(Signing|Crypting|Deriving, ft)
   286  	if err != nil {
   287  		t.Error("failed to generate keys:", err)
   288  		return
   289  	}
   290  
   291  	if err = SaveKeyset(k, tempDir); err != nil {
   292  		t.Error("failed to save keys:", err)
   293  		return
   294  	}
   295  
   296  	if _, err = LoadKeys(Signing|Crypting|Deriving, nil, tempDir, SealPolicyDefault); err != nil {
   297  		t.Error("failed to load keys:", err)
   298  	}
   299  }
   300  
   301  // Test generating a new set of keys and saving/loading them to/from the disk
   302  // unsealed without a delegation.
   303  func TestUnsealedUndelegatedKeysSaveLoad(t *testing.T) {
   304  	tempDir, err := ioutil.TempDir("", "TestInitHosted")
   305  	if err != nil {
   306  		t.Fatal(err.Error())
   307  	}
   308  	defer os.RemoveAll(tempDir)
   309  
   310  	k, err := NewTemporaryTaoDelegatedKeys(Signing|Crypting|Deriving, nil)
   311  	if err != nil {
   312  		t.Error("failed to generate keys:", err)
   313  		return
   314  	}
   315  
   316  	if err = SaveKeyset(k, tempDir); err != nil {
   317  		t.Error("failed to save keys:", err)
   318  		return
   319  	}
   320  
   321  	if _, err = LoadKeys(Signing|Crypting|Deriving, nil, tempDir, SealPolicyDefault); err != nil {
   322  		t.Error("failed to load keys:", err)
   323  	}
   324  }
   325  
   326  func TestCorruptedCiphertext(t *testing.T) {
   327  	c := GenerateAnonymousCrypter()
   328  	if c == nil {
   329  		t.Fatal("GenerateAnonymousCrypter failed")
   330  	}
   331  
   332  	data := []byte("Test data to encrypt")
   333  	crypted, err := c.Encrypt(data)
   334  	if err != nil {
   335  		t.Fatal(err.Error())
   336  	}
   337  
   338  	var ed EncryptedData
   339  	if err := proto.Unmarshal(crypted, &ed); err != nil {
   340  		t.Fatal("Could not unmarshal the encrypted data")
   341  	}
   342  
   343  	// Read random data for the ciphertext.
   344  	if _, err := rand.Read(ed.Ciphertext); err != nil {
   345  		t.Fatal("Could not read random data into the ciphertext")
   346  	}
   347  
   348  	crypted2, err := proto.Marshal(&ed)
   349  	if err != nil {
   350  		t.Fatal("Could not marshal the corrupted ciphertext")
   351  	}
   352  
   353  	if _, err := c.Decrypt(crypted2); err == nil {
   354  		t.Fatal("Incorrectly succeeded at decrypting corrupted ciphertext")
   355  	}
   356  
   357  	// Corrupt each bit individually and make sure the test fails for any
   358  	// single bit flip. The range is over the first ciphertext, but this is
   359  	// identical to the range of the unmarshalled ciphertext in this loop.
   360  	for i := range ed.Ciphertext {
   361  		var ed2 EncryptedData
   362  		if err := proto.Unmarshal(crypted, &ed2); err != nil {
   363  			t.Fatal("Could not unmarshal the encrypted data a second time")
   364  		}
   365  
   366  		// Corrupt a single bit in the ciphertext.
   367  		ed2.Ciphertext[i] ^= ed2.Ciphertext[i]
   368  
   369  		crypted3, err := proto.Marshal(&ed2)
   370  		if err != nil {
   371  			t.Fatal("Could not marshal a second corrupted ciphertext")
   372  		}
   373  
   374  		if _, err := c.Decrypt(crypted3); err == nil {
   375  			t.Fatal("Incorrectly succeeded at decrypting a second corrupted ciphertext")
   376  		}
   377  	}
   378  }