github.com/huandu/go@v0.0.0-20151114150818-04e615e41150/src/crypto/tls/conn.go (about)

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