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