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