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	"crypto/sha512"
14	"errors"
15	"hash"
16)
17
18// Split a premaster secret in two as specified in RFC 4346, section 5.
19func splitPreMasterSecret(secret []byte) (s1, s2 []byte) {
20	s1 = secret[0 : (len(secret)+1)/2]
21	s2 = secret[len(secret)/2:]
22	return
23}
24
25// pHash implements the P_hash function, as defined in RFC 4346, section 5.
26func pHash(result, secret, seed []byte, hash func() hash.Hash) {
27	h := hmac.New(hash, secret)
28	h.Write(seed)
29	a := h.Sum(nil)
30
31	j := 0
32	for j < len(result) {
33		h.Reset()
34		h.Write(a)
35		h.Write(seed)
36		b := h.Sum(nil)
37		todo := len(b)
38		if j+todo > len(result) {
39			todo = len(result) - j
40		}
41		copy(result[j:j+todo], b)
42		j += todo
43
44		h.Reset()
45		h.Write(a)
46		a = h.Sum(nil)
47	}
48}
49
50// prf10 implements the TLS 1.0 pseudo-random function, as defined in RFC 2246, section 5.
51func prf10(result, secret, label, seed []byte) {
52	hashSHA1 := sha1.New
53	hashMD5 := md5.New
54
55	labelAndSeed := make([]byte, len(label)+len(seed))
56	copy(labelAndSeed, label)
57	copy(labelAndSeed[len(label):], seed)
58
59	s1, s2 := splitPreMasterSecret(secret)
60	pHash(result, s1, labelAndSeed, hashMD5)
61	result2 := make([]byte, len(result))
62	pHash(result2, s2, labelAndSeed, hashSHA1)
63
64	for i, b := range result2 {
65		result[i] ^= b
66	}
67}
68
69// prf12 implements the TLS 1.2 pseudo-random function, as defined in RFC 5246, section 5.
70func prf12(hashFunc func() hash.Hash) func(result, secret, label, seed []byte) {
71	return func(result, secret, label, seed []byte) {
72		labelAndSeed := make([]byte, len(label)+len(seed))
73		copy(labelAndSeed, label)
74		copy(labelAndSeed[len(label):], seed)
75
76		pHash(result, secret, labelAndSeed, hashFunc)
77	}
78}
79
80// prf30 implements the SSL 3.0 pseudo-random function, as defined in
81// www.mozilla.org/projects/security/pki/nss/ssl/draft302.txt section 6.
82func prf30(result, secret, label, seed []byte) {
83	hashSHA1 := sha1.New()
84	hashMD5 := md5.New()
85
86	done := 0
87	i := 0
88	// RFC5246 section 6.3 says that the largest PRF output needed is 128
89	// bytes. Since no more ciphersuites will be added to SSLv3, this will
90	// remain true. Each iteration gives us 16 bytes so 10 iterations will
91	// be sufficient.
92	var b [11]byte
93	for done < len(result) {
94		for j := 0; j <= i; j++ {
95			b[j] = 'A' + byte(i)
96		}
97
98		hashSHA1.Reset()
99		hashSHA1.Write(b[:i+1])
100		hashSHA1.Write(secret)
101		hashSHA1.Write(seed)
102		digest := hashSHA1.Sum(nil)
103
104		hashMD5.Reset()
105		hashMD5.Write(secret)
106		hashMD5.Write(digest)
107
108		done += copy(result[done:], hashMD5.Sum(nil))
109		i++
110	}
111}
112
113const (
114	tlsRandomLength      = 32 // Length of a random nonce in TLS 1.1.
115	masterSecretLength   = 48 // Length of a master secret in TLS 1.1.
116	finishedVerifyLength = 12 // Length of verify_data in a Finished message.
117)
118
119var masterSecretLabel = []byte("master secret")
120var extendedMasterSecretLabel = []byte("extended master secret")
121var keyExpansionLabel = []byte("key expansion")
122var clientFinishedLabel = []byte("client finished")
123var serverFinishedLabel = []byte("server finished")
124var channelIDLabel = []byte("TLS Channel ID signature\x00")
125var channelIDResumeLabel = []byte("Resumption\x00")
126
127func prfForVersion(version uint16, suite *cipherSuite) func(result, secret, label, seed []byte) {
128	switch version {
129	case VersionSSL30:
130		return prf30
131	case VersionTLS10, VersionTLS11:
132		return prf10
133	case VersionTLS12:
134		if suite.flags&suiteSHA384 != 0 {
135			return prf12(sha512.New384)
136		}
137		return prf12(sha256.New)
138	default:
139		panic("unknown version")
140	}
141}
142
143// masterFromPreMasterSecret generates the master secret from the pre-master
144// secret. See http://tools.ietf.org/html/rfc5246#section-8.1
145func masterFromPreMasterSecret(version uint16, suite *cipherSuite, preMasterSecret, clientRandom, serverRandom []byte) []byte {
146	var seed [tlsRandomLength * 2]byte
147	copy(seed[0:len(clientRandom)], clientRandom)
148	copy(seed[len(clientRandom):], serverRandom)
149	masterSecret := make([]byte, masterSecretLength)
150	prfForVersion(version, suite)(masterSecret, preMasterSecret, masterSecretLabel, seed[0:])
151	return masterSecret
152}
153
154// extendedMasterFromPreMasterSecret generates the master secret from the
155// pre-master secret when the Triple Handshake fix is in effect. See
156// https://tools.ietf.org/html/draft-ietf-tls-session-hash-01
157func extendedMasterFromPreMasterSecret(version uint16, suite *cipherSuite, preMasterSecret []byte, h finishedHash) []byte {
158	masterSecret := make([]byte, masterSecretLength)
159	prfForVersion(version, suite)(masterSecret, preMasterSecret, extendedMasterSecretLabel, h.Sum())
160	return masterSecret
161}
162
163// keysFromMasterSecret generates the connection keys from the master
164// secret, given the lengths of the MAC key, cipher key and IV, as defined in
165// RFC 2246, section 6.3.
166func keysFromMasterSecret(version uint16, suite *cipherSuite, masterSecret, clientRandom, serverRandom []byte, macLen, keyLen, ivLen int) (clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV []byte) {
167	var seed [tlsRandomLength * 2]byte
168	copy(seed[0:len(clientRandom)], serverRandom)
169	copy(seed[len(serverRandom):], clientRandom)
170
171	n := 2*macLen + 2*keyLen + 2*ivLen
172	keyMaterial := make([]byte, n)
173	prfForVersion(version, suite)(keyMaterial, masterSecret, keyExpansionLabel, seed[0:])
174	clientMAC = keyMaterial[:macLen]
175	keyMaterial = keyMaterial[macLen:]
176	serverMAC = keyMaterial[:macLen]
177	keyMaterial = keyMaterial[macLen:]
178	clientKey = keyMaterial[:keyLen]
179	keyMaterial = keyMaterial[keyLen:]
180	serverKey = keyMaterial[:keyLen]
181	keyMaterial = keyMaterial[keyLen:]
182	clientIV = keyMaterial[:ivLen]
183	keyMaterial = keyMaterial[ivLen:]
184	serverIV = keyMaterial[:ivLen]
185	return
186}
187
188// lookupTLSHash looks up the corresponding crypto.Hash for a given
189// TLS hash identifier.
190func lookupTLSHash(hash uint8) (crypto.Hash, error) {
191	switch hash {
192	case hashMD5:
193		return crypto.MD5, nil
194	case hashSHA1:
195		return crypto.SHA1, nil
196	case hashSHA224:
197		return crypto.SHA224, nil
198	case hashSHA256:
199		return crypto.SHA256, nil
200	case hashSHA384:
201		return crypto.SHA384, nil
202	case hashSHA512:
203		return crypto.SHA512, nil
204	default:
205		return 0, errors.New("tls: unsupported hash algorithm")
206	}
207}
208
209func newFinishedHash(version uint16, cipherSuite *cipherSuite) finishedHash {
210	if version >= VersionTLS12 {
211		newHash := sha256.New
212		if cipherSuite.flags&suiteSHA384 != 0 {
213			newHash = sha512.New384
214		}
215
216		return finishedHash{newHash(), newHash(), nil, nil, []byte{}, version, prf12(newHash)}
217	}
218	return finishedHash{sha1.New(), sha1.New(), md5.New(), md5.New(), []byte{}, version, prf10}
219}
220
221// A finishedHash calculates the hash of a set of handshake messages suitable
222// for including in a Finished message.
223type finishedHash struct {
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	prf     func(result, secret, label, seed []byte)
237}
238
239func (h *finishedHash) Write(msg []byte) (n int, err error) {
240	h.client.Write(msg)
241	h.server.Write(msg)
242
243	if h.version < VersionTLS12 {
244		h.clientMD5.Write(msg)
245		h.serverMD5.Write(msg)
246	}
247
248	if h.buffer != nil {
249		h.buffer = append(h.buffer, msg...)
250	}
251
252	return len(msg), nil
253}
254
255func (h finishedHash) Sum() []byte {
256	if h.version >= VersionTLS12 {
257		return h.client.Sum(nil)
258	}
259
260	out := make([]byte, 0, md5.Size+sha1.Size)
261	out = h.clientMD5.Sum(out)
262	return h.client.Sum(out)
263}
264
265// finishedSum30 calculates the contents of the verify_data member of a SSLv3
266// Finished message given the MD5 and SHA1 hashes of a set of handshake
267// messages.
268func finishedSum30(md5, sha1 hash.Hash, masterSecret []byte, magic []byte) []byte {
269	md5.Write(magic)
270	md5.Write(masterSecret)
271	md5.Write(ssl30Pad1[:])
272	md5Digest := md5.Sum(nil)
273
274	md5.Reset()
275	md5.Write(masterSecret)
276	md5.Write(ssl30Pad2[:])
277	md5.Write(md5Digest)
278	md5Digest = md5.Sum(nil)
279
280	sha1.Write(magic)
281	sha1.Write(masterSecret)
282	sha1.Write(ssl30Pad1[:40])
283	sha1Digest := sha1.Sum(nil)
284
285	sha1.Reset()
286	sha1.Write(masterSecret)
287	sha1.Write(ssl30Pad2[:40])
288	sha1.Write(sha1Digest)
289	sha1Digest = sha1.Sum(nil)
290
291	ret := make([]byte, len(md5Digest)+len(sha1Digest))
292	copy(ret, md5Digest)
293	copy(ret[len(md5Digest):], sha1Digest)
294	return ret
295}
296
297var ssl3ClientFinishedMagic = [4]byte{0x43, 0x4c, 0x4e, 0x54}
298var ssl3ServerFinishedMagic = [4]byte{0x53, 0x52, 0x56, 0x52}
299
300// clientSum returns the contents of the verify_data member of a client's
301// Finished message.
302func (h finishedHash) clientSum(masterSecret []byte) []byte {
303	if h.version == VersionSSL30 {
304		return finishedSum30(h.clientMD5, h.client, masterSecret, ssl3ClientFinishedMagic[:])
305	}
306
307	out := make([]byte, finishedVerifyLength)
308	h.prf(out, masterSecret, clientFinishedLabel, h.Sum())
309	return out
310}
311
312// serverSum returns the contents of the verify_data member of a server's
313// Finished message.
314func (h finishedHash) serverSum(masterSecret []byte) []byte {
315	if h.version == VersionSSL30 {
316		return finishedSum30(h.serverMD5, h.server, masterSecret, ssl3ServerFinishedMagic[:])
317	}
318
319	out := make([]byte, finishedVerifyLength)
320	h.prf(out, masterSecret, serverFinishedLabel, h.Sum())
321	return out
322}
323
324// selectClientCertSignatureAlgorithm returns a signatureAndHash to sign a
325// client's CertificateVerify with, or an error if none can be found.
326func (h finishedHash) selectClientCertSignatureAlgorithm(serverList, clientList []signatureAndHash, sigType uint8) (signatureAndHash, error) {
327	if h.version < VersionTLS12 {
328		// Nothing to negotiate before TLS 1.2.
329		return signatureAndHash{signature: sigType}, nil
330	}
331
332	for _, v := range serverList {
333		if v.signature == sigType && isSupportedSignatureAndHash(v, clientList) {
334			return v, nil
335		}
336	}
337	return signatureAndHash{}, errors.New("tls: no supported signature algorithm found for signing client certificate")
338}
339
340// hashForClientCertificate returns a digest, hash function, and TLS 1.2 hash
341// id suitable for signing by a TLS client certificate.
342func (h finishedHash) hashForClientCertificate(signatureAndHash signatureAndHash, masterSecret []byte) ([]byte, crypto.Hash, error) {
343	if h.version == VersionSSL30 {
344		if signatureAndHash.signature != signatureRSA {
345			return nil, 0, errors.New("tls: unsupported signature type for client certificate")
346		}
347
348		md5Hash := md5.New()
349		md5Hash.Write(h.buffer)
350		sha1Hash := sha1.New()
351		sha1Hash.Write(h.buffer)
352		return finishedSum30(md5Hash, sha1Hash, masterSecret, nil), crypto.MD5SHA1, nil
353	}
354	if h.version >= VersionTLS12 {
355		hashAlg, err := lookupTLSHash(signatureAndHash.hash)
356		if err != nil {
357			return nil, 0, err
358		}
359		hash := hashAlg.New()
360		hash.Write(h.buffer)
361		return hash.Sum(nil), hashAlg, nil
362	}
363	if signatureAndHash.signature == signatureECDSA {
364		return h.server.Sum(nil), crypto.SHA1, nil
365	}
366
367	return h.Sum(), crypto.MD5SHA1, nil
368}
369
370// hashForChannelID returns the hash to be signed for TLS Channel
371// ID. If a resumption, resumeHash has the previous handshake
372// hash. Otherwise, it is nil.
373func (h finishedHash) hashForChannelID(resumeHash []byte) []byte {
374	hash := sha256.New()
375	hash.Write(channelIDLabel)
376	if resumeHash != nil {
377		hash.Write(channelIDResumeLabel)
378		hash.Write(resumeHash)
379	}
380	hash.Write(h.server.Sum(nil))
381	return hash.Sum(nil)
382}
383
384// discardHandshakeBuffer is called when there is no more need to
385// buffer the entirety of the handshake messages.
386func (h *finishedHash) discardHandshakeBuffer() {
387	h.buffer = nil
388}
389