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