• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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(version uint16, cipherSuite *cipherSuite) finishedHash {
184	var ret finishedHash
185
186	if version >= VersionTLS12 {
187		ret.hash = cipherSuite.hash()
188
189		ret.client = ret.hash.New()
190		ret.server = ret.hash.New()
191
192		if version == VersionTLS12 {
193			ret.prf = prf12(ret.hash.New)
194		} else {
195			ret.secret = make([]byte, ret.hash.Size())
196		}
197	} else {
198		ret.hash = crypto.MD5SHA1
199
200		ret.client = sha1.New()
201		ret.server = sha1.New()
202		ret.clientMD5 = md5.New()
203		ret.serverMD5 = md5.New()
204
205		ret.prf = prf10
206	}
207
208	ret.buffer = []byte{}
209	ret.version = version
210	return ret
211}
212
213// A finishedHash calculates the hash of a set of handshake messages suitable
214// for including in a Finished message.
215type finishedHash struct {
216	hash crypto.Hash
217
218	client hash.Hash
219	server hash.Hash
220
221	// Prior to TLS 1.2, an additional MD5 hash is required.
222	clientMD5 hash.Hash
223	serverMD5 hash.Hash
224
225	// In TLS 1.2 (and SSL 3 for implementation convenience), a
226	// full buffer is required.
227	buffer []byte
228
229	version uint16
230	prf     func(result, secret, label, seed []byte)
231
232	// secret, in TLS 1.3, is the running input secret.
233	secret []byte
234}
235
236func (h *finishedHash) Write(msg []byte) (n int, err error) {
237	h.client.Write(msg)
238	h.server.Write(msg)
239
240	if h.version < VersionTLS12 {
241		h.clientMD5.Write(msg)
242		h.serverMD5.Write(msg)
243	}
244
245	if h.buffer != nil {
246		h.buffer = append(h.buffer, msg...)
247	}
248
249	return len(msg), nil
250}
251
252func (h finishedHash) Sum() []byte {
253	if h.version >= VersionTLS12 {
254		return h.client.Sum(nil)
255	}
256
257	out := make([]byte, 0, md5.Size+sha1.Size)
258	out = h.clientMD5.Sum(out)
259	return h.client.Sum(out)
260}
261
262// finishedSum30 calculates the contents of the verify_data member of a SSLv3
263// Finished message given the MD5 and SHA1 hashes of a set of handshake
264// messages.
265func finishedSum30(md5, sha1 hash.Hash, masterSecret []byte, magic []byte) []byte {
266	md5.Write(magic)
267	md5.Write(masterSecret)
268	md5.Write(ssl30Pad1[:])
269	md5Digest := md5.Sum(nil)
270
271	md5.Reset()
272	md5.Write(masterSecret)
273	md5.Write(ssl30Pad2[:])
274	md5.Write(md5Digest)
275	md5Digest = md5.Sum(nil)
276
277	sha1.Write(magic)
278	sha1.Write(masterSecret)
279	sha1.Write(ssl30Pad1[:40])
280	sha1Digest := sha1.Sum(nil)
281
282	sha1.Reset()
283	sha1.Write(masterSecret)
284	sha1.Write(ssl30Pad2[:40])
285	sha1.Write(sha1Digest)
286	sha1Digest = sha1.Sum(nil)
287
288	ret := make([]byte, len(md5Digest)+len(sha1Digest))
289	copy(ret, md5Digest)
290	copy(ret[len(md5Digest):], sha1Digest)
291	return ret
292}
293
294var ssl3ClientFinishedMagic = [4]byte{0x43, 0x4c, 0x4e, 0x54}
295var ssl3ServerFinishedMagic = [4]byte{0x53, 0x52, 0x56, 0x52}
296
297// clientSum returns the contents of the verify_data member of a client's
298// Finished message.
299func (h finishedHash) clientSum(baseKey []byte) []byte {
300	if h.version == VersionSSL30 {
301		return finishedSum30(h.clientMD5, h.client, baseKey, ssl3ClientFinishedMagic[:])
302	}
303
304	if h.version < VersionTLS13 {
305		out := make([]byte, finishedVerifyLength)
306		h.prf(out, baseKey, clientFinishedLabel, h.Sum())
307		return out
308	}
309
310	clientFinishedKey := hkdfExpandLabel(h.hash, baseKey, finishedLabel, nil, h.hash.Size())
311	finishedHMAC := hmac.New(h.hash.New, clientFinishedKey)
312	finishedHMAC.Write(h.appendContextHashes(nil))
313	return finishedHMAC.Sum(nil)
314}
315
316// serverSum returns the contents of the verify_data member of a server's
317// Finished message.
318func (h finishedHash) serverSum(baseKey []byte) []byte {
319	if h.version == VersionSSL30 {
320		return finishedSum30(h.serverMD5, h.server, baseKey, ssl3ServerFinishedMagic[:])
321	}
322
323	if h.version < VersionTLS13 {
324		out := make([]byte, finishedVerifyLength)
325		h.prf(out, baseKey, serverFinishedLabel, h.Sum())
326		return out
327	}
328
329	serverFinishedKey := hkdfExpandLabel(h.hash, baseKey, finishedLabel, nil, h.hash.Size())
330	finishedHMAC := hmac.New(h.hash.New, serverFinishedKey)
331	finishedHMAC.Write(h.appendContextHashes(nil))
332	return finishedHMAC.Sum(nil)
333}
334
335// hashForClientCertificateSSL3 returns the hash to be signed for client
336// certificates in SSL 3.0.
337func (h finishedHash) hashForClientCertificateSSL3(masterSecret []byte) []byte {
338	md5Hash := md5.New()
339	md5Hash.Write(h.buffer)
340	sha1Hash := sha1.New()
341	sha1Hash.Write(h.buffer)
342	return finishedSum30(md5Hash, sha1Hash, masterSecret, nil)
343}
344
345// hashForChannelID returns the hash to be signed for TLS Channel
346// ID. If a resumption, resumeHash has the previous handshake
347// hash. Otherwise, it is nil.
348func (h finishedHash) hashForChannelID(resumeHash []byte) []byte {
349	hash := sha256.New()
350	hash.Write(channelIDLabel)
351	if resumeHash != nil {
352		hash.Write(channelIDResumeLabel)
353		hash.Write(resumeHash)
354	}
355	hash.Write(h.Sum())
356	return hash.Sum(nil)
357}
358
359// discardHandshakeBuffer is called when there is no more need to
360// buffer the entirety of the handshake messages.
361func (h *finishedHash) discardHandshakeBuffer() {
362	h.buffer = nil
363}
364
365// zeroSecretTLS13 returns the default all zeros secret for TLS 1.3, used when a
366// given secret is not available in the handshake. See draft-ietf-tls-tls13-16,
367// section 7.1.
368func (h *finishedHash) zeroSecret() []byte {
369	return make([]byte, h.hash.Size())
370}
371
372// addEntropy incorporates ikm into the running TLS 1.3 secret with HKDF-Expand.
373func (h *finishedHash) addEntropy(ikm []byte) {
374	h.secret = hkdfExtract(h.hash.New, h.secret, ikm)
375}
376
377// hkdfExpandLabel implements TLS 1.3's HKDF-Expand-Label function, as defined
378// in section 7.1 of draft-ietf-tls-tls13-16.
379func hkdfExpandLabel(hash crypto.Hash, secret, label, hashValue []byte, length int) []byte {
380	if len(label) > 255 || len(hashValue) > 255 {
381		panic("hkdfExpandLabel: label or hashValue too long")
382	}
383	hkdfLabel := make([]byte, 3+9+len(label)+1+len(hashValue))
384	x := hkdfLabel
385	x[0] = byte(length >> 8)
386	x[1] = byte(length)
387	x[2] = byte(9 + len(label))
388	x = x[3:]
389	copy(x, []byte("TLS 1.3, "))
390	x = x[9:]
391	copy(x, label)
392	x = x[len(label):]
393	x[0] = byte(len(hashValue))
394	copy(x[1:], hashValue)
395	return hkdfExpand(hash.New, secret, hkdfLabel, length)
396}
397
398// appendContextHashes returns the concatenation of the handshake hash and the
399// resumption context hash, as used in TLS 1.3.
400func (h *finishedHash) appendContextHashes(b []byte) []byte {
401	b = h.client.Sum(b)
402	return b
403}
404
405// The following are labels for traffic secret derivation in TLS 1.3.
406var (
407	externalPSKBinderLabel        = []byte("external psk binder key")
408	resumptionPSKBinderLabel      = []byte("resumption psk binder key")
409	earlyTrafficLabel             = []byte("client early traffic secret")
410	clientHandshakeTrafficLabel   = []byte("client handshake traffic secret")
411	serverHandshakeTrafficLabel   = []byte("server handshake traffic secret")
412	clientApplicationTrafficLabel = []byte("client application traffic secret")
413	serverApplicationTrafficLabel = []byte("server application traffic secret")
414	applicationTrafficLabel       = []byte("application traffic secret")
415	exporterLabel                 = []byte("exporter master secret")
416	resumptionLabel               = []byte("resumption master secret")
417)
418
419// deriveSecret implements TLS 1.3's Derive-Secret function, as defined in
420// section 7.1 of draft ietf-tls-tls13-16.
421func (h *finishedHash) deriveSecret(label []byte) []byte {
422	return hkdfExpandLabel(h.hash, h.secret, label, h.appendContextHashes(nil), h.hash.Size())
423}
424
425// The following are context strings for CertificateVerify in TLS 1.3.
426var (
427	clientCertificateVerifyContextTLS13 = []byte("TLS 1.3, client CertificateVerify")
428	serverCertificateVerifyContextTLS13 = []byte("TLS 1.3, server CertificateVerify")
429	channelIDContextTLS13               = []byte("TLS 1.3, Channel ID")
430)
431
432// certificateVerifyMessage returns the input to be signed for CertificateVerify
433// in TLS 1.3.
434func (h *finishedHash) certificateVerifyInput(context []byte) []byte {
435	const paddingLen = 64
436	b := make([]byte, paddingLen, paddingLen+len(context)+1+2*h.hash.Size())
437	for i := 0; i < paddingLen; i++ {
438		b[i] = 32
439	}
440	b = append(b, context...)
441	b = append(b, 0)
442	b = h.appendContextHashes(b)
443	return b
444}
445
446type trafficDirection int
447
448const (
449	clientWrite trafficDirection = iota
450	serverWrite
451)
452
453var (
454	keyTLS13 = []byte("key")
455	ivTLS13  = []byte("iv")
456)
457
458// deriveTrafficAEAD derives traffic keys and constructs an AEAD given a traffic
459// secret.
460func deriveTrafficAEAD(version uint16, suite *cipherSuite, secret []byte, side trafficDirection) interface{} {
461	key := hkdfExpandLabel(suite.hash(), secret, keyTLS13, nil, suite.keyLen)
462	iv := hkdfExpandLabel(suite.hash(), secret, ivTLS13, nil, suite.ivLen(version))
463
464	return suite.aead(version, key, iv)
465}
466
467func updateTrafficSecret(hash crypto.Hash, secret []byte) []byte {
468	return hkdfExpandLabel(hash, secret, applicationTrafficLabel, nil, hash.Size())
469}
470
471func computePSKBinder(psk, label []byte, cipherSuite *cipherSuite, transcript, truncatedHello []byte) []byte {
472	finishedHash := newFinishedHash(VersionTLS13, cipherSuite)
473	finishedHash.addEntropy(psk)
474	binderKey := finishedHash.deriveSecret(label)
475	finishedHash.Write(transcript)
476	finishedHash.Write(truncatedHello)
477	return finishedHash.clientSum(binderKey)
478}
479