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