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