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