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