-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
370 lines (295 loc) · 9.21 KB
/
server.go
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package toyls
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"errors"
"math"
)
type handshakeServer struct {
// Certificates contains one or more certificate chains
// to present to the other side of the connection.
// Server configurations must include at least one certificate
// or else set GetCertificate.
//XXX Why does tls.Config has an []Certificate?
tls.Certificate
recordProtocol
clientRandom, serverRandom [32]byte
preMasterSecret []byte
masterSecret [48]byte
bytes.Buffer
}
func newHandshakeServer() *handshakeServer {
return &handshakeServer{}
}
func (s *handshakeServer) receiveClientHello(m []byte) ([][]byte, error) {
clientHello, err := deserializeClientHello(m)
if err != nil {
return nil, err
}
serializeRandom(s.clientRandom[:], &clientHello.random)
serverHello, err := s.agree(clientHello)
if err != nil {
return nil, err
}
s.Write(serverHello)
//TODO: they should all be in receive client hello
serverCertificate := s.sendCertificate()
s.Write(serverCertificate)
//IF we need a Server Key Exchange Message,
//send it NOW.
serverKeyExchange := []byte(nil)
s.Write(serverKeyExchange)
//IF we need a Certificate Request,
//send it NOW.
certificateRequest := []byte(nil)
s.Write(certificateRequest)
//MUST always finishes with a serverHelloDone
serverHelloDone, err := s.sendServerHelloDone()
if err != nil {
return nil, err
}
s.Write(serverHelloDone)
return zip(serverHello, serverCertificate, serverKeyExchange, certificateRequest, serverHelloDone), nil
}
func (s *handshakeServer) agree(h *clientHelloBody) ([]byte, error) {
version, err := s.checkSupportedVersion(h.clientVersion)
if err != nil {
return nil, err
}
cipherSuite, err := s.checkSupportedCipherSuites(h.cipherSuites)
if err != nil {
return nil, err
}
compressionMethod, err := s.checkSupportedCompressionMethods(h.compressionMethods)
if err != nil {
return nil, err
}
return s.sendServerHello(version, cipherSuite, compressionMethod)
}
func (s *handshakeServer) checkSupportedVersion(v protocolVersion) (protocolVersion, error) {
if v != VersionTLS12 {
return v, errors.New("unsupported version")
}
return v, nil
}
func (s *handshakeServer) checkSupportedCipherSuites(suites []cipherSuite) (cipherSuite, error) {
supported := cipherSuite{0x00, 0x2f}
for _, cs := range suites {
if cs == supported {
return cs, nil
}
}
return cipherSuite{}, errors.New("unsupported cipher suite")
}
func (s *handshakeServer) checkSupportedCompressionMethods(methods []uint8) (uint8, error) {
for _, cm := range methods {
if cm == 0 {
return cm, nil
}
}
return 0xff, errors.New("unsupported compression method")
}
func (s *handshakeServer) sendServerHello(version protocolVersion, cipherSuite cipherSuite, compressionMethod uint8) ([]byte, error) {
serverRandom := newRandom(rand.Reader)
serverHello := &serverHelloBody{
serverVersion: version,
random: serverRandom,
sessionID: nil, // we dont support session resume
cipherSuite: cipherSuite,
compressionMethod: compressionMethod,
}
message, err := serializeServerHello(serverHello)
if err != nil {
return nil, err
}
serializeRandom(s.serverRandom[:], &serverRandom)
return serializeHandshakeMessage(&handshakeMessage{
serverHelloType, message,
}), nil
}
func (s *handshakeServer) sendCertificate() []byte {
//Should have checked if the agreed-upon key exchange method uses
//certificates for authentication. For now, our method always supports.
return sendCertificate(s.Certificate)
}
func (s *handshakeServer) sendServerKeyExchange() ([]byte, error) {
//Our key exchange method does not send this message. Easy ;)
return nil, nil
}
func (s *handshakeServer) sendCertificateRequest() ([]byte, error) {
//Not supported, for now. Easy ;)
return nil, nil
}
func (s *handshakeServer) sendServerHelloDone() ([]byte, error) {
return serializeHandshakeMessage(&handshakeMessage{
serverHelloDoneType, nil,
}), nil
}
// func receiveCertificate()
// func receiveCertificateVerify()
func (s *handshakeServer) receiveClientKeyExchange(m []byte) error {
var err error
ciphertext := m[2:] // from the size onward
priv, ok := s.Certificate.PrivateKey.(crypto.Decrypter)
if !ok {
return errors.New("certificate private key does not implement crypto.Decrypter")
}
s.preMasterSecret, err = priv.Decrypt(rand.Reader, ciphertext, &rsa.PKCS1v15DecryptOptions{SessionKeyLen: 48})
if err != nil {
return err
}
return nil
}
func (s *handshakeServer) receiveFinished(m []byte) error {
//TODO
return nil
}
func (s *handshakeServer) sendFinished() ([]byte, error) {
//XXX This is exactly the same as the client. Should it be?
//TODO: Store preMasterSecret, clientRandom, serverRandom
verifyData, err := generateVerifyData(s.masterSecret[:], serverFinished, &s.Buffer)
if err != nil {
return nil, err
}
return serializeHandshakeMessage(&handshakeMessage{
finishedType, verifyData,
}), nil
}
// Serialize
func deserializeServerHello(h []byte) (*serverHelloBody, error) {
hello := &serverHelloBody{}
hello.serverVersion, h = extractProtocolVersion(h)
hello.random, h = extractRandom(h)
hello.sessionID, h = extractSessionID(h)
h = extractCipherSuite(hello.cipherSuite[:], h)
hello.compressionMethod = h[0]
//XXX It never fails
return hello, nil
}
func serializeServerHello(h *serverHelloBody) ([]byte, error) {
compressionMethodLen := 1
sessionIDLen := len(h.sessionID)
vectorSizesLen := 4
capacity := protocolVersionLen + randomLen + cipherSuiteLen + compressionMethodLen + sessionIDLen + vectorSizesLen
hello := make([]byte, 0, capacity)
hello = append(hello, h.serverVersion.major, h.serverVersion.minor)
gmtUnixTime := writeBytesFromUint32(h.random.gmtUnixTime)
hello = append(hello, gmtUnixTime[:]...)
hello = append(hello, h.random.randomBytes[:]...)
hello = append(hello, byte(sessionIDLen))
hello = append(hello, h.sessionID...)
hello = append(hello, h.cipherSuite[:]...)
hello = append(hello, h.compressionMethod)
return hello, nil
}
func deserializeCertificate(c []byte) (*certificateBody, error) {
certificateBody := &certificateBody{
certificateList: make([][]byte, 0, 10),
}
certListLen, c := extractUint24(c)
certLen := uint32(0)
vectorLenSize := uint32(3)
for i := uint32(0); i < certListLen; i += certLen + vectorLenSize {
certLen, c = extractUint24(c)
certificate := make([]byte, certLen)
copy(certificate[:], c[:certLen])
c = c[certLen:]
certificateBody.certificateList = append(certificateBody.certificateList,
certificate)
}
return certificateBody, nil
}
func serializeCertificate(c *certificateBody) ([]byte, error) {
certListBody := make([]byte, 0, 0xffffff) // 2^24-1 is maximim length
for _, ci := range c.certificateList {
if uint32(len(ci)) > uint32(math.Pow(2, 24)-1) {
return nil, errors.New("A certificate in the list has exceeded the size limiet of 2^24-1")
}
certificateLen := writeBytesFromUint24(uint32(len(ci)))
certListBody = append(certListBody, certificateLen[:]...)
certListBody = append(certListBody, ci...)
}
certificateListLen := writeBytesFromUint24(uint32(len(certListBody)))
cert := append(certificateListLen[:], certListBody...)
return cert, nil
}
func (c *handshakeServer) doHandshake() error {
r, err := c.readRecord(HANDSHAKE)
if err != nil {
return err
}
h := deserializeHandshakeMessage(r)
c.Write(r)
toSend, err := c.receiveClientHello(h.message)
if err != nil {
return err
}
//fmt.Println("server (serverHello) ->")
err = c.writeRecord(HANDSHAKE, toSend[0])
if err != nil {
return err
}
//fmt.Println("server (certificate) ->")
err = c.writeRecord(HANDSHAKE, toSend[1])
if err != nil {
return err
}
//fmt.Println("server (serverHelloDone) ->")
err = c.writeRecord(HANDSHAKE, toSend[2])
if err != nil {
return err
}
r, err = c.readRecord(HANDSHAKE)
if err != nil {
return err
}
h = deserializeHandshakeMessage(r)
c.Write(r)
err = c.receiveClientKeyExchange(h.message)
if err != nil {
return err
}
c.masterSecret = computeMasterSecret(c.preMasterSecret[:], c.clientRandom[:], c.serverRandom[:])
c.recordProtocol.establishKeys(c.masterSecret, c.clientRandom, c.serverRandom)
r, err = c.readRecord(CHANGE_CIPHER_SPEC)
if err != nil {
return err
}
//Reception of [ChangeCipherSpec] causes the receiver to instruct the record
//layer to immediately copy the read pending state into the read current state.
c.recordProtocol.changeReadCipherSpec()
r, err = c.readRecord(HANDSHAKE) //finished
if err != nil {
return err
}
h = deserializeHandshakeMessage(r)
c.Write(r)
err = c.receiveFinished(h.message) //should verify if finished has the correct hash
if err != nil {
return err
}
//fmt.Println("server (changeCipherSpec) ->")
err = c.writeRecord(CHANGE_CIPHER_SPEC, []byte{1})
if err != nil {
return err
}
//Immediately after sending [ChangeCipherSpec], the sender MUST instruct the
//record layer to make the write pending state the write active state.
c.recordProtocol.changeWriteCipherSpec()
m, err := c.sendFinished()
if err != nil {
return err
}
//fmt.Println("server (finished) ->")
err = c.writeRecord(HANDSHAKE, m)
if err != nil {
return err
}
return nil
}
func (c *handshakeServer) setRecordProtocol(r recordProtocol) {
c.recordProtocol = r
}