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