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