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