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