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

View as plain text