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