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