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