github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/gmtls/conn.go (about)

     1  // Copyright 2022 s1ren@github.com/hxx258456.
     2  
     3  /*
     4  gmtls是基于`golang/go`的`tls`包实现的国密改造版本。
     5  对应版权声明: thrid_licenses/github.com/golang/go/LICENSE
     6  */
     7  
     8  // TLS low level connection and record layer
     9  
    10  package gmtls
    11  
    12  import (
    13  	"bytes"
    14  	"context"
    15  	"crypto/cipher"
    16  	"crypto/subtle"
    17  	"errors"
    18  	"fmt"
    19  	"hash"
    20  	"io"
    21  	"net"
    22  	"sync"
    23  	"sync/atomic"
    24  	"time"
    25  
    26  	"gitee.com/zhaochuninhefei/zcgolog/zclog"
    27  	"github.com/hxx258456/ccgo/x509"
    28  )
    29  
    30  // Conn tls安全连接定义, 实现`net.Conn`接口
    31  // A Conn represents a secured connection.
    32  // It implements the net.Conn interface.
    33  type Conn struct {
    34  	// constant
    35  	conn        net.Conn
    36  	isClient    bool
    37  	handshakeFn func(context.Context) error // (*Conn).clientHandshake or serverHandshake
    38  
    39  	// handshakeStatus为1时代表正在传输应用数据,即当前不在握手阶段。
    40  	// 即一个连接要么处于握手阶段(handshakeStatus != 1),要么处于握手成功后的传输应用数据阶段(handshakeStatus == 1)。
    41  	// 该状态值的读写是同步原子操作。
    42  	// handshakeStatus is 1 if the connection is currently transferring
    43  	// application data (i.e. is not currently processing a handshake).
    44  	// This field is only to be accessed with sync/atomic.
    45  	handshakeStatus uint32
    46  	// constant after handshake; protected by handshakeMutex
    47  	handshakeMutex sync.Mutex
    48  	handshakeErr   error   // error resulting from handshake
    49  	vers           uint16  // TLS version
    50  	haveVers       bool    // 版本已协商
    51  	config         *Config // configuration passed to constructor
    52  
    53  	// 该连接到目前为止执行的握手次数,如果renegotiation被禁止,则该值只能是0或1。
    54  	// handshakes counts the number of handshakes performed on the
    55  	// connection so far. If renegotiation is disabled then this is either
    56  	// zero or one.
    57  	handshakes       int
    58  	didResume        bool     // 此连接是否是会话恢复
    59  	cipherSuite      uint16   // 该连接使用的密码套件
    60  	ocspResponse     []byte   // 装订的 OCSP 响应, 由服务端提供给客户端用于检查证书是否已撤销
    61  	scts             [][]byte // signed certificate timestamps from server
    62  	peerCertificates []*x509.Certificate
    63  
    64  	// verifiedChains是连接握手过程中构建的经过验证的证书链,而非服务端提供的证书链。
    65  	// verifiedChains contains the certificate chains that we built, as
    66  	// opposed to the ones presented by the server.
    67  	verifiedChains [][]*x509.Certificate
    68  	// serverName contains the server name indicated by the client, if any.
    69  	serverName string
    70  	// 安全重协商?
    71  	// secureRenegotiation is true if the server echoed the secure
    72  	// renegotiation extension. (This is meaningless as a server because
    73  	// renegotiation is not supported in that case.)
    74  	secureRenegotiation bool
    75  	// ekm是一个用于导出密钥材料的闭包函数
    76  	// ekm is a closure for exporting keying material.
    77  	ekm func(label string, context []byte, length int) ([]byte, error)
    78  	// 处理NewSessionTicket消息时的回复主密钥
    79  	// resumptionSecret is the resumption_master_secret for handling
    80  	// NewSessionTicket messages. nil if config.SessionTicketsDisabled.
    81  	resumptionSecret []byte
    82  
    83  	// ticketKeys 是此连接的一组活动会话票证密钥。
    84  	// 第一个用于加密新票证,并尝试全部解密票证。
    85  	// ticketKeys is the set of active session ticket keys for this
    86  	// connection. The first one is used to encrypt new tickets and
    87  	// all are tried to decrypt tickets.
    88  	ticketKeys []ticketKey
    89  
    90  	// 客户端在最近一次握手中发送的Finished消息是否该连接到目前为止的首次Finished。
    91  	// 首次Finished消息是 tls-unique 通道绑定值。
    92  	// clientFinishedIsFirst is true if the client sent the first Finished
    93  	// message during the most recent handshake. This is recorded because
    94  	// the first transmitted Finished message is the tls-unique
    95  	// channel-binding value.
    96  	clientFinishedIsFirst bool
    97  
    98  	// closeNotifyErr is any error from sending the alertCloseNotify record.
    99  	closeNotifyErr error
   100  	// closeNotifySent is true if the Conn attempted to send an
   101  	// alertCloseNotify record.
   102  	closeNotifySent bool
   103  
   104  	// clientFinished 和 serverFinished 用于记录客户端或服务器在最近一次握手中发送的 Finished 消息。
   105  	// 记录的目的是为了支持重新协商扩展和 tls-unique 通道绑定。
   106  	// clientFinished and serverFinished contain the Finished message sent
   107  	// by the client or server in the most recent handshake. This is
   108  	// retained to support the renegotiation extension and tls-unique
   109  	// channel-binding.
   110  	clientFinished [12]byte
   111  	serverFinished [12]byte
   112  
   113  	// 协商好的ALPN协议。
   114  	// 应用层协议协商(Application-Layer Protocol Negotiation,简称ALPN)是一个传输层安全协议(TLS) 的扩展,
   115  	// ALPN 使得应用层可以协商在安全连接层之上使用什么协议, 避免了额外的往返通讯, 并且独立于应用层协议。
   116  	// ALPN 用于 HTTP/2 连接, 和HTTP/1.x 相比, ALPN 的使用增强了网页的压缩率减少了网络延时。
   117  	// ALPN 和 HTTP/2 协议是伴随着 Google 开发 SPDY 协议出现的。
   118  	// clientProtocol is the negotiated ALPN protocol.
   119  	clientProtocol string
   120  
   121  	// input/output
   122  	in, out   halfConn
   123  	rawInput  bytes.Buffer // raw input, starting with a record header
   124  	input     bytes.Reader // application data waiting to be read, from rawInput.Next
   125  	hand      bytes.Buffer // handshake data waiting to be read
   126  	buffering bool         // whether records are buffered in sendBuf
   127  	sendBuf   []byte       // a buffer of records waiting to be sent
   128  
   129  	// bytesSent counts the bytes of application data sent.
   130  	// packetsSent counts packets.
   131  	bytesSent   int64
   132  	packetsSent int64
   133  
   134  	// retryCount counts the number of consecutive non-advancing records
   135  	// received by Conn.readRecord. That is, records that neither advance the
   136  	// handshake, nor deliver application data. Protected by in.Mutex.
   137  	retryCount int
   138  
   139  	// activeCall 是一个原子 int32。
   140  	// 低位标识 Close 是否被调用。
   141  	// 其余位记录 Conn.Write 中的 goroutine 的数量。
   142  	// activeCall is an atomic int32; the low bit is whether Close has
   143  	// been called. the rest of the bits are the number of goroutines
   144  	// in Conn.Write.
   145  	activeCall int32
   146  
   147  	tmp [16]byte
   148  }
   149  
   150  // Access to net.Conn methods.
   151  // Cannot just embed net.Conn because that would
   152  // export the struct field too.
   153  
   154  // LocalAddr returns the local network address.
   155  func (c *Conn) LocalAddr() net.Addr {
   156  	return c.conn.LocalAddr()
   157  }
   158  
   159  // RemoteAddr returns the remote network address.
   160  func (c *Conn) RemoteAddr() net.Addr {
   161  	return c.conn.RemoteAddr()
   162  }
   163  
   164  // SetDeadline sets the read and write deadlines associated with the connection.
   165  // A zero value for t means Read and Write will not time out.
   166  // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
   167  func (c *Conn) SetDeadline(t time.Time) error {
   168  	return c.conn.SetDeadline(t)
   169  }
   170  
   171  // SetReadDeadline sets the read deadline on the underlying connection.
   172  // A zero value for t means Read will not time out.
   173  func (c *Conn) SetReadDeadline(t time.Time) error {
   174  	return c.conn.SetReadDeadline(t)
   175  }
   176  
   177  // SetWriteDeadline sets the write deadline on the underlying connection.
   178  // A zero value for t means Write will not time out.
   179  // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
   180  func (c *Conn) SetWriteDeadline(t time.Time) error {
   181  	return c.conn.SetWriteDeadline(t)
   182  }
   183  
   184  // A halfConn represents one direction of the record layer
   185  // connection, either sending or receiving.
   186  type halfConn struct {
   187  	sync.Mutex
   188  
   189  	err     error       // first permanent error
   190  	version uint16      // protocol version
   191  	cipher  interface{} // cipher algorithm
   192  	mac     hash.Hash
   193  	seq     [8]byte // 64-bit sequence number
   194  
   195  	scratchBuf [13]byte // to avoid allocs; interface method args escape
   196  
   197  	nextCipher interface{} // next encryption state
   198  	nextMac    hash.Hash   // next MAC algorithm
   199  
   200  	trafficSecret []byte // current TLS 1.3 traffic secret
   201  }
   202  
   203  type permanentError struct {
   204  	err net.Error
   205  }
   206  
   207  func (e *permanentError) Error() string   { return e.err.Error() }
   208  func (e *permanentError) Unwrap() error   { return e.err }
   209  func (e *permanentError) Timeout() bool   { return e.err.Timeout() }
   210  func (e *permanentError) Temporary() bool { return false }
   211  
   212  func (hc *halfConn) setErrorLocked(err error) error {
   213  	if e, ok := err.(net.Error); ok {
   214  		hc.err = &permanentError{err: e}
   215  	} else {
   216  		hc.err = err
   217  	}
   218  	return hc.err
   219  }
   220  
   221  // prepareCipherSpec sets the encryption and MAC states
   222  // that a subsequent changeCipherSpec will use.
   223  func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac hash.Hash) {
   224  	hc.version = version
   225  	hc.nextCipher = cipher
   226  	hc.nextMac = mac
   227  }
   228  
   229  // changeCipherSpec changes the encryption and MAC states
   230  // to the ones previously passed to prepareCipherSpec.
   231  func (hc *halfConn) changeCipherSpec() error {
   232  	if hc.nextCipher == nil || hc.version == VersionTLS13 || hc.version == VersionGMSSL {
   233  		return alertInternalError
   234  	}
   235  	hc.cipher = hc.nextCipher
   236  	hc.mac = hc.nextMac
   237  	hc.nextCipher = nil
   238  	hc.nextMac = nil
   239  	for i := range hc.seq {
   240  		hc.seq[i] = 0
   241  	}
   242  	return nil
   243  }
   244  
   245  func (hc *halfConn) setTrafficSecret(suite *cipherSuiteTLS13, secret []byte) {
   246  	hc.trafficSecret = secret
   247  	key, iv := suite.trafficKey(secret)
   248  	hc.cipher = suite.aead(key, iv)
   249  	for i := range hc.seq {
   250  		hc.seq[i] = 0
   251  	}
   252  }
   253  
   254  // incSeq increments the sequence number.
   255  func (hc *halfConn) incSeq() {
   256  	for i := 7; i >= 0; i-- {
   257  		hc.seq[i]++
   258  		if hc.seq[i] != 0 {
   259  			return
   260  		}
   261  	}
   262  
   263  	// Not allowed to let sequence number wrap.
   264  	// Instead, must renegotiate before it does.
   265  	// Not likely enough to bother.
   266  	panic("gmtls: sequence number wraparound")
   267  }
   268  
   269  // explicitNonceLen returns the number of bytes of explicit nonce or IV included
   270  // in each record. Explicit nonces are present only in CBC modes after TLS 1.0
   271  // and in certain AEAD modes in TLS 1.2.
   272  func (hc *halfConn) explicitNonceLen() int {
   273  	if hc.cipher == nil {
   274  		return 0
   275  	}
   276  
   277  	switch c := hc.cipher.(type) {
   278  	case cipher.Stream:
   279  		return 0
   280  	case aead:
   281  		return c.explicitNonceLen()
   282  	case cbcMode:
   283  		// TLS 1.1 introduced a per-record explicit IV to fix the BEAST attack.
   284  		if hc.version >= VersionTLS11 {
   285  			return c.BlockSize()
   286  		}
   287  		return 0
   288  	default:
   289  		panic("unknown cipher type")
   290  	}
   291  }
   292  
   293  // extractPadding returns, in constant time, the length of the padding to remove
   294  // from the end of payload. It also returns a byte which is equal to 255 if the
   295  // padding was valid and 0 otherwise. See RFC 2246, Section 6.2.3.2.
   296  func extractPadding(payload []byte) (toRemove int, good byte) {
   297  	if len(payload) < 1 {
   298  		return 0, 0
   299  	}
   300  
   301  	paddingLen := payload[len(payload)-1]
   302  	t := uint(len(payload)-1) - uint(paddingLen)
   303  	// if len(payload) >= (paddingLen - 1) then the MSB of t is zero
   304  	good = byte(int32(^t) >> 31)
   305  
   306  	// The maximum possible padding length plus the actual length field
   307  	toCheck := 256
   308  	// The length of the padded data is public, so we can use an if here
   309  	if toCheck > len(payload) {
   310  		toCheck = len(payload)
   311  	}
   312  
   313  	for i := 0; i < toCheck; i++ {
   314  		t := uint(paddingLen) - uint(i)
   315  		// if i <= paddingLen then the MSB of t is zero
   316  		mask := byte(int32(^t) >> 31)
   317  		b := payload[len(payload)-1-i]
   318  		good &^= mask&paddingLen ^ mask&b
   319  	}
   320  
   321  	// We AND together the bits of good and replicate the result across
   322  	// all the bits.
   323  	good &= good << 4
   324  	good &= good << 2
   325  	good &= good << 1
   326  	good = uint8(int8(good) >> 7)
   327  
   328  	// Zero the padding length on error. This ensures any unchecked bytes
   329  	// are included in the MAC. Otherwise, an attacker that could
   330  	// distinguish MAC failures from padding failures could mount an attack
   331  	// similar to POODLE in SSL 3.0: given a good ciphertext that uses a
   332  	// full block's worth of padding, replace the final block with another
   333  	// block. If the MAC check passed but the padding check failed, the
   334  	// last byte of that block decrypted to the block size.
   335  	//
   336  	// See also macAndPaddingGood logic below.
   337  	paddingLen &= good
   338  
   339  	toRemove = int(paddingLen) + 1
   340  	return
   341  }
   342  
   343  func roundUp(a, b int) int {
   344  	return a + (b-a%b)%b
   345  }
   346  
   347  // cbcMode is an interface for block ciphers using cipher block chaining.
   348  type cbcMode interface {
   349  	cipher.BlockMode
   350  	SetIV([]byte)
   351  }
   352  
   353  // decrypt authenticates and decrypts the record if protection is active at
   354  // this stage. The returned plaintext might overlap with the input.
   355  func (hc *halfConn) decrypt(record []byte) ([]byte, recordType, error) {
   356  	var plaintext []byte
   357  	typ := recordType(record[0])
   358  	payload := record[recordHeaderLen:]
   359  
   360  	// In TLS 1.3, change_cipher_spec messages are to be ignored without being
   361  	// decrypted. See RFC 8446, Appendix D.4.
   362  	if (hc.version == VersionTLS13 || hc.version == VersionGMSSL) && typ == recordTypeChangeCipherSpec {
   363  		return payload, typ, nil
   364  	}
   365  
   366  	paddingGood := byte(255)
   367  	paddingLen := 0
   368  
   369  	explicitNonceLen := hc.explicitNonceLen()
   370  
   371  	if hc.cipher != nil {
   372  		switch c := hc.cipher.(type) {
   373  		case cipher.Stream:
   374  			c.XORKeyStream(payload, payload)
   375  		case aead:
   376  			if len(payload) < explicitNonceLen {
   377  				return nil, 0, alertBadRecordMAC
   378  			}
   379  			nonce := payload[:explicitNonceLen]
   380  			if len(nonce) == 0 {
   381  				nonce = hc.seq[:]
   382  			}
   383  			payload = payload[explicitNonceLen:]
   384  
   385  			var additionalData []byte
   386  			if hc.version == VersionTLS13 || hc.version == VersionGMSSL {
   387  				additionalData = record[:recordHeaderLen]
   388  			} else {
   389  				additionalData = append(hc.scratchBuf[:0], hc.seq[:]...)
   390  				additionalData = append(additionalData, record[:3]...)
   391  				n := len(payload) - c.Overhead()
   392  				additionalData = append(additionalData, byte(n>>8), byte(n))
   393  			}
   394  
   395  			var err error
   396  			plaintext, err = c.Open(payload[:0], nonce, payload, additionalData)
   397  			if err != nil {
   398  				return nil, 0, alertBadRecordMAC
   399  			}
   400  		case cbcMode:
   401  			blockSize := c.BlockSize()
   402  			minPayload := explicitNonceLen + roundUp(hc.mac.Size()+1, blockSize)
   403  			if len(payload)%blockSize != 0 || len(payload) < minPayload {
   404  				return nil, 0, alertBadRecordMAC
   405  			}
   406  
   407  			if explicitNonceLen > 0 {
   408  				c.SetIV(payload[:explicitNonceLen])
   409  				payload = payload[explicitNonceLen:]
   410  			}
   411  			c.CryptBlocks(payload, payload)
   412  
   413  			// In a limited attempt to protect against CBC padding oracles like
   414  			// Lucky13, the data past paddingLen (which is secret) is passed to
   415  			// the MAC function as extra data, to be fed into the HMAC after
   416  			// computing the digest. This makes the MAC roughly constant time as
   417  			// long as the digest computation is constant time and does not
   418  			// affect the subsequent write, modulo cache effects.
   419  			paddingLen, paddingGood = extractPadding(payload)
   420  		default:
   421  			panic("unknown cipher type")
   422  		}
   423  
   424  		if hc.version == VersionTLS13 || hc.version == VersionGMSSL {
   425  			if typ != recordTypeApplicationData {
   426  				return nil, 0, alertUnexpectedMessage
   427  			}
   428  			if len(plaintext) > maxPlaintext+1 {
   429  				return nil, 0, alertRecordOverflow
   430  			}
   431  			// Remove padding and find the ContentType scanning from the end.
   432  			for i := len(plaintext) - 1; i >= 0; i-- {
   433  				if plaintext[i] != 0 {
   434  					typ = recordType(plaintext[i])
   435  					plaintext = plaintext[:i]
   436  					break
   437  				}
   438  				if i == 0 {
   439  					return nil, 0, alertUnexpectedMessage
   440  				}
   441  			}
   442  		}
   443  	} else {
   444  		plaintext = payload
   445  	}
   446  
   447  	if hc.mac != nil {
   448  		macSize := hc.mac.Size()
   449  		if len(payload) < macSize {
   450  			return nil, 0, alertBadRecordMAC
   451  		}
   452  
   453  		n := len(payload) - macSize - paddingLen
   454  		n = subtle.ConstantTimeSelect(int(uint32(n)>>31), 0, n) // if n < 0 { n = 0 }
   455  		record[3] = byte(n >> 8)
   456  		record[4] = byte(n)
   457  		remoteMAC := payload[n : n+macSize]
   458  		localMAC := tls10MAC(hc.mac, hc.scratchBuf[:0], hc.seq[:], record[:recordHeaderLen], payload[:n], payload[n+macSize:])
   459  
   460  		// This is equivalent to checking the MACs and paddingGood
   461  		// separately, but in constant-time to prevent distinguishing
   462  		// padding failures from MAC failures. Depending on what value
   463  		// of paddingLen was returned on bad padding, distinguishing
   464  		// bad MAC from bad padding can lead to an attack.
   465  		//
   466  		// See also the logic at the end of extractPadding.
   467  		macAndPaddingGood := subtle.ConstantTimeCompare(localMAC, remoteMAC) & int(paddingGood)
   468  		if macAndPaddingGood != 1 {
   469  			return nil, 0, alertBadRecordMAC
   470  		}
   471  
   472  		plaintext = payload[:n]
   473  	}
   474  
   475  	hc.incSeq()
   476  	return plaintext, typ, nil
   477  }
   478  
   479  // sliceForAppend extends the input slice by n bytes. head is the full extended
   480  // slice, while tail is the appended part. If the original slice has sufficient
   481  // capacity no allocation is performed.
   482  func sliceForAppend(in []byte, n int) (head, tail []byte) {
   483  	if total := len(in) + n; cap(in) >= total {
   484  		head = in[:total]
   485  	} else {
   486  		head = make([]byte, total)
   487  		copy(head, in)
   488  	}
   489  	tail = head[len(in):]
   490  	return
   491  }
   492  
   493  // encrypt encrypts payload, adding the appropriate nonce and/or MAC, and
   494  // appends it to record, which must already contain the record header.
   495  func (hc *halfConn) encrypt(record, payload []byte, rand io.Reader) ([]byte, error) {
   496  	if hc.cipher == nil {
   497  		return append(record, payload...), nil
   498  	}
   499  
   500  	var explicitNonce []byte
   501  	if explicitNonceLen := hc.explicitNonceLen(); explicitNonceLen > 0 {
   502  		record, explicitNonce = sliceForAppend(record, explicitNonceLen)
   503  		if _, isCBC := hc.cipher.(cbcMode); !isCBC && explicitNonceLen < 16 {
   504  			// The AES-GCM construction in TLS has an explicit nonce so that the
   505  			// nonce can be random. However, the nonce is only 8 bytes which is
   506  			// too small for a secure, random nonce. Therefore we use the
   507  			// sequence number as the nonce. The 3DES-CBC construction also has
   508  			// an 8 bytes nonce but its nonces must be unpredictable (see RFC
   509  			// 5246, Appendix F.3), forcing us to use randomness. That's not
   510  			// 3DES' biggest problem anyway because the birthday bound on block
   511  			// collision is reached first due to its similarly small block size
   512  			// (see the Sweet32 attack).
   513  			copy(explicitNonce, hc.seq[:])
   514  		} else {
   515  			if _, err := io.ReadFull(rand, explicitNonce); err != nil {
   516  				return nil, err
   517  			}
   518  		}
   519  	}
   520  
   521  	var dst []byte
   522  	switch c := hc.cipher.(type) {
   523  	case cipher.Stream:
   524  		mac := tls10MAC(hc.mac, hc.scratchBuf[:0], hc.seq[:], record[:recordHeaderLen], payload, nil)
   525  		record, dst = sliceForAppend(record, len(payload)+len(mac))
   526  		c.XORKeyStream(dst[:len(payload)], payload)
   527  		c.XORKeyStream(dst[len(payload):], mac)
   528  	case aead:
   529  		nonce := explicitNonce
   530  		if len(nonce) == 0 {
   531  			nonce = hc.seq[:]
   532  		}
   533  
   534  		if hc.version == VersionTLS13 || hc.version == VersionGMSSL {
   535  			record = append(record, payload...)
   536  
   537  			// Encrypt the actual ContentType and replace the plaintext one.
   538  			record = append(record, record[0])
   539  			record[0] = byte(recordTypeApplicationData)
   540  
   541  			n := len(payload) + 1 + c.Overhead()
   542  			record[3] = byte(n >> 8)
   543  			record[4] = byte(n)
   544  
   545  			record = c.Seal(record[:recordHeaderLen],
   546  				nonce, record[recordHeaderLen:], record[:recordHeaderLen])
   547  		} else {
   548  			additionalData := append(hc.scratchBuf[:0], hc.seq[:]...)
   549  			additionalData = append(additionalData, record[:recordHeaderLen]...)
   550  			record = c.Seal(record, nonce, payload, additionalData)
   551  		}
   552  	case cbcMode:
   553  		mac := tls10MAC(hc.mac, hc.scratchBuf[:0], hc.seq[:], record[:recordHeaderLen], payload, nil)
   554  		blockSize := c.BlockSize()
   555  		plaintextLen := len(payload) + len(mac)
   556  		paddingLen := blockSize - plaintextLen%blockSize
   557  		record, dst = sliceForAppend(record, plaintextLen+paddingLen)
   558  		copy(dst, payload)
   559  		copy(dst[len(payload):], mac)
   560  		for i := plaintextLen; i < len(dst); i++ {
   561  			dst[i] = byte(paddingLen - 1)
   562  		}
   563  		if len(explicitNonce) > 0 {
   564  			c.SetIV(explicitNonce)
   565  		}
   566  		c.CryptBlocks(dst, dst)
   567  	default:
   568  		panic("unknown cipher type")
   569  	}
   570  
   571  	// Update length to include nonce, MAC and any block padding needed.
   572  	n := len(record) - recordHeaderLen
   573  	record[3] = byte(n >> 8)
   574  	record[4] = byte(n)
   575  	hc.incSeq()
   576  
   577  	return record, nil
   578  }
   579  
   580  // RecordHeaderError is returned when a TLS record header is invalid.
   581  type RecordHeaderError struct {
   582  	// Msg contains a human readable string that describes the error.
   583  	Msg string
   584  	// RecordHeader contains the five bytes of TLS record header that
   585  	// triggered the error.
   586  	RecordHeader [5]byte
   587  	// Conn provides the underlying net.Conn in the case that a client
   588  	// sent an initial handshake that didn't look like TLS.
   589  	// It is nil if there's already been a handshake or a TLS alert has
   590  	// been written to the connection.
   591  	Conn net.Conn
   592  }
   593  
   594  func (e RecordHeaderError) Error() string { return "gmtls: " + e.Msg }
   595  
   596  func (c *Conn) newRecordHeaderError(conn net.Conn, msg string) (err RecordHeaderError) {
   597  	err.Msg = msg
   598  	err.Conn = conn
   599  	copy(err.RecordHeader[:], c.rawInput.Bytes())
   600  	return err
   601  }
   602  
   603  func (c *Conn) readRecord() error {
   604  	return c.readRecordOrCCS(false)
   605  }
   606  
   607  func (c *Conn) readChangeCipherSpec() error {
   608  	return c.readRecordOrCCS(true)
   609  }
   610  
   611  // readRecordOrCCS reads one or more TLS records from the connection and
   612  // updates the record layer state. Some invariants:
   613  //   - c.in must be locked
   614  //   - c.input must be empty
   615  //
   616  // During the handshake one and only one of the following will happen:
   617  //   - c.hand grows
   618  //   - c.in.changeCipherSpec is called
   619  //   - an error is returned
   620  //
   621  // After the handshake one and only one of the following will happen:
   622  //   - c.hand grows
   623  //   - c.input is set
   624  //   - an error is returned
   625  func (c *Conn) readRecordOrCCS(expectChangeCipherSpec bool) error {
   626  	if c.in.err != nil {
   627  		return c.in.err
   628  	}
   629  	handshakeComplete := c.handshakeComplete()
   630  
   631  	// This function modifies c.rawInput, which owns the c.input memory.
   632  	if c.input.Len() != 0 {
   633  		return c.in.setErrorLocked(errors.New("gmtls: internal error: attempted to read record with pending application data"))
   634  	}
   635  	c.input.Reset(nil)
   636  
   637  	// Read header, payload.
   638  	if err := c.readFromUntil(c.conn, recordHeaderLen); err != nil {
   639  		// RFC 8446, Section 6.1 suggests that EOF without an alertCloseNotify
   640  		// is an error, but popular web sites seem to do this, so we accept it
   641  		// if and only if at the record boundary.
   642  		if err == io.ErrUnexpectedEOF && c.rawInput.Len() == 0 {
   643  			err = io.EOF
   644  		}
   645  		if e, ok := err.(net.Error); !ok || !e.Temporary() {
   646  			err := c.in.setErrorLocked(err)
   647  			if err != nil {
   648  				return err
   649  			}
   650  		}
   651  		return err
   652  	}
   653  	hdr := c.rawInput.Bytes()[:recordHeaderLen]
   654  	typ := recordType(hdr[0])
   655  
   656  	// No valid TLS record has a type of 0x80, however SSLv2 handshakes
   657  	// start with a uint16 length where the MSB is set and the first record
   658  	// is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
   659  	// an SSLv2 client.
   660  	if !handshakeComplete && typ == 0x80 {
   661  		_ = c.sendAlert(alertProtocolVersion)
   662  		return c.in.setErrorLocked(c.newRecordHeaderError(nil, "unsupported SSLv2 handshake received"))
   663  	}
   664  
   665  	vers := uint16(hdr[1])<<8 | uint16(hdr[2])
   666  	n := int(hdr[3])<<8 | int(hdr[4])
   667  	// gmssl采用tls1.3的处理
   668  	if c.haveVers && c.vers != VersionTLS13 && c.vers != VersionGMSSL && vers != c.vers {
   669  		_ = c.sendAlert(alertProtocolVersion)
   670  		msg := fmt.Sprintf("received record with version %x when expecting version %x", vers, c.vers)
   671  		return c.in.setErrorLocked(c.newRecordHeaderError(nil, msg))
   672  	}
   673  	if !c.haveVers {
   674  		// First message, be extra suspicious: this might not be a TLS
   675  		// client. Bail out before reading a full 'body', if possible.
   676  		// The current max version is 3.3 so if the version is >= 16.0,
   677  		// it's probably not real.
   678  		if (typ != recordTypeAlert && typ != recordTypeHandshake) || vers >= 0x1000 {
   679  			return c.in.setErrorLocked(c.newRecordHeaderError(c.conn, "first record does not look like a TLS handshake"))
   680  		}
   681  	}
   682  	if (c.vers == VersionTLS13 || c.vers == VersionGMSSL) && n > maxCiphertextTLS13 || n > maxCiphertext {
   683  		_ = c.sendAlert(alertRecordOverflow)
   684  		msg := fmt.Sprintf("oversized record received with length %d", n)
   685  		return c.in.setErrorLocked(c.newRecordHeaderError(nil, msg))
   686  	}
   687  	if err := c.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
   688  		if e, ok := err.(net.Error); !ok || !e.Temporary() {
   689  			err := c.in.setErrorLocked(err)
   690  			if err != nil {
   691  				return err
   692  			}
   693  		}
   694  		return err
   695  	}
   696  
   697  	// Process message.
   698  	record := c.rawInput.Next(recordHeaderLen + n)
   699  	data, typ, err := c.in.decrypt(record)
   700  	if err != nil {
   701  		return c.in.setErrorLocked(c.sendAlert(err.(alert)))
   702  	}
   703  	if len(data) > maxPlaintext {
   704  		return c.in.setErrorLocked(c.sendAlert(alertRecordOverflow))
   705  	}
   706  
   707  	// Application Data messages are always protected.
   708  	if c.in.cipher == nil && typ == recordTypeApplicationData {
   709  		return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   710  	}
   711  
   712  	if typ != recordTypeAlert && typ != recordTypeChangeCipherSpec && len(data) > 0 {
   713  		// This is a state-advancing message: reset the retry count.
   714  		c.retryCount = 0
   715  	}
   716  
   717  	// Handshake messages MUST NOT be interleaved with other record types in TLS 1.3.
   718  	if (c.vers == VersionTLS13 || c.vers == VersionGMSSL) && typ != recordTypeHandshake && c.hand.Len() > 0 {
   719  		return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   720  	}
   721  
   722  	switch typ {
   723  	default:
   724  		return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   725  
   726  	case recordTypeAlert:
   727  		if len(data) != 2 {
   728  			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   729  		}
   730  		if alert(data[1]) == alertCloseNotify {
   731  			return c.in.setErrorLocked(io.EOF)
   732  		}
   733  		if c.vers == VersionTLS13 || c.vers == VersionGMSSL {
   734  			return c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
   735  		}
   736  		switch data[0] {
   737  		case alertLevelWarning:
   738  			// Drop the record on the floor and retry.
   739  			return c.retryReadRecord(expectChangeCipherSpec)
   740  		case alertLevelError:
   741  			return c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
   742  		default:
   743  			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   744  		}
   745  
   746  	case recordTypeChangeCipherSpec:
   747  		if len(data) != 1 || data[0] != 1 {
   748  			return c.in.setErrorLocked(c.sendAlert(alertDecodeError))
   749  		}
   750  		// Handshake messages are not allowed to fragment across the CCS.
   751  		if c.hand.Len() > 0 {
   752  			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   753  		}
   754  		// In TLS 1.3, change_cipher_spec records are ignored until the
   755  		// Finished. See RFC 8446, Appendix D.4. Note that according to Section
   756  		// 5, a server can send a ChangeCipherSpec before its ServerHello, when
   757  		// c.vers is still unset. That's not useful though and suspicious if the
   758  		// server then selects a lower protocol version, so don't allow that.
   759  		if c.vers == VersionTLS13 || c.vers == VersionGMSSL {
   760  			return c.retryReadRecord(expectChangeCipherSpec)
   761  		}
   762  		if !expectChangeCipherSpec {
   763  			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   764  		}
   765  		if err := c.in.changeCipherSpec(); err != nil {
   766  			return c.in.setErrorLocked(c.sendAlert(err.(alert)))
   767  		}
   768  
   769  	case recordTypeApplicationData:
   770  		if !handshakeComplete || expectChangeCipherSpec {
   771  			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   772  		}
   773  		// Some OpenSSL servers send empty records in order to randomize the
   774  		// CBC IV. Ignore a limited number of empty records.
   775  		if len(data) == 0 {
   776  			return c.retryReadRecord(expectChangeCipherSpec)
   777  		}
   778  		// Note that data is owned by c.rawInput, following the Next call above,
   779  		// to avoid copying the plaintext. This is safe because c.rawInput is
   780  		// not read from or written to until c.input is drained.
   781  		c.input.Reset(data)
   782  
   783  	case recordTypeHandshake:
   784  		if len(data) == 0 || expectChangeCipherSpec {
   785  			return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   786  		}
   787  		c.hand.Write(data)
   788  	}
   789  
   790  	return nil
   791  }
   792  
   793  // retryReadRecord recurses into readRecordOrCCS to drop a non-advancing record, like
   794  // a warning alert, empty application_data, or a change_cipher_spec in TLS 1.3.
   795  func (c *Conn) retryReadRecord(expectChangeCipherSpec bool) error {
   796  	c.retryCount++
   797  	if c.retryCount > maxUselessRecords {
   798  		_ = c.sendAlert(alertUnexpectedMessage)
   799  		return c.in.setErrorLocked(errors.New("gmtls: too many ignored records"))
   800  	}
   801  	return c.readRecordOrCCS(expectChangeCipherSpec)
   802  }
   803  
   804  // atLeastReader reads from R, stopping with EOF once at least N bytes have been
   805  // read. It is different from an io.LimitedReader in that it doesn't cut short
   806  // the last Read call, and in that it considers an early EOF an error.
   807  type atLeastReader struct {
   808  	R io.Reader
   809  	N int64
   810  }
   811  
   812  func (r *atLeastReader) Read(p []byte) (int, error) {
   813  	if r.N <= 0 {
   814  		return 0, io.EOF
   815  	}
   816  	n, err := r.R.Read(p)
   817  	r.N -= int64(n) // won't underflow unless len(p) >= n > 9223372036854775809
   818  	if r.N > 0 && err == io.EOF {
   819  		return n, io.ErrUnexpectedEOF
   820  	}
   821  	if r.N <= 0 && err == nil {
   822  		return n, io.EOF
   823  	}
   824  	return n, err
   825  }
   826  
   827  // readFromUntil reads from r into c.rawInput until c.rawInput contains
   828  // at least n bytes or else returns an error.
   829  func (c *Conn) readFromUntil(r io.Reader, n int) error {
   830  	if c.rawInput.Len() >= n {
   831  		return nil
   832  	}
   833  	needs := n - c.rawInput.Len()
   834  	// There might be extra input waiting on the wire. Make a best effort
   835  	// attempt to fetch it so that it can be used in (*Conn).Read to
   836  	// "predict" closeNotify alerts.
   837  	c.rawInput.Grow(needs + bytes.MinRead)
   838  	_, err := c.rawInput.ReadFrom(&atLeastReader{r, int64(needs)})
   839  	return err
   840  }
   841  
   842  // sendAlert sends a TLS alert message.
   843  func (c *Conn) sendAlertLocked(err alert) error {
   844  	switch err {
   845  	case alertNoRenegotiation, alertCloseNotify:
   846  		c.tmp[0] = alertLevelWarning
   847  	default:
   848  		c.tmp[0] = alertLevelError
   849  	}
   850  	c.tmp[1] = byte(err)
   851  
   852  	_, writeErr := c.writeRecordLocked(recordTypeAlert, c.tmp[0:2])
   853  	if err == alertCloseNotify {
   854  		// closeNotify is a special case in that it isn't an error.
   855  		return writeErr
   856  	}
   857  
   858  	return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
   859  }
   860  
   861  // sendAlert sends a TLS alert message.
   862  func (c *Conn) sendAlert(err alert) error {
   863  	c.out.Lock()
   864  	defer c.out.Unlock()
   865  	return c.sendAlertLocked(err)
   866  }
   867  
   868  const (
   869  	// tcpMSSEstimate is a conservative estimate of the TCP maximum segment
   870  	// size (MSS). A constant is used, rather than querying the kernel for
   871  	// the actual MSS, to avoid complexity. The value here is the IPv6
   872  	// minimum MTU (1280 bytes) minus the overhead of an IPv6 header (40
   873  	// bytes) and a TCP header with timestamps (32 bytes).
   874  	tcpMSSEstimate = 1208
   875  
   876  	// recordSizeBoostThreshold is the number of bytes of application data
   877  	// sent after which the TLS record size will be increased to the
   878  	// maximum.
   879  	recordSizeBoostThreshold = 128 * 1024
   880  )
   881  
   882  // maxPayloadSizeForWrite returns the maximum TLS payload size to use for the
   883  // next application data record. There is the following trade-off:
   884  //
   885  //   - For latency-sensitive applications, such as web browsing, each TLS
   886  //     record should fit in one TCP segment.
   887  //   - For throughput-sensitive applications, such as large file transfers,
   888  //     larger TLS records better amortize framing and encryption overheads.
   889  //
   890  // A simple heuristic that works well in practice is to use small records for
   891  // the first 1MB of data, then use larger records for subsequent data, and
   892  // reset back to smaller records after the connection becomes idle. See "High
   893  // Performance Web Networking", Chapter 4, or:
   894  // https://www.igvita.com/2013/10/24/optimizing-tls-record-size-and-buffering-latency/
   895  //
   896  // In the interests of simplicity and determinism, this code does not attempt
   897  // to reset the record size once the connection is idle, however.
   898  func (c *Conn) maxPayloadSizeForWrite(typ recordType) int {
   899  	if c.config.DynamicRecordSizingDisabled || typ != recordTypeApplicationData {
   900  		return maxPlaintext
   901  	}
   902  
   903  	if c.bytesSent >= recordSizeBoostThreshold {
   904  		return maxPlaintext
   905  	}
   906  
   907  	// Subtract TLS overheads to get the maximum payload size.
   908  	payloadBytes := tcpMSSEstimate - recordHeaderLen - c.out.explicitNonceLen()
   909  	if c.out.cipher != nil {
   910  		switch ciph := c.out.cipher.(type) {
   911  		case cipher.Stream:
   912  			payloadBytes -= c.out.mac.Size()
   913  		case cipher.AEAD:
   914  			payloadBytes -= ciph.Overhead()
   915  		case cbcMode:
   916  			blockSize := ciph.BlockSize()
   917  			// The payload must fit in a multiple of blockSize, with
   918  			// room for at least one padding byte.
   919  			payloadBytes = (payloadBytes & ^(blockSize - 1)) - 1
   920  			// The MAC is appended before padding so affects the
   921  			// payload size directly.
   922  			payloadBytes -= c.out.mac.Size()
   923  		default:
   924  			panic("unknown cipher type")
   925  		}
   926  	}
   927  	if c.vers == VersionTLS13 || c.vers == VersionGMSSL {
   928  		payloadBytes-- // encrypted ContentType
   929  	}
   930  
   931  	// Allow packet growth in arithmetic progression up to max.
   932  	pkt := c.packetsSent
   933  	c.packetsSent++
   934  	if pkt > 1000 {
   935  		return maxPlaintext // avoid overflow in multiply below
   936  	}
   937  
   938  	n := payloadBytes * int(pkt+1)
   939  	if n > maxPlaintext {
   940  		n = maxPlaintext
   941  	}
   942  	return n
   943  }
   944  
   945  func (c *Conn) write(data []byte) (int, error) {
   946  	if c.buffering {
   947  		c.sendBuf = append(c.sendBuf, data...)
   948  		return len(data), nil
   949  	}
   950  
   951  	n, err := c.conn.Write(data)
   952  	c.bytesSent += int64(n)
   953  	return n, err
   954  }
   955  
   956  func (c *Conn) flush() (int, error) {
   957  	if len(c.sendBuf) == 0 {
   958  		return 0, nil
   959  	}
   960  
   961  	n, err := c.conn.Write(c.sendBuf)
   962  	c.bytesSent += int64(n)
   963  	c.sendBuf = nil
   964  	c.buffering = false
   965  	return n, err
   966  }
   967  
   968  // outBufPool pools the record-sized scratch buffers used by writeRecordLocked.
   969  var outBufPool = sync.Pool{
   970  	New: func() interface{} {
   971  		return new([]byte)
   972  	},
   973  }
   974  
   975  // writeRecordLocked writes a TLS record with the given type and payload to the
   976  // connection and updates the record layer state.
   977  func (c *Conn) writeRecordLocked(typ recordType, data []byte) (int, error) {
   978  	outBufPtr := outBufPool.Get().(*[]byte)
   979  	outBuf := *outBufPtr
   980  	defer func() {
   981  		// You might be tempted to simplify this by just passing &outBuf to Put,
   982  		// but that would make the local copy of the outBuf slice header escape
   983  		// to the heap, causing an allocation. Instead, we keep around the
   984  		// pointer to the slice header returned by Get, which is already on the
   985  		// heap, and overwrite and return that.
   986  		*outBufPtr = outBuf
   987  		outBufPool.Put(outBufPtr)
   988  	}()
   989  
   990  	var n int
   991  	for len(data) > 0 {
   992  		m := len(data)
   993  		if maxPayload := c.maxPayloadSizeForWrite(typ); m > maxPayload {
   994  			m = maxPayload
   995  		}
   996  
   997  		_, outBuf = sliceForAppend(outBuf[:0], recordHeaderLen)
   998  		outBuf[0] = byte(typ)
   999  		vers := c.vers
  1000  		if vers == 0 {
  1001  			// Some TLS servers fail if the record version is
  1002  			// greater than TLS 1.0 for the initial ClientHello.
  1003  			vers = VersionTLS10
  1004  		} else if vers == VersionTLS13 || vers == VersionGMSSL {
  1005  			// 出于兼容性考虑,将tls1.3与gmssl改为tls1.2,对应的信息将在扩展信息中展现。
  1006  			// TLS 1.3 froze the record layer version to 1.2.
  1007  			// See RFC 8446, Section 5.1.
  1008  			vers = VersionTLS12
  1009  		}
  1010  		outBuf[1] = byte(vers >> 8)
  1011  		outBuf[2] = byte(vers)
  1012  		outBuf[3] = byte(m >> 8)
  1013  		outBuf[4] = byte(m)
  1014  
  1015  		var err error
  1016  		outBuf, err = c.out.encrypt(outBuf, data[:m], c.config.rand())
  1017  		if err != nil {
  1018  			return n, err
  1019  		}
  1020  		if _, err := c.write(outBuf); err != nil {
  1021  			return n, err
  1022  		}
  1023  		n += m
  1024  		data = data[m:]
  1025  	}
  1026  	// tls1.3发出recordTypeChangeCipherSpec是为了兼容性对应,并不需要执行changeCipherSpec。
  1027  	// GMSSL暂时与tls1.3采用相同的对应
  1028  	if typ == recordTypeChangeCipherSpec && c.vers != VersionTLS13 && c.vers != VersionGMSSL {
  1029  		if err := c.out.changeCipherSpec(); err != nil {
  1030  			return n, c.sendAlertLocked(err.(alert))
  1031  		}
  1032  	}
  1033  
  1034  	return n, nil
  1035  }
  1036  
  1037  // 向tls连接写入一条消息
  1038  // writeRecord writes a TLS record with the given type and payload to the
  1039  // connection and updates the record layer state.
  1040  func (c *Conn) writeRecord(typ recordType, data []byte) (int, error) {
  1041  	c.out.Lock()
  1042  	defer c.out.Unlock()
  1043  
  1044  	return c.writeRecordLocked(typ, data)
  1045  }
  1046  
  1047  // 从tls连接读取下一条握手消息
  1048  // readHandshake reads the next handshake message from
  1049  // the record layer.
  1050  func (c *Conn) readHandshake() (interface{}, error) {
  1051  	for c.hand.Len() < 4 {
  1052  		if err := c.readRecord(); err != nil {
  1053  			return nil, err
  1054  		}
  1055  	}
  1056  
  1057  	data := c.hand.Bytes()
  1058  	n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
  1059  	if n > maxHandshake {
  1060  		err := c.sendAlertLocked(alertInternalError)
  1061  		if err != nil {
  1062  			return nil, err
  1063  		}
  1064  		return nil, c.in.setErrorLocked(fmt.Errorf("gmtls: handshake message of length %d bytes exceeds maximum of %d bytes", n, maxHandshake))
  1065  	}
  1066  	for c.hand.Len() < 4+n {
  1067  		if err := c.readRecord(); err != nil {
  1068  			return nil, err
  1069  		}
  1070  	}
  1071  	data = c.hand.Next(4 + n)
  1072  	var m handshakeMessage
  1073  	switch data[0] {
  1074  	case typeHelloRequest:
  1075  		m = new(helloRequestMsg)
  1076  	case typeClientHello:
  1077  		m = new(clientHelloMsg)
  1078  	case typeServerHello:
  1079  		m = new(serverHelloMsg)
  1080  	case typeNewSessionTicket:
  1081  		// GMSSL暂时采用tls1.3的处理
  1082  		if c.vers == VersionTLS13 || c.vers == VersionGMSSL {
  1083  			m = new(newSessionTicketMsgTLS13)
  1084  		} else {
  1085  			m = new(newSessionTicketMsg)
  1086  		}
  1087  	case typeCertificate:
  1088  		// GMSSL暂时采用tls1.3的处理
  1089  		if c.vers == VersionTLS13 || c.vers == VersionGMSSL {
  1090  			m = new(certificateMsgTLS13)
  1091  		} else {
  1092  			m = new(certificateMsg)
  1093  		}
  1094  	case typeCertificateRequest:
  1095  		// GMSSL暂时采用tls1.3的处理
  1096  		if c.vers == VersionTLS13 || c.vers == VersionGMSSL {
  1097  			m = new(certificateRequestMsgTLS13)
  1098  		} else {
  1099  			m = &certificateRequestMsg{
  1100  				hasSignatureAlgorithm: c.vers >= VersionTLS12,
  1101  			}
  1102  		}
  1103  	case typeCertificateStatus:
  1104  		m = new(certificateStatusMsg)
  1105  	case typeServerKeyExchange:
  1106  		m = new(serverKeyExchangeMsg)
  1107  	case typeServerHelloDone:
  1108  		m = new(serverHelloDoneMsg)
  1109  	case typeClientKeyExchange:
  1110  		m = new(clientKeyExchangeMsg)
  1111  	case typeCertificateVerify:
  1112  		m = &certificateVerifyMsg{
  1113  			// GMSSL暂时采用tls1.3的处理
  1114  			hasSignatureAlgorithm: c.vers >= VersionTLS12 || c.vers == VersionGMSSL,
  1115  		}
  1116  	case typeFinished:
  1117  		m = new(finishedMsg)
  1118  	case typeEncryptedExtensions:
  1119  		m = new(encryptedExtensionsMsg)
  1120  	case typeEndOfEarlyData:
  1121  		m = new(endOfEarlyDataMsg)
  1122  	case typeKeyUpdate:
  1123  		m = new(keyUpdateMsg)
  1124  	default:
  1125  		return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  1126  	}
  1127  
  1128  	// The handshake message unmarshalers
  1129  	// expect to be able to keep references to data,
  1130  	// so pass in a fresh copy that won't be overwritten.
  1131  	data = append([]byte(nil), data...)
  1132  
  1133  	if !m.unmarshal(data) {
  1134  		return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  1135  	}
  1136  	return m, nil
  1137  }
  1138  
  1139  var (
  1140  	errShutdown = errors.New("gmtls: protocol is shutdown")
  1141  )
  1142  
  1143  // Write writes data to the connection.
  1144  //
  1145  // As Write calls Handshake, in order to prevent indefinite blocking a deadline
  1146  // must be set for both Read and Write before Write is called when the handshake
  1147  // has not yet completed. See SetDeadline, SetReadDeadline, and
  1148  // SetWriteDeadline.
  1149  func (c *Conn) Write(b []byte) (int, error) {
  1150  	// interlock with Close below
  1151  	for {
  1152  		x := atomic.LoadInt32(&c.activeCall)
  1153  		if x&1 != 0 {
  1154  			return 0, net.ErrClosed
  1155  		}
  1156  		if atomic.CompareAndSwapInt32(&c.activeCall, x, x+2) {
  1157  			break
  1158  		}
  1159  	}
  1160  	defer atomic.AddInt32(&c.activeCall, -2)
  1161  
  1162  	if err := c.Handshake(); err != nil {
  1163  		return 0, err
  1164  	}
  1165  
  1166  	c.out.Lock()
  1167  	defer c.out.Unlock()
  1168  
  1169  	if err := c.out.err; err != nil {
  1170  		return 0, err
  1171  	}
  1172  
  1173  	if !c.handshakeComplete() {
  1174  		return 0, alertInternalError
  1175  	}
  1176  
  1177  	if c.closeNotifySent {
  1178  		return 0, errShutdown
  1179  	}
  1180  
  1181  	// TLS 1.0 is susceptible to a chosen-plaintext
  1182  	// attack when using block mode ciphers due to predictable IVs.
  1183  	// This can be prevented by splitting each Application Data
  1184  	// record into two records, effectively randomizing the IV.
  1185  	//
  1186  	// https://www.openssl.org/~bodo/tls-cbc.txt
  1187  	// https://bugzilla.mozilla.org/show_bug.cgi?id=665814
  1188  	// https://www.imperialviolet.org/2012/01/15/beastfollowup.html
  1189  
  1190  	var m int
  1191  	if len(b) > 1 && c.vers == VersionTLS10 {
  1192  		if _, ok := c.out.cipher.(cipher.BlockMode); ok {
  1193  			n, err := c.writeRecordLocked(recordTypeApplicationData, b[:1])
  1194  			if err != nil {
  1195  				return n, c.out.setErrorLocked(err)
  1196  			}
  1197  			m, b = 1, b[1:]
  1198  		}
  1199  	}
  1200  
  1201  	n, err := c.writeRecordLocked(recordTypeApplicationData, b)
  1202  	return n + m, c.out.setErrorLocked(err)
  1203  }
  1204  
  1205  // handleRenegotiation processes a HelloRequest handshake message.
  1206  func (c *Conn) handleRenegotiation() error {
  1207  	if c.vers == VersionTLS13 || c.vers == VersionGMSSL {
  1208  		return errors.New("gmtls: internal error: unexpected renegotiation")
  1209  	}
  1210  
  1211  	msg, err := c.readHandshake()
  1212  	if err != nil {
  1213  		return err
  1214  	}
  1215  
  1216  	helloReq, ok := msg.(*helloRequestMsg)
  1217  	if !ok {
  1218  		_ = c.sendAlert(alertUnexpectedMessage)
  1219  		return unexpectedMessageError(helloReq, msg)
  1220  	}
  1221  
  1222  	if !c.isClient {
  1223  		return c.sendAlert(alertNoRenegotiation)
  1224  	}
  1225  
  1226  	switch c.config.Renegotiation {
  1227  	case RenegotiateNever:
  1228  		return c.sendAlert(alertNoRenegotiation)
  1229  	case RenegotiateOnceAsClient:
  1230  		if c.handshakes > 1 {
  1231  			return c.sendAlert(alertNoRenegotiation)
  1232  		}
  1233  	case RenegotiateFreelyAsClient:
  1234  		// Ok.
  1235  	default:
  1236  		_ = c.sendAlert(alertInternalError)
  1237  		return errors.New("gmtls: unknown Renegotiation value")
  1238  	}
  1239  
  1240  	c.handshakeMutex.Lock()
  1241  	defer c.handshakeMutex.Unlock()
  1242  
  1243  	atomic.StoreUint32(&c.handshakeStatus, 0)
  1244  	if c.handshakeErr = c.clientHandshake(context.Background()); c.handshakeErr == nil {
  1245  		c.handshakes++
  1246  	}
  1247  	return c.handshakeErr
  1248  }
  1249  
  1250  // 处理握手完成后到达的握手消息。
  1251  //
  1252  //	比如服务端发出的 newSessionTicketMsgTLS13 或 keyUpdateMsg。
  1253  //
  1254  // handlePostHandshakeMessage processes a handshake message arrived after the
  1255  // handshake is complete. Up to TLS 1.2, it indicates the start of a renegotiation.
  1256  func (c *Conn) handlePostHandshakeMessage() error {
  1257  	if c.vers != VersionTLS13 && c.vers != VersionGMSSL {
  1258  		return c.handleRenegotiation()
  1259  	}
  1260  
  1261  	msg, err := c.readHandshake()
  1262  	if err != nil {
  1263  		return err
  1264  	}
  1265  
  1266  	c.retryCount++
  1267  	if c.retryCount > maxUselessRecords {
  1268  		_ = c.sendAlert(alertUnexpectedMessage)
  1269  		return c.in.setErrorLocked(errors.New("gmtls: too many non-advancing records"))
  1270  	}
  1271  
  1272  	switch msg := msg.(type) {
  1273  	case *newSessionTicketMsgTLS13:
  1274  		zclog.Print("===== 客户端接收到 newSessionTicketMsgTLS13")
  1275  		return c.handleNewSessionTicket(msg)
  1276  	case *keyUpdateMsg:
  1277  		zclog.Print("===== 客户端/服务端接收到 keyUpdateMsg")
  1278  		return c.handleKeyUpdate(msg)
  1279  	default:
  1280  		_ = c.sendAlert(alertUnexpectedMessage)
  1281  		return fmt.Errorf("gmtls: received unexpected handshake message of type %T", msg)
  1282  	}
  1283  }
  1284  
  1285  // 发起keyUpdateMsg, 或处理接收到的keyUpdateMsg
  1286  func (c *Conn) handleKeyUpdate(keyUpdate *keyUpdateMsg) error {
  1287  	cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite)
  1288  	if cipherSuite == nil {
  1289  		return c.in.setErrorLocked(c.sendAlert(alertInternalError))
  1290  	}
  1291  	// 派生新的对方的通信密钥并设置到连接通道in
  1292  	newSecret := cipherSuite.nextTrafficSecret(c.in.trafficSecret)
  1293  	c.in.setTrafficSecret(cipherSuite, newSecret)
  1294  	// 作为keyUpdate发起方(updateRequested == true),通知tls通信对方更新会话密钥
  1295  	if keyUpdate.updateRequested {
  1296  		c.out.Lock()
  1297  		defer c.out.Unlock()
  1298  		// 创建一个新的keyUpdateMsg,此时updateRequested默认为false
  1299  		msg := &keyUpdateMsg{}
  1300  		// 发送 keyUpdateMsg
  1301  		_, err := c.writeRecordLocked(recordTypeHandshake, msg.marshal())
  1302  		if err != nil {
  1303  			// Surface the error at the next write.
  1304  			err := c.out.setErrorLocked(err)
  1305  			if err != nil {
  1306  				return err
  1307  			}
  1308  			return nil
  1309  		}
  1310  		zclog.Print("===== 客户端/服务端发出 keyUpdateMsg")
  1311  		// 发出 keyUpdateMsg 之后才能派生新的己方通信密钥并设置到连接out通道
  1312  		newSecret := cipherSuite.nextTrafficSecret(c.out.trafficSecret)
  1313  		c.out.setTrafficSecret(cipherSuite, newSecret)
  1314  	}
  1315  	return nil
  1316  }
  1317  
  1318  // Read reads data from the connection.
  1319  //
  1320  // As Read calls Handshake, in order to prevent indefinite blocking a deadline
  1321  // must be set for both Read and Write before Read is called when the handshake
  1322  // has not yet completed. See SetDeadline, SetReadDeadline, and
  1323  // SetWriteDeadline.
  1324  func (c *Conn) Read(b []byte) (int, error) {
  1325  	zclog.Print("===== tls连接读取到一条消息")
  1326  	if err := c.Handshake(); err != nil {
  1327  		return 0, err
  1328  	}
  1329  	if len(b) == 0 {
  1330  		// Put this after Handshake, in case people were calling
  1331  		// Read(nil) for the side effect of the Handshake.
  1332  		return 0, nil
  1333  	}
  1334  
  1335  	c.in.Lock()
  1336  	defer c.in.Unlock()
  1337  
  1338  	for c.input.Len() == 0 {
  1339  		if err := c.readRecord(); err != nil {
  1340  			return 0, err
  1341  		}
  1342  		for c.hand.Len() > 0 {
  1343  			if err := c.handlePostHandshakeMessage(); err != nil {
  1344  				return 0, err
  1345  			}
  1346  		}
  1347  	}
  1348  
  1349  	n, _ := c.input.Read(b)
  1350  
  1351  	// If a close-notify alert is waiting, read it so that we can return (n,
  1352  	// EOF) instead of (n, nil), to signal to the HTTP response reading
  1353  	// goroutine that the connection is now closed. This eliminates a race
  1354  	// where the HTTP response reading goroutine would otherwise not observe
  1355  	// the EOF until its next read, by which time a client goroutine might
  1356  	// have already tried to reuse the HTTP connection for a new request.
  1357  	// See https://golang.org/cl/76400046 and https://golang.org/issue/3514
  1358  	if n != 0 && c.input.Len() == 0 && c.rawInput.Len() > 0 &&
  1359  		recordType(c.rawInput.Bytes()[0]) == recordTypeAlert {
  1360  		if err := c.readRecord(); err != nil {
  1361  			return n, err // will be io.EOF on closeNotify
  1362  		}
  1363  	}
  1364  
  1365  	return n, nil
  1366  }
  1367  
  1368  // Close closes the connection.
  1369  func (c *Conn) Close() error {
  1370  	// Interlock with Conn.Write above.
  1371  	var x int32
  1372  	for {
  1373  		x = atomic.LoadInt32(&c.activeCall)
  1374  		if x&1 != 0 {
  1375  			return net.ErrClosed
  1376  		}
  1377  		if atomic.CompareAndSwapInt32(&c.activeCall, x, x|1) {
  1378  			break
  1379  		}
  1380  	}
  1381  	if x != 0 {
  1382  		// io.Writer and io.Closer should not be used concurrently.
  1383  		// If Close is called while a Write is currently in-flight,
  1384  		// interpret that as a sign that this Close is really just
  1385  		// being used to break the Write and/or clean up resources and
  1386  		// avoid sending the alertCloseNotify, which may block
  1387  		// waiting on handshakeMutex or the c.out mutex.
  1388  		return c.conn.Close()
  1389  	}
  1390  
  1391  	var alertErr error
  1392  	if c.handshakeComplete() {
  1393  		if err := c.closeNotify(); err != nil {
  1394  			alertErr = fmt.Errorf("gmtls: failed to send closeNotify alert (but connection was closed anyway): %w", err)
  1395  		}
  1396  	}
  1397  
  1398  	if err := c.conn.Close(); err != nil {
  1399  		return err
  1400  	}
  1401  	return alertErr
  1402  }
  1403  
  1404  var errEarlyCloseWrite = errors.New("gmtls: CloseWrite called before handshake complete")
  1405  
  1406  // CloseWrite shuts down the writing side of the connection. It should only be
  1407  // called once the handshake has completed and does not call CloseWrite on the
  1408  // underlying connection. Most callers should just use Close.
  1409  func (c *Conn) CloseWrite() error {
  1410  	if !c.handshakeComplete() {
  1411  		return errEarlyCloseWrite
  1412  	}
  1413  
  1414  	return c.closeNotify()
  1415  }
  1416  
  1417  func (c *Conn) closeNotify() error {
  1418  	c.out.Lock()
  1419  	defer c.out.Unlock()
  1420  
  1421  	if !c.closeNotifySent {
  1422  		// Set a Write Deadline to prevent possibly blocking forever.
  1423  		err := c.SetWriteDeadline(time.Now().Add(time.Second * 5))
  1424  		if err != nil {
  1425  			return err
  1426  		}
  1427  		c.closeNotifyErr = c.sendAlertLocked(alertCloseNotify)
  1428  		c.closeNotifySent = true
  1429  		// Any subsequent writes will fail.
  1430  		err = c.SetWriteDeadline(time.Now())
  1431  		if err != nil {
  1432  			return err
  1433  		}
  1434  	}
  1435  	return c.closeNotifyErr
  1436  }
  1437  
  1438  // Handshake runs the client or server handshake
  1439  // protocol if it has not yet been run.
  1440  //
  1441  // Most uses of this package need not call Handshake explicitly: the
  1442  // first Read or Write will call it automatically.
  1443  //
  1444  // For control over canceling or setting a timeout on a handshake, use
  1445  // HandshakeContext or the Dialer's DialContext method instead.
  1446  func (c *Conn) Handshake() error {
  1447  	return c.HandshakeContext(context.Background())
  1448  }
  1449  
  1450  // HandshakeContext runs the client or server handshake
  1451  // protocol if it has not yet been run.
  1452  //
  1453  // The provided Context must be non-nil. If the context is canceled before
  1454  // the handshake is complete, the handshake is interrupted and an error is returned.
  1455  // Once the handshake has completed, cancellation of the context will not affect the
  1456  // connection.
  1457  //
  1458  // Most uses of this package need not call HandshakeContext explicitly: the
  1459  // first Read or Write will call it automatically.
  1460  func (c *Conn) HandshakeContext(ctx context.Context) error {
  1461  	// Delegate to unexported method for named return
  1462  	// without confusing documented signature.
  1463  	return c.handshakeContext(ctx)
  1464  }
  1465  
  1466  // 根据上下文环境执行握手
  1467  func (c *Conn) handshakeContext(ctx context.Context) (ret error) {
  1468  	handshakeCtx, cancel := context.WithCancel(ctx)
  1469  	// Note: defer this before starting the "interrupter" goroutine
  1470  	// so that we can tell the difference between the input being canceled and
  1471  	// this cancellation. In the former case, we need to close the connection.
  1472  	defer cancel()
  1473  
  1474  	// Start the "interrupter" goroutine, if this context might be canceled.
  1475  	// (The background context cannot).
  1476  	//
  1477  	// The interrupter goroutine waits for the input context to be done and
  1478  	// closes the connection if this happens before the function returns.
  1479  	if ctx.Done() != nil {
  1480  		done := make(chan struct{})
  1481  		interruptRes := make(chan error, 1)
  1482  		defer func() {
  1483  			close(done)
  1484  			if ctxErr := <-interruptRes; ctxErr != nil {
  1485  				// Return context error to user.
  1486  				ret = ctxErr
  1487  			}
  1488  		}()
  1489  		go func() {
  1490  			select {
  1491  			case <-handshakeCtx.Done():
  1492  				// Close the connection, discarding the error
  1493  				_ = c.conn.Close()
  1494  				interruptRes <- handshakeCtx.Err()
  1495  			case <-done:
  1496  				interruptRes <- nil
  1497  			}
  1498  		}()
  1499  	}
  1500  
  1501  	c.handshakeMutex.Lock()
  1502  	defer c.handshakeMutex.Unlock()
  1503  
  1504  	if err := c.handshakeErr; err != nil {
  1505  		return err
  1506  	}
  1507  	if c.handshakeComplete() {
  1508  		return nil
  1509  	}
  1510  
  1511  	c.in.Lock()
  1512  	defer c.in.Unlock()
  1513  	// 调用握手函数
  1514  	c.handshakeErr = c.handshakeFn(handshakeCtx)
  1515  	if c.handshakeErr == nil {
  1516  		c.handshakes++
  1517  	} else {
  1518  		// If an error occurred during the handshake try to flush the
  1519  		// alert that might be left in the buffer.
  1520  		_, err := c.flush()
  1521  		if err != nil {
  1522  			return err
  1523  		}
  1524  	}
  1525  
  1526  	if c.handshakeErr == nil && !c.handshakeComplete() {
  1527  		c.handshakeErr = errors.New("gmtls: internal error: handshake should have had a result")
  1528  	}
  1529  
  1530  	return c.handshakeErr
  1531  }
  1532  
  1533  // ConnectionState returns basic TLS details about the connection.
  1534  func (c *Conn) ConnectionState() ConnectionState {
  1535  	c.handshakeMutex.Lock()
  1536  	defer c.handshakeMutex.Unlock()
  1537  	return c.connectionStateLocked()
  1538  }
  1539  
  1540  func (c *Conn) connectionStateLocked() ConnectionState {
  1541  	var state ConnectionState
  1542  	state.HandshakeComplete = c.handshakeComplete()
  1543  	state.Version = c.vers
  1544  	state.NegotiatedProtocol = c.clientProtocol
  1545  	state.DidResume = c.didResume
  1546  	state.NegotiatedProtocolIsMutual = true
  1547  	state.ServerName = c.serverName
  1548  	state.CipherSuite = c.cipherSuite
  1549  	state.PeerCertificates = c.peerCertificates
  1550  	state.VerifiedChains = c.verifiedChains
  1551  	state.SignedCertificateTimestamps = c.scts
  1552  	state.OCSPResponse = c.ocspResponse
  1553  	if !c.didResume && c.vers != VersionTLS13 && c.vers != VersionGMSSL {
  1554  		if c.clientFinishedIsFirst {
  1555  			state.TLSUnique = c.clientFinished[:]
  1556  		} else {
  1557  			state.TLSUnique = c.serverFinished[:]
  1558  		}
  1559  	}
  1560  	if c.config.Renegotiation != RenegotiateNever {
  1561  		state.ekm = noExportedKeyingMaterial
  1562  	} else {
  1563  		state.ekm = c.ekm
  1564  	}
  1565  	return state
  1566  }
  1567  
  1568  // OCSPResponse returns the stapled OCSP response from the TLS server, if
  1569  // any. (Only valid for client connections.)
  1570  func (c *Conn) OCSPResponse() []byte {
  1571  	c.handshakeMutex.Lock()
  1572  	defer c.handshakeMutex.Unlock()
  1573  
  1574  	return c.ocspResponse
  1575  }
  1576  
  1577  // VerifyHostname checks that the peer certificate chain is valid for
  1578  // connecting to host. If so, it returns nil; if not, it returns an error
  1579  // describing the problem.
  1580  func (c *Conn) VerifyHostname(host string) error {
  1581  	c.handshakeMutex.Lock()
  1582  	defer c.handshakeMutex.Unlock()
  1583  	if !c.isClient {
  1584  		return errors.New("gmtls: VerifyHostname called on TLS server connection")
  1585  	}
  1586  	if !c.handshakeComplete() {
  1587  		return errors.New("gmtls: handshake has not yet been performed")
  1588  	}
  1589  	if len(c.verifiedChains) == 0 {
  1590  		return errors.New("gmtls: handshake did not verify certificate chain")
  1591  	}
  1592  	return c.peerCertificates[0].VerifyHostname(host)
  1593  }
  1594  
  1595  func (c *Conn) handshakeComplete() bool {
  1596  	return atomic.LoadUint32(&c.handshakeStatus) == 1
  1597  }