blob: f3e24957bd9940dce214f302253cf6e855e8b1a2 [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
David Benjamind86c7672014-08-02 04:07:12 -0400703// writeV2Record writes a record for a V2ClientHello.
704func (c *Conn) writeV2Record(data []byte) (n int, err error) {
705 record := make([]byte, 2+len(data))
706 record[0] = uint8(len(data)>>8) | 0x80
707 record[1] = uint8(len(data))
708 copy(record[2:], data)
709 return c.conn.Write(record)
710}
711
Adam Langley95c29f32014-06-20 12:00:00 -0700712// writeRecord writes a TLS record with the given type and payload
713// to the connection and updates the record layer state.
714// c.out.Mutex <= L.
715func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
716 b := c.out.newBlock()
David Benjamin98214542014-08-07 18:02:39 -0400717 first := true
718 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
Adam Langley95c29f32014-06-20 12:00:00 -0700719 for len(data) > 0 {
720 m := len(data)
721 if m > maxPlaintext {
722 m = maxPlaintext
723 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400724 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength {
725 m = c.config.Bugs.MaxHandshakeRecordLength
David Benjamin98214542014-08-07 18:02:39 -0400726 // By default, do not fragment the client_version or
727 // server_version, which are located in the first 6
728 // bytes.
729 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
730 m = 6
731 }
David Benjamin43ec06f2014-08-05 02:28:57 -0400732 }
Adam Langley95c29f32014-06-20 12:00:00 -0700733 explicitIVLen := 0
734 explicitIVIsSeq := false
David Benjamin98214542014-08-07 18:02:39 -0400735 first = false
Adam Langley95c29f32014-06-20 12:00:00 -0700736
737 var cbc cbcMode
738 if c.out.version >= VersionTLS11 {
739 var ok bool
740 if cbc, ok = c.out.cipher.(cbcMode); ok {
741 explicitIVLen = cbc.BlockSize()
742 }
743 }
744 if explicitIVLen == 0 {
745 if _, ok := c.out.cipher.(cipher.AEAD); ok {
746 explicitIVLen = 8
747 // The AES-GCM construction in TLS has an
748 // explicit nonce so that the nonce can be
749 // random. However, the nonce is only 8 bytes
750 // which is too small for a secure, random
751 // nonce. Therefore we use the sequence number
752 // as the nonce.
753 explicitIVIsSeq = true
754 }
755 }
756 b.resize(recordHeaderLen + explicitIVLen + m)
757 b.data[0] = byte(typ)
758 vers := c.vers
759 if vers == 0 {
760 // Some TLS servers fail if the record version is
761 // greater than TLS 1.0 for the initial ClientHello.
762 vers = VersionTLS10
763 }
764 b.data[1] = byte(vers >> 8)
765 b.data[2] = byte(vers)
766 b.data[3] = byte(m >> 8)
767 b.data[4] = byte(m)
768 if explicitIVLen > 0 {
769 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
770 if explicitIVIsSeq {
771 copy(explicitIV, c.out.seq[:])
772 } else {
773 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
774 break
775 }
776 }
777 }
778 copy(b.data[recordHeaderLen+explicitIVLen:], data)
779 c.out.encrypt(b, explicitIVLen)
780 _, err = c.conn.Write(b.data)
781 if err != nil {
782 break
783 }
784 n += m
785 data = data[m:]
786 }
787 c.out.freeBlock(b)
788
789 if typ == recordTypeChangeCipherSpec {
Adam Langley80842bd2014-06-20 12:00:00 -0700790 err = c.out.changeCipherSpec(c.config)
Adam Langley95c29f32014-06-20 12:00:00 -0700791 if err != nil {
792 // Cannot call sendAlert directly,
793 // because we already hold c.out.Mutex.
794 c.tmp[0] = alertLevelError
795 c.tmp[1] = byte(err.(alert))
796 c.writeRecord(recordTypeAlert, c.tmp[0:2])
797 return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
798 }
799 }
800 return
801}
802
803// readHandshake reads the next handshake message from
804// the record layer.
805// c.in.Mutex < L; c.out.Mutex < L.
806func (c *Conn) readHandshake() (interface{}, error) {
807 for c.hand.Len() < 4 {
808 if err := c.in.err; err != nil {
809 return nil, err
810 }
811 if err := c.readRecord(recordTypeHandshake); err != nil {
812 return nil, err
813 }
814 }
815
816 data := c.hand.Bytes()
817 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
818 if n > maxHandshake {
819 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
820 }
821 for c.hand.Len() < 4+n {
822 if err := c.in.err; err != nil {
823 return nil, err
824 }
825 if err := c.readRecord(recordTypeHandshake); err != nil {
826 return nil, err
827 }
828 }
829 data = c.hand.Next(4 + n)
830 var m handshakeMessage
831 switch data[0] {
832 case typeClientHello:
833 m = new(clientHelloMsg)
834 case typeServerHello:
835 m = new(serverHelloMsg)
836 case typeNewSessionTicket:
837 m = new(newSessionTicketMsg)
838 case typeCertificate:
839 m = new(certificateMsg)
840 case typeCertificateRequest:
841 m = &certificateRequestMsg{
842 hasSignatureAndHash: c.vers >= VersionTLS12,
843 }
844 case typeCertificateStatus:
845 m = new(certificateStatusMsg)
846 case typeServerKeyExchange:
847 m = new(serverKeyExchangeMsg)
848 case typeServerHelloDone:
849 m = new(serverHelloDoneMsg)
850 case typeClientKeyExchange:
851 m = new(clientKeyExchangeMsg)
852 case typeCertificateVerify:
853 m = &certificateVerifyMsg{
854 hasSignatureAndHash: c.vers >= VersionTLS12,
855 }
856 case typeNextProtocol:
857 m = new(nextProtoMsg)
858 case typeFinished:
859 m = new(finishedMsg)
860 default:
861 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
862 }
863
864 // The handshake message unmarshallers
865 // expect to be able to keep references to data,
866 // so pass in a fresh copy that won't be overwritten.
867 data = append([]byte(nil), data...)
868
869 if !m.unmarshal(data) {
870 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
871 }
872 return m, nil
873}
874
875// Write writes data to the connection.
876func (c *Conn) Write(b []byte) (int, error) {
877 if err := c.Handshake(); err != nil {
878 return 0, err
879 }
880
881 c.out.Lock()
882 defer c.out.Unlock()
883
884 if err := c.out.err; err != nil {
885 return 0, err
886 }
887
888 if !c.handshakeComplete {
889 return 0, alertInternalError
890 }
891
892 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
893 // attack when using block mode ciphers due to predictable IVs.
894 // This can be prevented by splitting each Application Data
895 // record into two records, effectively randomizing the IV.
896 //
897 // http://www.openssl.org/~bodo/tls-cbc.txt
898 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
899 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
900
901 var m int
902 if len(b) > 1 && c.vers <= VersionTLS10 {
903 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
904 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
905 if err != nil {
906 return n, c.out.setErrorLocked(err)
907 }
908 m, b = 1, b[1:]
909 }
910 }
911
912 n, err := c.writeRecord(recordTypeApplicationData, b)
913 return n + m, c.out.setErrorLocked(err)
914}
915
916// Read can be made to time out and return a net.Error with Timeout() == true
917// after a fixed time limit; see SetDeadline and SetReadDeadline.
918func (c *Conn) Read(b []byte) (n int, err error) {
919 if err = c.Handshake(); err != nil {
920 return
921 }
922
923 c.in.Lock()
924 defer c.in.Unlock()
925
926 // Some OpenSSL servers send empty records in order to randomize the
927 // CBC IV. So this loop ignores a limited number of empty records.
928 const maxConsecutiveEmptyRecords = 100
929 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
930 for c.input == nil && c.in.err == nil {
931 if err := c.readRecord(recordTypeApplicationData); err != nil {
932 // Soft error, like EAGAIN
933 return 0, err
934 }
935 }
936 if err := c.in.err; err != nil {
937 return 0, err
938 }
939
940 n, err = c.input.Read(b)
941 if c.input.off >= len(c.input.data) {
942 c.in.freeBlock(c.input)
943 c.input = nil
944 }
945
946 // If a close-notify alert is waiting, read it so that
947 // we can return (n, EOF) instead of (n, nil), to signal
948 // to the HTTP response reading goroutine that the
949 // connection is now closed. This eliminates a race
950 // where the HTTP response reading goroutine would
951 // otherwise not observe the EOF until its next read,
952 // by which time a client goroutine might have already
953 // tried to reuse the HTTP connection for a new
954 // request.
955 // See https://codereview.appspot.com/76400046
956 // and http://golang.org/issue/3514
957 if ri := c.rawInput; ri != nil &&
958 n != 0 && err == nil &&
959 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
960 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
961 err = recErr // will be io.EOF on closeNotify
962 }
963 }
964
965 if n != 0 || err != nil {
966 return n, err
967 }
968 }
969
970 return 0, io.ErrNoProgress
971}
972
973// Close closes the connection.
974func (c *Conn) Close() error {
975 var alertErr error
976
977 c.handshakeMutex.Lock()
978 defer c.handshakeMutex.Unlock()
979 if c.handshakeComplete {
980 alertErr = c.sendAlert(alertCloseNotify)
981 }
982
983 if err := c.conn.Close(); err != nil {
984 return err
985 }
986 return alertErr
987}
988
989// Handshake runs the client or server handshake
990// protocol if it has not yet been run.
991// Most uses of this package need not call Handshake
992// explicitly: the first Read or Write will call it automatically.
993func (c *Conn) Handshake() error {
994 c.handshakeMutex.Lock()
995 defer c.handshakeMutex.Unlock()
996 if err := c.handshakeErr; err != nil {
997 return err
998 }
999 if c.handshakeComplete {
1000 return nil
1001 }
1002
1003 if c.isClient {
1004 c.handshakeErr = c.clientHandshake()
1005 } else {
1006 c.handshakeErr = c.serverHandshake()
1007 }
1008 return c.handshakeErr
1009}
1010
1011// ConnectionState returns basic TLS details about the connection.
1012func (c *Conn) ConnectionState() ConnectionState {
1013 c.handshakeMutex.Lock()
1014 defer c.handshakeMutex.Unlock()
1015
1016 var state ConnectionState
1017 state.HandshakeComplete = c.handshakeComplete
1018 if c.handshakeComplete {
1019 state.Version = c.vers
1020 state.NegotiatedProtocol = c.clientProtocol
1021 state.DidResume = c.didResume
1022 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
1023 state.CipherSuite = c.cipherSuite
1024 state.PeerCertificates = c.peerCertificates
1025 state.VerifiedChains = c.verifiedChains
1026 state.ServerName = c.serverName
1027 }
1028
1029 return state
1030}
1031
1032// OCSPResponse returns the stapled OCSP response from the TLS server, if
1033// any. (Only valid for client connections.)
1034func (c *Conn) OCSPResponse() []byte {
1035 c.handshakeMutex.Lock()
1036 defer c.handshakeMutex.Unlock()
1037
1038 return c.ocspResponse
1039}
1040
1041// VerifyHostname checks that the peer certificate chain is valid for
1042// connecting to host. If so, it returns nil; if not, it returns an error
1043// describing the problem.
1044func (c *Conn) VerifyHostname(host string) error {
1045 c.handshakeMutex.Lock()
1046 defer c.handshakeMutex.Unlock()
1047 if !c.isClient {
1048 return errors.New("tls: VerifyHostname called on TLS server connection")
1049 }
1050 if !c.handshakeComplete {
1051 return errors.New("tls: handshake has not yet been performed")
1052 }
1053 return c.peerCertificates[0].VerifyHostname(host)
1054}