gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/gmtls/conn.go (about) 1 // Copyright (c) 2022 zhaochun 2 // core-gm 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 "log" 28 "net" 29 "sync" 30 "sync/atomic" 31 "time" 32 33 "gitee.com/ks-custle/core-gm/x509" 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 // 622 // During the handshake one and only one of the following will happen: 623 // - c.hand grows 624 // - c.in.changeCipherSpec is called 625 // - an error is returned 626 // 627 // After the handshake one and only one of the following will happen: 628 // - c.hand grows 629 // - c.input is set 630 // - an error is returned 631 func (c *Conn) readRecordOrCCS(expectChangeCipherSpec bool) error { 632 if c.in.err != nil { 633 return c.in.err 634 } 635 handshakeComplete := c.handshakeComplete() 636 637 // This function modifies c.rawInput, which owns the c.input memory. 638 if c.input.Len() != 0 { 639 return c.in.setErrorLocked(errors.New("gmtls: internal error: attempted to read record with pending application data")) 640 } 641 c.input.Reset(nil) 642 643 // Read header, payload. 644 if err := c.readFromUntil(c.conn, recordHeaderLen); err != nil { 645 // RFC 8446, Section 6.1 suggests that EOF without an alertCloseNotify 646 // is an error, but popular web sites seem to do this, so we accept it 647 // if and only if at the record boundary. 648 if err == io.ErrUnexpectedEOF && c.rawInput.Len() == 0 { 649 err = io.EOF 650 } 651 if e, ok := err.(net.Error); !ok || !e.Temporary() { 652 err := c.in.setErrorLocked(err) 653 if err != nil { 654 return err 655 } 656 } 657 return err 658 } 659 hdr := c.rawInput.Bytes()[:recordHeaderLen] 660 typ := recordType(hdr[0]) 661 662 // No valid TLS record has a type of 0x80, however SSLv2 handshakes 663 // start with a uint16 length where the MSB is set and the first record 664 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests 665 // an SSLv2 client. 666 if !handshakeComplete && typ == 0x80 { 667 _ = c.sendAlert(alertProtocolVersion) 668 return c.in.setErrorLocked(c.newRecordHeaderError(nil, "unsupported SSLv2 handshake received")) 669 } 670 671 vers := uint16(hdr[1])<<8 | uint16(hdr[2]) 672 n := int(hdr[3])<<8 | int(hdr[4]) 673 // gmssl采用tls1.3的处理 674 if c.haveVers && c.vers != VersionTLS13 && c.vers != VersionGMSSL && vers != c.vers { 675 _ = c.sendAlert(alertProtocolVersion) 676 msg := fmt.Sprintf("received record with version %x when expecting version %x", vers, c.vers) 677 return c.in.setErrorLocked(c.newRecordHeaderError(nil, msg)) 678 } 679 if !c.haveVers { 680 // First message, be extra suspicious: this might not be a TLS 681 // client. Bail out before reading a full 'body', if possible. 682 // The current max version is 3.3 so if the version is >= 16.0, 683 // it's probably not real. 684 if (typ != recordTypeAlert && typ != recordTypeHandshake) || vers >= 0x1000 { 685 return c.in.setErrorLocked(c.newRecordHeaderError(c.conn, "first record does not look like a TLS handshake")) 686 } 687 } 688 if (c.vers == VersionTLS13 || c.vers == VersionGMSSL) && n > maxCiphertextTLS13 || n > maxCiphertext { 689 _ = c.sendAlert(alertRecordOverflow) 690 msg := fmt.Sprintf("oversized record received with length %d", n) 691 return c.in.setErrorLocked(c.newRecordHeaderError(nil, msg)) 692 } 693 if err := c.readFromUntil(c.conn, recordHeaderLen+n); err != nil { 694 if e, ok := err.(net.Error); !ok || !e.Temporary() { 695 err := c.in.setErrorLocked(err) 696 if err != nil { 697 return err 698 } 699 } 700 return err 701 } 702 703 // Process message. 704 record := c.rawInput.Next(recordHeaderLen + n) 705 data, typ, err := c.in.decrypt(record) 706 if err != nil { 707 return c.in.setErrorLocked(c.sendAlert(err.(alert))) 708 } 709 if len(data) > maxPlaintext { 710 return c.in.setErrorLocked(c.sendAlert(alertRecordOverflow)) 711 } 712 713 // Application Data messages are always protected. 714 if c.in.cipher == nil && typ == recordTypeApplicationData { 715 return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 716 } 717 718 if typ != recordTypeAlert && typ != recordTypeChangeCipherSpec && len(data) > 0 { 719 // This is a state-advancing message: reset the retry count. 720 c.retryCount = 0 721 } 722 723 // Handshake messages MUST NOT be interleaved with other record types in TLS 1.3. 724 if (c.vers == VersionTLS13 || c.vers == VersionGMSSL) && typ != recordTypeHandshake && c.hand.Len() > 0 { 725 return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 726 } 727 728 switch typ { 729 default: 730 return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 731 732 case recordTypeAlert: 733 if len(data) != 2 { 734 return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 735 } 736 if alert(data[1]) == alertCloseNotify { 737 return c.in.setErrorLocked(io.EOF) 738 } 739 if c.vers == VersionTLS13 || c.vers == VersionGMSSL { 740 return c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])}) 741 } 742 switch data[0] { 743 case alertLevelWarning: 744 // Drop the record on the floor and retry. 745 return c.retryReadRecord(expectChangeCipherSpec) 746 case alertLevelError: 747 return c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])}) 748 default: 749 return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 750 } 751 752 case recordTypeChangeCipherSpec: 753 if len(data) != 1 || data[0] != 1 { 754 return c.in.setErrorLocked(c.sendAlert(alertDecodeError)) 755 } 756 // Handshake messages are not allowed to fragment across the CCS. 757 if c.hand.Len() > 0 { 758 return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 759 } 760 // In TLS 1.3, change_cipher_spec records are ignored until the 761 // Finished. See RFC 8446, Appendix D.4. Note that according to Section 762 // 5, a server can send a ChangeCipherSpec before its ServerHello, when 763 // c.vers is still unset. That's not useful though and suspicious if the 764 // server then selects a lower protocol version, so don't allow that. 765 if c.vers == VersionTLS13 || c.vers == VersionGMSSL { 766 return c.retryReadRecord(expectChangeCipherSpec) 767 } 768 if !expectChangeCipherSpec { 769 return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 770 } 771 if err := c.in.changeCipherSpec(); err != nil { 772 return c.in.setErrorLocked(c.sendAlert(err.(alert))) 773 } 774 775 case recordTypeApplicationData: 776 if !handshakeComplete || expectChangeCipherSpec { 777 return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 778 } 779 // Some OpenSSL servers send empty records in order to randomize the 780 // CBC IV. Ignore a limited number of empty records. 781 if len(data) == 0 { 782 return c.retryReadRecord(expectChangeCipherSpec) 783 } 784 // Note that data is owned by c.rawInput, following the Next call above, 785 // to avoid copying the plaintext. This is safe because c.rawInput is 786 // not read from or written to until c.input is drained. 787 c.input.Reset(data) 788 789 case recordTypeHandshake: 790 if len(data) == 0 || expectChangeCipherSpec { 791 return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 792 } 793 c.hand.Write(data) 794 } 795 796 return nil 797 } 798 799 // retryReadRecord recurses into readRecordOrCCS to drop a non-advancing record, like 800 // a warning alert, empty application_data, or a change_cipher_spec in TLS 1.3. 801 func (c *Conn) retryReadRecord(expectChangeCipherSpec bool) error { 802 c.retryCount++ 803 if c.retryCount > maxUselessRecords { 804 _ = c.sendAlert(alertUnexpectedMessage) 805 return c.in.setErrorLocked(errors.New("gmtls: too many ignored records")) 806 } 807 return c.readRecordOrCCS(expectChangeCipherSpec) 808 } 809 810 // atLeastReader reads from R, stopping with EOF once at least N bytes have been 811 // read. It is different from an io.LimitedReader in that it doesn't cut short 812 // the last Read call, and in that it considers an early EOF an error. 813 type atLeastReader struct { 814 R io.Reader 815 N int64 816 } 817 818 func (r *atLeastReader) Read(p []byte) (int, error) { 819 if r.N <= 0 { 820 return 0, io.EOF 821 } 822 n, err := r.R.Read(p) 823 r.N -= int64(n) // won't underflow unless len(p) >= n > 9223372036854775809 824 if r.N > 0 && err == io.EOF { 825 return n, io.ErrUnexpectedEOF 826 } 827 if r.N <= 0 && err == nil { 828 return n, io.EOF 829 } 830 return n, err 831 } 832 833 // readFromUntil reads from r into c.rawInput until c.rawInput contains 834 // at least n bytes or else returns an error. 835 func (c *Conn) readFromUntil(r io.Reader, n int) error { 836 if c.rawInput.Len() >= n { 837 return nil 838 } 839 needs := n - c.rawInput.Len() 840 // There might be extra input waiting on the wire. Make a best effort 841 // attempt to fetch it so that it can be used in (*Conn).Read to 842 // "predict" closeNotify alerts. 843 c.rawInput.Grow(needs + bytes.MinRead) 844 _, err := c.rawInput.ReadFrom(&atLeastReader{r, int64(needs)}) 845 return err 846 } 847 848 // sendAlert sends a TLS alert message. 849 func (c *Conn) sendAlertLocked(err alert) error { 850 switch err { 851 case alertNoRenegotiation, alertCloseNotify: 852 c.tmp[0] = alertLevelWarning 853 default: 854 c.tmp[0] = alertLevelError 855 } 856 c.tmp[1] = byte(err) 857 858 _, writeErr := c.writeRecordLocked(recordTypeAlert, c.tmp[0:2]) 859 if err == alertCloseNotify { 860 // closeNotify is a special case in that it isn't an error. 861 return writeErr 862 } 863 864 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err}) 865 } 866 867 // sendAlert sends a TLS alert message. 868 func (c *Conn) sendAlert(err alert) error { 869 c.out.Lock() 870 defer c.out.Unlock() 871 return c.sendAlertLocked(err) 872 } 873 874 const ( 875 // tcpMSSEstimate is a conservative estimate of the TCP maximum segment 876 // size (MSS). A constant is used, rather than querying the kernel for 877 // the actual MSS, to avoid complexity. The value here is the IPv6 878 // minimum MTU (1280 bytes) minus the overhead of an IPv6 header (40 879 // bytes) and a TCP header with timestamps (32 bytes). 880 tcpMSSEstimate = 1208 881 882 // recordSizeBoostThreshold is the number of bytes of application data 883 // sent after which the TLS record size will be increased to the 884 // maximum. 885 recordSizeBoostThreshold = 128 * 1024 886 ) 887 888 // maxPayloadSizeForWrite returns the maximum TLS payload size to use for the 889 // next application data record. There is the following trade-off: 890 // 891 // - For latency-sensitive applications, such as web browsing, each TLS 892 // record should fit in one TCP segment. 893 // - For throughput-sensitive applications, such as large file transfers, 894 // larger TLS records better amortize framing and encryption overheads. 895 // 896 // A simple heuristic that works well in practice is to use small records for 897 // the first 1MB of data, then use larger records for subsequent data, and 898 // reset back to smaller records after the connection becomes idle. See "High 899 // Performance Web Networking", Chapter 4, or: 900 // https://www.igvita.com/2013/10/24/optimizing-tls-record-size-and-buffering-latency/ 901 // 902 // In the interests of simplicity and determinism, this code does not attempt 903 // to reset the record size once the connection is idle, however. 904 func (c *Conn) maxPayloadSizeForWrite(typ recordType) int { 905 if c.config.DynamicRecordSizingDisabled || typ != recordTypeApplicationData { 906 return maxPlaintext 907 } 908 909 if c.bytesSent >= recordSizeBoostThreshold { 910 return maxPlaintext 911 } 912 913 // Subtract TLS overheads to get the maximum payload size. 914 payloadBytes := tcpMSSEstimate - recordHeaderLen - c.out.explicitNonceLen() 915 if c.out.cipher != nil { 916 switch ciph := c.out.cipher.(type) { 917 case cipher.Stream: 918 payloadBytes -= c.out.mac.Size() 919 case cipher.AEAD: 920 payloadBytes -= ciph.Overhead() 921 case cbcMode: 922 blockSize := ciph.BlockSize() 923 // The payload must fit in a multiple of blockSize, with 924 // room for at least one padding byte. 925 payloadBytes = (payloadBytes & ^(blockSize - 1)) - 1 926 // The MAC is appended before padding so affects the 927 // payload size directly. 928 payloadBytes -= c.out.mac.Size() 929 default: 930 panic("unknown cipher type") 931 } 932 } 933 if c.vers == VersionTLS13 || c.vers == VersionGMSSL { 934 payloadBytes-- // encrypted ContentType 935 } 936 937 // Allow packet growth in arithmetic progression up to max. 938 pkt := c.packetsSent 939 c.packetsSent++ 940 if pkt > 1000 { 941 return maxPlaintext // avoid overflow in multiply below 942 } 943 944 n := payloadBytes * int(pkt+1) 945 if n > maxPlaintext { 946 n = maxPlaintext 947 } 948 return n 949 } 950 951 func (c *Conn) write(data []byte) (int, error) { 952 if c.buffering { 953 c.sendBuf = append(c.sendBuf, data...) 954 return len(data), nil 955 } 956 957 n, err := c.conn.Write(data) 958 c.bytesSent += int64(n) 959 return n, err 960 } 961 962 func (c *Conn) flush() (int, error) { 963 if len(c.sendBuf) == 0 { 964 return 0, nil 965 } 966 967 n, err := c.conn.Write(c.sendBuf) 968 c.bytesSent += int64(n) 969 c.sendBuf = nil 970 c.buffering = false 971 return n, err 972 } 973 974 // outBufPool pools the record-sized scratch buffers used by writeRecordLocked. 975 var outBufPool = sync.Pool{ 976 New: func() interface{} { 977 return new([]byte) 978 }, 979 } 980 981 // writeRecordLocked writes a TLS record with the given type and payload to the 982 // connection and updates the record layer state. 983 func (c *Conn) writeRecordLocked(typ recordType, data []byte) (int, error) { 984 outBufPtr := outBufPool.Get().(*[]byte) 985 outBuf := *outBufPtr 986 defer func() { 987 // You might be tempted to simplify this by just passing &outBuf to Put, 988 // but that would make the local copy of the outBuf slice header escape 989 // to the heap, causing an allocation. Instead, we keep around the 990 // pointer to the slice header returned by Get, which is already on the 991 // heap, and overwrite and return that. 992 *outBufPtr = outBuf 993 outBufPool.Put(outBufPtr) 994 }() 995 996 var n int 997 for len(data) > 0 { 998 m := len(data) 999 if maxPayload := c.maxPayloadSizeForWrite(typ); m > maxPayload { 1000 m = maxPayload 1001 } 1002 1003 _, outBuf = sliceForAppend(outBuf[:0], recordHeaderLen) 1004 outBuf[0] = byte(typ) 1005 vers := c.vers 1006 if vers == 0 { 1007 // Some TLS servers fail if the record version is 1008 // greater than TLS 1.0 for the initial ClientHello. 1009 vers = VersionTLS10 1010 } else if vers == VersionTLS13 || vers == VersionGMSSL { 1011 // 出于兼容性考虑,将tls1.3与gmssl改为tls1.2,对应的信息将在扩展信息中展现。 1012 // TLS 1.3 froze the record layer version to 1.2. 1013 // See RFC 8446, Section 5.1. 1014 vers = VersionTLS12 1015 } 1016 outBuf[1] = byte(vers >> 8) 1017 outBuf[2] = byte(vers) 1018 outBuf[3] = byte(m >> 8) 1019 outBuf[4] = byte(m) 1020 1021 var err error 1022 outBuf, err = c.out.encrypt(outBuf, data[:m], c.config.rand()) 1023 if err != nil { 1024 return n, err 1025 } 1026 if _, err := c.write(outBuf); err != nil { 1027 return n, err 1028 } 1029 n += m 1030 data = data[m:] 1031 } 1032 // tls1.3发出recordTypeChangeCipherSpec是为了兼容性对应,并不需要执行changeCipherSpec。 1033 // GMSSL暂时与tls1.3采用相同的对应 1034 if typ == recordTypeChangeCipherSpec && c.vers != VersionTLS13 && c.vers != VersionGMSSL { 1035 if err := c.out.changeCipherSpec(); err != nil { 1036 return n, c.sendAlertLocked(err.(alert)) 1037 } 1038 } 1039 1040 return n, nil 1041 } 1042 1043 // 向tls连接写入一条消息 1044 // writeRecord writes a TLS record with the given type and payload to the 1045 // connection and updates the record layer state. 1046 func (c *Conn) writeRecord(typ recordType, data []byte) (int, error) { 1047 c.out.Lock() 1048 defer c.out.Unlock() 1049 1050 return c.writeRecordLocked(typ, data) 1051 } 1052 1053 // 从tls连接读取下一条握手消息 1054 // readHandshake reads the next handshake message from 1055 // the record layer. 1056 func (c *Conn) readHandshake() (interface{}, error) { 1057 for c.hand.Len() < 4 { 1058 if err := c.readRecord(); err != nil { 1059 return nil, err 1060 } 1061 } 1062 1063 data := c.hand.Bytes() 1064 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3]) 1065 if n > maxHandshake { 1066 err := c.sendAlertLocked(alertInternalError) 1067 if err != nil { 1068 return nil, err 1069 } 1070 return nil, c.in.setErrorLocked(fmt.Errorf("gmtls: handshake message of length %d bytes exceeds maximum of %d bytes", n, maxHandshake)) 1071 } 1072 for c.hand.Len() < 4+n { 1073 if err := c.readRecord(); err != nil { 1074 return nil, err 1075 } 1076 } 1077 data = c.hand.Next(4 + n) 1078 var m handshakeMessage 1079 switch data[0] { 1080 case typeHelloRequest: 1081 m = new(helloRequestMsg) 1082 case typeClientHello: 1083 m = new(clientHelloMsg) 1084 case typeServerHello: 1085 m = new(serverHelloMsg) 1086 case typeNewSessionTicket: 1087 // GMSSL暂时采用tls1.3的处理 1088 if c.vers == VersionTLS13 || c.vers == VersionGMSSL { 1089 m = new(newSessionTicketMsgTLS13) 1090 } else { 1091 m = new(newSessionTicketMsg) 1092 } 1093 case typeCertificate: 1094 // GMSSL暂时采用tls1.3的处理 1095 if c.vers == VersionTLS13 || c.vers == VersionGMSSL { 1096 m = new(certificateMsgTLS13) 1097 } else { 1098 m = new(certificateMsg) 1099 } 1100 case typeCertificateRequest: 1101 // GMSSL暂时采用tls1.3的处理 1102 if c.vers == VersionTLS13 || c.vers == VersionGMSSL { 1103 m = new(certificateRequestMsgTLS13) 1104 } else { 1105 m = &certificateRequestMsg{ 1106 hasSignatureAlgorithm: c.vers >= VersionTLS12, 1107 } 1108 } 1109 case typeCertificateStatus: 1110 m = new(certificateStatusMsg) 1111 case typeServerKeyExchange: 1112 m = new(serverKeyExchangeMsg) 1113 case typeServerHelloDone: 1114 m = new(serverHelloDoneMsg) 1115 case typeClientKeyExchange: 1116 m = new(clientKeyExchangeMsg) 1117 case typeCertificateVerify: 1118 m = &certificateVerifyMsg{ 1119 // GMSSL暂时采用tls1.3的处理 1120 hasSignatureAlgorithm: c.vers >= VersionTLS12 || c.vers == VersionGMSSL, 1121 } 1122 case typeFinished: 1123 m = new(finishedMsg) 1124 case typeEncryptedExtensions: 1125 m = new(encryptedExtensionsMsg) 1126 case typeEndOfEarlyData: 1127 m = new(endOfEarlyDataMsg) 1128 case typeKeyUpdate: 1129 m = new(keyUpdateMsg) 1130 default: 1131 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 1132 } 1133 1134 // The handshake message unmarshalers 1135 // expect to be able to keep references to data, 1136 // so pass in a fresh copy that won't be overwritten. 1137 data = append([]byte(nil), data...) 1138 1139 if !m.unmarshal(data) { 1140 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 1141 } 1142 return m, nil 1143 } 1144 1145 var ( 1146 errShutdown = errors.New("gmtls: protocol is shutdown") 1147 ) 1148 1149 // Write writes data to the connection. 1150 // 1151 // As Write calls Handshake, in order to prevent indefinite blocking a deadline 1152 // must be set for both Read and Write before Write is called when the handshake 1153 // has not yet completed. See SetDeadline, SetReadDeadline, and 1154 // SetWriteDeadline. 1155 func (c *Conn) Write(b []byte) (int, error) { 1156 // interlock with Close below 1157 for { 1158 x := atomic.LoadInt32(&c.activeCall) 1159 if x&1 != 0 { 1160 return 0, net.ErrClosed 1161 } 1162 if atomic.CompareAndSwapInt32(&c.activeCall, x, x+2) { 1163 break 1164 } 1165 } 1166 defer atomic.AddInt32(&c.activeCall, -2) 1167 1168 if err := c.Handshake(); err != nil { 1169 return 0, err 1170 } 1171 1172 c.out.Lock() 1173 defer c.out.Unlock() 1174 1175 if err := c.out.err; err != nil { 1176 return 0, err 1177 } 1178 1179 if !c.handshakeComplete() { 1180 return 0, alertInternalError 1181 } 1182 1183 if c.closeNotifySent { 1184 return 0, errShutdown 1185 } 1186 1187 // TLS 1.0 is susceptible to a chosen-plaintext 1188 // attack when using block mode ciphers due to predictable IVs. 1189 // This can be prevented by splitting each Application Data 1190 // record into two records, effectively randomizing the IV. 1191 // 1192 // https://www.openssl.org/~bodo/tls-cbc.txt 1193 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814 1194 // https://www.imperialviolet.org/2012/01/15/beastfollowup.html 1195 1196 var m int 1197 if len(b) > 1 && c.vers == VersionTLS10 { 1198 if _, ok := c.out.cipher.(cipher.BlockMode); ok { 1199 n, err := c.writeRecordLocked(recordTypeApplicationData, b[:1]) 1200 if err != nil { 1201 return n, c.out.setErrorLocked(err) 1202 } 1203 m, b = 1, b[1:] 1204 } 1205 } 1206 1207 n, err := c.writeRecordLocked(recordTypeApplicationData, b) 1208 return n + m, c.out.setErrorLocked(err) 1209 } 1210 1211 // handleRenegotiation processes a HelloRequest handshake message. 1212 func (c *Conn) handleRenegotiation() error { 1213 if c.vers == VersionTLS13 || c.vers == VersionGMSSL { 1214 return errors.New("gmtls: internal error: unexpected renegotiation") 1215 } 1216 1217 msg, err := c.readHandshake() 1218 if err != nil { 1219 return err 1220 } 1221 1222 helloReq, ok := msg.(*helloRequestMsg) 1223 if !ok { 1224 _ = c.sendAlert(alertUnexpectedMessage) 1225 return unexpectedMessageError(helloReq, msg) 1226 } 1227 1228 if !c.isClient { 1229 return c.sendAlert(alertNoRenegotiation) 1230 } 1231 1232 switch c.config.Renegotiation { 1233 case RenegotiateNever: 1234 return c.sendAlert(alertNoRenegotiation) 1235 case RenegotiateOnceAsClient: 1236 if c.handshakes > 1 { 1237 return c.sendAlert(alertNoRenegotiation) 1238 } 1239 case RenegotiateFreelyAsClient: 1240 // Ok. 1241 default: 1242 _ = c.sendAlert(alertInternalError) 1243 return errors.New("gmtls: unknown Renegotiation value") 1244 } 1245 1246 c.handshakeMutex.Lock() 1247 defer c.handshakeMutex.Unlock() 1248 1249 atomic.StoreUint32(&c.handshakeStatus, 0) 1250 if c.handshakeErr = c.clientHandshake(context.Background()); c.handshakeErr == nil { 1251 c.handshakes++ 1252 } 1253 return c.handshakeErr 1254 } 1255 1256 // 处理握手完成后到达的握手消息。 1257 // 1258 // 比如服务端发出的 newSessionTicketMsgTLS13 或 keyUpdateMsg。 1259 // 1260 // handlePostHandshakeMessage processes a handshake message arrived after the 1261 // handshake is complete. Up to TLS 1.2, it indicates the start of a renegotiation. 1262 func (c *Conn) handlePostHandshakeMessage() error { 1263 if c.vers != VersionTLS13 && c.vers != VersionGMSSL { 1264 return c.handleRenegotiation() 1265 } 1266 1267 msg, err := c.readHandshake() 1268 if err != nil { 1269 return err 1270 } 1271 1272 c.retryCount++ 1273 if c.retryCount > maxUselessRecords { 1274 _ = c.sendAlert(alertUnexpectedMessage) 1275 return c.in.setErrorLocked(errors.New("gmtls: too many non-advancing records")) 1276 } 1277 1278 switch msg := msg.(type) { 1279 case *newSessionTicketMsgTLS13: 1280 fmt.Println("===== 客户端接收到 newSessionTicketMsgTLS13") 1281 return c.handleNewSessionTicket(msg) 1282 case *keyUpdateMsg: 1283 fmt.Println("===== 客户端/服务端接收到 keyUpdateMsg") 1284 return c.handleKeyUpdate(msg) 1285 default: 1286 _ = c.sendAlert(alertUnexpectedMessage) 1287 return fmt.Errorf("gmtls: received unexpected handshake message of type %T", msg) 1288 } 1289 } 1290 1291 // 发起keyUpdateMsg, 或处理接收到的keyUpdateMsg 1292 func (c *Conn) handleKeyUpdate(keyUpdate *keyUpdateMsg) error { 1293 cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite) 1294 if cipherSuite == nil { 1295 return c.in.setErrorLocked(c.sendAlert(alertInternalError)) 1296 } 1297 // 派生新的对方的通信密钥并设置到连接通道in 1298 newSecret := cipherSuite.nextTrafficSecret(c.in.trafficSecret) 1299 c.in.setTrafficSecret(cipherSuite, newSecret) 1300 // 作为keyUpdate发起方(updateRequested == true),通知tls通信对方更新会话密钥 1301 if keyUpdate.updateRequested { 1302 c.out.Lock() 1303 defer c.out.Unlock() 1304 // 创建一个新的keyUpdateMsg,此时updateRequested默认为false 1305 msg := &keyUpdateMsg{} 1306 // 发送 keyUpdateMsg 1307 _, err := c.writeRecordLocked(recordTypeHandshake, msg.marshal()) 1308 if err != nil { 1309 // Surface the error at the next write. 1310 err := c.out.setErrorLocked(err) 1311 if err != nil { 1312 return err 1313 } 1314 return nil 1315 } 1316 fmt.Println("===== 客户端/服务端发出 keyUpdateMsg") 1317 // 发出 keyUpdateMsg 之后才能派生新的己方通信密钥并设置到连接out通道 1318 newSecret := cipherSuite.nextTrafficSecret(c.out.trafficSecret) 1319 c.out.setTrafficSecret(cipherSuite, newSecret) 1320 } 1321 return nil 1322 } 1323 1324 // Read reads data from the connection. 1325 // 1326 // As Read calls Handshake, in order to prevent indefinite blocking a deadline 1327 // must be set for both Read and Write before Read is called when the handshake 1328 // has not yet completed. See SetDeadline, SetReadDeadline, and 1329 // SetWriteDeadline. 1330 func (c *Conn) Read(b []byte) (int, error) { 1331 //fmt.Println("===== tls连接读取到一条消息") 1332 if err := c.Handshake(); err != nil { 1333 log.Fatal(err) 1334 return 0, err 1335 } 1336 if len(b) == 0 { 1337 // Put this after Handshake, in case people were calling 1338 // Read(nil) for the side effect of the Handshake. 1339 return 0, nil 1340 } 1341 1342 c.in.Lock() 1343 defer c.in.Unlock() 1344 1345 for c.input.Len() == 0 { 1346 if err := c.readRecord(); err != nil { 1347 return 0, err 1348 } 1349 for c.hand.Len() > 0 { 1350 if err := c.handlePostHandshakeMessage(); err != nil { 1351 return 0, err 1352 } 1353 } 1354 } 1355 1356 n, _ := c.input.Read(b) 1357 1358 // If a close-notify alert is waiting, read it so that we can return (n, 1359 // EOF) instead of (n, nil), to signal to the HTTP response reading 1360 // goroutine that the connection is now closed. This eliminates a race 1361 // where the HTTP response reading goroutine would otherwise not observe 1362 // the EOF until its next read, by which time a client goroutine might 1363 // have already tried to reuse the HTTP connection for a new request. 1364 // See https://golang.org/cl/76400046 and https://golang.org/issue/3514 1365 if n != 0 && c.input.Len() == 0 && c.rawInput.Len() > 0 && 1366 recordType(c.rawInput.Bytes()[0]) == recordTypeAlert { 1367 if err := c.readRecord(); err != nil { 1368 return n, err // will be io.EOF on closeNotify 1369 } 1370 } 1371 1372 return n, nil 1373 } 1374 1375 // Close closes the connection. 1376 func (c *Conn) Close() error { 1377 // Interlock with Conn.Write above. 1378 var x int32 1379 for { 1380 x = atomic.LoadInt32(&c.activeCall) 1381 if x&1 != 0 { 1382 return net.ErrClosed 1383 } 1384 if atomic.CompareAndSwapInt32(&c.activeCall, x, x|1) { 1385 break 1386 } 1387 } 1388 if x != 0 { 1389 // io.Writer and io.Closer should not be used concurrently. 1390 // If Close is called while a Write is currently in-flight, 1391 // interpret that as a sign that this Close is really just 1392 // being used to break the Write and/or clean up resources and 1393 // avoid sending the alertCloseNotify, which may block 1394 // waiting on handshakeMutex or the c.out mutex. 1395 return c.conn.Close() 1396 } 1397 1398 var alertErr error 1399 if c.handshakeComplete() { 1400 if err := c.closeNotify(); err != nil { 1401 alertErr = fmt.Errorf("gmtls: failed to send closeNotify alert (but connection was closed anyway): %w", err) 1402 } 1403 } 1404 1405 if err := c.conn.Close(); err != nil { 1406 return err 1407 } 1408 return alertErr 1409 } 1410 1411 var errEarlyCloseWrite = errors.New("gmtls: CloseWrite called before handshake complete") 1412 1413 // CloseWrite shuts down the writing side of the connection. It should only be 1414 // called once the handshake has completed and does not call CloseWrite on the 1415 // underlying connection. Most callers should just use Close. 1416 func (c *Conn) CloseWrite() error { 1417 if !c.handshakeComplete() { 1418 return errEarlyCloseWrite 1419 } 1420 1421 return c.closeNotify() 1422 } 1423 1424 func (c *Conn) closeNotify() error { 1425 c.out.Lock() 1426 defer c.out.Unlock() 1427 1428 if !c.closeNotifySent { 1429 // Set a Write Deadline to prevent possibly blocking forever. 1430 err := c.SetWriteDeadline(time.Now().Add(time.Second * 5)) 1431 if err != nil { 1432 return err 1433 } 1434 c.closeNotifyErr = c.sendAlertLocked(alertCloseNotify) 1435 c.closeNotifySent = true 1436 // Any subsequent writes will fail. 1437 err = c.SetWriteDeadline(time.Now()) 1438 if err != nil { 1439 return err 1440 } 1441 } 1442 return c.closeNotifyErr 1443 } 1444 1445 // Handshake runs the client or server handshake 1446 // protocol if it has not yet been run. 1447 // 1448 // Most uses of this package need not call Handshake explicitly: the 1449 // first Read or Write will call it automatically. 1450 // 1451 // For control over canceling or setting a timeout on a handshake, use 1452 // HandshakeContext or the Dialer's DialContext method instead. 1453 func (c *Conn) Handshake() error { 1454 return c.HandshakeContext(context.Background()) 1455 } 1456 1457 // HandshakeContext runs the client or server handshake 1458 // protocol if it has not yet been run. 1459 // 1460 // The provided Context must be non-nil. If the context is canceled before 1461 // the handshake is complete, the handshake is interrupted and an error is returned. 1462 // Once the handshake has completed, cancellation of the context will not affect the 1463 // connection. 1464 // 1465 // Most uses of this package need not call HandshakeContext explicitly: the 1466 // first Read or Write will call it automatically. 1467 func (c *Conn) HandshakeContext(ctx context.Context) error { 1468 // Delegate to unexported method for named return 1469 // without confusing documented signature. 1470 return c.handshakeContext(ctx) 1471 } 1472 1473 // 根据上下文环境执行握手 1474 func (c *Conn) handshakeContext(ctx context.Context) (ret error) { 1475 handshakeCtx, cancel := context.WithCancel(ctx) 1476 // Note: defer this before starting the "interrupter" goroutine 1477 // so that we can tell the difference between the input being canceled and 1478 // this cancellation. In the former case, we need to close the connection. 1479 defer cancel() 1480 1481 // Start the "interrupter" goroutine, if this context might be canceled. 1482 // (The background context cannot). 1483 // 1484 // The interrupter goroutine waits for the input context to be done and 1485 // closes the connection if this happens before the function returns. 1486 if ctx.Done() != nil { 1487 done := make(chan struct{}) 1488 interruptRes := make(chan error, 1) 1489 defer func() { 1490 close(done) 1491 if ctxErr := <-interruptRes; ctxErr != nil { 1492 // Return context error to user. 1493 ret = ctxErr 1494 } 1495 }() 1496 go func() { 1497 select { 1498 case <-handshakeCtx.Done(): 1499 // Close the connection, discarding the error 1500 _ = c.conn.Close() 1501 interruptRes <- handshakeCtx.Err() 1502 case <-done: 1503 interruptRes <- nil 1504 } 1505 }() 1506 } 1507 1508 c.handshakeMutex.Lock() 1509 defer c.handshakeMutex.Unlock() 1510 1511 if err := c.handshakeErr; err != nil { 1512 return err 1513 } 1514 if c.handshakeComplete() { 1515 return nil 1516 } 1517 1518 c.in.Lock() 1519 defer c.in.Unlock() 1520 // 调用握手函数 1521 c.handshakeErr = c.handshakeFn(handshakeCtx) 1522 if c.handshakeErr == nil { 1523 c.handshakes++ 1524 } else { 1525 // If an error occurred during the handshake try to flush the 1526 // alert that might be left in the buffer. 1527 _, err := c.flush() 1528 if err != nil { 1529 return err 1530 } 1531 } 1532 1533 if c.handshakeErr == nil && !c.handshakeComplete() { 1534 c.handshakeErr = errors.New("gmtls: internal error: handshake should have had a result") 1535 } 1536 1537 return c.handshakeErr 1538 } 1539 1540 // ConnectionState returns basic TLS details about the connection. 1541 func (c *Conn) ConnectionState() ConnectionState { 1542 c.handshakeMutex.Lock() 1543 defer c.handshakeMutex.Unlock() 1544 return c.connectionStateLocked() 1545 } 1546 1547 func (c *Conn) connectionStateLocked() ConnectionState { 1548 var state ConnectionState 1549 state.HandshakeComplete = c.handshakeComplete() 1550 state.Version = c.vers 1551 state.NegotiatedProtocol = c.clientProtocol 1552 state.DidResume = c.didResume 1553 state.NegotiatedProtocolIsMutual = true 1554 state.ServerName = c.serverName 1555 state.CipherSuite = c.cipherSuite 1556 state.PeerCertificates = c.peerCertificates 1557 state.VerifiedChains = c.verifiedChains 1558 state.SignedCertificateTimestamps = c.scts 1559 state.OCSPResponse = c.ocspResponse 1560 if !c.didResume && c.vers != VersionTLS13 && c.vers != VersionGMSSL { 1561 if c.clientFinishedIsFirst { 1562 state.TLSUnique = c.clientFinished[:] 1563 } else { 1564 state.TLSUnique = c.serverFinished[:] 1565 } 1566 } 1567 if c.config.Renegotiation != RenegotiateNever { 1568 state.ekm = noExportedKeyingMaterial 1569 } else { 1570 state.ekm = c.ekm 1571 } 1572 return state 1573 } 1574 1575 // OCSPResponse returns the stapled OCSP response from the TLS server, if 1576 // any. (Only valid for client connections.) 1577 func (c *Conn) OCSPResponse() []byte { 1578 c.handshakeMutex.Lock() 1579 defer c.handshakeMutex.Unlock() 1580 1581 return c.ocspResponse 1582 } 1583 1584 // VerifyHostname checks that the peer certificate chain is valid for 1585 // connecting to host. If so, it returns nil; if not, it returns an error 1586 // describing the problem. 1587 func (c *Conn) VerifyHostname(host string) error { 1588 c.handshakeMutex.Lock() 1589 defer c.handshakeMutex.Unlock() 1590 if !c.isClient { 1591 return errors.New("gmtls: VerifyHostname called on TLS server connection") 1592 } 1593 if !c.handshakeComplete() { 1594 return errors.New("gmtls: handshake has not yet been performed") 1595 } 1596 if len(c.verifiedChains) == 0 { 1597 return errors.New("gmtls: handshake did not verify certificate chain") 1598 } 1599 return c.peerCertificates[0].VerifyHostname(host) 1600 } 1601 1602 func (c *Conn) handshakeComplete() bool { 1603 return atomic.LoadUint32(&c.handshakeStatus) == 1 1604 }