summaryrefslogtreecommitdiff
path: root/src/pkg/crypto/tls/handshake_client.go
blob: 1c6bd4b81bd68fb076f2441be5da234e0f2ff25c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package tls

import (
	"crypto/hmac";
	"crypto/rc4";
	"crypto/rsa";
	"crypto/sha1";
	"crypto/subtle";
	"crypto/x509";
	"io";
)

// A serverHandshake performs the server side of the TLS 1.1 handshake protocol.
type clientHandshake struct {
	writeChan	chan<- interface{};
	controlChan	chan<- interface{};
	msgChan		<-chan interface{};
	config		*Config;
}

func (h *clientHandshake) loop(writeChan chan<- interface{}, controlChan chan<- interface{}, msgChan <-chan interface{}, config *Config) {
	h.writeChan = writeChan;
	h.controlChan = controlChan;
	h.msgChan = msgChan;
	h.config = config;

	defer close(writeChan);
	defer close(controlChan);

	finishedHash := newFinishedHash();

	hello := &clientHelloMsg{
		major: defaultMajor,
		minor: defaultMinor,
		cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
		compressionMethods: []uint8{compressionNone},
		random: make([]byte, 32),
	};

	currentTime := uint32(config.Time());
	hello.random[0] = byte(currentTime >> 24);
	hello.random[1] = byte(currentTime >> 16);
	hello.random[2] = byte(currentTime >> 8);
	hello.random[3] = byte(currentTime);
	_, err := io.ReadFull(config.Rand, hello.random[4:]);
	if err != nil {
		h.error(alertInternalError);
		return;
	}

	finishedHash.Write(hello.marshal());
	writeChan <- writerSetVersion{defaultMajor, defaultMinor};
	writeChan <- hello;

	serverHello, ok := h.readHandshakeMsg().(*serverHelloMsg);
	if !ok {
		h.error(alertUnexpectedMessage);
		return;
	}
	finishedHash.Write(serverHello.marshal());
	major, minor, ok := mutualVersion(serverHello.major, serverHello.minor);
	if !ok {
		h.error(alertProtocolVersion);
		return;
	}

	writeChan <- writerSetVersion{major, minor};

	if serverHello.cipherSuite != TLS_RSA_WITH_RC4_128_SHA ||
		serverHello.compressionMethod != compressionNone {
		h.error(alertUnexpectedMessage);
		return;
	}

	certMsg, ok := h.readHandshakeMsg().(*certificateMsg);
	if !ok || len(certMsg.certificates) == 0 {
		h.error(alertUnexpectedMessage);
		return;
	}
	finishedHash.Write(certMsg.marshal());

	certs := make([]*x509.Certificate, len(certMsg.certificates));
	for i, asn1Data := range certMsg.certificates {
		cert, err := x509.ParseCertificate(asn1Data);
		if err != nil {
			h.error(alertBadCertificate);
			return;
		}
		certs[i] = cert;
	}

	// TODO(agl): do better validation of certs: max path length, name restrictions etc.
	for i := 1; i < len(certs); i++ {
		if certs[i-1].CheckSignatureFrom(certs[i]) != nil {
			h.error(alertBadCertificate);
			return;
		}
	}

	if config.RootCAs != nil {
		root := config.RootCAs.FindParent(certs[len(certs)-1]);
		if root == nil {
			h.error(alertBadCertificate);
			return;
		}
		if certs[len(certs)-1].CheckSignatureFrom(root) != nil {
			h.error(alertBadCertificate);
			return;
		}
	}

	pub, ok := certs[0].PublicKey.(*rsa.PublicKey);
	if !ok {
		h.error(alertUnsupportedCertificate);
		return;
	}

	shd, ok := h.readHandshakeMsg().(*serverHelloDoneMsg);
	if !ok {
		h.error(alertUnexpectedMessage);
		return;
	}
	finishedHash.Write(shd.marshal());

	ckx := new(clientKeyExchangeMsg);
	preMasterSecret := make([]byte, 48);
	// Note that the version number in the preMasterSecret must be the
	// version offered in the ClientHello.
	preMasterSecret[0] = defaultMajor;
	preMasterSecret[1] = defaultMinor;
	_, err = io.ReadFull(config.Rand, preMasterSecret[2:]);
	if err != nil {
		h.error(alertInternalError);
		return;
	}

	ckx.ciphertext, err = rsa.EncryptPKCS1v15(config.Rand, pub, preMasterSecret);
	if err != nil {
		h.error(alertInternalError);
		return;
	}

	finishedHash.Write(ckx.marshal());
	writeChan <- ckx;

	suite := cipherSuites[0];
	masterSecret, clientMAC, serverMAC, clientKey, serverKey :=
		keysFromPreMasterSecret11(preMasterSecret, hello.random, serverHello.random, suite.hashLength, suite.cipherKeyLength);

	cipher, _ := rc4.NewCipher(clientKey);
	writeChan <- writerChangeCipherSpec{cipher, hmac.New(sha1.New(), clientMAC)};

	finished := new(finishedMsg);
	finished.verifyData = finishedHash.clientSum(masterSecret);
	finishedHash.Write(finished.marshal());
	writeChan <- finished;

	// TODO(agl): this is cut-through mode which should probably be an option.
	writeChan <- writerEnableApplicationData{};

	_, ok = h.readHandshakeMsg().(changeCipherSpec);
	if !ok {
		h.error(alertUnexpectedMessage);
		return;
	}

	cipher2, _ := rc4.NewCipher(serverKey);
	controlChan <- &newCipherSpec{cipher2, hmac.New(sha1.New(), serverMAC)};

	serverFinished, ok := h.readHandshakeMsg().(*finishedMsg);
	if !ok {
		h.error(alertUnexpectedMessage);
		return;
	}

	verify := finishedHash.serverSum(masterSecret);
	if len(verify) != len(serverFinished.verifyData) ||
		subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
		h.error(alertHandshakeFailure);
		return;
	}

	controlChan <- ConnectionState{true, "TLS_RSA_WITH_RC4_128_SHA", 0};

	// This should just block forever.
	_ = h.readHandshakeMsg();
	h.error(alertUnexpectedMessage);
	return;
}

func (h *clientHandshake) readHandshakeMsg() interface{} {
	v := <-h.msgChan;
	if closed(h.msgChan) {
		// If the channel closed then the processor received an error
		// from the peer and we don't want to echo it back to them.
		h.msgChan = nil;
		return 0;
	}
	if _, ok := v.(alert); ok {
		// We got an alert from the processor. We forward to the writer
		// and shutdown.
		h.writeChan <- v;
		h.msgChan = nil;
		return 0;
	}
	return v;
}

func (h *clientHandshake) error(e alertType) {
	if h.msgChan != nil {
		// If we didn't get an error from the processor, then we need
		// to tell it about the error.
		go func() {
			for _ = range h.msgChan {
			}
		}();
		h.controlChan <- ConnectionState{false, "", e};
		close(h.controlChan);
		h.writeChan <- alert{alertLevelError, e};
	}
}