blob: 5371a645320215fae1cac9fde046fa1a246263d0 [file] [log] [blame]
Adam Langley95c29f32014-06-20 12:00:00 -07001// Copyright 2010 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
5// TLS low level connection and record layer
6
7package main
8
9import (
10 "bytes"
11 "crypto/cipher"
12 "crypto/subtle"
13 "crypto/x509"
14 "errors"
15 "fmt"
16 "io"
17 "net"
18 "sync"
19 "time"
20)
21
22// A Conn represents a secured connection.
23// It implements the net.Conn interface.
24type Conn struct {
25 // constant
26 conn net.Conn
David Benjamin83c0bc92014-08-04 01:23:53 -040027 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -070028 isClient bool
29
30 // constant after handshake; protected by handshakeMutex
31 handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
32 handshakeErr error // error resulting from handshake
33 vers uint16 // TLS version
34 haveVers bool // version has been negotiated
35 config *Config // configuration passed to constructor
36 handshakeComplete bool
37 didResume bool // whether this connection was a session resumption
38 cipherSuite uint16
39 ocspResponse []byte // stapled OCSP response
40 peerCertificates []*x509.Certificate
41 // verifiedChains contains the certificate chains that we built, as
42 // opposed to the ones presented by the server.
43 verifiedChains [][]*x509.Certificate
44 // serverName contains the server name indicated by the client, if any.
45 serverName string
46
47 clientProtocol string
48 clientProtocolFallback bool
49
50 // input/output
51 in, out halfConn // in.Mutex < out.Mutex
52 rawInput *block // raw input, right off the wire
David Benjamin83c0bc92014-08-04 01:23:53 -040053 input *block // application record waiting to be read
54 hand bytes.Buffer // handshake record waiting to be read
55
56 // DTLS state
57 sendHandshakeSeq uint16
58 recvHandshakeSeq uint16
59 handMsg []byte // pending assembled handshake message
60 handMsgLen int // handshake message length, not including the header
Adam Langley95c29f32014-06-20 12:00:00 -070061
62 tmp [16]byte
63}
64
65// Access to net.Conn methods.
66// Cannot just embed net.Conn because that would
67// export the struct field too.
68
69// LocalAddr returns the local network address.
70func (c *Conn) LocalAddr() net.Addr {
71 return c.conn.LocalAddr()
72}
73
74// RemoteAddr returns the remote network address.
75func (c *Conn) RemoteAddr() net.Addr {
76 return c.conn.RemoteAddr()
77}
78
79// SetDeadline sets the read and write deadlines associated with the connection.
80// A zero value for t means Read and Write will not time out.
81// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
82func (c *Conn) SetDeadline(t time.Time) error {
83 return c.conn.SetDeadline(t)
84}
85
86// SetReadDeadline sets the read deadline on the underlying connection.
87// A zero value for t means Read will not time out.
88func (c *Conn) SetReadDeadline(t time.Time) error {
89 return c.conn.SetReadDeadline(t)
90}
91
92// SetWriteDeadline sets the write deadline on the underlying conneciton.
93// A zero value for t means Write will not time out.
94// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
95func (c *Conn) SetWriteDeadline(t time.Time) error {
96 return c.conn.SetWriteDeadline(t)
97}
98
99// A halfConn represents one direction of the record layer
100// connection, either sending or receiving.
101type halfConn struct {
102 sync.Mutex
103
David Benjamin83c0bc92014-08-04 01:23:53 -0400104 err error // first permanent error
105 version uint16 // protocol version
106 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -0700107 cipher interface{} // cipher algorithm
108 mac macFunction
109 seq [8]byte // 64-bit sequence number
110 bfree *block // list of free blocks
111
112 nextCipher interface{} // next encryption state
113 nextMac macFunction // next MAC algorithm
114
115 // used to save allocating a new buffer for each MAC.
116 inDigestBuf, outDigestBuf []byte
Adam Langley80842bd2014-06-20 12:00:00 -0700117
118 config *Config
Adam Langley95c29f32014-06-20 12:00:00 -0700119}
120
121func (hc *halfConn) setErrorLocked(err error) error {
122 hc.err = err
123 return err
124}
125
126func (hc *halfConn) error() error {
127 hc.Lock()
128 err := hc.err
129 hc.Unlock()
130 return err
131}
132
133// prepareCipherSpec sets the encryption and MAC states
134// that a subsequent changeCipherSpec will use.
135func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
136 hc.version = version
137 hc.nextCipher = cipher
138 hc.nextMac = mac
139}
140
141// changeCipherSpec changes the encryption and MAC states
142// to the ones previously passed to prepareCipherSpec.
Adam Langley80842bd2014-06-20 12:00:00 -0700143func (hc *halfConn) changeCipherSpec(config *Config) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700144 if hc.nextCipher == nil {
145 return alertInternalError
146 }
147 hc.cipher = hc.nextCipher
148 hc.mac = hc.nextMac
149 hc.nextCipher = nil
150 hc.nextMac = nil
Adam Langley80842bd2014-06-20 12:00:00 -0700151 hc.config = config
David Benjamin83c0bc92014-08-04 01:23:53 -0400152 hc.incEpoch()
Adam Langley95c29f32014-06-20 12:00:00 -0700153 return nil
154}
155
156// incSeq increments the sequence number.
157func (hc *halfConn) incSeq() {
David Benjamin83c0bc92014-08-04 01:23:53 -0400158 limit := 0
159 if hc.isDTLS {
160 // Increment up to the epoch in DTLS.
161 limit = 2
162 }
163 for i := 7; i >= limit; i-- {
Adam Langley95c29f32014-06-20 12:00:00 -0700164 hc.seq[i]++
165 if hc.seq[i] != 0 {
166 return
167 }
168 }
169
170 // Not allowed to let sequence number wrap.
171 // Instead, must renegotiate before it does.
172 // Not likely enough to bother.
173 panic("TLS: sequence number wraparound")
174}
175
David Benjamin83c0bc92014-08-04 01:23:53 -0400176// incEpoch resets the sequence number. In DTLS, it increments the
177// epoch half of the sequence number.
178func (hc *halfConn) incEpoch() {
179 limit := 0
180 if hc.isDTLS {
181 for i := 1; i >= 0; i-- {
182 hc.seq[i]++
183 if hc.seq[i] != 0 {
184 break
185 }
186 if i == 0 {
187 panic("TLS: epoch number wraparound")
188 }
189 }
190 limit = 2
Adam Langley95c29f32014-06-20 12:00:00 -0700191 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400192 seq := hc.seq[limit:]
193 for i := range seq {
194 seq[i] = 0
195 }
196}
197
198func (hc *halfConn) recordHeaderLen() int {
199 if hc.isDTLS {
200 return dtlsRecordHeaderLen
201 }
202 return tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700203}
204
205// removePadding returns an unpadded slice, in constant time, which is a prefix
206// of the input. It also returns a byte which is equal to 255 if the padding
207// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
208func removePadding(payload []byte) ([]byte, byte) {
209 if len(payload) < 1 {
210 return payload, 0
211 }
212
213 paddingLen := payload[len(payload)-1]
214 t := uint(len(payload)-1) - uint(paddingLen)
215 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
216 good := byte(int32(^t) >> 31)
217
218 toCheck := 255 // the maximum possible padding length
219 // The length of the padded data is public, so we can use an if here
220 if toCheck+1 > len(payload) {
221 toCheck = len(payload) - 1
222 }
223
224 for i := 0; i < toCheck; i++ {
225 t := uint(paddingLen) - uint(i)
226 // if i <= paddingLen then the MSB of t is zero
227 mask := byte(int32(^t) >> 31)
228 b := payload[len(payload)-1-i]
229 good &^= mask&paddingLen ^ mask&b
230 }
231
232 // We AND together the bits of good and replicate the result across
233 // all the bits.
234 good &= good << 4
235 good &= good << 2
236 good &= good << 1
237 good = uint8(int8(good) >> 7)
238
239 toRemove := good&paddingLen + 1
240 return payload[:len(payload)-int(toRemove)], good
241}
242
243// removePaddingSSL30 is a replacement for removePadding in the case that the
244// protocol version is SSLv3. In this version, the contents of the padding
245// are random and cannot be checked.
246func removePaddingSSL30(payload []byte) ([]byte, byte) {
247 if len(payload) < 1 {
248 return payload, 0
249 }
250
251 paddingLen := int(payload[len(payload)-1]) + 1
252 if paddingLen > len(payload) {
253 return payload, 0
254 }
255
256 return payload[:len(payload)-paddingLen], 255
257}
258
259func roundUp(a, b int) int {
260 return a + (b-a%b)%b
261}
262
263// cbcMode is an interface for block ciphers using cipher block chaining.
264type cbcMode interface {
265 cipher.BlockMode
266 SetIV([]byte)
267}
268
269// decrypt checks and strips the mac and decrypts the data in b. Returns a
270// success boolean, the number of bytes to skip from the start of the record in
271// order to get the application payload, and an optional alert value.
272func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, alertValue alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400273 recordHeaderLen := hc.recordHeaderLen()
274
Adam Langley95c29f32014-06-20 12:00:00 -0700275 // pull out payload
276 payload := b.data[recordHeaderLen:]
277
278 macSize := 0
279 if hc.mac != nil {
280 macSize = hc.mac.Size()
281 }
282
283 paddingGood := byte(255)
284 explicitIVLen := 0
285
David Benjamin83c0bc92014-08-04 01:23:53 -0400286 seq := hc.seq[:]
287 if hc.isDTLS {
288 // DTLS sequence numbers are explicit.
289 seq = b.data[3:11]
290 }
291
Adam Langley95c29f32014-06-20 12:00:00 -0700292 // decrypt
293 if hc.cipher != nil {
294 switch c := hc.cipher.(type) {
295 case cipher.Stream:
296 c.XORKeyStream(payload, payload)
297 case cipher.AEAD:
298 explicitIVLen = 8
299 if len(payload) < explicitIVLen {
300 return false, 0, alertBadRecordMAC
301 }
302 nonce := payload[:8]
303 payload = payload[8:]
304
305 var additionalData [13]byte
David Benjamin83c0bc92014-08-04 01:23:53 -0400306 copy(additionalData[:], seq)
Adam Langley95c29f32014-06-20 12:00:00 -0700307 copy(additionalData[8:], b.data[:3])
308 n := len(payload) - c.Overhead()
309 additionalData[11] = byte(n >> 8)
310 additionalData[12] = byte(n)
311 var err error
312 payload, err = c.Open(payload[:0], nonce, payload, additionalData[:])
313 if err != nil {
314 return false, 0, alertBadRecordMAC
315 }
316 b.resize(recordHeaderLen + explicitIVLen + len(payload))
317 case cbcMode:
318 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400319 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700320 explicitIVLen = blockSize
321 }
322
323 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
324 return false, 0, alertBadRecordMAC
325 }
326
327 if explicitIVLen > 0 {
328 c.SetIV(payload[:explicitIVLen])
329 payload = payload[explicitIVLen:]
330 }
331 c.CryptBlocks(payload, payload)
332 if hc.version == VersionSSL30 {
333 payload, paddingGood = removePaddingSSL30(payload)
334 } else {
335 payload, paddingGood = removePadding(payload)
336 }
337 b.resize(recordHeaderLen + explicitIVLen + len(payload))
338
339 // note that we still have a timing side-channel in the
340 // MAC check, below. An attacker can align the record
341 // so that a correct padding will cause one less hash
342 // block to be calculated. Then they can iteratively
343 // decrypt a record by breaking each byte. See
344 // "Password Interception in a SSL/TLS Channel", Brice
345 // Canvel et al.
346 //
347 // However, our behavior matches OpenSSL, so we leak
348 // only as much as they do.
349 default:
350 panic("unknown cipher type")
351 }
352 }
353
354 // check, strip mac
355 if hc.mac != nil {
356 if len(payload) < macSize {
357 return false, 0, alertBadRecordMAC
358 }
359
360 // strip mac off payload, b.data
361 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400362 b.data[recordHeaderLen-2] = byte(n >> 8)
363 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700364 b.resize(recordHeaderLen + explicitIVLen + n)
365 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400366 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700367
368 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
369 return false, 0, alertBadRecordMAC
370 }
371 hc.inDigestBuf = localMAC
372 }
373 hc.incSeq()
374
375 return true, recordHeaderLen + explicitIVLen, 0
376}
377
378// padToBlockSize calculates the needed padding block, if any, for a payload.
379// On exit, prefix aliases payload and extends to the end of the last full
380// block of payload. finalBlock is a fresh slice which contains the contents of
381// any suffix of payload as well as the needed padding to make finalBlock a
382// full block.
Adam Langley80842bd2014-06-20 12:00:00 -0700383func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700384 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700385 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700386
387 paddingLen := blockSize - overrun
388 finalSize := blockSize
389 if config.Bugs.MaxPadding {
390 for paddingLen+blockSize <= 256 {
391 paddingLen += blockSize
392 }
393 finalSize = 256
394 }
395 finalBlock = make([]byte, finalSize)
396 for i := range finalBlock {
Adam Langley95c29f32014-06-20 12:00:00 -0700397 finalBlock[i] = byte(paddingLen - 1)
398 }
Adam Langley80842bd2014-06-20 12:00:00 -0700399 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
400 finalBlock[overrun] ^= 0xff
401 }
402 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700403 return
404}
405
406// encrypt encrypts and macs the data in b.
407func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400408 recordHeaderLen := hc.recordHeaderLen()
409
Adam Langley95c29f32014-06-20 12:00:00 -0700410 // mac
411 if hc.mac != nil {
David Benjamin83c0bc92014-08-04 01:23:53 -0400412 mac := hc.mac.MAC(hc.outDigestBuf, hc.seq[0:], b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], b.data[recordHeaderLen+explicitIVLen:])
Adam Langley95c29f32014-06-20 12:00:00 -0700413
414 n := len(b.data)
415 b.resize(n + len(mac))
416 copy(b.data[n:], mac)
417 hc.outDigestBuf = mac
418 }
419
420 payload := b.data[recordHeaderLen:]
421
422 // encrypt
423 if hc.cipher != nil {
424 switch c := hc.cipher.(type) {
425 case cipher.Stream:
426 c.XORKeyStream(payload, payload)
427 case cipher.AEAD:
428 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
429 b.resize(len(b.data) + c.Overhead())
430 nonce := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
431 payload := b.data[recordHeaderLen+explicitIVLen:]
432 payload = payload[:payloadLen]
433
434 var additionalData [13]byte
435 copy(additionalData[:], hc.seq[:])
436 copy(additionalData[8:], b.data[:3])
437 additionalData[11] = byte(payloadLen >> 8)
438 additionalData[12] = byte(payloadLen)
439
440 c.Seal(payload[:0], nonce, payload, additionalData[:])
441 case cbcMode:
442 blockSize := c.BlockSize()
443 if explicitIVLen > 0 {
444 c.SetIV(payload[:explicitIVLen])
445 payload = payload[explicitIVLen:]
446 }
Adam Langley80842bd2014-06-20 12:00:00 -0700447 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700448 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
449 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
450 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
451 default:
452 panic("unknown cipher type")
453 }
454 }
455
456 // update length to include MAC and any block padding needed.
457 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400458 b.data[recordHeaderLen-2] = byte(n >> 8)
459 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700460 hc.incSeq()
461
462 return true, 0
463}
464
465// A block is a simple data buffer.
466type block struct {
467 data []byte
468 off int // index for Read
469 link *block
470}
471
472// resize resizes block to be n bytes, growing if necessary.
473func (b *block) resize(n int) {
474 if n > cap(b.data) {
475 b.reserve(n)
476 }
477 b.data = b.data[0:n]
478}
479
480// reserve makes sure that block contains a capacity of at least n bytes.
481func (b *block) reserve(n int) {
482 if cap(b.data) >= n {
483 return
484 }
485 m := cap(b.data)
486 if m == 0 {
487 m = 1024
488 }
489 for m < n {
490 m *= 2
491 }
492 data := make([]byte, len(b.data), m)
493 copy(data, b.data)
494 b.data = data
495}
496
497// readFromUntil reads from r into b until b contains at least n bytes
498// or else returns an error.
499func (b *block) readFromUntil(r io.Reader, n int) error {
500 // quick case
501 if len(b.data) >= n {
502 return nil
503 }
504
505 // read until have enough.
506 b.reserve(n)
507 for {
508 m, err := r.Read(b.data[len(b.data):cap(b.data)])
509 b.data = b.data[0 : len(b.data)+m]
510 if len(b.data) >= n {
511 // TODO(bradfitz,agl): slightly suspicious
512 // that we're throwing away r.Read's err here.
513 break
514 }
515 if err != nil {
516 return err
517 }
518 }
519 return nil
520}
521
522func (b *block) Read(p []byte) (n int, err error) {
523 n = copy(p, b.data[b.off:])
524 b.off += n
525 return
526}
527
528// newBlock allocates a new block, from hc's free list if possible.
529func (hc *halfConn) newBlock() *block {
530 b := hc.bfree
531 if b == nil {
532 return new(block)
533 }
534 hc.bfree = b.link
535 b.link = nil
536 b.resize(0)
537 return b
538}
539
540// freeBlock returns a block to hc's free list.
541// The protocol is such that each side only has a block or two on
542// its free list at a time, so there's no need to worry about
543// trimming the list, etc.
544func (hc *halfConn) freeBlock(b *block) {
545 b.link = hc.bfree
546 hc.bfree = b
547}
548
549// splitBlock splits a block after the first n bytes,
550// returning a block with those n bytes and a
551// block with the remainder. the latter may be nil.
552func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
553 if len(b.data) <= n {
554 return b, nil
555 }
556 bb := hc.newBlock()
557 bb.resize(len(b.data) - n)
558 copy(bb.data, b.data[n:])
559 b.data = b.data[0:n]
560 return b, bb
561}
562
David Benjamin83c0bc92014-08-04 01:23:53 -0400563func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
564 if c.isDTLS {
565 return c.dtlsDoReadRecord(want)
566 }
567
568 recordHeaderLen := tlsRecordHeaderLen
569
570 if c.rawInput == nil {
571 c.rawInput = c.in.newBlock()
572 }
573 b := c.rawInput
574
575 // Read header, payload.
576 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
577 // RFC suggests that EOF without an alertCloseNotify is
578 // an error, but popular web sites seem to do this,
579 // so we can't make it an error.
580 // if err == io.EOF {
581 // err = io.ErrUnexpectedEOF
582 // }
583 if e, ok := err.(net.Error); !ok || !e.Temporary() {
584 c.in.setErrorLocked(err)
585 }
586 return 0, nil, err
587 }
588 typ := recordType(b.data[0])
589
590 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
591 // start with a uint16 length where the MSB is set and the first record
592 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
593 // an SSLv2 client.
594 if want == recordTypeHandshake && typ == 0x80 {
595 c.sendAlert(alertProtocolVersion)
596 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
597 }
598
599 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
600 n := int(b.data[3])<<8 | int(b.data[4])
601 if c.haveVers && vers != c.vers {
602 c.sendAlert(alertProtocolVersion)
603 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers))
604 }
605 if n > maxCiphertext {
606 c.sendAlert(alertRecordOverflow)
607 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
608 }
609 if !c.haveVers {
610 // First message, be extra suspicious:
611 // this might not be a TLS client.
612 // Bail out before reading a full 'body', if possible.
613 // The current max version is 3.1.
614 // If the version is >= 16.0, it's probably not real.
615 // Similarly, a clientHello message encodes in
616 // well under a kilobyte. If the length is >= 12 kB,
617 // it's probably not real.
618 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
619 c.sendAlert(alertUnexpectedMessage)
620 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
621 }
622 }
623 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
624 if err == io.EOF {
625 err = io.ErrUnexpectedEOF
626 }
627 if e, ok := err.(net.Error); !ok || !e.Temporary() {
628 c.in.setErrorLocked(err)
629 }
630 return 0, nil, err
631 }
632
633 // Process message.
634 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
635 ok, off, err := c.in.decrypt(b)
636 if !ok {
637 c.in.setErrorLocked(c.sendAlert(err))
638 }
639 b.off = off
640 return typ, b, nil
641}
642
Adam Langley95c29f32014-06-20 12:00:00 -0700643// readRecord reads the next TLS record from the connection
644// and updates the record layer state.
645// c.in.Mutex <= L; c.input == nil.
646func (c *Conn) readRecord(want recordType) error {
647 // Caller must be in sync with connection:
648 // handshake data if handshake not yet completed,
649 // else application data. (We don't support renegotiation.)
650 switch want {
651 default:
652 c.sendAlert(alertInternalError)
653 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
654 case recordTypeHandshake, recordTypeChangeCipherSpec:
655 if c.handshakeComplete {
656 c.sendAlert(alertInternalError)
657 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
658 }
659 case recordTypeApplicationData:
660 if !c.handshakeComplete {
661 c.sendAlert(alertInternalError)
662 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
663 }
664 }
665
666Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400667 typ, b, err := c.doReadRecord(want)
668 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700669 return err
670 }
Adam Langley95c29f32014-06-20 12:00:00 -0700671 data := b.data[b.off:]
672 if len(data) > maxPlaintext {
673 err := c.sendAlert(alertRecordOverflow)
674 c.in.freeBlock(b)
675 return c.in.setErrorLocked(err)
676 }
677
678 switch typ {
679 default:
680 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
681
682 case recordTypeAlert:
683 if len(data) != 2 {
684 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
685 break
686 }
687 if alert(data[1]) == alertCloseNotify {
688 c.in.setErrorLocked(io.EOF)
689 break
690 }
691 switch data[0] {
692 case alertLevelWarning:
693 // drop on the floor
694 c.in.freeBlock(b)
695 goto Again
696 case alertLevelError:
697 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
698 default:
699 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
700 }
701
702 case recordTypeChangeCipherSpec:
703 if typ != want || len(data) != 1 || data[0] != 1 {
704 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
705 break
706 }
Adam Langley80842bd2014-06-20 12:00:00 -0700707 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700708 if err != nil {
709 c.in.setErrorLocked(c.sendAlert(err.(alert)))
710 }
711
712 case recordTypeApplicationData:
713 if typ != want {
714 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
715 break
716 }
717 c.input = b
718 b = nil
719
720 case recordTypeHandshake:
721 // TODO(rsc): Should at least pick off connection close.
722 if typ != want {
723 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
724 }
725 c.hand.Write(data)
726 }
727
728 if b != nil {
729 c.in.freeBlock(b)
730 }
731 return c.in.err
732}
733
734// sendAlert sends a TLS alert message.
735// c.out.Mutex <= L.
736func (c *Conn) sendAlertLocked(err alert) error {
737 switch err {
738 case alertNoRenegotiation, alertCloseNotify:
739 c.tmp[0] = alertLevelWarning
740 default:
741 c.tmp[0] = alertLevelError
742 }
743 c.tmp[1] = byte(err)
744 c.writeRecord(recordTypeAlert, c.tmp[0:2])
745 // closeNotify is a special case in that it isn't an error:
746 if err != alertCloseNotify {
747 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
748 }
749 return nil
750}
751
752// sendAlert sends a TLS alert message.
753// L < c.out.Mutex.
754func (c *Conn) sendAlert(err alert) error {
755 c.out.Lock()
756 defer c.out.Unlock()
757 return c.sendAlertLocked(err)
758}
759
David Benjamind86c7672014-08-02 04:07:12 -0400760// writeV2Record writes a record for a V2ClientHello.
761func (c *Conn) writeV2Record(data []byte) (n int, err error) {
762 record := make([]byte, 2+len(data))
763 record[0] = uint8(len(data)>>8) | 0x80
764 record[1] = uint8(len(data))
765 copy(record[2:], data)
766 return c.conn.Write(record)
767}
768
Adam Langley95c29f32014-06-20 12:00:00 -0700769// writeRecord writes a TLS record with the given type and payload
770// to the connection and updates the record layer state.
771// c.out.Mutex <= L.
772func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400773 if c.isDTLS {
774 return c.dtlsWriteRecord(typ, data)
775 }
776
777 recordHeaderLen := tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700778 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -0400779 first := true
780 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
Adam Langley95c29f32014-06-20 12:00:00 -0700781 for len(data) > 0 {
782 m := len(data)
783 if m > maxPlaintext {
784 m = maxPlaintext
785 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400786 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
787 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -0400788 // By default, do not fragment the client_version or
789 // server_version, which are located in the first 6
790 // bytes.
791 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
792 m = 6
793 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400794 }
Adam Langley95c29f32014-06-20 12:00:00 -0700795 explicitIVLen := 0
796 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -0400797 first = false
Adam Langley95c29f32014-06-20 12:00:00 -0700798
799 var cbc cbcMode
800 if c.out.version >= VersionTLS11 {
801 var ok bool
802 if cbc, ok = c.out.cipher.(cbcMode); ok {
803 explicitIVLen = cbc.BlockSize()
804 }
805 }
806 if explicitIVLen == 0 {
807 if _, ok := c.out.cipher.(cipher.AEAD); ok {
808 explicitIVLen = 8
809 // The AES-GCM construction in TLS has an
810 // explicit nonce so that the nonce can be
811 // random. However, the nonce is only 8 bytes
812 // which is too small for a secure, random
813 // nonce. Therefore we use the sequence number
814 // as the nonce.
815 explicitIVIsSeq = true
816 }
817 }
818 b.resize(recordHeaderLen + explicitIVLen + m)
819 b.data[0] = byte(typ)
820 vers := c.vers
821 if vers == 0 {
822 // Some TLS servers fail if the record version is
823 // greater than TLS 1.0 for the initial ClientHello.
824 vers = VersionTLS10
825 }
826 b.data[1] = byte(vers >> 8)
827 b.data[2] = byte(vers)
828 b.data[3] = byte(m >> 8)
829 b.data[4] = byte(m)
830 if explicitIVLen > 0 {
831 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
832 if explicitIVIsSeq {
833 copy(explicitIV, c.out.seq[:])
834 } else {
835 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
836 break
837 }
838 }
839 }
840 copy(b.data[recordHeaderLen+explicitIVLen:], data)
841 c.out.encrypt(b, explicitIVLen)
842 _, err = c.conn.Write(b.data)
843 if err != nil {
844 break
845 }
846 n += m
847 data = data[m:]
848 }
849 c.out.freeBlock(b)
850
851 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -0700852 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700853 if err != nil {
854 // Cannot call sendAlert directly,
855 // because we already hold c.out.Mutex.
856 c.tmp[0] = alertLevelError
857 c.tmp[1] = byte(err.(alert))
858 c.writeRecord(recordTypeAlert, c.tmp[0:2])
859 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
860 }
861 }
862 return
863}
864
David Benjamin83c0bc92014-08-04 01:23:53 -0400865func (c *Conn) doReadHandshake() ([]byte, error) {
866 if c.isDTLS {
867 return c.dtlsDoReadHandshake()
868 }
869
Adam Langley95c29f32014-06-20 12:00:00 -0700870 for c.hand.Len() < 4 {
871 if err := c.in.err; err != nil {
872 return nil, err
873 }
874 if err := c.readRecord(recordTypeHandshake); err != nil {
875 return nil, err
876 }
877 }
878
879 data := c.hand.Bytes()
880 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
881 if n > maxHandshake {
882 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
883 }
884 for c.hand.Len() < 4+n {
885 if err := c.in.err; err != nil {
886 return nil, err
887 }
888 if err := c.readRecord(recordTypeHandshake); err != nil {
889 return nil, err
890 }
891 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400892 return c.hand.Next(4 + n), nil
893}
894
895// readHandshake reads the next handshake message from
896// the record layer.
897// c.in.Mutex < L; c.out.Mutex < L.
898func (c *Conn) readHandshake() (interface{}, error) {
899 data, err := c.doReadHandshake()
900 if err != nil {
901 return nil, err
902 }
903
Adam Langley95c29f32014-06-20 12:00:00 -0700904 var m handshakeMessage
905 switch data[0] {
906 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -0400907 m = &clientHelloMsg{
908 isDTLS: c.isDTLS,
909 }
Adam Langley95c29f32014-06-20 12:00:00 -0700910 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -0400911 m = &serverHelloMsg{
912 isDTLS: c.isDTLS,
913 }
Adam Langley95c29f32014-06-20 12:00:00 -0700914 case typeNewSessionTicket:
915 m = new(newSessionTicketMsg)
916 case typeCertificate:
917 m = new(certificateMsg)
918 case typeCertificateRequest:
919 m = &certificateRequestMsg{
920 hasSignatureAndHash: c.vers >= VersionTLS12,
921 }
922 case typeCertificateStatus:
923 m = new(certificateStatusMsg)
924 case typeServerKeyExchange:
925 m = new(serverKeyExchangeMsg)
926 case typeServerHelloDone:
927 m = new(serverHelloDoneMsg)
928 case typeClientKeyExchange:
929 m = new(clientKeyExchangeMsg)
930 case typeCertificateVerify:
931 m = &certificateVerifyMsg{
932 hasSignatureAndHash: c.vers >= VersionTLS12,
933 }
934 case typeNextProtocol:
935 m = new(nextProtoMsg)
936 case typeFinished:
937 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400938 case typeHelloVerifyRequest:
939 m = new(helloVerifyRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -0700940 default:
941 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
942 }
943
944 // The handshake message unmarshallers
945 // expect to be able to keep references to data,
946 // so pass in a fresh copy that won't be overwritten.
947 data = append([]byte(nil), data...)
948
949 if !m.unmarshal(data) {
950 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
951 }
952 return m, nil
953}
954
955// Write writes data to the connection.
956func (c *Conn) Write(b []byte) (int, error) {
957 if err := c.Handshake(); err != nil {
958 return 0, err
959 }
960
961 c.out.Lock()
962 defer c.out.Unlock()
963
964 if err := c.out.err; err != nil {
965 return 0, err
966 }
967
968 if !c.handshakeComplete {
969 return 0, alertInternalError
970 }
971
972 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
973 // attack when using block mode ciphers due to predictable IVs.
974 // This can be prevented by splitting each Application Data
975 // record into two records, effectively randomizing the IV.
976 //
977 // http://www.openssl.org/~bodo/tls-cbc.txt
978 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
979 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
980
981 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -0400982 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700983 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
984 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
985 if err != nil {
986 return n, c.out.setErrorLocked(err)
987 }
988 m, b = 1, b[1:]
989 }
990 }
991
992 n, err := c.writeRecord(recordTypeApplicationData, b)
993 return n + m, c.out.setErrorLocked(err)
994}
995
996// Read can be made to time out and return a net.Error with Timeout() == true
997// after a fixed time limit; see SetDeadline and SetReadDeadline.
998func (c *Conn) Read(b []byte) (n int, err error) {
999 if err = c.Handshake(); err != nil {
1000 return
1001 }
1002
1003 c.in.Lock()
1004 defer c.in.Unlock()
1005
1006 // Some OpenSSL servers send empty records in order to randomize the
1007 // CBC IV. So this loop ignores a limited number of empty records.
1008 const maxConsecutiveEmptyRecords = 100
1009 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1010 for c.input == nil && c.in.err == nil {
1011 if err := c.readRecord(recordTypeApplicationData); err != nil {
1012 // Soft error, like EAGAIN
1013 return 0, err
1014 }
1015 }
1016 if err := c.in.err; err != nil {
1017 return 0, err
1018 }
1019
1020 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001021 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001022 c.in.freeBlock(c.input)
1023 c.input = nil
1024 }
1025
1026 // If a close-notify alert is waiting, read it so that
1027 // we can return (n, EOF) instead of (n, nil), to signal
1028 // to the HTTP response reading goroutine that the
1029 // connection is now closed. This eliminates a race
1030 // where the HTTP response reading goroutine would
1031 // otherwise not observe the EOF until its next read,
1032 // by which time a client goroutine might have already
1033 // tried to reuse the HTTP connection for a new
1034 // request.
1035 // See https://codereview.appspot.com/76400046
1036 // and http://golang.org/issue/3514
1037 if ri := c.rawInput; ri != nil &&
1038 n != 0 && err == nil &&
1039 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1040 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1041 err = recErr // will be io.EOF on closeNotify
1042 }
1043 }
1044
1045 if n != 0 || err != nil {
1046 return n, err
1047 }
1048 }
1049
1050 return 0, io.ErrNoProgress
1051}
1052
1053// Close closes the connection.
1054func (c *Conn) Close() error {
1055 var alertErr error
1056
1057 c.handshakeMutex.Lock()
1058 defer c.handshakeMutex.Unlock()
1059 if c.handshakeComplete {
1060 alertErr = c.sendAlert(alertCloseNotify)
1061 }
1062
1063 if err := c.conn.Close(); err != nil {
1064 return err
1065 }
1066 return alertErr
1067}
1068
1069// Handshake runs the client or server handshake
1070// protocol if it has not yet been run.
1071// Most uses of this package need not call Handshake
1072// explicitly: the first Read or Write will call it automatically.
1073func (c *Conn) Handshake() error {
1074 c.handshakeMutex.Lock()
1075 defer c.handshakeMutex.Unlock()
1076 if err := c.handshakeErr; err != nil {
1077 return err
1078 }
1079 if c.handshakeComplete {
1080 return nil
1081 }
1082
1083 if c.isClient {
1084 c.handshakeErr = c.clientHandshake()
1085 } else {
1086 c.handshakeErr = c.serverHandshake()
1087 }
1088 return c.handshakeErr
1089}
1090
1091// ConnectionState returns basic TLS details about the connection.
1092func (c *Conn) ConnectionState() ConnectionState {
1093 c.handshakeMutex.Lock()
1094 defer c.handshakeMutex.Unlock()
1095
1096 var state ConnectionState
1097 state.HandshakeComplete = c.handshakeComplete
1098 if c.handshakeComplete {
1099 state.Version = c.vers
1100 state.NegotiatedProtocol = c.clientProtocol
1101 state.DidResume = c.didResume
1102 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
1103 state.CipherSuite = c.cipherSuite
1104 state.PeerCertificates = c.peerCertificates
1105 state.VerifiedChains = c.verifiedChains
1106 state.ServerName = c.serverName
1107 }
1108
1109 return state
1110}
1111
1112// OCSPResponse returns the stapled OCSP response from the TLS server, if
1113// any. (Only valid for client connections.)
1114func (c *Conn) OCSPResponse() []byte {
1115 c.handshakeMutex.Lock()
1116 defer c.handshakeMutex.Unlock()
1117
1118 return c.ocspResponse
1119}
1120
1121// VerifyHostname checks that the peer certificate chain is valid for
1122// connecting to host. If so, it returns nil; if not, it returns an error
1123// describing the problem.
1124func (c *Conn) VerifyHostname(host string) error {
1125 c.handshakeMutex.Lock()
1126 defer c.handshakeMutex.Unlock()
1127 if !c.isClient {
1128 return errors.New("tls: VerifyHostname called on TLS server connection")
1129 }
1130 if !c.handshakeComplete {
1131 return errors.New("tls: handshake has not yet been performed")
1132 }
1133 return c.peerCertificates[0].VerifyHostname(host)
1134}