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