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

     1  //
     2  // Licensed under the Apache License, Version 2.0 (the "License");
     3  // you may not use this file except in compliance with the License.
     4  // You may obtain a copy of the License at
     5  //
     6  //     http://www.apache.org/licenses/LICENSE-2.0
     7  //
     8  // Unless required by applicable law or agreed to in writing, software
     9  // distributed under the License is distributed on an "AS IS" BASIS,
    10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package tao
    15  
    16  import (
    17  	"crypto/aes"
    18  	"crypto/rand"
    19  	"crypto/sha256"
    20  	"crypto/sha512"
    21  	"crypto/x509"
    22  	"crypto/x509/pkix"
    23  	"errors"
    24  	"fmt"
    25  	"io/ioutil"
    26  	"os"
    27  	"path"
    28  
    29  	"github.com/golang/protobuf/proto"
    30  	"github.com/jlmucb/cloudproxy/go/tao/auth"
    31  	"github.com/jlmucb/cloudproxy/go/util"
    32  	"golang.org/x/crypto/pbkdf2"
    33  )
    34  
    35  // A KeyType represent the type(s) of keys held by a Keys struct.
    36  type KeyType int
    37  
    38  // These are the types of supported keys.
    39  const (
    40  	Signing KeyType = 1 << iota
    41  	Crypting
    42  	Deriving
    43  )
    44  
    45  // The Keys structure manages a set of signing, verifying, encrypting,
    46  // and key-deriving // keys for many uses.  To some extent, the field
    47  // meanings will differ between uses.  The comments below are focused
    48  // on the use of the Keys structure for domains, including the policy
    49  // domain, and Tao's (Root and Stacked).
    50  type Keys struct {
    51  
    52  	// This is the directory the Keys structure is saved to and
    53  	// restored from.
    54  	dir string
    55  
    56  	// This is the policy for the keys, for example, governing
    57  	// what the sealing/unsealing policy is.
    58  	policy string
    59  
    60  	// This represents the key types for the keys generated for this structure.
    61  	// Note: the VerifyingKey is not generated for this structure so is
    62  	// not included.
    63  	keyTypes KeyType
    64  
    65  	// This represents the private key used to sign statements.
    66  	SigningKey *Signer
    67  
    68  	// This represents the keys for the symmetric suite used to encrypt and
    69  	// integrity protect data.
    70  	CryptingKey *Crypter
    71  
    72  	// This is the deriving key used to obtain keys from a master secret
    73  	// like passwords in the case of domain keys.
    74  	DerivingKey *Deriver
    75  
    76  	// This represents the public key of the SigningKey.
    77  	VerifyingKey *Verifier
    78  
    79  	// This is an attestation by my host appointing the public key of
    80  	// the Signing key.  This can be nil.
    81  	Delegation *Attestation
    82  
    83  	// This is the certificate for the signing key.
    84  	// For a Root Tao, this cert is signed by the policy key or
    85  	// other authority.  It can be nil.
    86  	Cert *x509.Certificate
    87  
    88  	// This is the certificate chain from the signer of Cert to the
    89  	// policy key (or other authority).
    90  	CertChain []*x509.Certificate
    91  }
    92  
    93  // The paths to the filename used by the Keys type.
    94  const (
    95  	X509VerifierPath    = "cert"
    96  	PBEKeysetPath       = "keys"
    97  	PBESignerPath       = "signer"
    98  	SealedKeysetPath    = "sealed_keyset"
    99  	PlaintextKeysetPath = "plaintext_keyset"
   100  )
   101  
   102  // X509VerifierPath returns the path to the verifier key, stored as an X.509
   103  // certificate.
   104  func (k *Keys) X509VerifierPath() string {
   105  	if k.dir == "" {
   106  		return ""
   107  	}
   108  	return path.Join(k.dir, X509VerifierPath)
   109  }
   110  
   111  // PBEKeysetPath returns the path for stored keys.
   112  func (k *Keys) PBEKeysetPath() string {
   113  	if k.dir == "" {
   114  		return ""
   115  	}
   116  	return path.Join(k.dir, PBEKeysetPath)
   117  }
   118  
   119  // PBESignerPath returns the path for a stored signing key.
   120  func (k *Keys) PBESignerPath() string {
   121  	if k.dir == "" {
   122  		return ""
   123  	}
   124  	return path.Join(k.dir, PBESignerPath)
   125  }
   126  
   127  // Generate or restore a signer.
   128  // InitializeSigner uses marshaledCryptoKey to restore a signer from
   129  // a serialized CryptoKey if it's not nil; otherwise it generates one.
   130  // If generated, the remainder of the arguments are used as parameters;
   131  // otherwise they are ignored.
   132  func InitializeSigner(marshaledCryptoKey []byte, keyType string, keyName *string, keyEpoch *int32, keyPurpose *string, keyStatus *string) (*Signer, error) {
   133  	if marshaledCryptoKey != nil {
   134  		k, err := UnmarshalCryptoKey(marshaledCryptoKey)
   135  		if err != nil {
   136  			return nil, errors.New("Can't UnmarshalCryptoKey")
   137  		}
   138  		s := SignerFromCryptoKey(*k)
   139  		if s == nil {
   140  			k.Clear()
   141  			return nil, errors.New("Can't SignerFromCryptoKey")
   142  		}
   143  		if s.Header.KeyPurpose == nil || *s.Header.KeyPurpose != "signing" {
   144  			k.Clear()
   145  			s.Clear()
   146  			return nil, errors.New("Recovered key not a signer")
   147  		}
   148  	}
   149  	k := GenerateCryptoKey(keyType, keyName, keyEpoch, keyPurpose, keyStatus)
   150  	if k == nil {
   151  		return nil, errors.New("Can't GenerateCryptoKey")
   152  	}
   153  	s := SignerFromCryptoKey(*k)
   154  	if s == nil {
   155  		k.Clear()
   156  		return nil, errors.New("Can't SignerFromCryptoKey")
   157  	}
   158  	if s.Header.KeyPurpose == nil || *s.Header.KeyPurpose != "signing" {
   159  		k.Clear()
   160  		s.Clear()
   161  		return nil, errors.New("Recovered key not a signer")
   162  	}
   163  	return s, nil
   164  }
   165  
   166  // Generate or restore a crypter.
   167  // InitializeCrypter uses marshaledCryptoKey to restore a signer from
   168  // a serialized CryptoKey if it's not nil; otherwise it generates one.
   169  // If generated, the remainder of the arguments are used as parameters;
   170  // otherwise they are ignored.
   171  func InitializeCrypter(marshaledCryptoKey []byte, keyType string, keyName *string, keyEpoch *int32, keyPurpose *string, keyStatus *string) (*Crypter, error) {
   172  	if marshaledCryptoKey != nil {
   173  		k, err := UnmarshalCryptoKey(marshaledCryptoKey)
   174  		if err != nil {
   175  			return nil, errors.New("Can't UnmarshalCryptoKey")
   176  		}
   177  		c := CrypterFromCryptoKey(*k)
   178  		if c == nil {
   179  			k.Clear()
   180  			return nil, errors.New("Can't CrypterFromCryptoKey")
   181  		}
   182  		if c.Header.KeyPurpose == nil || *c.Header.KeyPurpose != "crypting" {
   183  			k.Clear()
   184  			c.Clear()
   185  			return nil, errors.New("Recovered key not a crypter")
   186  		}
   187  	}
   188  	k := GenerateCryptoKey(keyType, keyName, keyEpoch, keyPurpose, keyStatus)
   189  	if k == nil {
   190  		return nil, errors.New("Can't GenerateCryptoKey")
   191  	}
   192  	c := CrypterFromCryptoKey(*k)
   193  	if c == nil {
   194  		k.Clear()
   195  		return nil, errors.New("Can't CrypterFromCryptoKey")
   196  	}
   197  	if c.Header.KeyPurpose == nil || *c.Header.KeyPurpose != "crypting" {
   198  		k.Clear()
   199  		c.Clear()
   200  		return nil, errors.New("Recovered key not a crypter")
   201  	}
   202  	return c, nil
   203  }
   204  
   205  // Generate or restore a deriver.
   206  // InitializeDeriver uses marshaledCryptoKey to restore a signer from
   207  // a serialized CryptoKey if it's not nil; otherwise it generates one.
   208  // If generated, the remainder of the arguments are used as parameters;
   209  // otherwise they are ignored.
   210  func InitializeDeriver(marshaledCryptoKey []byte, keyType string, keyName *string, keyEpoch *int32, keyPurpose *string, keyStatus *string) (*Deriver, error) {
   211  	if marshaledCryptoKey != nil {
   212  		k, err := UnmarshalCryptoKey(marshaledCryptoKey)
   213  		if err != nil {
   214  			return nil, errors.New("Can't UnmarshalCryptoKey")
   215  		}
   216  		d := DeriverFromCryptoKey(*k)
   217  		if d == nil {
   218  			k.Clear()
   219  			return nil, errors.New("Can't DeriverFromCryptoKey")
   220  		}
   221  		if d.Header.KeyPurpose == nil || *d.Header.KeyPurpose != "deriving" {
   222  			k.Clear()
   223  			return nil, errors.New("Recovered key not a deriver")
   224  		}
   225  	}
   226  	k := GenerateCryptoKey(keyType, keyName, keyEpoch, keyPurpose, keyStatus)
   227  	if k == nil {
   228  		return nil, errors.New("Can't GenerateCryptoKey")
   229  	}
   230  	d := DeriverFromCryptoKey(*k)
   231  	if d == nil {
   232  		k.Clear()
   233  		return nil, errors.New("Can't DeriverFromCryptoKey")
   234  	}
   235  	if d.Header.KeyPurpose == nil || *d.Header.KeyPurpose != "deriving" {
   236  		k.Clear()
   237  		d.Clear()
   238  		return nil, errors.New("Recovered key not a deriver")
   239  	}
   240  	return d, nil
   241  }
   242  
   243  func PrintKeys(keys *Keys) {
   244  	fmt.Printf("dir: %s\n", keys.dir)
   245  	fmt.Printf("policy: %s\n", keys.policy)
   246  	fmt.Printf("Key types: ")
   247  	if keys.keyTypes&Signing != 0 {
   248  		fmt.Printf("Signing ")
   249  	}
   250  	if keys.keyTypes&Crypting != 0 {
   251  		fmt.Printf("Crypting ")
   252  	}
   253  	if keys.keyTypes&Deriving != 0 {
   254  		fmt.Printf("Deriving ")
   255  	}
   256  	fmt.Printf("\n")
   257  	if keys.SigningKey != nil {
   258  		PrintCryptoKeyHeader(*keys.SigningKey.Header)
   259  	}
   260  	if keys.VerifyingKey != nil {
   261  		PrintCryptoKeyHeader(*keys.VerifyingKey.Header)
   262  	}
   263  	if keys.CryptingKey != nil {
   264  		PrintCryptoKeyHeader(*keys.CryptingKey.Header)
   265  	}
   266  	if keys.DerivingKey != nil {
   267  		PrintCryptoKeyHeader(*keys.DerivingKey.Header)
   268  	}
   269  	if keys.Delegation != nil {
   270  		fmt.Printf("Delegation present\n")
   271  	} else {
   272  		fmt.Printf("Delegation empty\n")
   273  	}
   274  	if keys.Cert != nil {
   275  		fmt.Printf("Cert present\n")
   276  	} else {
   277  		fmt.Printf("Cert empty\n")
   278  	}
   279  }
   280  
   281  // Encodes Keys to Cryptokeyset
   282  func CryptoKeysetFromKeys(k *Keys) (*CryptoKeyset, error) {
   283  	// fill in keys, cert, attestation
   284  	var keyList [][]byte
   285  	if k.keyTypes&Signing == Signing {
   286  		ck := &CryptoKey{
   287  			KeyHeader: k.SigningKey.Header,
   288  		}
   289  		keyComponents, err := KeyComponentsFromSigner(k.SigningKey)
   290  		if err != nil {
   291  			return nil, errors.New("Can't get key components from signing key")
   292  		}
   293  		ck.KeyComponents = keyComponents
   294  		serializedCryptoKey, err := proto.Marshal(ck)
   295  		if err != nil {
   296  			return nil, errors.New("Can't serialize signing key")
   297  		}
   298  		keyList = append(keyList, serializedCryptoKey)
   299  	}
   300  
   301  	if k.keyTypes&Crypting == Crypting {
   302  		ck := &CryptoKey{
   303  			KeyHeader: k.CryptingKey.Header,
   304  		}
   305  		keyComponents, err := KeyComponentsFromCrypter(k.CryptingKey)
   306  		if err != nil {
   307  			return nil, errors.New("Can't get key components from crypting key")
   308  		}
   309  		ck.KeyComponents = keyComponents
   310  		serializedCryptoKey, err := proto.Marshal(ck)
   311  		if err != nil {
   312  			return nil, errors.New("Can't serialize crypting key")
   313  		}
   314  		keyList = append(keyList, serializedCryptoKey)
   315  	}
   316  
   317  	if k.keyTypes&Deriving == Deriving {
   318  		ck := &CryptoKey{
   319  			KeyHeader: k.DerivingKey.Header,
   320  		}
   321  		keyComponents, err := KeyComponentsFromDeriver(k.DerivingKey)
   322  		if err != nil {
   323  			return nil, errors.New("Can't get key components from deriving key")
   324  		}
   325  		ck.KeyComponents = keyComponents
   326  		serializedCryptoKey, err := proto.Marshal(ck)
   327  		if err != nil {
   328  			return nil, errors.New("Can't serialize deriving key")
   329  		}
   330  		keyList = append(keyList, serializedCryptoKey)
   331  	}
   332  
   333  	cks := &CryptoKeyset{
   334  		Keys: keyList,
   335  	}
   336  	if k.Cert != nil {
   337  		cks.Cert = k.Cert.Raw
   338  	}
   339  	cks.Delegation = k.Delegation
   340  	for i := 0; i < len(k.CertChain); i++ {
   341  		cks.CertChain = append(cks.CertChain, k.CertChain[i].Raw)
   342  	}
   343  	return cks, nil
   344  }
   345  
   346  // KeysFromCryptoKeyset decodes a CryptoKeyset into a Keys structure.
   347  func KeysFromCryptoKeyset(cks *CryptoKeyset) (*Keys, error) {
   348  	k := new(Keys)
   349  
   350  	for i := 0; i < len(cks.Keys); i++ {
   351  		var ck CryptoKey
   352  		err := proto.Unmarshal(cks.Keys[i], &ck)
   353  		if err != nil {
   354  			return nil, errors.New("Can't unmarshal cryptokey")
   355  		}
   356  		if ck.KeyHeader.KeyType == nil {
   357  			return nil, errors.New("Missing KeyType in CryptoHeader")
   358  		}
   359  		switch *ck.KeyHeader.KeyPurpose {
   360  		default:
   361  			return nil, errors.New("Unknown purpose")
   362  		case "signing":
   363  			k.SigningKey = SignerFromCryptoKey(ck)
   364  			if k.SigningKey == nil {
   365  				return nil, errors.New("Can't recover signing key from cryptokey")
   366  			}
   367  			k.keyTypes |= Signing
   368  		case "crypting":
   369  			k.CryptingKey = CrypterFromCryptoKey(ck)
   370  			if k.CryptingKey == nil {
   371  				return nil, errors.New("Can't recover crypting key from cryptokey")
   372  			}
   373  			k.keyTypes |= Crypting
   374  		case "deriving":
   375  			k.DerivingKey = DeriverFromCryptoKey(ck)
   376  			if k.DerivingKey == nil {
   377  				return nil, errors.New("Can't recover deriving key from cryptokey")
   378  			}
   379  			k.keyTypes |= Deriving
   380  		}
   381  	}
   382  	k.Cert = nil
   383  	if cks.Cert != nil {
   384  		cert, err := x509.ParseCertificate(cks.Cert)
   385  		if err != nil {
   386  			return nil, err
   387  		}
   388  		k.Cert = cert
   389  	}
   390  	// CertChain
   391  	for i := 0; i < len(cks.CertChain); i++ {
   392  		cert, err := x509.ParseCertificate(cks.CertChain[i])
   393  		if err != nil {
   394  			return nil, err
   395  		}
   396  		k.CertChain = append(k.CertChain, cert)
   397  	}
   398  	k.Delegation = cks.Delegation
   399  	return k, nil
   400  }
   401  
   402  func MarshalKeyset(cks *CryptoKeyset) ([]byte, error) {
   403  	return proto.Marshal(cks)
   404  }
   405  
   406  func UnmarshalKeyset(buf []byte, cks *CryptoKeyset) error {
   407  	return proto.Unmarshal(buf, cks)
   408  }
   409  
   410  func MarshalKeys(k *Keys) ([]byte, error) {
   411  	cks, err := CryptoKeysetFromKeys(k)
   412  	if err != nil {
   413  		return nil, err
   414  	}
   415  	return MarshalKeyset(cks)
   416  }
   417  
   418  func UnmarshalKeys(b []byte) (*Keys, error) {
   419  	var cks CryptoKeyset
   420  	err := UnmarshalKeyset(b, &cks)
   421  	if err != nil {
   422  		return nil, errors.New("Can't unmarshal key set")
   423  	}
   424  	return KeysFromCryptoKeyset(&cks)
   425  }
   426  
   427  // SealedKeysetPath returns the path for a stored signing key.
   428  func (k *Keys) SealedKeysetPath() string {
   429  	if k.dir == "" {
   430  		return ""
   431  	}
   432  
   433  	return path.Join(k.dir, SealedKeysetPath)
   434  }
   435  
   436  // PlaintextKeysetPath returns the path for a key stored in plaintext (this is
   437  // not normally the case).
   438  func (k *Keys) PlaintextKeysetPath() string {
   439  	if k.dir == "" {
   440  		return ""
   441  	}
   442  
   443  	return path.Join(k.dir, PlaintextKeysetPath)
   444  }
   445  
   446  // NewTemporaryKeys creates a new Keys structure with the specified keys.
   447  func NewTemporaryKeys(keyTypes KeyType) (*Keys, error) {
   448  	k := &Keys{
   449  		keyTypes: keyTypes,
   450  	}
   451  	if k.keyTypes == 0 || (k.keyTypes & ^Signing & ^Crypting & ^Deriving != 0) {
   452  		return nil, errors.New("bad key type")
   453  	}
   454  
   455  	var err error
   456  	if k.keyTypes&Signing == Signing {
   457  		k.SigningKey = GenerateAnonymousSigner()
   458  		if k.SigningKey == nil {
   459  			return nil, errors.New("Can't generate signer")
   460  		}
   461  		k.VerifyingKey = k.SigningKey.GetVerifierFromSigner()
   462  		if k.VerifyingKey == nil {
   463  			return nil, errors.New("Can't get verifier from signer")
   464  		}
   465  	}
   466  
   467  	if k.keyTypes&Crypting == Crypting {
   468  		k.CryptingKey = GenerateAnonymousCrypter()
   469  		if k.CryptingKey == nil {
   470  			return nil, errors.New("Can't generate crypter")
   471  		}
   472  	}
   473  
   474  	if k.keyTypes&Deriving == Deriving {
   475  		k.DerivingKey = GenerateAnonymousDeriver()
   476  		if k.DerivingKey == nil {
   477  			return nil, err
   478  		}
   479  	}
   480  	return k, nil
   481  }
   482  
   483  // NewSignedOnDiskPBEKeys creates the same type of keys as NewOnDiskPBEKeys but
   484  // signs a certificate for the signer with the provided Keys, which must have
   485  // both a SigningKey and a Certificate.
   486  func NewSignedOnDiskPBEKeys(keyTypes KeyType, password []byte, path string, name *pkix.Name, serial int, signer *Keys) (*Keys, error) {
   487  	if signer == nil || name == nil {
   488  		return nil, errors.New("must supply a signer and a name")
   489  	}
   490  
   491  	if signer.Cert == nil || signer.SigningKey == nil {
   492  		return nil, newError("the signing key must have a SigningKey and a Cert")
   493  	}
   494  
   495  	if keyTypes&Signing == 0 {
   496  		return nil, errors.New("can't sign a key that has no signer")
   497  	}
   498  
   499  	k, err := NewOnDiskPBEKeys(keyTypes, password, path, nil)
   500  	if err != nil {
   501  		return nil, err
   502  	}
   503  
   504  	// If there's already a cert, then this means that there was already a
   505  	// keyset on disk, so don't create a new signed certificate.
   506  	if k.Cert == nil {
   507  		pkInt := PublicKeyAlgFromSignerAlg(*signer.SigningKey.Header.KeyType)
   508  		sigInt := SignatureAlgFromSignerAlg(*signer.SigningKey.Header.KeyType)
   509  		k.Cert, err = signer.SigningKey.CreateSignedX509(signer.Cert, serial, k.VerifyingKey, pkInt, sigInt, name)
   510  		if err != nil {
   511  			return nil, err
   512  		}
   513  
   514  		if err = util.WritePath(k.X509VerifierPath(), k.Cert.Raw, 0777, 0666); err != nil {
   515  			return nil, err
   516  		}
   517  	}
   518  
   519  	return k, nil
   520  }
   521  
   522  // NewOnDiskPBEKeys creates a new Keys structure with the specified key types
   523  // store under PBE on disk. If keys are generated and name is not nil, then a
   524  // self-signed x509 certificate will be generated and saved as well.
   525  func NewOnDiskPBEKeys(keyTypes KeyType, password []byte, path string, name *pkix.Name) (*Keys, error) {
   526  	if keyTypes == 0 || (keyTypes & ^Signing & ^Crypting & ^Deriving != 0) {
   527  		return nil, newError("bad key type")
   528  	}
   529  
   530  	if path == "" {
   531  		return nil, newError("bad init call: no path for keys")
   532  	}
   533  
   534  	if len(password) == 0 {
   535  		// This means there's no secret information: just load a public verifying key.
   536  		if keyTypes & ^Signing != 0 {
   537  			return nil, newError("without a password, only a verifying key can be loaded")
   538  		}
   539  
   540  		k := &Keys{
   541  			keyTypes: keyTypes,
   542  			dir:      path,
   543  		}
   544  		cert, err := loadCert(k.X509VerifierPath())
   545  		if err != nil {
   546  			return nil, errors.New("Couldn't load cert")
   547  		}
   548  		if cert == nil {
   549  			return nil, errors.New("Empty cert")
   550  		}
   551  		k.Cert = cert
   552  		v, err := VerifierFromX509(cert)
   553  		if err != nil {
   554  			return nil, err
   555  		}
   556  		k.VerifyingKey = v
   557  		return k, nil
   558  	} else {
   559  		// Check to see if there are already keys.
   560  		tk := &Keys{
   561  			keyTypes: keyTypes,
   562  			dir:      path,
   563  		}
   564  		f, err := os.Open(tk.PBEKeysetPath())
   565  		if err == nil {
   566  			defer f.Close()
   567  			ks, err := ioutil.ReadAll(f)
   568  			if err != nil {
   569  				return nil, err
   570  			}
   571  
   572  			data, err := PBEDecrypt(ks, password)
   573  			if err != nil {
   574  				return nil, err
   575  			}
   576  			defer ZeroBytes(data)
   577  
   578  			k, err := UnmarshalKeys(data)
   579  			if err != nil {
   580  				return nil, err
   581  			}
   582  			k.dir = path
   583  
   584  			// Note that this loads the certificate if it's
   585  			// present, and it returns nil otherwise.
   586  			if k.Cert == nil {
   587  				cert, err := loadCert(k.X509VerifierPath())
   588  				if err != nil {
   589  					return nil, err
   590  				}
   591  				k.Cert = cert
   592  				if k.Cert == nil {
   593  					k.VerifyingKey = k.SigningKey.GetVerifierFromSigner()
   594  				} else {
   595  					k.VerifyingKey, err = VerifierFromX509(cert)
   596  					if err != nil {
   597  						return nil, errors.New("Can't get verifying key (1)")
   598  					}
   599  				}
   600  			} else {
   601  				k.VerifyingKey, err = VerifierFromX509(k.Cert)
   602  				if err != nil {
   603  					return nil, errors.New("Can't get verifying key (2)")
   604  				}
   605  			}
   606  			return k, nil
   607  		} else {
   608  			// Create and store a new set of keys.
   609  			k, err := NewTemporaryKeys(keyTypes)
   610  			if err != nil {
   611  				return nil, err
   612  			}
   613  			k.dir = path
   614  
   615  			// Use correct cert name
   616  			signerAlg := SignerTypeFromSuiteName(TaoCryptoSuite)
   617  			if signerAlg == nil {
   618  				return nil, errors.New("SignerTypeFromSuiteName failed")
   619  			}
   620  			pkInt := PublicKeyAlgFromSignerAlg(*signerAlg)
   621  			skInt := SignatureAlgFromSignerAlg(*signerAlg)
   622  			if pkInt < 0 || skInt < 0 {
   623  				return nil, errors.New("Can't get PublicKeyAlgFromSignerAlg")
   624  			}
   625  
   626  			// reset cert and verifying keys
   627  			if name == nil {
   628  				us := "US"
   629  				textName := "Some Tao service"
   630  				name = &pkix.Name{
   631  					Organization: []string{textName},
   632  					CommonName:   textName,
   633  					Country:      []string{us},
   634  				}
   635  			}
   636  			cert, err := k.SigningKey.CreateSelfSignedX509(pkInt, skInt, int64(1), name)
   637  			if err != nil {
   638  				return nil, errors.New("Can't create self signing cert")
   639  			}
   640  			k.Cert = cert
   641  			k.VerifyingKey, err = VerifierFromX509(cert)
   642  
   643  			m, err := MarshalKeys(k)
   644  			if err != nil {
   645  				return nil, err
   646  			}
   647  			defer ZeroBytes(m)
   648  
   649  			enc, err := PBEEncrypt(m, password)
   650  			if err != nil {
   651  				return nil, err
   652  			}
   653  
   654  			if err = util.WritePath(k.PBEKeysetPath(), enc, 0777, 0600); err != nil {
   655  				return nil, err
   656  			}
   657  
   658  			if k.SigningKey != nil && name != nil {
   659  				err = k.newCert(name)
   660  				if err != nil {
   661  					return nil, err
   662  				}
   663  			}
   664  			return k, nil
   665  		}
   666  	}
   667  	return nil, errors.New("Shouldnt happen")
   668  
   669  }
   670  
   671  func (k *Keys) newCert(name *pkix.Name) (err error) {
   672  	pkInt := PublicKeyAlgFromSignerAlg(*k.SigningKey.Header.KeyType)
   673  	sigInt := SignatureAlgFromSignerAlg(*k.SigningKey.Header.KeyType)
   674  	if pkInt < 0 || sigInt < 0 {
   675  		return errors.New("No signing algorithm")
   676  	}
   677  	k.Cert, err = k.SigningKey.CreateSelfSignedX509(pkInt, sigInt, int64(1), name)
   678  	if err != nil {
   679  		return err
   680  	}
   681  	if err = util.WritePath(k.X509VerifierPath(), k.Cert.Raw, 0777, 0666); err != nil {
   682  		return err
   683  	}
   684  	return nil
   685  }
   686  
   687  func loadCert(path string) (*x509.Certificate, error) {
   688  	f, err := os.Open(path)
   689  	// Allow this operation to fail silently, since there isn't always a
   690  	// certificate available.
   691  	if err != nil {
   692  		return nil, nil
   693  	}
   694  	defer f.Close()
   695  
   696  	der, err := ioutil.ReadAll(f)
   697  	if err != nil {
   698  		return nil, err
   699  	}
   700  
   701  	return x509.ParseCertificate(der)
   702  }
   703  
   704  // NewTemporaryTaoDelegatedKeys initializes a set of temporary keys under a host
   705  // Tao, using the Tao to generate a delegation for the signing key. Since these
   706  // keys are never stored on disk, they are not sealed to the Tao.
   707  func NewTemporaryTaoDelegatedKeys(keyTypes KeyType, t Tao) (*Keys, error) {
   708  	k, err := NewTemporaryKeys(keyTypes)
   709  	if err != nil {
   710  		return nil, err
   711  	}
   712  
   713  	if t != nil && k.SigningKey != nil {
   714  
   715  		self, err := t.GetTaoName()
   716  		if err != nil {
   717  			return nil, err
   718  		}
   719  
   720  		s := &auth.Speaksfor{
   721  			Delegate:  k.SigningKey.ToPrincipal(),
   722  			Delegator: self,
   723  		}
   724  		if k.Delegation, err = t.Attest(&self, nil, nil, s); err != nil {
   725  			return nil, err
   726  		}
   727  	}
   728  
   729  	return k, nil
   730  }
   731  
   732  // PBEEncrypt encrypts plaintext using a password to generate a key. Note that
   733  // since this is for private program data, we don't try for compatibility with
   734  // the C++ Tao version of the code.
   735  func PBEEncrypt(plaintext, password []byte) ([]byte, error) {
   736  	if password == nil || len(password) == 0 {
   737  		return nil, newError("null or empty password")
   738  	}
   739  	cipherName := CipherTypeFromSuiteName(TaoCryptoSuite)
   740  	hashName := HashTypeFromSuiteName(TaoCryptoSuite)
   741  	if cipherName == nil || hashName == nil {
   742  		return nil, errors.New("Bad cipher in PBEEncrypt")
   743  	}
   744  	pbed := &PBEData{
   745  		Version: CryptoVersion_CRYPTO_VERSION_2.Enum(),
   746  		Cipher:  proto.String(*cipherName),
   747  		Hmac:    proto.String(*hashName),
   748  		// The IV is required, so we include it, but this algorithm doesn't use it.
   749  		Iv:         make([]byte, aes.BlockSize),
   750  		Iterations: proto.Int32(4096),
   751  		Salt:       make([]byte, aes.BlockSize),
   752  	}
   753  
   754  	// We use the first half of the salt for the AES key and the second
   755  	// half for the HMAC key, since the standard recommends at least 8
   756  	// bytes of salt.
   757  	if _, err := rand.Read(pbed.Salt); err != nil {
   758  		return nil, err
   759  	}
   760  
   761  	var aesKey []byte
   762  	var hmacKey []byte
   763  	switch TaoCryptoSuite  {
   764  	default:
   765  		return nil, errors.New("Unsupported cipher suite")
   766  	case Basic128BitCipherSuite:
   767  		// 128-bit AES key.
   768  		aesKey = pbkdf2.Key(password, pbed.Salt[:8], int(*pbed.Iterations), 16, sha256.New)
   769  		defer ZeroBytes(aesKey)
   770  		// 64-byte HMAC-SHA256 key.
   771  		hmacKey = pbkdf2.Key(password, pbed.Salt[8:], int(*pbed.Iterations), 32, sha256.New)
   772  		defer ZeroBytes(hmacKey)
   773  	case Basic192BitCipherSuite:
   774  		// 256-bit AES key.
   775  		aesKey = pbkdf2.Key(password, pbed.Salt[:8], int(*pbed.Iterations), 32, sha512.New384)
   776  		defer ZeroBytes(aesKey)
   777  		// 48-byte HMAC-SHA384 key.
   778  		hmacKey = pbkdf2.Key(password, pbed.Salt[8:], int(*pbed.Iterations), 48, sha512.New384)
   779  		defer ZeroBytes(hmacKey)
   780  	case Basic256BitCipherSuite:
   781  		// 256-bit AES key.
   782  		aesKey = pbkdf2.Key(password, pbed.Salt[:8], int(*pbed.Iterations), 32, sha512.New)
   783  		defer ZeroBytes(aesKey)
   784  		// 64-byte HMAC-SHA512 key.
   785  		hmacKey = pbkdf2.Key(password, pbed.Salt[8:], int(*pbed.Iterations), 64, sha512.New)
   786  		defer ZeroBytes(hmacKey)
   787  	}
   788  
   789  	ver := CryptoVersion_CRYPTO_VERSION_2
   790  	keyName := "PBEKey"
   791  	keyEpoch := int32(1)
   792  	keyType := CrypterTypeFromSuiteName(TaoCryptoSuite)
   793  	keyPurpose := "crypting"
   794  	keyStatus := "active"
   795  	ch := &CryptoHeader{
   796  		Version:    &ver,
   797  		KeyName:    &keyName,
   798  		KeyEpoch:   &keyEpoch,
   799  		KeyType:    keyType,
   800  		KeyPurpose: &keyPurpose,
   801  		KeyStatus:  &keyStatus,
   802  	}
   803  	ck := &CryptoKey{
   804  		KeyHeader: ch,
   805  	}
   806  	ck.KeyComponents = append(ck.KeyComponents, aesKey)
   807  	ck.KeyComponents = append(ck.KeyComponents, hmacKey)
   808  	c := CrypterFromCryptoKey(*ck)
   809  	if c == nil {
   810  		return nil, errors.New("Empty crypter")
   811  	}
   812  	// Note that we're abusing the PBEData format here, since the IV and
   813  	// the MAC are actually contained in the ciphertext from Encrypt().
   814  	var err error
   815  	if pbed.Ciphertext, err = c.Encrypt(plaintext); err != nil {
   816  		return nil, err
   817  	}
   818  	return proto.Marshal(pbed)
   819  }
   820  
   821  // PBEDecrypt decrypts ciphertext using a password to generate a key. Note that
   822  // since this is for private program data, we don't try for compatibility with
   823  // the C++ Tao version of the code.
   824  func PBEDecrypt(ciphertext, password []byte) ([]byte, error) {
   825  	if password == nil || len(password) == 0 {
   826  		return nil, newError("null or empty password")
   827  	}
   828  
   829  	var pbed PBEData
   830  	if err := proto.Unmarshal(ciphertext, &pbed); err != nil {
   831  		return nil, err
   832  	}
   833  
   834  	// Recover the keys from the password and the PBE header.
   835  	if *pbed.Version != CryptoVersion_CRYPTO_VERSION_2 {
   836  		return nil, newError("bad version")
   837  	}
   838  
   839  	var aesKey []byte
   840  	var hmacKey []byte
   841  	switch TaoCryptoSuite  {
   842  	default:
   843  		return nil, errors.New("Unsupported cipher suite")
   844  	case Basic128BitCipherSuite:
   845  		// 128-bit AES key.
   846  		aesKey = pbkdf2.Key(password, pbed.Salt[:8], int(*pbed.Iterations), 16, sha256.New)
   847  		defer ZeroBytes(aesKey)
   848  		// 64-byte HMAC-SHA256 key.
   849  		hmacKey = pbkdf2.Key(password, pbed.Salt[8:], int(*pbed.Iterations), 32, sha256.New)
   850  	case Basic192BitCipherSuite:
   851  		// 256-bit AES key.
   852  		aesKey = pbkdf2.Key(password, pbed.Salt[:8], int(*pbed.Iterations), 32, sha512.New384)
   853  		defer ZeroBytes(aesKey)
   854  		// 48-byte HMAC-SHA384 key.
   855  		hmacKey = pbkdf2.Key(password, pbed.Salt[8:], int(*pbed.Iterations), 48, sha512.New384)
   856  		defer ZeroBytes(hmacKey)
   857  	case Basic256BitCipherSuite:
   858  		// 256-bit AES key.
   859  		aesKey = pbkdf2.Key(password, pbed.Salt[:8], int(*pbed.Iterations), 32, sha512.New)
   860  		defer ZeroBytes(aesKey)
   861  		// 64-byte HMAC-SHA512 key.
   862  		hmacKey = pbkdf2.Key(password, pbed.Salt[8:], int(*pbed.Iterations), 64, sha512.New)
   863  		defer ZeroBytes(hmacKey)
   864  	}
   865  
   866  	ck := new(CryptoKey)
   867  	ver := CryptoVersion_CRYPTO_VERSION_2
   868  	keyName := "PBEKey"
   869  	keyEpoch := int32(1)
   870  	keyType := CrypterTypeFromSuiteName(TaoCryptoSuite)
   871  	if keyType == nil {
   872  		return nil, newError("bad CrypterTypeFromSuiteName")
   873  	}
   874  	keyPurpose := "crypting"
   875  	keyStatus := "active"
   876  	ch := &CryptoHeader{
   877  		Version:    &ver,
   878  		KeyName:    &keyName,
   879  		KeyEpoch:   &keyEpoch,
   880  		KeyType:    keyType,
   881  		KeyPurpose: &keyPurpose,
   882  		KeyStatus:  &keyStatus,
   883  	}
   884  	ck.KeyHeader = ch
   885  	ck.KeyComponents = append(ck.KeyComponents, aesKey)
   886  	ck.KeyComponents = append(ck.KeyComponents, hmacKey)
   887  	c := CrypterFromCryptoKey(*ck)
   888  
   889  	defer ZeroBytes(hmacKey)
   890  
   891  	// Note that we're abusing the PBEData format here, since the IV and
   892  	// the MAC are actually contained in the ciphertext from Encrypt().
   893  	data, err := c.Decrypt(pbed.Ciphertext)
   894  	if err != nil {
   895  		return nil, err
   896  	}
   897  
   898  	return data, nil
   899  }
   900  
   901  // NewOnDiskTaoSealedKeys sets up the keys sealed under a host Tao or reads sealed keys.
   902  func NewOnDiskTaoSealedKeys(keyTypes KeyType, t Tao, path, policy string) (*Keys, error) {
   903  
   904  	// Fail if no parent Tao exists (otherwise t.Seal() would not be called).
   905  	if t == nil {
   906  		return nil, errors.New("parent tao is nil")
   907  	}
   908  
   909  	k := &Keys{
   910  		keyTypes: keyTypes,
   911  		dir:      path,
   912  		policy:   policy,
   913  	}
   914  
   915  	// Check if keys exist: if not, generate and save a new set.
   916  	f, err := os.Open(k.SealedKeysetPath())
   917  	if err != nil {
   918  		k, err = NewTemporaryTaoDelegatedKeys(keyTypes, t)
   919  		if err != nil {
   920  			return nil, err
   921  		}
   922  		k.dir = path
   923  		k.policy = policy
   924  
   925  		if err = k.Save(t); err != nil {
   926  			return k, err
   927  		}
   928  		return k, nil
   929  	}
   930  	f.Close()
   931  
   932  	// Otherwise, load from file.
   933  	return LoadKeys(keyTypes, t, path, policy)
   934  }
   935  
   936  // Save serializes, seals, and writes a key set to disk. It calls t.Seal().
   937  func (k *Keys) Save(t Tao) error {
   938  	// Marshal key set.
   939  	m, err := MarshalKeys(k)
   940  	if err != nil {
   941  		return err
   942  	}
   943  	// cks.Delegation = k.Delegation
   944  
   945  	// TODO(tmroeder): defer zeroKeyset(cks)
   946  	defer ZeroBytes(m)
   947  
   948  	data, err := t.Seal(m, k.policy)
   949  	if err != nil {
   950  		return err
   951  	}
   952  
   953  	if err = util.WritePath(k.SealedKeysetPath(), data, 0700, 0600); err != nil {
   954  		return err
   955  	}
   956  
   957  	return nil
   958  }
   959  
   960  // LoadKeys reads a key set from file. If there is a parent tao (t!=nil), then
   961  // expect the keys are sealed and call t.Unseal(); otherwise, expect the key
   962  // set to be plaintext.
   963  func LoadKeys(keyTypes KeyType, t Tao, path, policy string) (*Keys, error) {
   964  	k := &Keys{
   965  		keyTypes: keyTypes,
   966  		dir:      path,
   967  		policy:   policy,
   968  	}
   969  
   970  	// Check to see if there are already keys.
   971  	var keysetPath string
   972  	if t == nil {
   973  		keysetPath = k.PlaintextKeysetPath()
   974  	} else {
   975  		keysetPath = k.SealedKeysetPath()
   976  	}
   977  	f, err := os.Open(keysetPath)
   978  	if err != nil {
   979  		return nil, err
   980  	}
   981  	defer f.Close()
   982  
   983  	ks, err := ioutil.ReadAll(f)
   984  	if err != nil {
   985  		return nil, err
   986  	}
   987  
   988  	if t != nil {
   989  		data, p, err := t.Unseal(ks)
   990  		if err != nil {
   991  			return nil, err
   992  		}
   993  		defer ZeroBytes(data)
   994  
   995  		if p != policy {
   996  			return nil, errors.New("invalid policy from Unseal")
   997  		}
   998  		return UnmarshalKeys(data)
   999  	} else {
  1000  		return UnmarshalKeys(ks)
  1001  	}
  1002  	return nil, errors.New("Shouldnt happen")
  1003  }
  1004  
  1005  // NewSecret creates and encrypts a new secret value of the given length, or it
  1006  // reads and decrypts the value and checks that it's the right length. It
  1007  // creates the file and its parent directories if these directories do not
  1008  // exist.
  1009  func (k *Keys) NewSecret(file string, length int) ([]byte, error) {
  1010  	if _, err := os.Stat(file); err != nil {
  1011  		// Create the parent directories and the file.
  1012  		if err := os.MkdirAll(path.Dir(file), 0700); err != nil {
  1013  			return nil, err
  1014  		}
  1015  
  1016  		secret := make([]byte, length)
  1017  		if _, err := rand.Read(secret); err != nil {
  1018  			return nil, err
  1019  		}
  1020  
  1021  		enc, err := k.CryptingKey.Encrypt(secret)
  1022  		if err != nil {
  1023  			return nil, err
  1024  		}
  1025  
  1026  		if err := ioutil.WriteFile(file, enc, 0700); err != nil {
  1027  			return nil, err
  1028  		}
  1029  
  1030  		return secret, nil
  1031  	}
  1032  
  1033  	enc, err := ioutil.ReadFile(file)
  1034  	if err != nil {
  1035  		return nil, err
  1036  	}
  1037  
  1038  	dec, err := k.CryptingKey.Decrypt(enc)
  1039  	if err != nil {
  1040  		return nil, err
  1041  	}
  1042  
  1043  	if len(dec) != length {
  1044  		ZeroBytes(dec)
  1045  		return nil, newError("The decrypted value had length %d, but it should have had length %d", len(dec), length)
  1046  	}
  1047  
  1048  	return dec, nil
  1049  }
  1050  
  1051  // SaveKeyset serializes and saves a Keys object to disk in plaintext.
  1052  func SaveKeyset(k *Keys, dir string) error {
  1053  	k.dir = dir
  1054  	m, err := MarshalKeys(k)
  1055  	if err != nil {
  1056  		return err
  1057  	}
  1058  
  1059  	if err = util.WritePath(k.PlaintextKeysetPath(), m, 0700, 0600); err != nil {
  1060  		return err
  1061  	}
  1062  
  1063  	return nil
  1064  }