blob: 897175e33da4c1ae48551b723d7cfe22404ea49f [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
Adam Langley2ae77d22014-10-28 17:29:33 -070053 // verify_data values for the renegotiation extension.
54 clientVerify []byte
55 serverVerify []byte
56
David Benjamind30a9902014-08-24 01:44:23 -040057 channelID *ecdsa.PublicKey
58
Adam Langley95c29f32014-06-20 12:00:00 -070059 // input/output
60 in, out halfConn // in.Mutex < out.Mutex
61 rawInput *block // raw input, right off the wire
David Benjamin83c0bc92014-08-04 01:23:53 -040062 input *block // application record waiting to be read
63 hand bytes.Buffer // handshake record waiting to be read
64
65 // DTLS state
66 sendHandshakeSeq uint16
67 recvHandshakeSeq uint16
68 handMsg []byte // pending assembled handshake message
69 handMsgLen int // handshake message length, not including the header
Adam Langley95c29f32014-06-20 12:00:00 -070070
71 tmp [16]byte
72}
73
74// Access to net.Conn methods.
75// Cannot just embed net.Conn because that would
76// export the struct field too.
77
78// LocalAddr returns the local network address.
79func (c *Conn) LocalAddr() net.Addr {
80 return c.conn.LocalAddr()
81}
82
83// RemoteAddr returns the remote network address.
84func (c *Conn) RemoteAddr() net.Addr {
85 return c.conn.RemoteAddr()
86}
87
88// SetDeadline sets the read and write deadlines associated with the connection.
89// A zero value for t means Read and Write will not time out.
90// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
91func (c *Conn) SetDeadline(t time.Time) error {
92 return c.conn.SetDeadline(t)
93}
94
95// SetReadDeadline sets the read deadline on the underlying connection.
96// A zero value for t means Read will not time out.
97func (c *Conn) SetReadDeadline(t time.Time) error {
98 return c.conn.SetReadDeadline(t)
99}
100
101// SetWriteDeadline sets the write deadline on the underlying conneciton.
102// A zero value for t means Write will not time out.
103// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
104func (c *Conn) SetWriteDeadline(t time.Time) error {
105 return c.conn.SetWriteDeadline(t)
106}
107
108// A halfConn represents one direction of the record layer
109// connection, either sending or receiving.
110type halfConn struct {
111 sync.Mutex
112
David Benjamin83c0bc92014-08-04 01:23:53 -0400113 err error // first permanent error
114 version uint16 // protocol version
115 isDTLS bool
Adam Langley95c29f32014-06-20 12:00:00 -0700116 cipher interface{} // cipher algorithm
117 mac macFunction
118 seq [8]byte // 64-bit sequence number
119 bfree *block // list of free blocks
120
121 nextCipher interface{} // next encryption state
122 nextMac macFunction // next MAC algorithm
123
124 // used to save allocating a new buffer for each MAC.
125 inDigestBuf, outDigestBuf []byte
Adam Langley80842bd2014-06-20 12:00:00 -0700126
127 config *Config
Adam Langley95c29f32014-06-20 12:00:00 -0700128}
129
130func (hc *halfConn) setErrorLocked(err error) error {
131 hc.err = err
132 return err
133}
134
135func (hc *halfConn) error() error {
Adam Langley2ae77d22014-10-28 17:29:33 -0700136 // This should be locked, but I've removed it for the renegotiation
137 // tests since we don't concurrently read and write the same tls.Conn
138 // in any case during testing.
Adam Langley95c29f32014-06-20 12:00:00 -0700139 err := hc.err
Adam Langley95c29f32014-06-20 12:00:00 -0700140 return err
141}
142
143// prepareCipherSpec sets the encryption and MAC states
144// that a subsequent changeCipherSpec will use.
145func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
146 hc.version = version
147 hc.nextCipher = cipher
148 hc.nextMac = mac
149}
150
151// changeCipherSpec changes the encryption and MAC states
152// to the ones previously passed to prepareCipherSpec.
Adam Langley80842bd2014-06-20 12:00:00 -0700153func (hc *halfConn) changeCipherSpec(config *Config) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700154 if hc.nextCipher == nil {
155 return alertInternalError
156 }
157 hc.cipher = hc.nextCipher
158 hc.mac = hc.nextMac
159 hc.nextCipher = nil
160 hc.nextMac = nil
Adam Langley80842bd2014-06-20 12:00:00 -0700161 hc.config = config
David Benjamin83c0bc92014-08-04 01:23:53 -0400162 hc.incEpoch()
Adam Langley95c29f32014-06-20 12:00:00 -0700163 return nil
164}
165
166// incSeq increments the sequence number.
167func (hc *halfConn) incSeq() {
David Benjamin83c0bc92014-08-04 01:23:53 -0400168 limit := 0
169 if hc.isDTLS {
170 // Increment up to the epoch in DTLS.
171 limit = 2
172 }
173 for i := 7; i >= limit; i-- {
Adam Langley95c29f32014-06-20 12:00:00 -0700174 hc.seq[i]++
175 if hc.seq[i] != 0 {
176 return
177 }
178 }
179
180 // Not allowed to let sequence number wrap.
181 // Instead, must renegotiate before it does.
182 // Not likely enough to bother.
183 panic("TLS: sequence number wraparound")
184}
185
David Benjamin83c0bc92014-08-04 01:23:53 -0400186// incEpoch resets the sequence number. In DTLS, it increments the
187// epoch half of the sequence number.
188func (hc *halfConn) incEpoch() {
189 limit := 0
190 if hc.isDTLS {
191 for i := 1; i >= 0; i-- {
192 hc.seq[i]++
193 if hc.seq[i] != 0 {
194 break
195 }
196 if i == 0 {
197 panic("TLS: epoch number wraparound")
198 }
199 }
200 limit = 2
Adam Langley95c29f32014-06-20 12:00:00 -0700201 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400202 seq := hc.seq[limit:]
203 for i := range seq {
204 seq[i] = 0
205 }
206}
207
208func (hc *halfConn) recordHeaderLen() int {
209 if hc.isDTLS {
210 return dtlsRecordHeaderLen
211 }
212 return tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700213}
214
215// removePadding returns an unpadded slice, in constant time, which is a prefix
216// of the input. It also returns a byte which is equal to 255 if the padding
217// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
218func removePadding(payload []byte) ([]byte, byte) {
219 if len(payload) < 1 {
220 return payload, 0
221 }
222
223 paddingLen := payload[len(payload)-1]
224 t := uint(len(payload)-1) - uint(paddingLen)
225 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
226 good := byte(int32(^t) >> 31)
227
228 toCheck := 255 // the maximum possible padding length
229 // The length of the padded data is public, so we can use an if here
230 if toCheck+1 > len(payload) {
231 toCheck = len(payload) - 1
232 }
233
234 for i := 0; i < toCheck; i++ {
235 t := uint(paddingLen) - uint(i)
236 // if i <= paddingLen then the MSB of t is zero
237 mask := byte(int32(^t) >> 31)
238 b := payload[len(payload)-1-i]
239 good &^= mask&paddingLen ^ mask&b
240 }
241
242 // We AND together the bits of good and replicate the result across
243 // all the bits.
244 good &= good << 4
245 good &= good << 2
246 good &= good << 1
247 good = uint8(int8(good) >> 7)
248
249 toRemove := good&paddingLen + 1
250 return payload[:len(payload)-int(toRemove)], good
251}
252
253// removePaddingSSL30 is a replacement for removePadding in the case that the
254// protocol version is SSLv3. In this version, the contents of the padding
255// are random and cannot be checked.
256func removePaddingSSL30(payload []byte) ([]byte, byte) {
257 if len(payload) < 1 {
258 return payload, 0
259 }
260
261 paddingLen := int(payload[len(payload)-1]) + 1
262 if paddingLen > len(payload) {
263 return payload, 0
264 }
265
266 return payload[:len(payload)-paddingLen], 255
267}
268
269func roundUp(a, b int) int {
270 return a + (b-a%b)%b
271}
272
273// cbcMode is an interface for block ciphers using cipher block chaining.
274type cbcMode interface {
275 cipher.BlockMode
276 SetIV([]byte)
277}
278
279// decrypt checks and strips the mac and decrypts the data in b. Returns a
280// success boolean, the number of bytes to skip from the start of the record in
281// order to get the application payload, and an optional alert value.
282func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, alertValue alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400283 recordHeaderLen := hc.recordHeaderLen()
284
Adam Langley95c29f32014-06-20 12:00:00 -0700285 // pull out payload
286 payload := b.data[recordHeaderLen:]
287
288 macSize := 0
289 if hc.mac != nil {
290 macSize = hc.mac.Size()
291 }
292
293 paddingGood := byte(255)
294 explicitIVLen := 0
295
David Benjamin83c0bc92014-08-04 01:23:53 -0400296 seq := hc.seq[:]
297 if hc.isDTLS {
298 // DTLS sequence numbers are explicit.
299 seq = b.data[3:11]
300 }
301
Adam Langley95c29f32014-06-20 12:00:00 -0700302 // decrypt
303 if hc.cipher != nil {
304 switch c := hc.cipher.(type) {
305 case cipher.Stream:
306 c.XORKeyStream(payload, payload)
307 case cipher.AEAD:
308 explicitIVLen = 8
309 if len(payload) < explicitIVLen {
310 return false, 0, alertBadRecordMAC
311 }
312 nonce := payload[:8]
313 payload = payload[8:]
314
315 var additionalData [13]byte
David Benjamin83c0bc92014-08-04 01:23:53 -0400316 copy(additionalData[:], seq)
Adam Langley95c29f32014-06-20 12:00:00 -0700317 copy(additionalData[8:], b.data[:3])
318 n := len(payload) - c.Overhead()
319 additionalData[11] = byte(n >> 8)
320 additionalData[12] = byte(n)
321 var err error
322 payload, err = c.Open(payload[:0], nonce, payload, additionalData[:])
323 if err != nil {
324 return false, 0, alertBadRecordMAC
325 }
326 b.resize(recordHeaderLen + explicitIVLen + len(payload))
327 case cbcMode:
328 blockSize := c.BlockSize()
David Benjamin83c0bc92014-08-04 01:23:53 -0400329 if hc.version >= VersionTLS11 || hc.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -0700330 explicitIVLen = blockSize
331 }
332
333 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
334 return false, 0, alertBadRecordMAC
335 }
336
337 if explicitIVLen > 0 {
338 c.SetIV(payload[:explicitIVLen])
339 payload = payload[explicitIVLen:]
340 }
341 c.CryptBlocks(payload, payload)
342 if hc.version == VersionSSL30 {
343 payload, paddingGood = removePaddingSSL30(payload)
344 } else {
345 payload, paddingGood = removePadding(payload)
346 }
347 b.resize(recordHeaderLen + explicitIVLen + len(payload))
348
349 // note that we still have a timing side-channel in the
350 // MAC check, below. An attacker can align the record
351 // so that a correct padding will cause one less hash
352 // block to be calculated. Then they can iteratively
353 // decrypt a record by breaking each byte. See
354 // "Password Interception in a SSL/TLS Channel", Brice
355 // Canvel et al.
356 //
357 // However, our behavior matches OpenSSL, so we leak
358 // only as much as they do.
359 default:
360 panic("unknown cipher type")
361 }
362 }
363
364 // check, strip mac
365 if hc.mac != nil {
366 if len(payload) < macSize {
367 return false, 0, alertBadRecordMAC
368 }
369
370 // strip mac off payload, b.data
371 n := len(payload) - macSize
David Benjamin83c0bc92014-08-04 01:23:53 -0400372 b.data[recordHeaderLen-2] = byte(n >> 8)
373 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700374 b.resize(recordHeaderLen + explicitIVLen + n)
375 remoteMAC := payload[n:]
David Benjamin83c0bc92014-08-04 01:23:53 -0400376 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n])
Adam Langley95c29f32014-06-20 12:00:00 -0700377
378 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
379 return false, 0, alertBadRecordMAC
380 }
381 hc.inDigestBuf = localMAC
382 }
383 hc.incSeq()
384
385 return true, recordHeaderLen + explicitIVLen, 0
386}
387
388// padToBlockSize calculates the needed padding block, if any, for a payload.
389// On exit, prefix aliases payload and extends to the end of the last full
390// block of payload. finalBlock is a fresh slice which contains the contents of
391// any suffix of payload as well as the needed padding to make finalBlock a
392// full block.
Adam Langley80842bd2014-06-20 12:00:00 -0700393func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
Adam Langley95c29f32014-06-20 12:00:00 -0700394 overrun := len(payload) % blockSize
Adam Langley95c29f32014-06-20 12:00:00 -0700395 prefix = payload[:len(payload)-overrun]
Adam Langley80842bd2014-06-20 12:00:00 -0700396
397 paddingLen := blockSize - overrun
398 finalSize := blockSize
399 if config.Bugs.MaxPadding {
400 for paddingLen+blockSize <= 256 {
401 paddingLen += blockSize
402 }
403 finalSize = 256
404 }
405 finalBlock = make([]byte, finalSize)
406 for i := range finalBlock {
Adam Langley95c29f32014-06-20 12:00:00 -0700407 finalBlock[i] = byte(paddingLen - 1)
408 }
Adam Langley80842bd2014-06-20 12:00:00 -0700409 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
410 finalBlock[overrun] ^= 0xff
411 }
412 copy(finalBlock, payload[len(payload)-overrun:])
Adam Langley95c29f32014-06-20 12:00:00 -0700413 return
414}
415
416// encrypt encrypts and macs the data in b.
417func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400418 recordHeaderLen := hc.recordHeaderLen()
419
Adam Langley95c29f32014-06-20 12:00:00 -0700420 // mac
421 if hc.mac != nil {
David Benjamin83c0bc92014-08-04 01:23:53 -0400422 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 -0700423
424 n := len(b.data)
425 b.resize(n + len(mac))
426 copy(b.data[n:], mac)
427 hc.outDigestBuf = mac
428 }
429
430 payload := b.data[recordHeaderLen:]
431
432 // encrypt
433 if hc.cipher != nil {
434 switch c := hc.cipher.(type) {
435 case cipher.Stream:
436 c.XORKeyStream(payload, payload)
437 case cipher.AEAD:
438 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
439 b.resize(len(b.data) + c.Overhead())
440 nonce := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
441 payload := b.data[recordHeaderLen+explicitIVLen:]
442 payload = payload[:payloadLen]
443
444 var additionalData [13]byte
445 copy(additionalData[:], hc.seq[:])
446 copy(additionalData[8:], b.data[:3])
447 additionalData[11] = byte(payloadLen >> 8)
448 additionalData[12] = byte(payloadLen)
449
450 c.Seal(payload[:0], nonce, payload, additionalData[:])
451 case cbcMode:
452 blockSize := c.BlockSize()
453 if explicitIVLen > 0 {
454 c.SetIV(payload[:explicitIVLen])
455 payload = payload[explicitIVLen:]
456 }
Adam Langley80842bd2014-06-20 12:00:00 -0700457 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700458 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
459 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
460 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
461 default:
462 panic("unknown cipher type")
463 }
464 }
465
466 // update length to include MAC and any block padding needed.
467 n := len(b.data) - recordHeaderLen
David Benjamin83c0bc92014-08-04 01:23:53 -0400468 b.data[recordHeaderLen-2] = byte(n >> 8)
469 b.data[recordHeaderLen-1] = byte(n)
Adam Langley95c29f32014-06-20 12:00:00 -0700470 hc.incSeq()
471
472 return true, 0
473}
474
475// A block is a simple data buffer.
476type block struct {
477 data []byte
478 off int // index for Read
479 link *block
480}
481
482// resize resizes block to be n bytes, growing if necessary.
483func (b *block) resize(n int) {
484 if n > cap(b.data) {
485 b.reserve(n)
486 }
487 b.data = b.data[0:n]
488}
489
490// reserve makes sure that block contains a capacity of at least n bytes.
491func (b *block) reserve(n int) {
492 if cap(b.data) >= n {
493 return
494 }
495 m := cap(b.data)
496 if m == 0 {
497 m = 1024
498 }
499 for m < n {
500 m *= 2
501 }
502 data := make([]byte, len(b.data), m)
503 copy(data, b.data)
504 b.data = data
505}
506
507// readFromUntil reads from r into b until b contains at least n bytes
508// or else returns an error.
509func (b *block) readFromUntil(r io.Reader, n int) error {
510 // quick case
511 if len(b.data) >= n {
512 return nil
513 }
514
515 // read until have enough.
516 b.reserve(n)
517 for {
518 m, err := r.Read(b.data[len(b.data):cap(b.data)])
519 b.data = b.data[0 : len(b.data)+m]
520 if len(b.data) >= n {
521 // TODO(bradfitz,agl): slightly suspicious
522 // that we're throwing away r.Read's err here.
523 break
524 }
525 if err != nil {
526 return err
527 }
528 }
529 return nil
530}
531
532func (b *block) Read(p []byte) (n int, err error) {
533 n = copy(p, b.data[b.off:])
534 b.off += n
535 return
536}
537
538// newBlock allocates a new block, from hc's free list if possible.
539func (hc *halfConn) newBlock() *block {
540 b := hc.bfree
541 if b == nil {
542 return new(block)
543 }
544 hc.bfree = b.link
545 b.link = nil
546 b.resize(0)
547 return b
548}
549
550// freeBlock returns a block to hc's free list.
551// The protocol is such that each side only has a block or two on
552// its free list at a time, so there's no need to worry about
553// trimming the list, etc.
554func (hc *halfConn) freeBlock(b *block) {
555 b.link = hc.bfree
556 hc.bfree = b
557}
558
559// splitBlock splits a block after the first n bytes,
560// returning a block with those n bytes and a
561// block with the remainder. the latter may be nil.
562func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
563 if len(b.data) <= n {
564 return b, nil
565 }
566 bb := hc.newBlock()
567 bb.resize(len(b.data) - n)
568 copy(bb.data, b.data[n:])
569 b.data = b.data[0:n]
570 return b, bb
571}
572
David Benjamin83c0bc92014-08-04 01:23:53 -0400573func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
574 if c.isDTLS {
575 return c.dtlsDoReadRecord(want)
576 }
577
578 recordHeaderLen := tlsRecordHeaderLen
579
580 if c.rawInput == nil {
581 c.rawInput = c.in.newBlock()
582 }
583 b := c.rawInput
584
585 // Read header, payload.
586 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
587 // RFC suggests that EOF without an alertCloseNotify is
588 // an error, but popular web sites seem to do this,
589 // so we can't make it an error.
590 // if err == io.EOF {
591 // err = io.ErrUnexpectedEOF
592 // }
593 if e, ok := err.(net.Error); !ok || !e.Temporary() {
594 c.in.setErrorLocked(err)
595 }
596 return 0, nil, err
597 }
598 typ := recordType(b.data[0])
599
600 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
601 // start with a uint16 length where the MSB is set and the first record
602 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
603 // an SSLv2 client.
604 if want == recordTypeHandshake && typ == 0x80 {
605 c.sendAlert(alertProtocolVersion)
606 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
607 }
608
609 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
610 n := int(b.data[3])<<8 | int(b.data[4])
611 if c.haveVers && vers != c.vers {
612 c.sendAlert(alertProtocolVersion)
613 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers))
614 }
615 if n > maxCiphertext {
616 c.sendAlert(alertRecordOverflow)
617 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
618 }
619 if !c.haveVers {
620 // First message, be extra suspicious:
621 // this might not be a TLS client.
622 // Bail out before reading a full 'body', if possible.
623 // The current max version is 3.1.
624 // If the version is >= 16.0, it's probably not real.
625 // Similarly, a clientHello message encodes in
626 // well under a kilobyte. If the length is >= 12 kB,
627 // it's probably not real.
628 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
629 c.sendAlert(alertUnexpectedMessage)
630 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
631 }
632 }
633 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
634 if err == io.EOF {
635 err = io.ErrUnexpectedEOF
636 }
637 if e, ok := err.(net.Error); !ok || !e.Temporary() {
638 c.in.setErrorLocked(err)
639 }
640 return 0, nil, err
641 }
642
643 // Process message.
644 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
645 ok, off, err := c.in.decrypt(b)
646 if !ok {
647 c.in.setErrorLocked(c.sendAlert(err))
648 }
649 b.off = off
650 return typ, b, nil
651}
652
Adam Langley95c29f32014-06-20 12:00:00 -0700653// readRecord reads the next TLS record from the connection
654// and updates the record layer state.
655// c.in.Mutex <= L; c.input == nil.
656func (c *Conn) readRecord(want recordType) error {
657 // Caller must be in sync with connection:
658 // handshake data if handshake not yet completed,
Adam Langley2ae77d22014-10-28 17:29:33 -0700659 // else application data.
Adam Langley95c29f32014-06-20 12:00:00 -0700660 switch want {
661 default:
662 c.sendAlert(alertInternalError)
663 return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
664 case recordTypeHandshake, recordTypeChangeCipherSpec:
665 if c.handshakeComplete {
666 c.sendAlert(alertInternalError)
667 return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
668 }
669 case recordTypeApplicationData:
David Benjamine58c4f52014-08-24 03:47:07 -0400670 if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart {
Adam Langley95c29f32014-06-20 12:00:00 -0700671 c.sendAlert(alertInternalError)
672 return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
673 }
674 }
675
676Again:
David Benjamin83c0bc92014-08-04 01:23:53 -0400677 typ, b, err := c.doReadRecord(want)
678 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700679 return err
680 }
Adam Langley95c29f32014-06-20 12:00:00 -0700681 data := b.data[b.off:]
682 if len(data) > maxPlaintext {
683 err := c.sendAlert(alertRecordOverflow)
684 c.in.freeBlock(b)
685 return c.in.setErrorLocked(err)
686 }
687
688 switch typ {
689 default:
690 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
691
692 case recordTypeAlert:
693 if len(data) != 2 {
694 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
695 break
696 }
697 if alert(data[1]) == alertCloseNotify {
698 c.in.setErrorLocked(io.EOF)
699 break
700 }
701 switch data[0] {
702 case alertLevelWarning:
703 // drop on the floor
704 c.in.freeBlock(b)
705 goto Again
706 case alertLevelError:
707 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
708 default:
709 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
710 }
711
712 case recordTypeChangeCipherSpec:
713 if typ != want || len(data) != 1 || data[0] != 1 {
714 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
715 break
716 }
Adam Langley80842bd2014-06-20 12:00:00 -0700717 err := c.in.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700718 if err != nil {
719 c.in.setErrorLocked(c.sendAlert(err.(alert)))
720 }
721
722 case recordTypeApplicationData:
723 if typ != want {
724 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
725 break
726 }
727 c.input = b
728 b = nil
729
730 case recordTypeHandshake:
731 // TODO(rsc): Should at least pick off connection close.
732 if typ != want {
Adam Langley2ae77d22014-10-28 17:29:33 -0700733 // A client might need to process a HelloRequest from
734 // the server, thus receiving a handshake message when
735 // application data is expected is ok.
736 if !c.isClient {
737 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
738 }
Adam Langley95c29f32014-06-20 12:00:00 -0700739 }
740 c.hand.Write(data)
741 }
742
743 if b != nil {
744 c.in.freeBlock(b)
745 }
746 return c.in.err
747}
748
749// sendAlert sends a TLS alert message.
750// c.out.Mutex <= L.
751func (c *Conn) sendAlertLocked(err alert) error {
752 switch err {
753 case alertNoRenegotiation, alertCloseNotify:
754 c.tmp[0] = alertLevelWarning
755 default:
756 c.tmp[0] = alertLevelError
757 }
758 c.tmp[1] = byte(err)
759 c.writeRecord(recordTypeAlert, c.tmp[0:2])
760 // closeNotify is a special case in that it isn't an error:
761 if err != alertCloseNotify {
762 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
763 }
764 return nil
765}
766
767// sendAlert sends a TLS alert message.
768// L < c.out.Mutex.
769func (c *Conn) sendAlert(err alert) error {
770 c.out.Lock()
771 defer c.out.Unlock()
772 return c.sendAlertLocked(err)
773}
774
David Benjamind86c7672014-08-02 04:07:12 -0400775// writeV2Record writes a record for a V2ClientHello.
776func (c *Conn) writeV2Record(data []byte) (n int, err error) {
777 record := make([]byte, 2+len(data))
778 record[0] = uint8(len(data)>>8) | 0x80
779 record[1] = uint8(len(data))
780 copy(record[2:], data)
781 return c.conn.Write(record)
782}
783
Adam Langley95c29f32014-06-20 12:00:00 -0700784// writeRecord writes a TLS record with the given type and payload
785// to the connection and updates the record layer state.
786// c.out.Mutex <= L.
787func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
David Benjamin83c0bc92014-08-04 01:23:53 -0400788 if c.isDTLS {
789 return c.dtlsWriteRecord(typ, data)
790 }
791
792 recordHeaderLen := tlsRecordHeaderLen
Adam Langley95c29f32014-06-20 12:00:00 -0700793 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -0400794 first := true
795 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
Adam Langley95c29f32014-06-20 12:00:00 -0700796 for len(data) > 0 {
797 m := len(data)
798 if m > maxPlaintext {
799 m = maxPlaintext
800 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400801 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
802 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -0400803 // By default, do not fragment the client_version or
804 // server_version, which are located in the first 6
805 // bytes.
806 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
807 m = 6
808 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400809 }
Adam Langley95c29f32014-06-20 12:00:00 -0700810 explicitIVLen := 0
811 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -0400812 first = false
Adam Langley95c29f32014-06-20 12:00:00 -0700813
814 var cbc cbcMode
815 if c.out.version >= VersionTLS11 {
816 var ok bool
817 if cbc, ok = c.out.cipher.(cbcMode); ok {
818 explicitIVLen = cbc.BlockSize()
819 }
820 }
821 if explicitIVLen == 0 {
822 if _, ok := c.out.cipher.(cipher.AEAD); ok {
823 explicitIVLen = 8
824 // The AES-GCM construction in TLS has an
825 // explicit nonce so that the nonce can be
826 // random. However, the nonce is only 8 bytes
827 // which is too small for a secure, random
828 // nonce. Therefore we use the sequence number
829 // as the nonce.
830 explicitIVIsSeq = true
831 }
832 }
833 b.resize(recordHeaderLen + explicitIVLen + m)
834 b.data[0] = byte(typ)
835 vers := c.vers
836 if vers == 0 {
837 // Some TLS servers fail if the record version is
838 // greater than TLS 1.0 for the initial ClientHello.
839 vers = VersionTLS10
840 }
841 b.data[1] = byte(vers >> 8)
842 b.data[2] = byte(vers)
843 b.data[3] = byte(m >> 8)
844 b.data[4] = byte(m)
845 if explicitIVLen > 0 {
846 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
847 if explicitIVIsSeq {
848 copy(explicitIV, c.out.seq[:])
849 } else {
850 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
851 break
852 }
853 }
854 }
855 copy(b.data[recordHeaderLen+explicitIVLen:], data)
856 c.out.encrypt(b, explicitIVLen)
857 _, err = c.conn.Write(b.data)
858 if err != nil {
859 break
860 }
861 n += m
862 data = data[m:]
863 }
864 c.out.freeBlock(b)
865
866 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -0700867 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700868 if err != nil {
869 // Cannot call sendAlert directly,
870 // because we already hold c.out.Mutex.
871 c.tmp[0] = alertLevelError
872 c.tmp[1] = byte(err.(alert))
873 c.writeRecord(recordTypeAlert, c.tmp[0:2])
874 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
875 }
876 }
877 return
878}
879
David Benjamin83c0bc92014-08-04 01:23:53 -0400880func (c *Conn) doReadHandshake() ([]byte, error) {
881 if c.isDTLS {
882 return c.dtlsDoReadHandshake()
883 }
884
Adam Langley95c29f32014-06-20 12:00:00 -0700885 for c.hand.Len() < 4 {
886 if err := c.in.err; err != nil {
887 return nil, err
888 }
889 if err := c.readRecord(recordTypeHandshake); err != nil {
890 return nil, err
891 }
892 }
893
894 data := c.hand.Bytes()
895 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
896 if n > maxHandshake {
897 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
898 }
899 for c.hand.Len() < 4+n {
900 if err := c.in.err; err != nil {
901 return nil, err
902 }
903 if err := c.readRecord(recordTypeHandshake); err != nil {
904 return nil, err
905 }
906 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400907 return c.hand.Next(4 + n), nil
908}
909
910// readHandshake reads the next handshake message from
911// the record layer.
912// c.in.Mutex < L; c.out.Mutex < L.
913func (c *Conn) readHandshake() (interface{}, error) {
914 data, err := c.doReadHandshake()
915 if err != nil {
916 return nil, err
917 }
918
Adam Langley95c29f32014-06-20 12:00:00 -0700919 var m handshakeMessage
920 switch data[0] {
Adam Langley2ae77d22014-10-28 17:29:33 -0700921 case typeHelloRequest:
922 m = new(helloRequestMsg)
Adam Langley95c29f32014-06-20 12:00:00 -0700923 case typeClientHello:
David Benjamin83c0bc92014-08-04 01:23:53 -0400924 m = &clientHelloMsg{
925 isDTLS: c.isDTLS,
926 }
Adam Langley95c29f32014-06-20 12:00:00 -0700927 case typeServerHello:
David Benjamin83c0bc92014-08-04 01:23:53 -0400928 m = &serverHelloMsg{
929 isDTLS: c.isDTLS,
930 }
Adam Langley95c29f32014-06-20 12:00:00 -0700931 case typeNewSessionTicket:
932 m = new(newSessionTicketMsg)
933 case typeCertificate:
934 m = new(certificateMsg)
935 case typeCertificateRequest:
936 m = &certificateRequestMsg{
937 hasSignatureAndHash: c.vers >= VersionTLS12,
938 }
939 case typeCertificateStatus:
940 m = new(certificateStatusMsg)
941 case typeServerKeyExchange:
942 m = new(serverKeyExchangeMsg)
943 case typeServerHelloDone:
944 m = new(serverHelloDoneMsg)
945 case typeClientKeyExchange:
946 m = new(clientKeyExchangeMsg)
947 case typeCertificateVerify:
948 m = &certificateVerifyMsg{
949 hasSignatureAndHash: c.vers >= VersionTLS12,
950 }
951 case typeNextProtocol:
952 m = new(nextProtoMsg)
953 case typeFinished:
954 m = new(finishedMsg)
David Benjamin83c0bc92014-08-04 01:23:53 -0400955 case typeHelloVerifyRequest:
956 m = new(helloVerifyRequestMsg)
David Benjamind30a9902014-08-24 01:44:23 -0400957 case typeEncryptedExtensions:
958 m = new(encryptedExtensionsMsg)
Adam Langley95c29f32014-06-20 12:00:00 -0700959 default:
960 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
961 }
962
963 // The handshake message unmarshallers
964 // expect to be able to keep references to data,
965 // so pass in a fresh copy that won't be overwritten.
966 data = append([]byte(nil), data...)
967
968 if !m.unmarshal(data) {
969 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
970 }
971 return m, nil
972}
973
974// Write writes data to the connection.
975func (c *Conn) Write(b []byte) (int, error) {
976 if err := c.Handshake(); err != nil {
977 return 0, err
978 }
979
980 c.out.Lock()
981 defer c.out.Unlock()
982
983 if err := c.out.err; err != nil {
984 return 0, err
985 }
986
987 if !c.handshakeComplete {
988 return 0, alertInternalError
989 }
990
991 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
992 // attack when using block mode ciphers due to predictable IVs.
993 // This can be prevented by splitting each Application Data
994 // record into two records, effectively randomizing the IV.
995 //
996 // http://www.openssl.org/~bodo/tls-cbc.txt
997 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
998 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
999
1000 var m int
David Benjamin83c0bc92014-08-04 01:23:53 -04001001 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001002 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
1003 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
1004 if err != nil {
1005 return n, c.out.setErrorLocked(err)
1006 }
1007 m, b = 1, b[1:]
1008 }
1009 }
1010
1011 n, err := c.writeRecord(recordTypeApplicationData, b)
1012 return n + m, c.out.setErrorLocked(err)
1013}
1014
Adam Langley2ae77d22014-10-28 17:29:33 -07001015func (c *Conn) handleRenegotiation() error {
1016 c.handshakeComplete = false
1017 if !c.isClient {
1018 panic("renegotiation should only happen for a client")
1019 }
1020
1021 msg, err := c.readHandshake()
1022 if err != nil {
1023 return err
1024 }
1025 _, ok := msg.(*helloRequestMsg)
1026 if !ok {
1027 c.sendAlert(alertUnexpectedMessage)
1028 return alertUnexpectedMessage
1029 }
1030
1031 return c.Handshake()
1032}
1033
Adam Langley95c29f32014-06-20 12:00:00 -07001034// Read can be made to time out and return a net.Error with Timeout() == true
1035// after a fixed time limit; see SetDeadline and SetReadDeadline.
1036func (c *Conn) Read(b []byte) (n int, err error) {
1037 if err = c.Handshake(); err != nil {
1038 return
1039 }
1040
1041 c.in.Lock()
1042 defer c.in.Unlock()
1043
1044 // Some OpenSSL servers send empty records in order to randomize the
1045 // CBC IV. So this loop ignores a limited number of empty records.
1046 const maxConsecutiveEmptyRecords = 100
1047 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
1048 for c.input == nil && c.in.err == nil {
1049 if err := c.readRecord(recordTypeApplicationData); err != nil {
1050 // Soft error, like EAGAIN
1051 return 0, err
1052 }
Adam Langley2ae77d22014-10-28 17:29:33 -07001053 if c.hand.Len() > 0 {
1054 // We received handshake bytes, indicating the
1055 // start of a renegotiation.
1056 if err := c.handleRenegotiation(); err != nil {
1057 return 0, err
1058 }
1059 continue
1060 }
Adam Langley95c29f32014-06-20 12:00:00 -07001061 }
1062 if err := c.in.err; err != nil {
1063 return 0, err
1064 }
1065
1066 n, err = c.input.Read(b)
David Benjamin83c0bc92014-08-04 01:23:53 -04001067 if c.input.off >= len(c.input.data) || c.isDTLS {
Adam Langley95c29f32014-06-20 12:00:00 -07001068 c.in.freeBlock(c.input)
1069 c.input = nil
1070 }
1071
1072 // If a close-notify alert is waiting, read it so that
1073 // we can return (n, EOF) instead of (n, nil), to signal
1074 // to the HTTP response reading goroutine that the
1075 // connection is now closed. This eliminates a race
1076 // where the HTTP response reading goroutine would
1077 // otherwise not observe the EOF until its next read,
1078 // by which time a client goroutine might have already
1079 // tried to reuse the HTTP connection for a new
1080 // request.
1081 // See https://codereview.appspot.com/76400046
1082 // and http://golang.org/issue/3514
1083 if ri := c.rawInput; ri != nil &&
1084 n != 0 && err == nil &&
1085 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
1086 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
1087 err = recErr // will be io.EOF on closeNotify
1088 }
1089 }
1090
1091 if n != 0 || err != nil {
1092 return n, err
1093 }
1094 }
1095
1096 return 0, io.ErrNoProgress
1097}
1098
1099// Close closes the connection.
1100func (c *Conn) Close() error {
1101 var alertErr error
1102
1103 c.handshakeMutex.Lock()
1104 defer c.handshakeMutex.Unlock()
1105 if c.handshakeComplete {
1106 alertErr = c.sendAlert(alertCloseNotify)
1107 }
1108
1109 if err := c.conn.Close(); err != nil {
1110 return err
1111 }
1112 return alertErr
1113}
1114
1115// Handshake runs the client or server handshake
1116// protocol if it has not yet been run.
1117// Most uses of this package need not call Handshake
1118// explicitly: the first Read or Write will call it automatically.
1119func (c *Conn) Handshake() error {
1120 c.handshakeMutex.Lock()
1121 defer c.handshakeMutex.Unlock()
1122 if err := c.handshakeErr; err != nil {
1123 return err
1124 }
1125 if c.handshakeComplete {
1126 return nil
1127 }
1128
1129 if c.isClient {
1130 c.handshakeErr = c.clientHandshake()
1131 } else {
1132 c.handshakeErr = c.serverHandshake()
1133 }
1134 return c.handshakeErr
1135}
1136
1137// ConnectionState returns basic TLS details about the connection.
1138func (c *Conn) ConnectionState() ConnectionState {
1139 c.handshakeMutex.Lock()
1140 defer c.handshakeMutex.Unlock()
1141
1142 var state ConnectionState
1143 state.HandshakeComplete = c.handshakeComplete
1144 if c.handshakeComplete {
1145 state.Version = c.vers
1146 state.NegotiatedProtocol = c.clientProtocol
1147 state.DidResume = c.didResume
1148 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
David Benjaminfc7b0862014-09-06 13:21:53 -04001149 state.NegotiatedProtocolFromALPN = c.usedALPN
Adam Langley95c29f32014-06-20 12:00:00 -07001150 state.CipherSuite = c.cipherSuite
1151 state.PeerCertificates = c.peerCertificates
1152 state.VerifiedChains = c.verifiedChains
1153 state.ServerName = c.serverName
David Benjamind30a9902014-08-24 01:44:23 -04001154 state.ChannelID = c.channelID
Adam Langley95c29f32014-06-20 12:00:00 -07001155 }
1156
1157 return state
1158}
1159
1160// OCSPResponse returns the stapled OCSP response from the TLS server, if
1161// any. (Only valid for client connections.)
1162func (c *Conn) OCSPResponse() []byte {
1163 c.handshakeMutex.Lock()
1164 defer c.handshakeMutex.Unlock()
1165
1166 return c.ocspResponse
1167}
1168
1169// VerifyHostname checks that the peer certificate chain is valid for
1170// connecting to host. If so, it returns nil; if not, it returns an error
1171// describing the problem.
1172func (c *Conn) VerifyHostname(host string) error {
1173 c.handshakeMutex.Lock()
1174 defer c.handshakeMutex.Unlock()
1175 if !c.isClient {
1176 return errors.New("tls: VerifyHostname called on TLS server connection")
1177 }
1178 if !c.handshakeComplete {
1179 return errors.New("tls: handshake has not yet been performed")
1180 }
1181 return c.peerCertificates[0].VerifyHostname(host)
1182}