1// Copyright 2009 The Go Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style 3// license that can be found in the LICENSE file. 4 5package runner 6 7import ( 8 "crypto" 9 "crypto/hmac" 10 "crypto/md5" 11 "crypto/sha1" 12 "crypto/sha256" 13 "hash" 14) 15 16// Split a premaster secret in two as specified in RFC 4346, section 5. 17func splitPreMasterSecret(secret []byte) (s1, s2 []byte) { 18 s1 = secret[0 : (len(secret)+1)/2] 19 s2 = secret[len(secret)/2:] 20 return 21} 22 23// pHash implements the P_hash function, as defined in RFC 4346, section 5. 24func pHash(result, secret, seed []byte, hash func() hash.Hash) { 25 h := hmac.New(hash, secret) 26 h.Write(seed) 27 a := h.Sum(nil) 28 29 j := 0 30 for j < len(result) { 31 h.Reset() 32 h.Write(a) 33 h.Write(seed) 34 b := h.Sum(nil) 35 todo := len(b) 36 if j+todo > len(result) { 37 todo = len(result) - j 38 } 39 copy(result[j:j+todo], b) 40 j += todo 41 42 h.Reset() 43 h.Write(a) 44 a = h.Sum(nil) 45 } 46} 47 48// prf10 implements the TLS 1.0 pseudo-random function, as defined in RFC 2246, section 5. 49func prf10(result, secret, label, seed []byte) { 50 hashSHA1 := sha1.New 51 hashMD5 := md5.New 52 53 labelAndSeed := make([]byte, len(label)+len(seed)) 54 copy(labelAndSeed, label) 55 copy(labelAndSeed[len(label):], seed) 56 57 s1, s2 := splitPreMasterSecret(secret) 58 pHash(result, s1, labelAndSeed, hashMD5) 59 result2 := make([]byte, len(result)) 60 pHash(result2, s2, labelAndSeed, hashSHA1) 61 62 for i, b := range result2 { 63 result[i] ^= b 64 } 65} 66 67// prf12 implements the TLS 1.2 pseudo-random function, as defined in RFC 5246, section 5. 68func prf12(hashFunc func() hash.Hash) func(result, secret, label, seed []byte) { 69 return func(result, secret, label, seed []byte) { 70 labelAndSeed := make([]byte, len(label)+len(seed)) 71 copy(labelAndSeed, label) 72 copy(labelAndSeed[len(label):], seed) 73 74 pHash(result, secret, labelAndSeed, hashFunc) 75 } 76} 77 78// prf30 implements the SSL 3.0 pseudo-random function, as defined in 79// www.mozilla.org/projects/security/pki/nss/ssl/draft302.txt section 6. 80func prf30(result, secret, label, seed []byte) { 81 hashSHA1 := sha1.New() 82 hashMD5 := md5.New() 83 84 done := 0 85 i := 0 86 // RFC5246 section 6.3 says that the largest PRF output needed is 128 87 // bytes. Since no more ciphersuites will be added to SSLv3, this will 88 // remain true. Each iteration gives us 16 bytes so 10 iterations will 89 // be sufficient. 90 var b [11]byte 91 for done < len(result) { 92 for j := 0; j <= i; j++ { 93 b[j] = 'A' + byte(i) 94 } 95 96 hashSHA1.Reset() 97 hashSHA1.Write(b[:i+1]) 98 hashSHA1.Write(secret) 99 hashSHA1.Write(seed) 100 digest := hashSHA1.Sum(nil) 101 102 hashMD5.Reset() 103 hashMD5.Write(secret) 104 hashMD5.Write(digest) 105 106 done += copy(result[done:], hashMD5.Sum(nil)) 107 i++ 108 } 109} 110 111const ( 112 tlsRandomLength = 32 // Length of a random nonce in TLS 1.1. 113 masterSecretLength = 48 // Length of a master secret in TLS 1.1. 114 finishedVerifyLength = 12 // Length of verify_data in a Finished message. 115) 116 117var masterSecretLabel = []byte("master secret") 118var extendedMasterSecretLabel = []byte("extended master secret") 119var keyExpansionLabel = []byte("key expansion") 120var clientFinishedLabel = []byte("client finished") 121var serverFinishedLabel = []byte("server finished") 122var finishedLabel = []byte("finished") 123var channelIDLabel = []byte("TLS Channel ID signature\x00") 124var channelIDResumeLabel = []byte("Resumption\x00") 125 126func prfForVersion(version uint16, suite *cipherSuite) func(result, secret, label, seed []byte) { 127 switch version { 128 case VersionSSL30: 129 return prf30 130 case VersionTLS10, VersionTLS11: 131 return prf10 132 case VersionTLS12: 133 return prf12(suite.hash().New) 134 } 135 panic("unknown version") 136} 137 138// masterFromPreMasterSecret generates the master secret from the pre-master 139// secret. See http://tools.ietf.org/html/rfc5246#section-8.1 140func masterFromPreMasterSecret(version uint16, suite *cipherSuite, preMasterSecret, clientRandom, serverRandom []byte) []byte { 141 var seed [tlsRandomLength * 2]byte 142 copy(seed[0:len(clientRandom)], clientRandom) 143 copy(seed[len(clientRandom):], serverRandom) 144 masterSecret := make([]byte, masterSecretLength) 145 prfForVersion(version, suite)(masterSecret, preMasterSecret, masterSecretLabel, seed[0:]) 146 return masterSecret 147} 148 149// extendedMasterFromPreMasterSecret generates the master secret from the 150// pre-master secret when the Triple Handshake fix is in effect. See 151// https://tools.ietf.org/html/rfc7627 152func extendedMasterFromPreMasterSecret(version uint16, suite *cipherSuite, preMasterSecret []byte, h finishedHash) []byte { 153 masterSecret := make([]byte, masterSecretLength) 154 prfForVersion(version, suite)(masterSecret, preMasterSecret, extendedMasterSecretLabel, h.Sum()) 155 return masterSecret 156} 157 158// keysFromMasterSecret generates the connection keys from the master 159// secret, given the lengths of the MAC key, cipher key and IV, as defined in 160// RFC 2246, section 6.3. 161func keysFromMasterSecret(version uint16, suite *cipherSuite, masterSecret, clientRandom, serverRandom []byte, macLen, keyLen, ivLen int) (clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV []byte) { 162 var seed [tlsRandomLength * 2]byte 163 copy(seed[0:len(clientRandom)], serverRandom) 164 copy(seed[len(serverRandom):], clientRandom) 165 166 n := 2*macLen + 2*keyLen + 2*ivLen 167 keyMaterial := make([]byte, n) 168 prfForVersion(version, suite)(keyMaterial, masterSecret, keyExpansionLabel, seed[0:]) 169 clientMAC = keyMaterial[:macLen] 170 keyMaterial = keyMaterial[macLen:] 171 serverMAC = keyMaterial[:macLen] 172 keyMaterial = keyMaterial[macLen:] 173 clientKey = keyMaterial[:keyLen] 174 keyMaterial = keyMaterial[keyLen:] 175 serverKey = keyMaterial[:keyLen] 176 keyMaterial = keyMaterial[keyLen:] 177 clientIV = keyMaterial[:ivLen] 178 keyMaterial = keyMaterial[ivLen:] 179 serverIV = keyMaterial[:ivLen] 180 return 181} 182 183func newFinishedHash(wireVersion uint16, isDTLS bool, cipherSuite *cipherSuite) finishedHash { 184 var ret finishedHash 185 186 version, ok := wireToVersion(wireVersion, isDTLS) 187 if !ok { 188 panic("unknown version") 189 } 190 191 if version >= VersionTLS12 { 192 ret.hash = cipherSuite.hash() 193 194 ret.client = ret.hash.New() 195 ret.server = ret.hash.New() 196 197 if version == VersionTLS12 { 198 ret.prf = prf12(ret.hash.New) 199 } else { 200 ret.secret = make([]byte, ret.hash.Size()) 201 } 202 } else { 203 ret.hash = crypto.MD5SHA1 204 205 ret.client = sha1.New() 206 ret.server = sha1.New() 207 ret.clientMD5 = md5.New() 208 ret.serverMD5 = md5.New() 209 210 ret.prf = prf10 211 } 212 213 ret.buffer = []byte{} 214 ret.version = version 215 ret.wireVersion = wireVersion 216 return ret 217} 218 219// A finishedHash calculates the hash of a set of handshake messages suitable 220// for including in a Finished message. 221type finishedHash struct { 222 hash crypto.Hash 223 224 client hash.Hash 225 server hash.Hash 226 227 // Prior to TLS 1.2, an additional MD5 hash is required. 228 clientMD5 hash.Hash 229 serverMD5 hash.Hash 230 231 // In TLS 1.2 (and SSL 3 for implementation convenience), a 232 // full buffer is required. 233 buffer []byte 234 235 version uint16 236 wireVersion uint16 237 prf func(result, secret, label, seed []byte) 238 239 // secret, in TLS 1.3, is the running input secret. 240 secret []byte 241} 242 243func (h *finishedHash) UpdateForHelloRetryRequest() (err error) { 244 data := newByteBuilder() 245 data.addU8(typeMessageHash) 246 data.addU24(h.hash.Size()) 247 data.addBytes(h.Sum()) 248 h.client = h.hash.New() 249 h.server = h.hash.New() 250 if h.buffer != nil { 251 h.buffer = []byte{} 252 } 253 h.Write(data.finish()) 254 return nil 255} 256 257func (h *finishedHash) Write(msg []byte) (n int, err error) { 258 h.client.Write(msg) 259 h.server.Write(msg) 260 261 if h.version < VersionTLS12 { 262 h.clientMD5.Write(msg) 263 h.serverMD5.Write(msg) 264 } 265 266 if h.buffer != nil { 267 h.buffer = append(h.buffer, msg...) 268 } 269 270 return len(msg), nil 271} 272 273func (h finishedHash) Sum() []byte { 274 if h.version >= VersionTLS12 { 275 return h.client.Sum(nil) 276 } 277 278 out := make([]byte, 0, md5.Size+sha1.Size) 279 out = h.clientMD5.Sum(out) 280 return h.client.Sum(out) 281} 282 283// finishedSum30 calculates the contents of the verify_data member of a SSLv3 284// Finished message given the MD5 and SHA1 hashes of a set of handshake 285// messages. 286func finishedSum30(md5, sha1 hash.Hash, masterSecret []byte, magic []byte) []byte { 287 md5.Write(magic) 288 md5.Write(masterSecret) 289 md5.Write(ssl30Pad1[:]) 290 md5Digest := md5.Sum(nil) 291 292 md5.Reset() 293 md5.Write(masterSecret) 294 md5.Write(ssl30Pad2[:]) 295 md5.Write(md5Digest) 296 md5Digest = md5.Sum(nil) 297 298 sha1.Write(magic) 299 sha1.Write(masterSecret) 300 sha1.Write(ssl30Pad1[:40]) 301 sha1Digest := sha1.Sum(nil) 302 303 sha1.Reset() 304 sha1.Write(masterSecret) 305 sha1.Write(ssl30Pad2[:40]) 306 sha1.Write(sha1Digest) 307 sha1Digest = sha1.Sum(nil) 308 309 ret := make([]byte, len(md5Digest)+len(sha1Digest)) 310 copy(ret, md5Digest) 311 copy(ret[len(md5Digest):], sha1Digest) 312 return ret 313} 314 315var ssl3ClientFinishedMagic = [4]byte{0x43, 0x4c, 0x4e, 0x54} 316var ssl3ServerFinishedMagic = [4]byte{0x53, 0x52, 0x56, 0x52} 317 318// clientSum returns the contents of the verify_data member of a client's 319// Finished message. 320func (h finishedHash) clientSum(baseKey []byte) []byte { 321 if h.version == VersionSSL30 { 322 return finishedSum30(h.clientMD5, h.client, baseKey, ssl3ClientFinishedMagic[:]) 323 } 324 325 if h.version < VersionTLS13 { 326 out := make([]byte, finishedVerifyLength) 327 h.prf(out, baseKey, clientFinishedLabel, h.Sum()) 328 return out 329 } 330 331 clientFinishedKey := hkdfExpandLabel(h.hash, baseKey, finishedLabel, nil, h.hash.Size()) 332 finishedHMAC := hmac.New(h.hash.New, clientFinishedKey) 333 finishedHMAC.Write(h.appendContextHashes(nil)) 334 return finishedHMAC.Sum(nil) 335} 336 337// serverSum returns the contents of the verify_data member of a server's 338// Finished message. 339func (h finishedHash) serverSum(baseKey []byte) []byte { 340 if h.version == VersionSSL30 { 341 return finishedSum30(h.serverMD5, h.server, baseKey, ssl3ServerFinishedMagic[:]) 342 } 343 344 if h.version < VersionTLS13 { 345 out := make([]byte, finishedVerifyLength) 346 h.prf(out, baseKey, serverFinishedLabel, h.Sum()) 347 return out 348 } 349 350 serverFinishedKey := hkdfExpandLabel(h.hash, baseKey, finishedLabel, nil, h.hash.Size()) 351 finishedHMAC := hmac.New(h.hash.New, serverFinishedKey) 352 finishedHMAC.Write(h.appendContextHashes(nil)) 353 return finishedHMAC.Sum(nil) 354} 355 356// hashForClientCertificateSSL3 returns the hash to be signed for client 357// certificates in SSL 3.0. 358func (h finishedHash) hashForClientCertificateSSL3(masterSecret []byte) []byte { 359 md5Hash := md5.New() 360 md5Hash.Write(h.buffer) 361 sha1Hash := sha1.New() 362 sha1Hash.Write(h.buffer) 363 return finishedSum30(md5Hash, sha1Hash, masterSecret, nil) 364} 365 366// hashForChannelID returns the hash to be signed for TLS Channel 367// ID. If a resumption, resumeHash has the previous handshake 368// hash. Otherwise, it is nil. 369func (h finishedHash) hashForChannelID(resumeHash []byte) []byte { 370 hash := sha256.New() 371 hash.Write(channelIDLabel) 372 if resumeHash != nil { 373 hash.Write(channelIDResumeLabel) 374 hash.Write(resumeHash) 375 } 376 hash.Write(h.Sum()) 377 return hash.Sum(nil) 378} 379 380// discardHandshakeBuffer is called when there is no more need to 381// buffer the entirety of the handshake messages. 382func (h *finishedHash) discardHandshakeBuffer() { 383 h.buffer = nil 384} 385 386// zeroSecretTLS13 returns the default all zeros secret for TLS 1.3, used when a 387// given secret is not available in the handshake. See RFC 8446, section 7.1. 388func (h *finishedHash) zeroSecret() []byte { 389 return make([]byte, h.hash.Size()) 390} 391 392// addEntropy incorporates ikm into the running TLS 1.3 secret with HKDF-Expand. 393func (h *finishedHash) addEntropy(ikm []byte) { 394 h.secret = hkdfExtract(h.hash.New, h.secret, ikm) 395} 396 397func (h *finishedHash) nextSecret() { 398 h.secret = hkdfExpandLabel(h.hash, h.secret, []byte("derived"), h.hash.New().Sum(nil), h.hash.Size()) 399} 400 401// hkdfExpandLabel implements TLS 1.3's HKDF-Expand-Label function, as defined 402// in section 7.1 of RFC 8446. 403func hkdfExpandLabel(hash crypto.Hash, secret, label, hashValue []byte, length int) []byte { 404 if len(label) > 255 || len(hashValue) > 255 { 405 panic("hkdfExpandLabel: label or hashValue too long") 406 } 407 408 versionLabel := []byte("tls13 ") 409 hkdfLabel := make([]byte, 3+len(versionLabel)+len(label)+1+len(hashValue)) 410 x := hkdfLabel 411 x[0] = byte(length >> 8) 412 x[1] = byte(length) 413 x[2] = byte(len(versionLabel) + len(label)) 414 x = x[3:] 415 copy(x, versionLabel) 416 x = x[len(versionLabel):] 417 copy(x, label) 418 x = x[len(label):] 419 x[0] = byte(len(hashValue)) 420 copy(x[1:], hashValue) 421 return hkdfExpand(hash.New, secret, hkdfLabel, length) 422} 423 424// appendContextHashes returns the concatenation of the handshake hash and the 425// resumption context hash, as used in TLS 1.3. 426func (h *finishedHash) appendContextHashes(b []byte) []byte { 427 b = h.client.Sum(b) 428 return b 429} 430 431// The following are labels for traffic secret derivation in TLS 1.3. 432var ( 433 externalPSKBinderLabel = []byte("ext binder") 434 resumptionPSKBinderLabel = []byte("res binder") 435 earlyTrafficLabel = []byte("c e traffic") 436 clientHandshakeTrafficLabel = []byte("c hs traffic") 437 serverHandshakeTrafficLabel = []byte("s hs traffic") 438 clientApplicationTrafficLabel = []byte("c ap traffic") 439 serverApplicationTrafficLabel = []byte("s ap traffic") 440 applicationTrafficLabel = []byte("traffic upd") 441 earlyExporterLabel = []byte("e exp master") 442 exporterLabel = []byte("exp master") 443 resumptionLabel = []byte("res master") 444 445 resumptionPSKLabel = []byte("resumption") 446) 447 448// deriveSecret implements TLS 1.3's Derive-Secret function, as defined in 449// section 7.1 of draft ietf-tls-tls13-16. 450func (h *finishedHash) deriveSecret(label []byte) []byte { 451 return hkdfExpandLabel(h.hash, h.secret, label, h.appendContextHashes(nil), h.hash.Size()) 452} 453 454// The following are context strings for CertificateVerify in TLS 1.3. 455var ( 456 clientCertificateVerifyContextTLS13 = []byte("TLS 1.3, client CertificateVerify") 457 serverCertificateVerifyContextTLS13 = []byte("TLS 1.3, server CertificateVerify") 458 channelIDContextTLS13 = []byte("TLS 1.3, Channel ID") 459) 460 461// certificateVerifyMessage returns the input to be signed for CertificateVerify 462// in TLS 1.3. 463func (h *finishedHash) certificateVerifyInput(context []byte) []byte { 464 const paddingLen = 64 465 b := make([]byte, paddingLen, paddingLen+len(context)+1+2*h.hash.Size()) 466 for i := 0; i < paddingLen; i++ { 467 b[i] = 32 468 } 469 b = append(b, context...) 470 b = append(b, 0) 471 b = h.appendContextHashes(b) 472 return b 473} 474 475type trafficDirection int 476 477const ( 478 clientWrite trafficDirection = iota 479 serverWrite 480) 481 482var ( 483 keyTLS13 = []byte("key") 484 ivTLS13 = []byte("iv") 485) 486 487// deriveTrafficAEAD derives traffic keys and constructs an AEAD given a traffic 488// secret. 489func deriveTrafficAEAD(version uint16, suite *cipherSuite, secret []byte, side trafficDirection) interface{} { 490 key := hkdfExpandLabel(suite.hash(), secret, keyTLS13, nil, suite.keyLen) 491 iv := hkdfExpandLabel(suite.hash(), secret, ivTLS13, nil, suite.ivLen(version)) 492 493 return suite.aead(version, key, iv) 494} 495 496func updateTrafficSecret(hash crypto.Hash, version uint16, secret []byte) []byte { 497 return hkdfExpandLabel(hash, secret, applicationTrafficLabel, nil, hash.Size()) 498} 499 500func computePSKBinder(psk []byte, version uint16, label []byte, cipherSuite *cipherSuite, clientHello, helloRetryRequest, truncatedHello []byte) []byte { 501 finishedHash := newFinishedHash(version, false, cipherSuite) 502 finishedHash.addEntropy(psk) 503 binderKey := finishedHash.deriveSecret(label) 504 finishedHash.Write(clientHello) 505 if len(helloRetryRequest) != 0 { 506 finishedHash.UpdateForHelloRetryRequest() 507 } 508 finishedHash.Write(helloRetryRequest) 509 finishedHash.Write(truncatedHello) 510 return finishedHash.clientSum(binderKey) 511} 512 513func deriveSessionPSK(suite *cipherSuite, version uint16, masterSecret []byte, nonce []byte) []byte { 514 hash := suite.hash() 515 return hkdfExpandLabel(hash, masterSecret, resumptionPSKLabel, nonce, hash.Size()) 516} 517