github.com/jlmucb/cloudproxy@v0.0.0-20170830161738-b5aa0b619bc4/go/tpm2/support.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 supports direct communication with a tpm 2.0 device under Linux. 16 17 package tpm2 18 19 import ( 20 "bytes" 21 "crypto/aes" 22 "crypto/cipher" 23 "crypto/hmac" 24 "crypto/rand" 25 "crypto/rsa" 26 "crypto/sha1" 27 "crypto/sha256" 28 "crypto/x509" 29 "crypto/x509/pkix" 30 "errors" 31 "fmt" 32 "math/big" 33 "strconv" 34 "strings" 35 "time" 36 37 "github.com/golang/glog" 38 "github.com/golang/protobuf/proto" 39 ) 40 41 func GetPublicKeyFromDerCert(derCert []byte) (*rsa.PublicKey, error) { 42 cert, err := x509.ParseCertificate(derCert) 43 if err != nil { 44 return nil, err 45 } 46 47 var publicKey *rsa.PublicKey 48 switch k := cert.PublicKey.(type) { 49 case *rsa.PublicKey: 50 publicKey = k 51 case *rsa.PrivateKey: 52 publicKey = &k.PublicKey 53 default: 54 return nil, errors.New("Wrong public key type") 55 } 56 return publicKey, nil 57 } 58 59 func GenerateSelfSignedCertFromKey(signingKey *rsa.PrivateKey, subjectOrgName string, 60 subjectCommonName string, serialNumber *big.Int, 61 notBefore time.Time, notAfter time.Time) ([]byte, error) { 62 signTemplate := x509.Certificate{ 63 SerialNumber: serialNumber, 64 Subject: pkix.Name{ 65 Organization: []string{subjectOrgName}, 66 CommonName: subjectCommonName, 67 }, 68 NotBefore: notBefore, 69 NotAfter: notAfter, 70 KeyUsage: x509.KeyUsageCertSign, 71 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, 72 BasicConstraintsValid: true, 73 IsCA: true, 74 } 75 publicKey := &signingKey.PublicKey 76 derCert, err := x509.CreateCertificate(rand.Reader, &signTemplate, &signTemplate, 77 publicKey, signingKey) 78 if err != nil { 79 return nil, errors.New("Can't CreateCertificate") 80 } 81 return derCert, nil 82 } 83 84 func GenerateCertFromKeys(signingKey *rsa.PrivateKey, signerDerPolicyCert []byte, 85 subjectKey *rsa.PublicKey, subjectOrgName string, subjectCommonName string, 86 serialNumber *big.Int, notBefore time.Time, notAfter time.Time) ([]byte, error) { 87 signingCert, err := x509.ParseCertificate(signerDerPolicyCert) 88 if err != nil { 89 return nil, errors.New("Can't parse signer certificate") 90 } 91 92 // fmt.Printf("Serial: %x\n", serialNumber) 93 // fmt.Printf("notBefore: %s, notAfter: %s\n", notBefore, notAfter) 94 signTemplate := x509.Certificate{ 95 SerialNumber: serialNumber, 96 Subject: pkix.Name{ 97 Organization: []string{subjectOrgName}, 98 CommonName: subjectCommonName, 99 }, 100 NotBefore: notBefore, 101 NotAfter: notAfter, 102 KeyUsage: x509.KeyUsageCertSign, 103 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, 104 BasicConstraintsValid: true, 105 // IsCA: false, 106 IsCA: true, 107 } 108 derSignedCert, err := x509.CreateCertificate(rand.Reader, &signTemplate, signingCert, 109 subjectKey, signingKey) 110 if err != nil { 111 glog.Infof("GenerateCertFromKeys: %s", err) 112 fmt.Printf("%s\n", err) 113 return nil, errors.New("Can't CreateCertificate") 114 } 115 return derSignedCert, nil 116 } 117 118 func SerializeRsaPrivateKey(key *rsa.PrivateKey) ([]byte, error) { 119 msg, err := MarshalRsaPrivateToProto(key) 120 if err != nil { 121 return nil, errors.New("Can't marshall private key") 122 } 123 out, err := proto.Marshal(msg) 124 if err != nil { 125 return nil, errors.New("Can't serialize private key") 126 } 127 return out, nil 128 } 129 130 func DeserializeRsaKey(in []byte) (*rsa.PrivateKey, error) { 131 msg := new(RsaPrivateKeyMessage) 132 err := proto.Unmarshal(in, msg) 133 key, err := UnmarshalRsaPrivateFromProto(msg) 134 if err != nil { 135 return nil, errors.New("Can't Unmarshal private key") 136 } 137 return key, nil 138 } 139 140 func PublicKeyFromPrivate(priv interface{}) *rsa.PublicKey { 141 switch k := priv.(type) { 142 case *rsa.PrivateKey: 143 return &k.PublicKey 144 default: 145 return nil 146 } 147 } 148 149 func KDFA(alg uint16, key []byte, label string, contextU []byte, 150 contextV []byte, bits int) ([]byte, error) { 151 counter := uint32(0) 152 bytes_left := (bits + 7) / 8 153 var out []byte 154 for bytes_left > 0 { 155 counter = counter + 1 156 if alg == AlgTPM_ALG_SHA1 { 157 mac := hmac.New(sha1.New, key) 158 // copy counter (big Endian), label, contextU, contextV, bits (big Endian) 159 outa, _ := pack([]interface{}{&counter}) 160 var arr [32]byte 161 copy(arr[0:], label) 162 arr[len(label)] = 0 163 outc := append(contextU, contextV...) 164 u_bits := uint32(bits) 165 outd, _ := pack([]interface{}{&u_bits}) 166 in := append(outa, append(arr[0:len(label)+1], append(outc, outd...)...)...) 167 mac.Write(in) 168 out = append(out, mac.Sum(nil)...) 169 bytes_left -= 20 170 } else if alg == AlgTPM_ALG_SHA256 { 171 mac := hmac.New(sha256.New, key) 172 // copy counter (big Endian), label, contextU, contextV, bits (big Endian) 173 outa, _ := pack([]interface{}{&counter}) 174 var arr [32]byte 175 copy(arr[0:], label) 176 arr[len(label)] = 0 177 outc := append(contextU, contextV...) 178 u_bits := uint32(bits) 179 outd, _ := pack([]interface{}{&u_bits}) 180 in := append(outa, append(arr[0:len(label)+1], 181 append(outc, outd...)...)...) 182 mac.Write(in) 183 out = append(out, mac.Sum(nil)...) 184 bytes_left -= 32 185 } else { 186 return nil, errors.New("Unsupported key hmac alg") 187 } 188 } 189 return out, nil 190 } 191 192 // Return: out_hmac, output_data 193 func EncryptDataWithCredential(encrypt_flag bool, hash_alg_id uint16, 194 unmarshaled_credential []byte, inData []byte, 195 inHmac []byte) ([]byte, []byte, error) { 196 var contextV []byte 197 derivedKeys, err := KDFA(hash_alg_id, unmarshaled_credential, 198 "PROTECT", contextV, contextV, 512) 199 if err != nil { 200 fmt.Printf("EncryptDataWithCredential can't derive keys\n") 201 glog.Infof("EncryptDataWithCredential: can't derive keys") 202 return nil, nil, errors.New("KDFA failed") 203 } 204 var calculatedHmac []byte 205 outData := make([]byte, len(inData), len(inData)) 206 iv := derivedKeys[16:32] 207 key := derivedKeys[0:16] 208 dec, err := aes.NewCipher(key) 209 ctr := cipher.NewCTR(dec, iv) 210 ctr.XORKeyStream(outData, inData) 211 212 var toHash []byte 213 if encrypt_flag == true { 214 toHash = inData 215 } else { 216 toHash = outData 217 } 218 // Calculate hmac on output data 219 if hash_alg_id == AlgTPM_ALG_SHA1 { 220 hm := hmac.New(sha1.New, derivedKeys[48:64]) 221 hm.Write(toHash) 222 calculatedHmac = hm.Sum(nil) 223 } else if hash_alg_id == AlgTPM_ALG_SHA256 { 224 hm := hmac.New(sha256.New, derivedKeys[32:64]) 225 hm.Write(toHash) 226 calculatedHmac = hm.Sum(nil) 227 } else { 228 fmt.Printf("EncryptDataWithCredential unrecognized hmac alg\n") 229 glog.Infof("EncryptDataWithCredential: unrecognized hmac alg") 230 return nil, nil, errors.New("Unsupported Hash alg") 231 } 232 233 if encrypt_flag == false { 234 if bytes.Compare(calculatedHmac, inHmac) != 0 { 235 return nil, nil, errors.New("Integrity check fails") 236 } 237 } 238 239 return calculatedHmac, outData, nil 240 } 241 242 func StringToIntList(in string) ([]int, error) { 243 strList := strings.Split(in, ",") 244 ints := make([]int, len(strList)) 245 for i, s := range strList { 246 var err error 247 ints[i], err = strconv.Atoi(strings.TrimPrefix(s, " ")) 248 if err != nil { 249 return nil, errors.New("Can't convert strings to ints") 250 } 251 } 252 return ints, nil 253 } 254 255 func ComputeHashValue(alg uint16, to_hash []byte) ([]byte, error) { 256 if alg == uint16(AlgTPM_ALG_SHA1) { 257 hash := sha1.New() 258 hash.Write(to_hash) 259 hash_value := hash.Sum(nil) 260 return hash_value, nil 261 } else if alg == uint16(AlgTPM_ALG_SHA256) { 262 hash := sha256.New() 263 hash.Write(to_hash) 264 hash_value := hash.Sum(nil) 265 return hash_value, nil 266 } else { 267 return nil, errors.New("unsupported hash alg") 268 } 269 } 270 271 func SizeHash(alg_id uint16) int { 272 if alg_id == uint16(AlgTPM_ALG_SHA1) { 273 return 20 274 } else if alg_id == uint16(AlgTPM_ALG_SHA256) { 275 return 32 276 } else { 277 return -1 278 } 279 } 280 281 func VerifyDerCert(der_cert []byte, der_signing_cert []byte) (bool, error) { 282 roots := x509.NewCertPool() 283 opts := x509.VerifyOptions{ 284 Roots: roots, 285 } 286 287 // Verify key 288 policy_cert, err := x509.ParseCertificate(der_signing_cert) 289 if err != nil { 290 return false, errors.New("Signing ParseCertificate fails") 291 } 292 roots.AddCert(policy_cert) 293 // fmt.Printf("Root cert: %x\n", der_signing_cert) 294 295 // Verify key 296 cert, err := x509.ParseCertificate(der_cert) 297 if err != nil { 298 return false, errors.New("Cert ParseCertificate fails") 299 } 300 301 roots.AddCert(policy_cert) 302 opts.Roots = roots 303 chains, err := cert.Verify(opts) 304 if err != nil { 305 return false, errors.New("Verify fails") 306 } 307 if chains != nil { 308 return true, nil 309 } else { 310 return false, nil 311 } 312 313 } 314 315 func MarshalRsaPrivateToProto(key *rsa.PrivateKey) (*RsaPrivateKeyMessage, error) { 316 if key == nil { 317 return nil, errors.New("No key") 318 } 319 msg := new(RsaPrivateKeyMessage) 320 msg.PublicKey = new(RsaPublicKeyMessage) 321 msg.D = key.D.Bytes() 322 msg.PublicKey.Exponent = []byte{0, 1, 0, 1} 323 msg.PublicKey.Modulus = key.N.Bytes() 324 l := int32(len(msg.PublicKey.Modulus) * 8) 325 msg.PublicKey.BitModulusSize = &l 326 // if len(key.Primes == 2 { 327 // msg.PublicKey.P = msg.Primes[0].Bytes() 328 // msg.PublicKey.Q = msg.Primes[1].Bytes() 329 // } 330 return msg, nil 331 } 332 333 func UnmarshalRsaPrivateFromProto(msg *RsaPrivateKeyMessage) (*rsa.PrivateKey, error) { 334 if msg == nil { 335 return nil, errors.New("No message") 336 } 337 key := new(rsa.PrivateKey) 338 key.D = new(big.Int) 339 key.D.SetBytes(msg.D) 340 key.PublicKey.N = new(big.Int) 341 key.PublicKey.N.SetBytes(msg.PublicKey.Modulus) 342 key.PublicKey.E = 0x10001 // Fix 343 // if msg.PublicKey.P != nil && msg.PublicKey.Q != nil { 344 // msg.Primes[0] = new(big.Int) 345 // msg.Primes[1] = new(big.Int) 346 // msg.Primes[0].SetBytes(msg.PublicKey.P) 347 // msg.Primes[1].SetBytes(msg.PublicKey.Q) 348 // } 349 return key, nil 350 }