github.com/rohankumardubey/syslog-redirector-golang@v0.0.0-20140320174030-4859f03d829a/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  	for i := range hc.seq {
   150  		hc.seq[i] = 0
   151  	}
   152  	return nil
   153  }
   154  
   155  // incSeq increments the sequence number.
   156  func (hc *halfConn) incSeq() {
   157  	for i := 7; i >= 0; i-- {
   158  		hc.seq[i]++
   159  		if hc.seq[i] != 0 {
   160  			return
   161  		}
   162  	}
   163  
   164  	// Not allowed to let sequence number wrap.
   165  	// Instead, must renegotiate before it does.
   166  	// Not likely enough to bother.
   167  	panic("TLS: sequence number wraparound")
   168  }
   169  
   170  // resetSeq resets the sequence number to zero.
   171  func (hc *halfConn) resetSeq() {
   172  	for i := range hc.seq {
   173  		hc.seq[i] = 0
   174  	}
   175  }
   176  
   177  // removePadding returns an unpadded slice, in constant time, which is a prefix
   178  // of the input. It also returns a byte which is equal to 255 if the padding
   179  // was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
   180  func removePadding(payload []byte) ([]byte, byte) {
   181  	if len(payload) < 1 {
   182  		return payload, 0
   183  	}
   184  
   185  	paddingLen := payload[len(payload)-1]
   186  	t := uint(len(payload)-1) - uint(paddingLen)
   187  	// if len(payload) >= (paddingLen - 1) then the MSB of t is zero
   188  	good := byte(int32(^t) >> 31)
   189  
   190  	toCheck := 255 // the maximum possible padding length
   191  	// The length of the padded data is public, so we can use an if here
   192  	if toCheck+1 > len(payload) {
   193  		toCheck = len(payload) - 1
   194  	}
   195  
   196  	for i := 0; i < toCheck; i++ {
   197  		t := uint(paddingLen) - uint(i)
   198  		// if i <= paddingLen then the MSB of t is zero
   199  		mask := byte(int32(^t) >> 31)
   200  		b := payload[len(payload)-1-i]
   201  		good &^= mask&paddingLen ^ mask&b
   202  	}
   203  
   204  	// We AND together the bits of good and replicate the result across
   205  	// all the bits.
   206  	good &= good << 4
   207  	good &= good << 2
   208  	good &= good << 1
   209  	good = uint8(int8(good) >> 7)
   210  
   211  	toRemove := good&paddingLen + 1
   212  	return payload[:len(payload)-int(toRemove)], good
   213  }
   214  
   215  // removePaddingSSL30 is a replacement for removePadding in the case that the
   216  // protocol version is SSLv3. In this version, the contents of the padding
   217  // are random and cannot be checked.
   218  func removePaddingSSL30(payload []byte) ([]byte, byte) {
   219  	if len(payload) < 1 {
   220  		return payload, 0
   221  	}
   222  
   223  	paddingLen := int(payload[len(payload)-1]) + 1
   224  	if paddingLen > len(payload) {
   225  		return payload, 0
   226  	}
   227  
   228  	return payload[:len(payload)-paddingLen], 255
   229  }
   230  
   231  func roundUp(a, b int) int {
   232  	return a + (b-a%b)%b
   233  }
   234  
   235  // cbcMode is an interface for block ciphers using cipher block chaining.
   236  type cbcMode interface {
   237  	cipher.BlockMode
   238  	SetIV([]byte)
   239  }
   240  
   241  // decrypt checks and strips the mac and decrypts the data in b. Returns a
   242  // success boolean, the number of bytes to skip from the start of the record in
   243  // order to get the application payload, and an optional alert value.
   244  func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, alertValue alert) {
   245  	// pull out payload
   246  	payload := b.data[recordHeaderLen:]
   247  
   248  	macSize := 0
   249  	if hc.mac != nil {
   250  		macSize = hc.mac.Size()
   251  	}
   252  
   253  	paddingGood := byte(255)
   254  	explicitIVLen := 0
   255  
   256  	// decrypt
   257  	if hc.cipher != nil {
   258  		switch c := hc.cipher.(type) {
   259  		case cipher.Stream:
   260  			c.XORKeyStream(payload, payload)
   261  		case cipher.AEAD:
   262  			explicitIVLen = 8
   263  			if len(payload) < explicitIVLen {
   264  				return false, 0, alertBadRecordMAC
   265  			}
   266  			nonce := payload[:8]
   267  			payload = payload[8:]
   268  
   269  			var additionalData [13]byte
   270  			copy(additionalData[:], hc.seq[:])
   271  			copy(additionalData[8:], b.data[:3])
   272  			n := len(payload) - c.Overhead()
   273  			additionalData[11] = byte(n >> 8)
   274  			additionalData[12] = byte(n)
   275  			var err error
   276  			payload, err = c.Open(payload[:0], nonce, payload, additionalData[:])
   277  			if err != nil {
   278  				return false, 0, alertBadRecordMAC
   279  			}
   280  			b.resize(recordHeaderLen + explicitIVLen + len(payload))
   281  		case cbcMode:
   282  			blockSize := c.BlockSize()
   283  			if hc.version >= VersionTLS11 {
   284  				explicitIVLen = blockSize
   285  			}
   286  
   287  			if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
   288  				return false, 0, alertBadRecordMAC
   289  			}
   290  
   291  			if explicitIVLen > 0 {
   292  				c.SetIV(payload[:explicitIVLen])
   293  				payload = payload[explicitIVLen:]
   294  			}
   295  			c.CryptBlocks(payload, payload)
   296  			if hc.version == VersionSSL30 {
   297  				payload, paddingGood = removePaddingSSL30(payload)
   298  			} else {
   299  				payload, paddingGood = removePadding(payload)
   300  			}
   301  			b.resize(recordHeaderLen + explicitIVLen + len(payload))
   302  
   303  			// note that we still have a timing side-channel in the
   304  			// MAC check, below. An attacker can align the record
   305  			// so that a correct padding will cause one less hash
   306  			// block to be calculated. Then they can iteratively
   307  			// decrypt a record by breaking each byte. See
   308  			// "Password Interception in a SSL/TLS Channel", Brice
   309  			// Canvel et al.
   310  			//
   311  			// However, our behavior matches OpenSSL, so we leak
   312  			// only as much as they do.
   313  		default:
   314  			panic("unknown cipher type")
   315  		}
   316  	}
   317  
   318  	// check, strip mac
   319  	if hc.mac != nil {
   320  		if len(payload) < macSize {
   321  			return false, 0, alertBadRecordMAC
   322  		}
   323  
   324  		// strip mac off payload, b.data
   325  		n := len(payload) - macSize
   326  		b.data[3] = byte(n >> 8)
   327  		b.data[4] = byte(n)
   328  		b.resize(recordHeaderLen + explicitIVLen + n)
   329  		remoteMAC := payload[n:]
   330  		localMAC := hc.mac.MAC(hc.inDigestBuf, hc.seq[0:], b.data[:recordHeaderLen], payload[:n])
   331  
   332  		if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
   333  			return false, 0, alertBadRecordMAC
   334  		}
   335  		hc.inDigestBuf = localMAC
   336  	}
   337  	hc.incSeq()
   338  
   339  	return true, recordHeaderLen + explicitIVLen, 0
   340  }
   341  
   342  // padToBlockSize calculates the needed padding block, if any, for a payload.
   343  // On exit, prefix aliases payload and extends to the end of the last full
   344  // block of payload. finalBlock is a fresh slice which contains the contents of
   345  // any suffix of payload as well as the needed padding to make finalBlock a
   346  // full block.
   347  func padToBlockSize(payload []byte, blockSize int) (prefix, finalBlock []byte) {
   348  	overrun := len(payload) % blockSize
   349  	paddingLen := blockSize - overrun
   350  	prefix = payload[:len(payload)-overrun]
   351  	finalBlock = make([]byte, blockSize)
   352  	copy(finalBlock, payload[len(payload)-overrun:])
   353  	for i := overrun; i < blockSize; i++ {
   354  		finalBlock[i] = byte(paddingLen - 1)
   355  	}
   356  	return
   357  }
   358  
   359  // encrypt encrypts and macs the data in b.
   360  func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) {
   361  	// mac
   362  	if hc.mac != nil {
   363  		mac := hc.mac.MAC(hc.outDigestBuf, hc.seq[0:], b.data[:recordHeaderLen], b.data[recordHeaderLen+explicitIVLen:])
   364  
   365  		n := len(b.data)
   366  		b.resize(n + len(mac))
   367  		copy(b.data[n:], mac)
   368  		hc.outDigestBuf = mac
   369  	}
   370  
   371  	payload := b.data[recordHeaderLen:]
   372  
   373  	// encrypt
   374  	if hc.cipher != nil {
   375  		switch c := hc.cipher.(type) {
   376  		case cipher.Stream:
   377  			c.XORKeyStream(payload, payload)
   378  		case cipher.AEAD:
   379  			payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
   380  			b.resize(len(b.data) + c.Overhead())
   381  			nonce := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
   382  			payload := b.data[recordHeaderLen+explicitIVLen:]
   383  			payload = payload[:payloadLen]
   384  
   385  			var additionalData [13]byte
   386  			copy(additionalData[:], hc.seq[:])
   387  			copy(additionalData[8:], b.data[:3])
   388  			additionalData[11] = byte(payloadLen >> 8)
   389  			additionalData[12] = byte(payloadLen)
   390  
   391  			c.Seal(payload[:0], nonce, payload, additionalData[:])
   392  		case cbcMode:
   393  			blockSize := c.BlockSize()
   394  			if explicitIVLen > 0 {
   395  				c.SetIV(payload[:explicitIVLen])
   396  				payload = payload[explicitIVLen:]
   397  			}
   398  			prefix, finalBlock := padToBlockSize(payload, blockSize)
   399  			b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
   400  			c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
   401  			c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
   402  		default:
   403  			panic("unknown cipher type")
   404  		}
   405  	}
   406  
   407  	// update length to include MAC and any block padding needed.
   408  	n := len(b.data) - recordHeaderLen
   409  	b.data[3] = byte(n >> 8)
   410  	b.data[4] = byte(n)
   411  	hc.incSeq()
   412  
   413  	return true, 0
   414  }
   415  
   416  // A block is a simple data buffer.
   417  type block struct {
   418  	data []byte
   419  	off  int // index for Read
   420  	link *block
   421  }
   422  
   423  // resize resizes block to be n bytes, growing if necessary.
   424  func (b *block) resize(n int) {
   425  	if n > cap(b.data) {
   426  		b.reserve(n)
   427  	}
   428  	b.data = b.data[0:n]
   429  }
   430  
   431  // reserve makes sure that block contains a capacity of at least n bytes.
   432  func (b *block) reserve(n int) {
   433  	if cap(b.data) >= n {
   434  		return
   435  	}
   436  	m := cap(b.data)
   437  	if m == 0 {
   438  		m = 1024
   439  	}
   440  	for m < n {
   441  		m *= 2
   442  	}
   443  	data := make([]byte, len(b.data), m)
   444  	copy(data, b.data)
   445  	b.data = data
   446  }
   447  
   448  // readFromUntil reads from r into b until b contains at least n bytes
   449  // or else returns an error.
   450  func (b *block) readFromUntil(r io.Reader, n int) error {
   451  	// quick case
   452  	if len(b.data) >= n {
   453  		return nil
   454  	}
   455  
   456  	// read until have enough.
   457  	b.reserve(n)
   458  	for {
   459  		m, err := r.Read(b.data[len(b.data):cap(b.data)])
   460  		b.data = b.data[0 : len(b.data)+m]
   461  		if len(b.data) >= n {
   462  			break
   463  		}
   464  		if err != nil {
   465  			return err
   466  		}
   467  	}
   468  	return nil
   469  }
   470  
   471  func (b *block) Read(p []byte) (n int, err error) {
   472  	n = copy(p, b.data[b.off:])
   473  	b.off += n
   474  	return
   475  }
   476  
   477  // newBlock allocates a new block, from hc's free list if possible.
   478  func (hc *halfConn) newBlock() *block {
   479  	b := hc.bfree
   480  	if b == nil {
   481  		return new(block)
   482  	}
   483  	hc.bfree = b.link
   484  	b.link = nil
   485  	b.resize(0)
   486  	return b
   487  }
   488  
   489  // freeBlock returns a block to hc's free list.
   490  // The protocol is such that each side only has a block or two on
   491  // its free list at a time, so there's no need to worry about
   492  // trimming the list, etc.
   493  func (hc *halfConn) freeBlock(b *block) {
   494  	b.link = hc.bfree
   495  	hc.bfree = b
   496  }
   497  
   498  // splitBlock splits a block after the first n bytes,
   499  // returning a block with those n bytes and a
   500  // block with the remainder.  the latter may be nil.
   501  func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
   502  	if len(b.data) <= n {
   503  		return b, nil
   504  	}
   505  	bb := hc.newBlock()
   506  	bb.resize(len(b.data) - n)
   507  	copy(bb.data, b.data[n:])
   508  	b.data = b.data[0:n]
   509  	return b, bb
   510  }
   511  
   512  // readRecord reads the next TLS record from the connection
   513  // and updates the record layer state.
   514  // c.in.Mutex <= L; c.input == nil.
   515  func (c *Conn) readRecord(want recordType) error {
   516  	// Caller must be in sync with connection:
   517  	// handshake data if handshake not yet completed,
   518  	// else application data.  (We don't support renegotiation.)
   519  	switch want {
   520  	default:
   521  		return c.sendAlert(alertInternalError)
   522  	case recordTypeHandshake, recordTypeChangeCipherSpec:
   523  		if c.handshakeComplete {
   524  			return c.sendAlert(alertInternalError)
   525  		}
   526  	case recordTypeApplicationData:
   527  		if !c.handshakeComplete {
   528  			return c.sendAlert(alertInternalError)
   529  		}
   530  	}
   531  
   532  Again:
   533  	if c.rawInput == nil {
   534  		c.rawInput = c.in.newBlock()
   535  	}
   536  	b := c.rawInput
   537  
   538  	// Read header, payload.
   539  	if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
   540  		// RFC suggests that EOF without an alertCloseNotify is
   541  		// an error, but popular web sites seem to do this,
   542  		// so we can't make it an error.
   543  		// if err == io.EOF {
   544  		// 	err = io.ErrUnexpectedEOF
   545  		// }
   546  		if e, ok := err.(net.Error); !ok || !e.Temporary() {
   547  			c.setError(err)
   548  		}
   549  		return err
   550  	}
   551  	typ := recordType(b.data[0])
   552  
   553  	// No valid TLS record has a type of 0x80, however SSLv2 handshakes
   554  	// start with a uint16 length where the MSB is set and the first record
   555  	// is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
   556  	// an SSLv2 client.
   557  	if want == recordTypeHandshake && typ == 0x80 {
   558  		c.sendAlert(alertProtocolVersion)
   559  		return errors.New("tls: unsupported SSLv2 handshake received")
   560  	}
   561  
   562  	vers := uint16(b.data[1])<<8 | uint16(b.data[2])
   563  	n := int(b.data[3])<<8 | int(b.data[4])
   564  	if c.haveVers && vers != c.vers {
   565  		return c.sendAlert(alertProtocolVersion)
   566  	}
   567  	if n > maxCiphertext {
   568  		return c.sendAlert(alertRecordOverflow)
   569  	}
   570  	if !c.haveVers {
   571  		// First message, be extra suspicious:
   572  		// this might not be a TLS client.
   573  		// Bail out before reading a full 'body', if possible.
   574  		// The current max version is 3.1.
   575  		// If the version is >= 16.0, it's probably not real.
   576  		// Similarly, a clientHello message encodes in
   577  		// well under a kilobyte.  If the length is >= 12 kB,
   578  		// it's probably not real.
   579  		if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
   580  			return c.sendAlert(alertUnexpectedMessage)
   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.setError(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  		return c.sendAlert(err)
   598  	}
   599  	b.off = off
   600  	data := b.data[b.off:]
   601  	if len(data) > maxPlaintext {
   602  		c.sendAlert(alertRecordOverflow)
   603  		c.in.freeBlock(b)
   604  		return c.error()
   605  	}
   606  
   607  	switch typ {
   608  	default:
   609  		c.sendAlert(alertUnexpectedMessage)
   610  
   611  	case recordTypeAlert:
   612  		if len(data) != 2 {
   613  			c.sendAlert(alertUnexpectedMessage)
   614  			break
   615  		}
   616  		if alert(data[1]) == alertCloseNotify {
   617  			c.setError(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.setError(&net.OpError{Op: "remote error", Err: alert(data[1])})
   627  		default:
   628  			c.sendAlert(alertUnexpectedMessage)
   629  		}
   630  
   631  	case recordTypeChangeCipherSpec:
   632  		if typ != want || len(data) != 1 || data[0] != 1 {
   633  			c.sendAlert(alertUnexpectedMessage)
   634  			break
   635  		}
   636  		err := c.in.changeCipherSpec()
   637  		if err != nil {
   638  			c.sendAlert(err.(alert))
   639  		}
   640  
   641  	case recordTypeApplicationData:
   642  		if typ != want {
   643  			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.sendAlert(alertNoRenegotiation)
   653  		}
   654  		c.hand.Write(data)
   655  	}
   656  
   657  	if b != nil {
   658  		c.in.freeBlock(b)
   659  	}
   660  	return c.error()
   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.setError(&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.setError(&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.error(); 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  		c.sendAlert(alertInternalError)
   785  		return nil, c.error()
   786  	}
   787  	for c.hand.Len() < 4+n {
   788  		if err := c.error(); err != nil {
   789  			return nil, err
   790  		}
   791  		if err := c.readRecord(recordTypeHandshake); err != nil {
   792  			return nil, err
   793  		}
   794  	}
   795  	data = c.hand.Next(4 + n)
   796  	var m handshakeMessage
   797  	switch data[0] {
   798  	case typeClientHello:
   799  		m = new(clientHelloMsg)
   800  	case typeServerHello:
   801  		m = new(serverHelloMsg)
   802  	case typeCertificate:
   803  		m = new(certificateMsg)
   804  	case typeCertificateRequest:
   805  		m = &certificateRequestMsg{
   806  			hasSignatureAndHash: c.vers >= VersionTLS12,
   807  		}
   808  	case typeCertificateStatus:
   809  		m = new(certificateStatusMsg)
   810  	case typeServerKeyExchange:
   811  		m = new(serverKeyExchangeMsg)
   812  	case typeServerHelloDone:
   813  		m = new(serverHelloDoneMsg)
   814  	case typeClientKeyExchange:
   815  		m = new(clientKeyExchangeMsg)
   816  	case typeCertificateVerify:
   817  		m = &certificateVerifyMsg{
   818  			hasSignatureAndHash: c.vers >= VersionTLS12,
   819  		}
   820  	case typeNextProtocol:
   821  		m = new(nextProtoMsg)
   822  	case typeFinished:
   823  		m = new(finishedMsg)
   824  	default:
   825  		c.sendAlert(alertUnexpectedMessage)
   826  		return nil, 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  		c.sendAlert(alertUnexpectedMessage)
   836  		return nil, alertUnexpectedMessage
   837  	}
   838  	return m, nil
   839  }
   840  
   841  // Write writes data to the connection.
   842  func (c *Conn) Write(b []byte) (int, error) {
   843  	if err := c.error(); err != nil {
   844  		return 0, err
   845  	}
   846  
   847  	if err := c.Handshake(); err != nil {
   848  		return 0, c.setError(err)
   849  	}
   850  
   851  	c.out.Lock()
   852  	defer c.out.Unlock()
   853  
   854  	if !c.handshakeComplete {
   855  		return 0, alertInternalError
   856  	}
   857  
   858  	// SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
   859  	// attack when using block mode ciphers due to predictable IVs.
   860  	// This can be prevented by splitting each Application Data
   861  	// record into two records, effectively randomizing the IV.
   862  	//
   863  	// http://www.openssl.org/~bodo/tls-cbc.txt
   864  	// https://bugzilla.mozilla.org/show_bug.cgi?id=665814
   865  	// http://www.imperialviolet.org/2012/01/15/beastfollowup.html
   866  
   867  	var m int
   868  	if len(b) > 1 && c.vers <= VersionTLS10 {
   869  		if _, ok := c.out.cipher.(cipher.BlockMode); ok {
   870  			n, err := c.writeRecord(recordTypeApplicationData, b[:1])
   871  			if err != nil {
   872  				return n, c.setError(err)
   873  			}
   874  			m, b = 1, b[1:]
   875  		}
   876  	}
   877  
   878  	n, err := c.writeRecord(recordTypeApplicationData, b)
   879  	return n + m, c.setError(err)
   880  }
   881  
   882  // Read can be made to time out and return a net.Error with Timeout() == true
   883  // after a fixed time limit; see SetDeadline and SetReadDeadline.
   884  func (c *Conn) Read(b []byte) (n int, err error) {
   885  	if err = c.Handshake(); err != nil {
   886  		return
   887  	}
   888  
   889  	c.in.Lock()
   890  	defer c.in.Unlock()
   891  
   892  	// Some OpenSSL servers send empty records in order to randomize the
   893  	// CBC IV. So this loop ignores a limited number of empty records.
   894  	const maxConsecutiveEmptyRecords = 100
   895  	for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
   896  		for c.input == nil && c.error() == nil {
   897  			if err := c.readRecord(recordTypeApplicationData); err != nil {
   898  				// Soft error, like EAGAIN
   899  				return 0, err
   900  			}
   901  		}
   902  		if err := c.error(); err != nil {
   903  			return 0, err
   904  		}
   905  
   906  		n, err = c.input.Read(b)
   907  		if c.input.off >= len(c.input.data) {
   908  			c.in.freeBlock(c.input)
   909  			c.input = nil
   910  		}
   911  
   912  		if n != 0 || err != nil {
   913  			return n, err
   914  		}
   915  	}
   916  
   917  	return 0, io.ErrNoProgress
   918  }
   919  
   920  // Close closes the connection.
   921  func (c *Conn) Close() error {
   922  	var alertErr error
   923  
   924  	c.handshakeMutex.Lock()
   925  	defer c.handshakeMutex.Unlock()
   926  	if c.handshakeComplete {
   927  		alertErr = c.sendAlert(alertCloseNotify)
   928  	}
   929  
   930  	if err := c.conn.Close(); err != nil {
   931  		return err
   932  	}
   933  	return alertErr
   934  }
   935  
   936  // Handshake runs the client or server handshake
   937  // protocol if it has not yet been run.
   938  // Most uses of this package need not call Handshake
   939  // explicitly: the first Read or Write will call it automatically.
   940  func (c *Conn) Handshake() error {
   941  	c.handshakeMutex.Lock()
   942  	defer c.handshakeMutex.Unlock()
   943  	if err := c.error(); err != nil {
   944  		return err
   945  	}
   946  	if c.handshakeComplete {
   947  		return nil
   948  	}
   949  	if c.isClient {
   950  		return c.clientHandshake()
   951  	}
   952  	return c.serverHandshake()
   953  }
   954  
   955  // ConnectionState returns basic TLS details about the connection.
   956  func (c *Conn) ConnectionState() ConnectionState {
   957  	c.handshakeMutex.Lock()
   958  	defer c.handshakeMutex.Unlock()
   959  
   960  	var state ConnectionState
   961  	state.HandshakeComplete = c.handshakeComplete
   962  	if c.handshakeComplete {
   963  		state.NegotiatedProtocol = c.clientProtocol
   964  		state.DidResume = c.didResume
   965  		state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
   966  		state.CipherSuite = c.cipherSuite
   967  		state.PeerCertificates = c.peerCertificates
   968  		state.VerifiedChains = c.verifiedChains
   969  		state.ServerName = c.serverName
   970  	}
   971  
   972  	return state
   973  }
   974  
   975  // OCSPResponse returns the stapled OCSP response from the TLS server, if
   976  // any. (Only valid for client connections.)
   977  func (c *Conn) OCSPResponse() []byte {
   978  	c.handshakeMutex.Lock()
   979  	defer c.handshakeMutex.Unlock()
   980  
   981  	return c.ocspResponse
   982  }
   983  
   984  // VerifyHostname checks that the peer certificate chain is valid for
   985  // connecting to host.  If so, it returns nil; if not, it returns an error
   986  // describing the problem.
   987  func (c *Conn) VerifyHostname(host string) error {
   988  	c.handshakeMutex.Lock()
   989  	defer c.handshakeMutex.Unlock()
   990  	if !c.isClient {
   991  		return errors.New("VerifyHostname called on TLS server connection")
   992  	}
   993  	if !c.handshakeComplete {
   994  		return errors.New("TLS handshake has not yet been performed")
   995  	}
   996  	return c.peerCertificates[0].VerifyHostname(host)
   997  }