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