...
Run Format

Source file src/crypto/tls/conn.go

     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		"sync/atomic"
    20		"time"
    21	)
    22	
    23	// A Conn represents a secured connection.
    24	// It implements the net.Conn interface.
    25	type Conn struct {
    26		// constant
    27		conn     net.Conn
    28		isClient bool
    29	
    30		// constant after handshake; protected by handshakeMutex
    31		handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
    32		handshakeErr   error      // error resulting from handshake
    33		vers           uint16     // TLS version
    34		haveVers       bool       // version has been negotiated
    35		config         *Config    // configuration passed to constructor
    36		// handshakeComplete is true if the connection is currently transfering
    37		// application data (i.e. is not currently processing a handshake).
    38		handshakeComplete bool
    39		// handshakes counts the number of handshakes performed on the
    40		// connection so far. If renegotiation is disabled then this is either
    41		// zero or one.
    42		handshakes       int
    43		didResume        bool // whether this connection was a session resumption
    44		cipherSuite      uint16
    45		ocspResponse     []byte   // stapled OCSP response
    46		scts             [][]byte // signed certificate timestamps from server
    47		peerCertificates []*x509.Certificate
    48		// verifiedChains contains the certificate chains that we built, as
    49		// opposed to the ones presented by the server.
    50		verifiedChains [][]*x509.Certificate
    51		// serverName contains the server name indicated by the client, if any.
    52		serverName string
    53		// secureRenegotiation is true if the server echoed the secure
    54		// renegotiation extension. (This is meaningless as a server because
    55		// renegotiation is not supported in that case.)
    56		secureRenegotiation bool
    57	
    58		// clientFinishedIsFirst is true if the client sent the first Finished
    59		// message during the most recent handshake. This is recorded because
    60		// the first transmitted Finished message is the tls-unique
    61		// channel-binding value.
    62		clientFinishedIsFirst bool
    63		// clientFinished and serverFinished contain the Finished message sent
    64		// by the client or server in the most recent handshake. This is
    65		// retained to support the renegotiation extension and tls-unique
    66		// channel-binding.
    67		clientFinished [12]byte
    68		serverFinished [12]byte
    69	
    70		clientProtocol         string
    71		clientProtocolFallback bool
    72	
    73		// input/output
    74		in, out   halfConn     // in.Mutex < out.Mutex
    75		rawInput  *block       // raw input, right off the wire
    76		input     *block       // application data waiting to be read
    77		hand      bytes.Buffer // handshake data waiting to be read
    78		buffering bool         // whether records are buffered in sendBuf
    79		sendBuf   []byte       // a buffer of records waiting to be sent
    80	
    81		// bytesSent counts the bytes of application data sent.
    82		// packetsSent counts packets.
    83		bytesSent   int64
    84		packetsSent int64
    85	
    86		// activeCall is an atomic int32; the low bit is whether Close has
    87		// been called. the rest of the bits are the number of goroutines
    88		// in Conn.Write.
    89		activeCall int32
    90	
    91		tmp [16]byte
    92	}
    93	
    94	// Access to net.Conn methods.
    95	// Cannot just embed net.Conn because that would
    96	// export the struct field too.
    97	
    98	// LocalAddr returns the local network address.
    99	func (c *Conn) LocalAddr() net.Addr {
   100		return c.conn.LocalAddr()
   101	}
   102	
   103	// RemoteAddr returns the remote network address.
   104	func (c *Conn) RemoteAddr() net.Addr {
   105		return c.conn.RemoteAddr()
   106	}
   107	
   108	// SetDeadline sets the read and write deadlines associated with the connection.
   109	// A zero value for t means Read and Write will not time out.
   110	// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
   111	func (c *Conn) SetDeadline(t time.Time) error {
   112		return c.conn.SetDeadline(t)
   113	}
   114	
   115	// SetReadDeadline sets the read deadline on the underlying connection.
   116	// A zero value for t means Read will not time out.
   117	func (c *Conn) SetReadDeadline(t time.Time) error {
   118		return c.conn.SetReadDeadline(t)
   119	}
   120	
   121	// SetWriteDeadline sets the write deadline on the underlying connection.
   122	// A zero value for t means Write will not time out.
   123	// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
   124	func (c *Conn) SetWriteDeadline(t time.Time) error {
   125		return c.conn.SetWriteDeadline(t)
   126	}
   127	
   128	// A halfConn represents one direction of the record layer
   129	// connection, either sending or receiving.
   130	type halfConn struct {
   131		sync.Mutex
   132	
   133		err            error       // first permanent error
   134		version        uint16      // protocol version
   135		cipher         interface{} // cipher algorithm
   136		mac            macFunction
   137		seq            [8]byte  // 64-bit sequence number
   138		bfree          *block   // list of free blocks
   139		additionalData [13]byte // to avoid allocs; interface method args escape
   140	
   141		nextCipher interface{} // next encryption state
   142		nextMac    macFunction // next MAC algorithm
   143	
   144		// used to save allocating a new buffer for each MAC.
   145		inDigestBuf, outDigestBuf []byte
   146	}
   147	
   148	func (hc *halfConn) setErrorLocked(err error) error {
   149		hc.err = err
   150		return err
   151	}
   152	
   153	// prepareCipherSpec sets the encryption and MAC states
   154	// that a subsequent changeCipherSpec will use.
   155	func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
   156		hc.version = version
   157		hc.nextCipher = cipher
   158		hc.nextMac = mac
   159	}
   160	
   161	// changeCipherSpec changes the encryption and MAC states
   162	// to the ones previously passed to prepareCipherSpec.
   163	func (hc *halfConn) changeCipherSpec() error {
   164		if hc.nextCipher == nil {
   165			return alertInternalError
   166		}
   167		hc.cipher = hc.nextCipher
   168		hc.mac = hc.nextMac
   169		hc.nextCipher = nil
   170		hc.nextMac = nil
   171		for i := range hc.seq {
   172			hc.seq[i] = 0
   173		}
   174		return nil
   175	}
   176	
   177	// incSeq increments the sequence number.
   178	func (hc *halfConn) incSeq() {
   179		for i := 7; i >= 0; i-- {
   180			hc.seq[i]++
   181			if hc.seq[i] != 0 {
   182				return
   183			}
   184		}
   185	
   186		// Not allowed to let sequence number wrap.
   187		// Instead, must renegotiate before it does.
   188		// Not likely enough to bother.
   189		panic("TLS: sequence number wraparound")
   190	}
   191	
   192	// removePadding returns an unpadded slice, in constant time, which is a prefix
   193	// of the input. It also returns a byte which is equal to 255 if the padding
   194	// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
   195	func removePadding(payload []byte) ([]byte, byte) {
   196		if len(payload) < 1 {
   197			return payload, 0
   198		}
   199	
   200		paddingLen := payload[len(payload)-1]
   201		t := uint(len(payload)-1) - uint(paddingLen)
   202		// if len(payload) >= (paddingLen - 1) then the MSB of t is zero
   203		good := byte(int32(^t) >> 31)
   204	
   205		toCheck := 255 // the maximum possible padding length
   206		// The length of the padded data is public, so we can use an if here
   207		if toCheck+1 > len(payload) {
   208			toCheck = len(payload) - 1
   209		}
   210	
   211		for i := 0; i < toCheck; i++ {
   212			t := uint(paddingLen) - uint(i)
   213			// if i <= paddingLen then the MSB of t is zero
   214			mask := byte(int32(^t) >> 31)
   215			b := payload[len(payload)-1-i]
   216			good &^= mask&paddingLen ^ mask&b
   217		}
   218	
   219		// We AND together the bits of good and replicate the result across
   220		// all the bits.
   221		good &= good << 4
   222		good &= good << 2
   223		good &= good << 1
   224		good = uint8(int8(good) >> 7)
   225	
   226		toRemove := good&paddingLen + 1
   227		return payload[:len(payload)-int(toRemove)], good
   228	}
   229	
   230	// removePaddingSSL30 is a replacement for removePadding in the case that the
   231	// protocol version is SSLv3. In this version, the contents of the padding
   232	// are random and cannot be checked.
   233	func removePaddingSSL30(payload []byte) ([]byte, byte) {
   234		if len(payload) < 1 {
   235			return payload, 0
   236		}
   237	
   238		paddingLen := int(payload[len(payload)-1]) + 1
   239		if paddingLen > len(payload) {
   240			return payload, 0
   241		}
   242	
   243		return payload[:len(payload)-paddingLen], 255
   244	}
   245	
   246	func roundUp(a, b int) int {
   247		return a + (b-a%b)%b
   248	}
   249	
   250	// cbcMode is an interface for block ciphers using cipher block chaining.
   251	type cbcMode interface {
   252		cipher.BlockMode
   253		SetIV([]byte)
   254	}
   255	
   256	// decrypt checks and strips the mac and decrypts the data in b. Returns a
   257	// success boolean, the number of bytes to skip from the start of the record in
   258	// order to get the application payload, and an optional alert value.
   259	func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, alertValue alert) {
   260		// pull out payload
   261		payload := b.data[recordHeaderLen:]
   262	
   263		macSize := 0
   264		if hc.mac != nil {
   265			macSize = hc.mac.Size()
   266		}
   267	
   268		paddingGood := byte(255)
   269		explicitIVLen := 0
   270	
   271		// decrypt
   272		if hc.cipher != nil {
   273			switch c := hc.cipher.(type) {
   274			case cipher.Stream:
   275				c.XORKeyStream(payload, payload)
   276			case cipher.AEAD:
   277				explicitIVLen = 8
   278				if len(payload) < explicitIVLen {
   279					return false, 0, alertBadRecordMAC
   280				}
   281				nonce := payload[:8]
   282				payload = payload[8:]
   283	
   284				copy(hc.additionalData[:], hc.seq[:])
   285				copy(hc.additionalData[8:], b.data[:3])
   286				n := len(payload) - c.Overhead()
   287				hc.additionalData[11] = byte(n >> 8)
   288				hc.additionalData[12] = byte(n)
   289				var err error
   290				payload, err = c.Open(payload[:0], nonce, payload, hc.additionalData[:])
   291				if err != nil {
   292					return false, 0, alertBadRecordMAC
   293				}
   294				b.resize(recordHeaderLen + explicitIVLen + len(payload))
   295			case cbcMode:
   296				blockSize := c.BlockSize()
   297				if hc.version >= VersionTLS11 {
   298					explicitIVLen = blockSize
   299				}
   300	
   301				if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
   302					return false, 0, alertBadRecordMAC
   303				}
   304	
   305				if explicitIVLen > 0 {
   306					c.SetIV(payload[:explicitIVLen])
   307					payload = payload[explicitIVLen:]
   308				}
   309				c.CryptBlocks(payload, payload)
   310				if hc.version == VersionSSL30 {
   311					payload, paddingGood = removePaddingSSL30(payload)
   312				} else {
   313					payload, paddingGood = removePadding(payload)
   314				}
   315				b.resize(recordHeaderLen + explicitIVLen + len(payload))
   316	
   317				// note that we still have a timing side-channel in the
   318				// MAC check, below. An attacker can align the record
   319				// so that a correct padding will cause one less hash
   320				// block to be calculated. Then they can iteratively
   321				// decrypt a record by breaking each byte. See
   322				// "Password Interception in a SSL/TLS Channel", Brice
   323				// Canvel et al.
   324				//
   325				// However, our behavior matches OpenSSL, so we leak
   326				// only as much as they do.
   327			default:
   328				panic("unknown cipher type")
   329			}
   330		}
   331	
   332		// check, strip mac
   333		if hc.mac != nil {
   334			if len(payload) < macSize {
   335				return false, 0, alertBadRecordMAC
   336			}
   337	
   338			// strip mac off payload, b.data
   339			n := len(payload) - macSize
   340			b.data[3] = byte(n >> 8)
   341			b.data[4] = byte(n)
   342			b.resize(recordHeaderLen + explicitIVLen + n)
   343			remoteMAC := payload[n:]
   344			localMAC := hc.mac.MAC(hc.inDigestBuf, hc.seq[0:], b.data[:recordHeaderLen], payload[:n])
   345	
   346			if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
   347				return false, 0, alertBadRecordMAC
   348			}
   349			hc.inDigestBuf = localMAC
   350		}
   351		hc.incSeq()
   352	
   353		return true, recordHeaderLen + explicitIVLen, 0
   354	}
   355	
   356	// padToBlockSize calculates the needed padding block, if any, for a payload.
   357	// On exit, prefix aliases payload and extends to the end of the last full
   358	// block of payload. finalBlock is a fresh slice which contains the contents of
   359	// any suffix of payload as well as the needed padding to make finalBlock a
   360	// full block.
   361	func padToBlockSize(payload []byte, blockSize int) (prefix, finalBlock []byte) {
   362		overrun := len(payload) % blockSize
   363		paddingLen := blockSize - overrun
   364		prefix = payload[:len(payload)-overrun]
   365		finalBlock = make([]byte, blockSize)
   366		copy(finalBlock, payload[len(payload)-overrun:])
   367		for i := overrun; i < blockSize; i++ {
   368			finalBlock[i] = byte(paddingLen - 1)
   369		}
   370		return
   371	}
   372	
   373	// encrypt encrypts and macs the data in b.
   374	func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) {
   375		// mac
   376		if hc.mac != nil {
   377			mac := hc.mac.MAC(hc.outDigestBuf, hc.seq[0:], b.data[:recordHeaderLen], b.data[recordHeaderLen+explicitIVLen:])
   378	
   379			n := len(b.data)
   380			b.resize(n + len(mac))
   381			copy(b.data[n:], mac)
   382			hc.outDigestBuf = mac
   383		}
   384	
   385		payload := b.data[recordHeaderLen:]
   386	
   387		// encrypt
   388		if hc.cipher != nil {
   389			switch c := hc.cipher.(type) {
   390			case cipher.Stream:
   391				c.XORKeyStream(payload, payload)
   392			case cipher.AEAD:
   393				payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
   394				b.resize(len(b.data) + c.Overhead())
   395				nonce := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
   396				payload := b.data[recordHeaderLen+explicitIVLen:]
   397				payload = payload[:payloadLen]
   398	
   399				copy(hc.additionalData[:], hc.seq[:])
   400				copy(hc.additionalData[8:], b.data[:3])
   401				hc.additionalData[11] = byte(payloadLen >> 8)
   402				hc.additionalData[12] = byte(payloadLen)
   403	
   404				c.Seal(payload[:0], nonce, payload, hc.additionalData[:])
   405			case cbcMode:
   406				blockSize := c.BlockSize()
   407				if explicitIVLen > 0 {
   408					c.SetIV(payload[:explicitIVLen])
   409					payload = payload[explicitIVLen:]
   410				}
   411				prefix, finalBlock := padToBlockSize(payload, blockSize)
   412				b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
   413				c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
   414				c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
   415			default:
   416				panic("unknown cipher type")
   417			}
   418		}
   419	
   420		// update length to include MAC and any block padding needed.
   421		n := len(b.data) - recordHeaderLen
   422		b.data[3] = byte(n >> 8)
   423		b.data[4] = byte(n)
   424		hc.incSeq()
   425	
   426		return true, 0
   427	}
   428	
   429	// A block is a simple data buffer.
   430	type block struct {
   431		data []byte
   432		off  int // index for Read
   433		link *block
   434	}
   435	
   436	// resize resizes block to be n bytes, growing if necessary.
   437	func (b *block) resize(n int) {
   438		if n > cap(b.data) {
   439			b.reserve(n)
   440		}
   441		b.data = b.data[0:n]
   442	}
   443	
   444	// reserve makes sure that block contains a capacity of at least n bytes.
   445	func (b *block) reserve(n int) {
   446		if cap(b.data) >= n {
   447			return
   448		}
   449		m := cap(b.data)
   450		if m == 0 {
   451			m = 1024
   452		}
   453		for m < n {
   454			m *= 2
   455		}
   456		data := make([]byte, len(b.data), m)
   457		copy(data, b.data)
   458		b.data = data
   459	}
   460	
   461	// readFromUntil reads from r into b until b contains at least n bytes
   462	// or else returns an error.
   463	func (b *block) readFromUntil(r io.Reader, n int) error {
   464		// quick case
   465		if len(b.data) >= n {
   466			return nil
   467		}
   468	
   469		// read until have enough.
   470		b.reserve(n)
   471		for {
   472			m, err := r.Read(b.data[len(b.data):cap(b.data)])
   473			b.data = b.data[0 : len(b.data)+m]
   474			if len(b.data) >= n {
   475				// TODO(bradfitz,agl): slightly suspicious
   476				// that we're throwing away r.Read's err here.
   477				break
   478			}
   479			if err != nil {
   480				return err
   481			}
   482		}
   483		return nil
   484	}
   485	
   486	func (b *block) Read(p []byte) (n int, err error) {
   487		n = copy(p, b.data[b.off:])
   488		b.off += n
   489		return
   490	}
   491	
   492	// newBlock allocates a new block, from hc's free list if possible.
   493	func (hc *halfConn) newBlock() *block {
   494		b := hc.bfree
   495		if b == nil {
   496			return new(block)
   497		}
   498		hc.bfree = b.link
   499		b.link = nil
   500		b.resize(0)
   501		return b
   502	}
   503	
   504	// freeBlock returns a block to hc's free list.
   505	// The protocol is such that each side only has a block or two on
   506	// its free list at a time, so there's no need to worry about
   507	// trimming the list, etc.
   508	func (hc *halfConn) freeBlock(b *block) {
   509		b.link = hc.bfree
   510		hc.bfree = b
   511	}
   512	
   513	// splitBlock splits a block after the first n bytes,
   514	// returning a block with those n bytes and a
   515	// block with the remainder.  the latter may be nil.
   516	func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
   517		if len(b.data) <= n {
   518			return b, nil
   519		}
   520		bb := hc.newBlock()
   521		bb.resize(len(b.data) - n)
   522		copy(bb.data, b.data[n:])
   523		b.data = b.data[0:n]
   524		return b, bb
   525	}
   526	
   527	// RecordHeaderError results when a TLS record header is invalid.
   528	type RecordHeaderError struct {
   529		// Msg contains a human readable string that describes the error.
   530		Msg string
   531		// RecordHeader contains the five bytes of TLS record header that
   532		// triggered the error.
   533		RecordHeader [5]byte
   534	}
   535	
   536	func (e RecordHeaderError) Error() string { return "tls: " + e.Msg }
   537	
   538	func (c *Conn) newRecordHeaderError(msg string) (err RecordHeaderError) {
   539		err.Msg = msg
   540		copy(err.RecordHeader[:], c.rawInput.data)
   541		return err
   542	}
   543	
   544	// readRecord reads the next TLS record from the connection
   545	// and updates the record layer state.
   546	// c.in.Mutex <= L; c.input == nil.
   547	func (c *Conn) readRecord(want recordType) error {
   548		// Caller must be in sync with connection:
   549		// handshake data if handshake not yet completed,
   550		// else application data.
   551		switch want {
   552		default:
   553			c.sendAlert(alertInternalError)
   554			return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
   555		case recordTypeHandshake, recordTypeChangeCipherSpec:
   556			if c.handshakeComplete {
   557				c.sendAlert(alertInternalError)
   558				return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested while not in handshake"))
   559			}
   560		case recordTypeApplicationData:
   561			if !c.handshakeComplete {
   562				c.sendAlert(alertInternalError)
   563				return c.in.setErrorLocked(errors.New("tls: application data record requested while in handshake"))
   564			}
   565		}
   566	
   567	Again:
   568		if c.rawInput == nil {
   569			c.rawInput = c.in.newBlock()
   570		}
   571		b := c.rawInput
   572	
   573		// Read header, payload.
   574		if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
   575			// RFC suggests that EOF without an alertCloseNotify is
   576			// an error, but popular web sites seem to do this,
   577			// so we can't make it an error.
   578			// if err == io.EOF {
   579			// 	err = io.ErrUnexpectedEOF
   580			// }
   581			if e, ok := err.(net.Error); !ok || !e.Temporary() {
   582				c.in.setErrorLocked(err)
   583			}
   584			return err
   585		}
   586		typ := recordType(b.data[0])
   587	
   588		// No valid TLS record has a type of 0x80, however SSLv2 handshakes
   589		// start with a uint16 length where the MSB is set and the first record
   590		// is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
   591		// an SSLv2 client.
   592		if want == recordTypeHandshake && typ == 0x80 {
   593			c.sendAlert(alertProtocolVersion)
   594			return c.in.setErrorLocked(c.newRecordHeaderError("unsupported SSLv2 handshake received"))
   595		}
   596	
   597		vers := uint16(b.data[1])<<8 | uint16(b.data[2])
   598		n := int(b.data[3])<<8 | int(b.data[4])
   599		if c.haveVers && vers != c.vers {
   600			c.sendAlert(alertProtocolVersion)
   601			msg := fmt.Sprintf("received record with version %x when expecting version %x", vers, c.vers)
   602			return c.in.setErrorLocked(c.newRecordHeaderError(msg))
   603		}
   604		if n > maxCiphertext {
   605			c.sendAlert(alertRecordOverflow)
   606			msg := fmt.Sprintf("oversized record received with length %d", n)
   607			return c.in.setErrorLocked(c.newRecordHeaderError(msg))
   608		}
   609		if !c.haveVers {
   610			// First message, be extra suspicious: this might not be a TLS
   611			// client. Bail out before reading a full 'body', if possible.
   612			// The current max version is 3.3 so if the version is >= 16.0,
   613			// it's probably not real.
   614			if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 {
   615				c.sendAlert(alertUnexpectedMessage)
   616				return c.in.setErrorLocked(c.newRecordHeaderError("first record does not look like a TLS handshake"))
   617			}
   618		}
   619		if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
   620			if err == io.EOF {
   621				err = io.ErrUnexpectedEOF
   622			}
   623			if e, ok := err.(net.Error); !ok || !e.Temporary() {
   624				c.in.setErrorLocked(err)
   625			}
   626			return err
   627		}
   628	
   629		// Process message.
   630		b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
   631		ok, off, err := c.in.decrypt(b)
   632		if !ok {
   633			c.in.setErrorLocked(c.sendAlert(err))
   634		}
   635		b.off = off
   636		data := b.data[b.off:]
   637		if len(data) > maxPlaintext {
   638			err := c.sendAlert(alertRecordOverflow)
   639			c.in.freeBlock(b)
   640			return c.in.setErrorLocked(err)
   641		}
   642	
   643		switch typ {
   644		default:
   645			c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   646	
   647		case recordTypeAlert:
   648			if len(data) != 2 {
   649				c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   650				break
   651			}
   652			if alert(data[1]) == alertCloseNotify {
   653				c.in.setErrorLocked(io.EOF)
   654				break
   655			}
   656			switch data[0] {
   657			case alertLevelWarning:
   658				// drop on the floor
   659				c.in.freeBlock(b)
   660				goto Again
   661			case alertLevelError:
   662				c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
   663			default:
   664				c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   665			}
   666	
   667		case recordTypeChangeCipherSpec:
   668			if typ != want || len(data) != 1 || data[0] != 1 {
   669				c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   670				break
   671			}
   672			err := c.in.changeCipherSpec()
   673			if err != nil {
   674				c.in.setErrorLocked(c.sendAlert(err.(alert)))
   675			}
   676	
   677		case recordTypeApplicationData:
   678			if typ != want {
   679				c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   680				break
   681			}
   682			c.input = b
   683			b = nil
   684	
   685		case recordTypeHandshake:
   686			// TODO(rsc): Should at least pick off connection close.
   687			if typ != want && !(c.isClient && c.config.Renegotiation != RenegotiateNever) {
   688				return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
   689			}
   690			c.hand.Write(data)
   691		}
   692	
   693		if b != nil {
   694			c.in.freeBlock(b)
   695		}
   696		return c.in.err
   697	}
   698	
   699	// sendAlert sends a TLS alert message.
   700	// c.out.Mutex <= L.
   701	func (c *Conn) sendAlertLocked(err alert) error {
   702		switch err {
   703		case alertNoRenegotiation, alertCloseNotify:
   704			c.tmp[0] = alertLevelWarning
   705		default:
   706			c.tmp[0] = alertLevelError
   707		}
   708		c.tmp[1] = byte(err)
   709	
   710		_, writeErr := c.writeRecordLocked(recordTypeAlert, c.tmp[0:2])
   711		if err == alertCloseNotify {
   712			// closeNotify is a special case in that it isn't an error.
   713			return writeErr
   714		}
   715	
   716		return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
   717	}
   718	
   719	// sendAlert sends a TLS alert message.
   720	// L < c.out.Mutex.
   721	func (c *Conn) sendAlert(err alert) error {
   722		c.out.Lock()
   723		defer c.out.Unlock()
   724		return c.sendAlertLocked(err)
   725	}
   726	
   727	const (
   728		// tcpMSSEstimate is a conservative estimate of the TCP maximum segment
   729		// size (MSS). A constant is used, rather than querying the kernel for
   730		// the actual MSS, to avoid complexity. The value here is the IPv6
   731		// minimum MTU (1280 bytes) minus the overhead of an IPv6 header (40
   732		// bytes) and a TCP header with timestamps (32 bytes).
   733		tcpMSSEstimate = 1208
   734	
   735		// recordSizeBoostThreshold is the number of bytes of application data
   736		// sent after which the TLS record size will be increased to the
   737		// maximum.
   738		recordSizeBoostThreshold = 128 * 1024
   739	)
   740	
   741	// maxPayloadSizeForWrite returns the maximum TLS payload size to use for the
   742	// next application data record. There is the following trade-off:
   743	//
   744	//   - For latency-sensitive applications, such as web browsing, each TLS
   745	//     record should fit in one TCP segment.
   746	//   - For throughput-sensitive applications, such as large file transfers,
   747	//     larger TLS records better amortize framing and encryption overheads.
   748	//
   749	// A simple heuristic that works well in practice is to use small records for
   750	// the first 1MB of data, then use larger records for subsequent data, and
   751	// reset back to smaller records after the connection becomes idle. See "High
   752	// Performance Web Networking", Chapter 4, or:
   753	// https://www.igvita.com/2013/10/24/optimizing-tls-record-size-and-buffering-latency/
   754	//
   755	// In the interests of simplicity and determinism, this code does not attempt
   756	// to reset the record size once the connection is idle, however.
   757	//
   758	// c.out.Mutex <= L.
   759	func (c *Conn) maxPayloadSizeForWrite(typ recordType, explicitIVLen int) int {
   760		if c.config.DynamicRecordSizingDisabled || typ != recordTypeApplicationData {
   761			return maxPlaintext
   762		}
   763	
   764		if c.bytesSent >= recordSizeBoostThreshold {
   765			return maxPlaintext
   766		}
   767	
   768		// Subtract TLS overheads to get the maximum payload size.
   769		macSize := 0
   770		if c.out.mac != nil {
   771			macSize = c.out.mac.Size()
   772		}
   773	
   774		payloadBytes := tcpMSSEstimate - recordHeaderLen - explicitIVLen
   775		if c.out.cipher != nil {
   776			switch ciph := c.out.cipher.(type) {
   777			case cipher.Stream:
   778				payloadBytes -= macSize
   779			case cipher.AEAD:
   780				payloadBytes -= ciph.Overhead()
   781			case cbcMode:
   782				blockSize := ciph.BlockSize()
   783				// The payload must fit in a multiple of blockSize, with
   784				// room for at least one padding byte.
   785				payloadBytes = (payloadBytes & ^(blockSize - 1)) - 1
   786				// The MAC is appended before padding so affects the
   787				// payload size directly.
   788				payloadBytes -= macSize
   789			default:
   790				panic("unknown cipher type")
   791			}
   792		}
   793	
   794		// Allow packet growth in arithmetic progression up to max.
   795		pkt := c.packetsSent
   796		c.packetsSent++
   797		if pkt > 1000 {
   798			return maxPlaintext // avoid overflow in multiply below
   799		}
   800	
   801		n := payloadBytes * int(pkt+1)
   802		if n > maxPlaintext {
   803			n = maxPlaintext
   804		}
   805		return n
   806	}
   807	
   808	// c.out.Mutex <= L.
   809	func (c *Conn) write(data []byte) (int, error) {
   810		if c.buffering {
   811			c.sendBuf = append(c.sendBuf, data...)
   812			return len(data), nil
   813		}
   814	
   815		n, err := c.conn.Write(data)
   816		c.bytesSent += int64(n)
   817		return n, err
   818	}
   819	
   820	func (c *Conn) flush() (int, error) {
   821		if len(c.sendBuf) == 0 {
   822			return 0, nil
   823		}
   824	
   825		n, err := c.conn.Write(c.sendBuf)
   826		c.bytesSent += int64(n)
   827		c.sendBuf = nil
   828		c.buffering = false
   829		return n, err
   830	}
   831	
   832	// writeRecordLocked writes a TLS record with the given type and payload to the
   833	// connection and updates the record layer state.
   834	// c.out.Mutex <= L.
   835	func (c *Conn) writeRecordLocked(typ recordType, data []byte) (int, error) {
   836		b := c.out.newBlock()
   837		defer c.out.freeBlock(b)
   838	
   839		var n int
   840		for len(data) > 0 {
   841			explicitIVLen := 0
   842			explicitIVIsSeq := false
   843	
   844			var cbc cbcMode
   845			if c.out.version >= VersionTLS11 {
   846				var ok bool
   847				if cbc, ok = c.out.cipher.(cbcMode); ok {
   848					explicitIVLen = cbc.BlockSize()
   849				}
   850			}
   851			if explicitIVLen == 0 {
   852				if _, ok := c.out.cipher.(cipher.AEAD); ok {
   853					explicitIVLen = 8
   854					// The AES-GCM construction in TLS has an
   855					// explicit nonce so that the nonce can be
   856					// random. However, the nonce is only 8 bytes
   857					// which is too small for a secure, random
   858					// nonce. Therefore we use the sequence number
   859					// as the nonce.
   860					explicitIVIsSeq = true
   861				}
   862			}
   863			m := len(data)
   864			if maxPayload := c.maxPayloadSizeForWrite(typ, explicitIVLen); m > maxPayload {
   865				m = maxPayload
   866			}
   867			b.resize(recordHeaderLen + explicitIVLen + m)
   868			b.data[0] = byte(typ)
   869			vers := c.vers
   870			if vers == 0 {
   871				// Some TLS servers fail if the record version is
   872				// greater than TLS 1.0 for the initial ClientHello.
   873				vers = VersionTLS10
   874			}
   875			b.data[1] = byte(vers >> 8)
   876			b.data[2] = byte(vers)
   877			b.data[3] = byte(m >> 8)
   878			b.data[4] = byte(m)
   879			if explicitIVLen > 0 {
   880				explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
   881				if explicitIVIsSeq {
   882					copy(explicitIV, c.out.seq[:])
   883				} else {
   884					if _, err := io.ReadFull(c.config.rand(), explicitIV); err != nil {
   885						return n, err
   886					}
   887				}
   888			}
   889			copy(b.data[recordHeaderLen+explicitIVLen:], data)
   890			c.out.encrypt(b, explicitIVLen)
   891			if _, err := c.write(b.data); err != nil {
   892				return n, err
   893			}
   894			n += m
   895			data = data[m:]
   896		}
   897	
   898		if typ == recordTypeChangeCipherSpec {
   899			if err := c.out.changeCipherSpec(); err != nil {
   900				return n, c.sendAlertLocked(err.(alert))
   901			}
   902		}
   903	
   904		return n, nil
   905	}
   906	
   907	// writeRecord writes a TLS record with the given type and payload to the
   908	// connection and updates the record layer state.
   909	// L < c.out.Mutex.
   910	func (c *Conn) writeRecord(typ recordType, data []byte) (int, error) {
   911		c.out.Lock()
   912		defer c.out.Unlock()
   913	
   914		return c.writeRecordLocked(typ, data)
   915	}
   916	
   917	// readHandshake reads the next handshake message from
   918	// the record layer.
   919	// c.in.Mutex < L; c.out.Mutex < L.
   920	func (c *Conn) readHandshake() (interface{}, error) {
   921		for c.hand.Len() < 4 {
   922			if err := c.in.err; err != nil {
   923				return nil, err
   924			}
   925			if err := c.readRecord(recordTypeHandshake); err != nil {
   926				return nil, err
   927			}
   928		}
   929	
   930		data := c.hand.Bytes()
   931		n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
   932		if n > maxHandshake {
   933			c.sendAlertLocked(alertInternalError)
   934			return nil, c.in.setErrorLocked(fmt.Errorf("tls: handshake message of length %d bytes exceeds maximum of %d bytes", n, maxHandshake))
   935		}
   936		for c.hand.Len() < 4+n {
   937			if err := c.in.err; err != nil {
   938				return nil, err
   939			}
   940			if err := c.readRecord(recordTypeHandshake); err != nil {
   941				return nil, err
   942			}
   943		}
   944		data = c.hand.Next(4 + n)
   945		var m handshakeMessage
   946		switch data[0] {
   947		case typeHelloRequest:
   948			m = new(helloRequestMsg)
   949		case typeClientHello:
   950			m = new(clientHelloMsg)
   951		case typeServerHello:
   952			m = new(serverHelloMsg)
   953		case typeNewSessionTicket:
   954			m = new(newSessionTicketMsg)
   955		case typeCertificate:
   956			m = new(certificateMsg)
   957		case typeCertificateRequest:
   958			m = &certificateRequestMsg{
   959				hasSignatureAndHash: c.vers >= VersionTLS12,
   960			}
   961		case typeCertificateStatus:
   962			m = new(certificateStatusMsg)
   963		case typeServerKeyExchange:
   964			m = new(serverKeyExchangeMsg)
   965		case typeServerHelloDone:
   966			m = new(serverHelloDoneMsg)
   967		case typeClientKeyExchange:
   968			m = new(clientKeyExchangeMsg)
   969		case typeCertificateVerify:
   970			m = &certificateVerifyMsg{
   971				hasSignatureAndHash: c.vers >= VersionTLS12,
   972			}
   973		case typeNextProtocol:
   974			m = new(nextProtoMsg)
   975		case typeFinished:
   976			m = new(finishedMsg)
   977		default:
   978			return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   979		}
   980	
   981		// The handshake message unmarshallers
   982		// expect to be able to keep references to data,
   983		// so pass in a fresh copy that won't be overwritten.
   984		data = append([]byte(nil), data...)
   985	
   986		if !m.unmarshal(data) {
   987			return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   988		}
   989		return m, nil
   990	}
   991	
   992	var errClosed = errors.New("tls: use of closed connection")
   993	
   994	// Write writes data to the connection.
   995	func (c *Conn) Write(b []byte) (int, error) {
   996		// interlock with Close below
   997		for {
   998			x := atomic.LoadInt32(&c.activeCall)
   999			if x&1 != 0 {
  1000				return 0, errClosed
  1001			}
  1002			if atomic.CompareAndSwapInt32(&c.activeCall, x, x+2) {
  1003				defer atomic.AddInt32(&c.activeCall, -2)
  1004				break
  1005			}
  1006		}
  1007	
  1008		if err := c.Handshake(); err != nil {
  1009			return 0, err
  1010		}
  1011	
  1012		c.out.Lock()
  1013		defer c.out.Unlock()
  1014	
  1015		if err := c.out.err; err != nil {
  1016			return 0, err
  1017		}
  1018	
  1019		if !c.handshakeComplete {
  1020			return 0, alertInternalError
  1021		}
  1022	
  1023		// SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
  1024		// attack when using block mode ciphers due to predictable IVs.
  1025		// This can be prevented by splitting each Application Data
  1026		// record into two records, effectively randomizing the IV.
  1027		//
  1028		// http://www.openssl.org/~bodo/tls-cbc.txt
  1029		// https://bugzilla.mozilla.org/show_bug.cgi?id=665814
  1030		// http://www.imperialviolet.org/2012/01/15/beastfollowup.html
  1031	
  1032		var m int
  1033		if len(b) > 1 && c.vers <= VersionTLS10 {
  1034			if _, ok := c.out.cipher.(cipher.BlockMode); ok {
  1035				n, err := c.writeRecordLocked(recordTypeApplicationData, b[:1])
  1036				if err != nil {
  1037					return n, c.out.setErrorLocked(err)
  1038				}
  1039				m, b = 1, b[1:]
  1040			}
  1041		}
  1042	
  1043		n, err := c.writeRecordLocked(recordTypeApplicationData, b)
  1044		return n + m, c.out.setErrorLocked(err)
  1045	}
  1046	
  1047	// handleRenegotiation processes a HelloRequest handshake message.
  1048	// c.in.Mutex <= L
  1049	func (c *Conn) handleRenegotiation() error {
  1050		msg, err := c.readHandshake()
  1051		if err != nil {
  1052			return err
  1053		}
  1054	
  1055		_, ok := msg.(*helloRequestMsg)
  1056		if !ok {
  1057			c.sendAlert(alertUnexpectedMessage)
  1058			return alertUnexpectedMessage
  1059		}
  1060	
  1061		if !c.isClient {
  1062			return c.sendAlert(alertNoRenegotiation)
  1063		}
  1064	
  1065		switch c.config.Renegotiation {
  1066		case RenegotiateNever:
  1067			return c.sendAlert(alertNoRenegotiation)
  1068		case RenegotiateOnceAsClient:
  1069			if c.handshakes > 1 {
  1070				return c.sendAlert(alertNoRenegotiation)
  1071			}
  1072		case RenegotiateFreelyAsClient:
  1073			// Ok.
  1074		default:
  1075			c.sendAlert(alertInternalError)
  1076			return errors.New("tls: unknown Renegotiation value")
  1077		}
  1078	
  1079		c.handshakeMutex.Lock()
  1080		defer c.handshakeMutex.Unlock()
  1081	
  1082		c.handshakeComplete = false
  1083		if c.handshakeErr = c.clientHandshake(); c.handshakeErr == nil {
  1084			c.handshakes++
  1085		}
  1086		return c.handshakeErr
  1087	}
  1088	
  1089	// Read can be made to time out and return a net.Error with Timeout() == true
  1090	// after a fixed time limit; see SetDeadline and SetReadDeadline.
  1091	func (c *Conn) Read(b []byte) (n int, err error) {
  1092		if err = c.Handshake(); err != nil {
  1093			return
  1094		}
  1095		if len(b) == 0 {
  1096			// Put this after Handshake, in case people were calling
  1097			// Read(nil) for the side effect of the Handshake.
  1098			return
  1099		}
  1100	
  1101		c.in.Lock()
  1102		defer c.in.Unlock()
  1103	
  1104		// Some OpenSSL servers send empty records in order to randomize the
  1105		// CBC IV. So this loop ignores a limited number of empty records.
  1106		const maxConsecutiveEmptyRecords = 100
  1107		for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
  1108			for c.input == nil && c.in.err == nil {
  1109				if err := c.readRecord(recordTypeApplicationData); err != nil {
  1110					// Soft error, like EAGAIN
  1111					return 0, err
  1112				}
  1113				if c.hand.Len() > 0 {
  1114					// We received handshake bytes, indicating the
  1115					// start of a renegotiation.
  1116					if err := c.handleRenegotiation(); err != nil {
  1117						return 0, err
  1118					}
  1119				}
  1120			}
  1121			if err := c.in.err; err != nil {
  1122				return 0, err
  1123			}
  1124	
  1125			n, err = c.input.Read(b)
  1126			if c.input.off >= len(c.input.data) {
  1127				c.in.freeBlock(c.input)
  1128				c.input = nil
  1129			}
  1130	
  1131			// If a close-notify alert is waiting, read it so that
  1132			// we can return (n, EOF) instead of (n, nil), to signal
  1133			// to the HTTP response reading goroutine that the
  1134			// connection is now closed. This eliminates a race
  1135			// where the HTTP response reading goroutine would
  1136			// otherwise not observe the EOF until its next read,
  1137			// by which time a client goroutine might have already
  1138			// tried to reuse the HTTP connection for a new
  1139			// request.
  1140			// See https://codereview.appspot.com/76400046
  1141			// and https://golang.org/issue/3514
  1142			if ri := c.rawInput; ri != nil &&
  1143				n != 0 && err == nil &&
  1144				c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
  1145				if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
  1146					err = recErr // will be io.EOF on closeNotify
  1147				}
  1148			}
  1149	
  1150			if n != 0 || err != nil {
  1151				return n, err
  1152			}
  1153		}
  1154	
  1155		return 0, io.ErrNoProgress
  1156	}
  1157	
  1158	// Close closes the connection.
  1159	func (c *Conn) Close() error {
  1160		// Interlock with Conn.Write above.
  1161		var x int32
  1162		for {
  1163			x = atomic.LoadInt32(&c.activeCall)
  1164			if x&1 != 0 {
  1165				return errClosed
  1166			}
  1167			if atomic.CompareAndSwapInt32(&c.activeCall, x, x|1) {
  1168				break
  1169			}
  1170		}
  1171		if x != 0 {
  1172			// io.Writer and io.Closer should not be used concurrently.
  1173			// If Close is called while a Write is currently in-flight,
  1174			// interpret that as a sign that this Close is really just
  1175			// being used to break the Write and/or clean up resources and
  1176			// avoid sending the alertCloseNotify, which may block
  1177			// waiting on handshakeMutex or the c.out mutex.
  1178			return c.conn.Close()
  1179		}
  1180	
  1181		var alertErr error
  1182	
  1183		c.handshakeMutex.Lock()
  1184		defer c.handshakeMutex.Unlock()
  1185		if c.handshakeComplete {
  1186			alertErr = c.sendAlert(alertCloseNotify)
  1187		}
  1188	
  1189		if err := c.conn.Close(); err != nil {
  1190			return err
  1191		}
  1192		return alertErr
  1193	}
  1194	
  1195	// Handshake runs the client or server handshake
  1196	// protocol if it has not yet been run.
  1197	// Most uses of this package need not call Handshake
  1198	// explicitly: the first Read or Write will call it automatically.
  1199	func (c *Conn) Handshake() error {
  1200		// c.handshakeErr and c.handshakeComplete are protected by
  1201		// c.handshakeMutex. In order to perform a handshake, we need to lock
  1202		// c.in also and c.handshakeMutex must be locked after c.in.
  1203		//
  1204		// However, if a Read() operation is hanging then it'll be holding the
  1205		// lock on c.in and so taking it here would cause all operations that
  1206		// need to check whether a handshake is pending (such as Write) to
  1207		// block.
  1208		//
  1209		// Thus we take c.handshakeMutex first and, if we find that a handshake
  1210		// is needed, then we unlock, acquire c.in and c.handshakeMutex in the
  1211		// correct order, and check again.
  1212		c.handshakeMutex.Lock()
  1213		defer c.handshakeMutex.Unlock()
  1214	
  1215		for i := 0; i < 2; i++ {
  1216			if i == 1 {
  1217				c.handshakeMutex.Unlock()
  1218				c.in.Lock()
  1219				defer c.in.Unlock()
  1220				c.handshakeMutex.Lock()
  1221			}
  1222	
  1223			if err := c.handshakeErr; err != nil {
  1224				return err
  1225			}
  1226			if c.handshakeComplete {
  1227				return nil
  1228			}
  1229		}
  1230	
  1231		if c.isClient {
  1232			c.handshakeErr = c.clientHandshake()
  1233		} else {
  1234			c.handshakeErr = c.serverHandshake()
  1235		}
  1236		if c.handshakeErr == nil {
  1237			c.handshakes++
  1238		}
  1239		return c.handshakeErr
  1240	}
  1241	
  1242	// ConnectionState returns basic TLS details about the connection.
  1243	func (c *Conn) ConnectionState() ConnectionState {
  1244		c.handshakeMutex.Lock()
  1245		defer c.handshakeMutex.Unlock()
  1246	
  1247		var state ConnectionState
  1248		state.HandshakeComplete = c.handshakeComplete
  1249		if c.handshakeComplete {
  1250			state.Version = c.vers
  1251			state.NegotiatedProtocol = c.clientProtocol
  1252			state.DidResume = c.didResume
  1253			state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
  1254			state.CipherSuite = c.cipherSuite
  1255			state.PeerCertificates = c.peerCertificates
  1256			state.VerifiedChains = c.verifiedChains
  1257			state.ServerName = c.serverName
  1258			state.SignedCertificateTimestamps = c.scts
  1259			state.OCSPResponse = c.ocspResponse
  1260			if !c.didResume {
  1261				if c.clientFinishedIsFirst {
  1262					state.TLSUnique = c.clientFinished[:]
  1263				} else {
  1264					state.TLSUnique = c.serverFinished[:]
  1265				}
  1266			}
  1267		}
  1268	
  1269		return state
  1270	}
  1271	
  1272	// OCSPResponse returns the stapled OCSP response from the TLS server, if
  1273	// any. (Only valid for client connections.)
  1274	func (c *Conn) OCSPResponse() []byte {
  1275		c.handshakeMutex.Lock()
  1276		defer c.handshakeMutex.Unlock()
  1277	
  1278		return c.ocspResponse
  1279	}
  1280	
  1281	// VerifyHostname checks that the peer certificate chain is valid for
  1282	// connecting to host. If so, it returns nil; if not, it returns an error
  1283	// describing the problem.
  1284	func (c *Conn) VerifyHostname(host string) error {
  1285		c.handshakeMutex.Lock()
  1286		defer c.handshakeMutex.Unlock()
  1287		if !c.isClient {
  1288			return errors.New("tls: VerifyHostname called on TLS server connection")
  1289		}
  1290		if !c.handshakeComplete {
  1291			return errors.New("tls: handshake has not yet been performed")
  1292		}
  1293		if len(c.verifiedChains) == 0 {
  1294			return errors.New("tls: handshake did not verify certificate chain")
  1295		}
  1296		return c.peerCertificates[0].VerifyHostname(host)
  1297	}
  1298	

View as plain text