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