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 | |
Adam Langley | dc7e9c4 | 2015-09-29 15:21:04 -0700 | [diff] [blame] | 7 | package runner |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 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" |
David Benjamin | 8e6db49 | 2015-07-25 18:29:23 -0400 | [diff] [blame] | 15 | "encoding/binary" |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 16 | "errors" |
| 17 | "fmt" |
| 18 | "io" |
| 19 | "net" |
| 20 | "sync" |
| 21 | "time" |
| 22 | ) |
| 23 | |
| 24 | // A Conn represents a secured connection. |
| 25 | // It implements the net.Conn interface. |
| 26 | type Conn struct { |
| 27 | // constant |
| 28 | conn net.Conn |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 29 | isDTLS bool |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 30 | isClient bool |
| 31 | |
| 32 | // constant after handshake; protected by handshakeMutex |
Adam Langley | 7571292 | 2014-10-10 16:23:43 -0700 | [diff] [blame] | 33 | handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex |
| 34 | handshakeErr error // error resulting from handshake |
| 35 | vers uint16 // TLS version |
| 36 | haveVers bool // version has been negotiated |
| 37 | config *Config // configuration passed to constructor |
| 38 | handshakeComplete bool |
| 39 | didResume bool // whether this connection was a session resumption |
| 40 | extendedMasterSecret bool // whether this session used an extended master secret |
David Benjamin | c565ebb | 2015-04-03 04:06:36 -0400 | [diff] [blame] | 41 | cipherSuite *cipherSuite |
Adam Langley | 7571292 | 2014-10-10 16:23:43 -0700 | [diff] [blame] | 42 | ocspResponse []byte // stapled OCSP response |
Paul Lietar | 4fac72e | 2015-09-09 13:44:55 +0100 | [diff] [blame] | 43 | sctList []byte // signed certificate timestamp list |
Adam Langley | 7571292 | 2014-10-10 16:23:43 -0700 | [diff] [blame] | 44 | peerCertificates []*x509.Certificate |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 45 | // verifiedChains contains the certificate chains that we built, as |
| 46 | // opposed to the ones presented by the server. |
| 47 | verifiedChains [][]*x509.Certificate |
| 48 | // serverName contains the server name indicated by the client, if any. |
Adam Langley | af0e32c | 2015-06-03 09:57:23 -0700 | [diff] [blame] | 49 | serverName string |
| 50 | // firstFinished contains the first Finished hash sent during the |
| 51 | // handshake. This is the "tls-unique" channel binding value. |
| 52 | firstFinished [12]byte |
Steven Valdez | 0d62f26 | 2015-09-04 12:41:04 -0400 | [diff] [blame] | 53 | // clientCertSignatureHash contains the TLS hash id for the hash that |
| 54 | // was used by the client to sign the handshake with a client |
| 55 | // certificate. This is only set by a server and is zero if no client |
| 56 | // certificates were used. |
| 57 | clientCertSignatureHash uint8 |
Adam Langley | af0e32c | 2015-06-03 09:57:23 -0700 | [diff] [blame] | 58 | |
David Benjamin | c565ebb | 2015-04-03 04:06:36 -0400 | [diff] [blame] | 59 | clientRandom, serverRandom [32]byte |
| 60 | masterSecret [48]byte |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 61 | |
| 62 | clientProtocol string |
| 63 | clientProtocolFallback bool |
David Benjamin | fc7b086 | 2014-09-06 13:21:53 -0400 | [diff] [blame] | 64 | usedALPN bool |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 65 | |
Adam Langley | 2ae77d2 | 2014-10-28 17:29:33 -0700 | [diff] [blame] | 66 | // verify_data values for the renegotiation extension. |
| 67 | clientVerify []byte |
| 68 | serverVerify []byte |
| 69 | |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame] | 70 | channelID *ecdsa.PublicKey |
| 71 | |
David Benjamin | ca6c826 | 2014-11-15 19:06:08 -0500 | [diff] [blame] | 72 | srtpProtectionProfile uint16 |
| 73 | |
David Benjamin | c44b1df | 2014-11-23 12:11:01 -0500 | [diff] [blame] | 74 | clientVersion uint16 |
| 75 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 76 | // input/output |
| 77 | in, out halfConn // in.Mutex < out.Mutex |
| 78 | rawInput *block // raw input, right off the wire |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 79 | input *block // application record waiting to be read |
| 80 | hand bytes.Buffer // handshake record waiting to be read |
| 81 | |
| 82 | // DTLS state |
| 83 | sendHandshakeSeq uint16 |
| 84 | recvHandshakeSeq uint16 |
David Benjamin | b3774b9 | 2015-01-31 17:16:01 -0500 | [diff] [blame] | 85 | handMsg []byte // pending assembled handshake message |
| 86 | handMsgLen int // handshake message length, not including the header |
| 87 | pendingFragments [][]byte // pending outgoing handshake fragments. |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 88 | |
| 89 | tmp [16]byte |
| 90 | } |
| 91 | |
David Benjamin | 5e961c1 | 2014-11-07 01:48:35 -0500 | [diff] [blame] | 92 | func (c *Conn) init() { |
| 93 | c.in.isDTLS = c.isDTLS |
| 94 | c.out.isDTLS = c.isDTLS |
| 95 | c.in.config = c.config |
| 96 | c.out.config = c.config |
David Benjamin | 8e6db49 | 2015-07-25 18:29:23 -0400 | [diff] [blame] | 97 | |
| 98 | c.out.updateOutSeq() |
David Benjamin | 5e961c1 | 2014-11-07 01:48:35 -0500 | [diff] [blame] | 99 | } |
| 100 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 101 | // Access to net.Conn methods. |
| 102 | // Cannot just embed net.Conn because that would |
| 103 | // export the struct field too. |
| 104 | |
| 105 | // LocalAddr returns the local network address. |
| 106 | func (c *Conn) LocalAddr() net.Addr { |
| 107 | return c.conn.LocalAddr() |
| 108 | } |
| 109 | |
| 110 | // RemoteAddr returns the remote network address. |
| 111 | func (c *Conn) RemoteAddr() net.Addr { |
| 112 | return c.conn.RemoteAddr() |
| 113 | } |
| 114 | |
| 115 | // SetDeadline sets the read and write deadlines associated with the connection. |
| 116 | // A zero value for t means Read and Write will not time out. |
| 117 | // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error. |
| 118 | func (c *Conn) SetDeadline(t time.Time) error { |
| 119 | return c.conn.SetDeadline(t) |
| 120 | } |
| 121 | |
| 122 | // SetReadDeadline sets the read deadline on the underlying connection. |
| 123 | // A zero value for t means Read will not time out. |
| 124 | func (c *Conn) SetReadDeadline(t time.Time) error { |
| 125 | return c.conn.SetReadDeadline(t) |
| 126 | } |
| 127 | |
| 128 | // SetWriteDeadline sets the write deadline on the underlying conneciton. |
| 129 | // A zero value for t means Write will not time out. |
| 130 | // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error. |
| 131 | func (c *Conn) SetWriteDeadline(t time.Time) error { |
| 132 | return c.conn.SetWriteDeadline(t) |
| 133 | } |
| 134 | |
| 135 | // A halfConn represents one direction of the record layer |
| 136 | // connection, either sending or receiving. |
| 137 | type halfConn struct { |
| 138 | sync.Mutex |
| 139 | |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 140 | err error // first permanent error |
| 141 | version uint16 // protocol version |
| 142 | isDTLS bool |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 143 | cipher interface{} // cipher algorithm |
| 144 | mac macFunction |
| 145 | seq [8]byte // 64-bit sequence number |
David Benjamin | 8e6db49 | 2015-07-25 18:29:23 -0400 | [diff] [blame] | 146 | outSeq [8]byte // Mapped sequence number |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 147 | bfree *block // list of free blocks |
| 148 | |
| 149 | nextCipher interface{} // next encryption state |
| 150 | nextMac macFunction // next MAC algorithm |
David Benjamin | 83f9040 | 2015-01-27 01:09:43 -0500 | [diff] [blame] | 151 | nextSeq [6]byte // next epoch's starting sequence number in DTLS |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 152 | |
| 153 | // used to save allocating a new buffer for each MAC. |
| 154 | inDigestBuf, outDigestBuf []byte |
Adam Langley | 80842bd | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 155 | |
| 156 | config *Config |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 157 | } |
| 158 | |
| 159 | func (hc *halfConn) setErrorLocked(err error) error { |
| 160 | hc.err = err |
| 161 | return err |
| 162 | } |
| 163 | |
| 164 | func (hc *halfConn) error() error { |
Adam Langley | 2ae77d2 | 2014-10-28 17:29:33 -0700 | [diff] [blame] | 165 | // This should be locked, but I've removed it for the renegotiation |
| 166 | // tests since we don't concurrently read and write the same tls.Conn |
| 167 | // in any case during testing. |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 168 | err := hc.err |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 169 | return err |
| 170 | } |
| 171 | |
| 172 | // prepareCipherSpec sets the encryption and MAC states |
| 173 | // that a subsequent changeCipherSpec will use. |
| 174 | func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) { |
| 175 | hc.version = version |
| 176 | hc.nextCipher = cipher |
| 177 | hc.nextMac = mac |
| 178 | } |
| 179 | |
| 180 | // changeCipherSpec changes the encryption and MAC states |
| 181 | // to the ones previously passed to prepareCipherSpec. |
Adam Langley | 80842bd | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 182 | func (hc *halfConn) changeCipherSpec(config *Config) error { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 183 | if hc.nextCipher == nil { |
| 184 | return alertInternalError |
| 185 | } |
| 186 | hc.cipher = hc.nextCipher |
| 187 | hc.mac = hc.nextMac |
| 188 | hc.nextCipher = nil |
| 189 | hc.nextMac = nil |
Adam Langley | 80842bd | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 190 | hc.config = config |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 191 | hc.incEpoch() |
David Benjamin | f2b8363 | 2016-03-01 22:57:46 -0500 | [diff] [blame] | 192 | |
| 193 | if config.Bugs.NullAllCiphers { |
| 194 | hc.cipher = nil |
| 195 | hc.mac = nil |
| 196 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 197 | return nil |
| 198 | } |
| 199 | |
| 200 | // incSeq increments the sequence number. |
David Benjamin | 5e961c1 | 2014-11-07 01:48:35 -0500 | [diff] [blame] | 201 | func (hc *halfConn) incSeq(isOutgoing bool) { |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 202 | limit := 0 |
David Benjamin | 5e961c1 | 2014-11-07 01:48:35 -0500 | [diff] [blame] | 203 | increment := uint64(1) |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 204 | if hc.isDTLS { |
| 205 | // Increment up to the epoch in DTLS. |
| 206 | limit = 2 |
| 207 | } |
| 208 | for i := 7; i >= limit; i-- { |
David Benjamin | 5e961c1 | 2014-11-07 01:48:35 -0500 | [diff] [blame] | 209 | increment += uint64(hc.seq[i]) |
| 210 | hc.seq[i] = byte(increment) |
| 211 | increment >>= 8 |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 212 | } |
| 213 | |
| 214 | // Not allowed to let sequence number wrap. |
| 215 | // Instead, must renegotiate before it does. |
| 216 | // Not likely enough to bother. |
David Benjamin | 5e961c1 | 2014-11-07 01:48:35 -0500 | [diff] [blame] | 217 | if increment != 0 { |
| 218 | panic("TLS: sequence number wraparound") |
| 219 | } |
David Benjamin | 8e6db49 | 2015-07-25 18:29:23 -0400 | [diff] [blame] | 220 | |
| 221 | hc.updateOutSeq() |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 222 | } |
| 223 | |
David Benjamin | 83f9040 | 2015-01-27 01:09:43 -0500 | [diff] [blame] | 224 | // incNextSeq increments the starting sequence number for the next epoch. |
| 225 | func (hc *halfConn) incNextSeq() { |
| 226 | for i := len(hc.nextSeq) - 1; i >= 0; i-- { |
| 227 | hc.nextSeq[i]++ |
| 228 | if hc.nextSeq[i] != 0 { |
| 229 | return |
| 230 | } |
| 231 | } |
| 232 | panic("TLS: sequence number wraparound") |
| 233 | } |
| 234 | |
| 235 | // incEpoch resets the sequence number. In DTLS, it also increments the epoch |
| 236 | // half of the sequence number. |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 237 | func (hc *halfConn) incEpoch() { |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 238 | if hc.isDTLS { |
| 239 | for i := 1; i >= 0; i-- { |
| 240 | hc.seq[i]++ |
| 241 | if hc.seq[i] != 0 { |
| 242 | break |
| 243 | } |
| 244 | if i == 0 { |
| 245 | panic("TLS: epoch number wraparound") |
| 246 | } |
| 247 | } |
David Benjamin | 83f9040 | 2015-01-27 01:09:43 -0500 | [diff] [blame] | 248 | copy(hc.seq[2:], hc.nextSeq[:]) |
| 249 | for i := range hc.nextSeq { |
| 250 | hc.nextSeq[i] = 0 |
| 251 | } |
| 252 | } else { |
| 253 | for i := range hc.seq { |
| 254 | hc.seq[i] = 0 |
| 255 | } |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 256 | } |
David Benjamin | 8e6db49 | 2015-07-25 18:29:23 -0400 | [diff] [blame] | 257 | |
| 258 | hc.updateOutSeq() |
| 259 | } |
| 260 | |
| 261 | func (hc *halfConn) updateOutSeq() { |
| 262 | if hc.config.Bugs.SequenceNumberMapping != nil { |
| 263 | seqU64 := binary.BigEndian.Uint64(hc.seq[:]) |
| 264 | seqU64 = hc.config.Bugs.SequenceNumberMapping(seqU64) |
| 265 | binary.BigEndian.PutUint64(hc.outSeq[:], seqU64) |
| 266 | |
| 267 | // The DTLS epoch cannot be changed. |
| 268 | copy(hc.outSeq[:2], hc.seq[:2]) |
| 269 | return |
| 270 | } |
| 271 | |
| 272 | copy(hc.outSeq[:], hc.seq[:]) |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 273 | } |
| 274 | |
| 275 | func (hc *halfConn) recordHeaderLen() int { |
| 276 | if hc.isDTLS { |
| 277 | return dtlsRecordHeaderLen |
| 278 | } |
| 279 | return tlsRecordHeaderLen |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 280 | } |
| 281 | |
| 282 | // removePadding returns an unpadded slice, in constant time, which is a prefix |
| 283 | // of the input. It also returns a byte which is equal to 255 if the padding |
| 284 | // was valid and 0 otherwise. See RFC 2246, section 6.2.3.2 |
| 285 | func removePadding(payload []byte) ([]byte, byte) { |
| 286 | if len(payload) < 1 { |
| 287 | return payload, 0 |
| 288 | } |
| 289 | |
| 290 | paddingLen := payload[len(payload)-1] |
| 291 | t := uint(len(payload)-1) - uint(paddingLen) |
| 292 | // if len(payload) >= (paddingLen - 1) then the MSB of t is zero |
| 293 | good := byte(int32(^t) >> 31) |
| 294 | |
| 295 | toCheck := 255 // the maximum possible padding length |
| 296 | // The length of the padded data is public, so we can use an if here |
| 297 | if toCheck+1 > len(payload) { |
| 298 | toCheck = len(payload) - 1 |
| 299 | } |
| 300 | |
| 301 | for i := 0; i < toCheck; i++ { |
| 302 | t := uint(paddingLen) - uint(i) |
| 303 | // if i <= paddingLen then the MSB of t is zero |
| 304 | mask := byte(int32(^t) >> 31) |
| 305 | b := payload[len(payload)-1-i] |
| 306 | good &^= mask&paddingLen ^ mask&b |
| 307 | } |
| 308 | |
| 309 | // We AND together the bits of good and replicate the result across |
| 310 | // all the bits. |
| 311 | good &= good << 4 |
| 312 | good &= good << 2 |
| 313 | good &= good << 1 |
| 314 | good = uint8(int8(good) >> 7) |
| 315 | |
| 316 | toRemove := good&paddingLen + 1 |
| 317 | return payload[:len(payload)-int(toRemove)], good |
| 318 | } |
| 319 | |
| 320 | // removePaddingSSL30 is a replacement for removePadding in the case that the |
| 321 | // protocol version is SSLv3. In this version, the contents of the padding |
| 322 | // are random and cannot be checked. |
| 323 | func removePaddingSSL30(payload []byte) ([]byte, byte) { |
| 324 | if len(payload) < 1 { |
| 325 | return payload, 0 |
| 326 | } |
| 327 | |
| 328 | paddingLen := int(payload[len(payload)-1]) + 1 |
| 329 | if paddingLen > len(payload) { |
| 330 | return payload, 0 |
| 331 | } |
| 332 | |
| 333 | return payload[:len(payload)-paddingLen], 255 |
| 334 | } |
| 335 | |
| 336 | func roundUp(a, b int) int { |
| 337 | return a + (b-a%b)%b |
| 338 | } |
| 339 | |
| 340 | // cbcMode is an interface for block ciphers using cipher block chaining. |
| 341 | type cbcMode interface { |
| 342 | cipher.BlockMode |
| 343 | SetIV([]byte) |
| 344 | } |
| 345 | |
| 346 | // decrypt checks and strips the mac and decrypts the data in b. Returns a |
| 347 | // success boolean, the number of bytes to skip from the start of the record in |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 348 | // order to get the application payload, the encrypted record type (or 0 |
| 349 | // if there is none), and an optional alert value. |
| 350 | func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, contentType recordType, alertValue alert) { |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 351 | recordHeaderLen := hc.recordHeaderLen() |
| 352 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 353 | // pull out payload |
| 354 | payload := b.data[recordHeaderLen:] |
| 355 | |
| 356 | macSize := 0 |
| 357 | if hc.mac != nil { |
| 358 | macSize = hc.mac.Size() |
| 359 | } |
| 360 | |
| 361 | paddingGood := byte(255) |
| 362 | explicitIVLen := 0 |
| 363 | |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 364 | seq := hc.seq[:] |
| 365 | if hc.isDTLS { |
| 366 | // DTLS sequence numbers are explicit. |
| 367 | seq = b.data[3:11] |
| 368 | } |
| 369 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 370 | // decrypt |
| 371 | if hc.cipher != nil { |
| 372 | switch c := hc.cipher.(type) { |
| 373 | case cipher.Stream: |
| 374 | c.XORKeyStream(payload, payload) |
David Benjamin | e9a80ff | 2015-04-07 00:46:46 -0400 | [diff] [blame] | 375 | case *tlsAead: |
| 376 | nonce := seq |
| 377 | if c.explicitNonce { |
| 378 | explicitIVLen = 8 |
| 379 | if len(payload) < explicitIVLen { |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 380 | return false, 0, 0, alertBadRecordMAC |
David Benjamin | e9a80ff | 2015-04-07 00:46:46 -0400 | [diff] [blame] | 381 | } |
| 382 | nonce = payload[:8] |
| 383 | payload = payload[8:] |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 384 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 385 | |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 386 | var additionalData []byte |
| 387 | if hc.version < VersionTLS13 { |
| 388 | additionalData = make([]byte, 13) |
| 389 | copy(additionalData, seq) |
| 390 | copy(additionalData[8:], b.data[:3]) |
| 391 | n := len(payload) - c.Overhead() |
| 392 | additionalData[11] = byte(n >> 8) |
| 393 | additionalData[12] = byte(n) |
| 394 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 395 | var err error |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 396 | payload, err = c.Open(payload[:0], nonce, payload, additionalData) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 397 | if err != nil { |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 398 | return false, 0, 0, alertBadRecordMAC |
| 399 | } |
| 400 | if hc.version >= VersionTLS13 { |
| 401 | i := len(payload) |
| 402 | for i > 0 && payload[i-1] == 0 { |
| 403 | i-- |
| 404 | } |
| 405 | payload = payload[:i] |
| 406 | if len(payload) == 0 { |
| 407 | return false, 0, 0, alertUnexpectedMessage |
| 408 | } |
| 409 | contentType = recordType(payload[len(payload)-1]) |
| 410 | payload = payload[:len(payload)-1] |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 411 | } |
| 412 | b.resize(recordHeaderLen + explicitIVLen + len(payload)) |
| 413 | case cbcMode: |
| 414 | blockSize := c.BlockSize() |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 415 | if hc.version >= VersionTLS11 || hc.isDTLS { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 416 | explicitIVLen = blockSize |
| 417 | } |
| 418 | |
| 419 | if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) { |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 420 | return false, 0, 0, alertBadRecordMAC |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 421 | } |
| 422 | |
| 423 | if explicitIVLen > 0 { |
| 424 | c.SetIV(payload[:explicitIVLen]) |
| 425 | payload = payload[explicitIVLen:] |
| 426 | } |
| 427 | c.CryptBlocks(payload, payload) |
| 428 | if hc.version == VersionSSL30 { |
| 429 | payload, paddingGood = removePaddingSSL30(payload) |
| 430 | } else { |
| 431 | payload, paddingGood = removePadding(payload) |
| 432 | } |
| 433 | b.resize(recordHeaderLen + explicitIVLen + len(payload)) |
| 434 | |
| 435 | // note that we still have a timing side-channel in the |
| 436 | // MAC check, below. An attacker can align the record |
| 437 | // so that a correct padding will cause one less hash |
| 438 | // block to be calculated. Then they can iteratively |
| 439 | // decrypt a record by breaking each byte. See |
| 440 | // "Password Interception in a SSL/TLS Channel", Brice |
| 441 | // Canvel et al. |
| 442 | // |
| 443 | // However, our behavior matches OpenSSL, so we leak |
| 444 | // only as much as they do. |
Matt Braithwaite | af09675 | 2015-09-02 19:48:16 -0700 | [diff] [blame] | 445 | case nullCipher: |
| 446 | break |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 447 | default: |
| 448 | panic("unknown cipher type") |
| 449 | } |
| 450 | } |
| 451 | |
| 452 | // check, strip mac |
| 453 | if hc.mac != nil { |
| 454 | if len(payload) < macSize { |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 455 | return false, 0, 0, alertBadRecordMAC |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 456 | } |
| 457 | |
| 458 | // strip mac off payload, b.data |
| 459 | n := len(payload) - macSize |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 460 | b.data[recordHeaderLen-2] = byte(n >> 8) |
| 461 | b.data[recordHeaderLen-1] = byte(n) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 462 | b.resize(recordHeaderLen + explicitIVLen + n) |
| 463 | remoteMAC := payload[n:] |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 464 | 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] | 465 | |
| 466 | if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 { |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 467 | return false, 0, 0, alertBadRecordMAC |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 468 | } |
| 469 | hc.inDigestBuf = localMAC |
| 470 | } |
David Benjamin | 5e961c1 | 2014-11-07 01:48:35 -0500 | [diff] [blame] | 471 | hc.incSeq(false) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 472 | |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 473 | return true, recordHeaderLen + explicitIVLen, contentType, 0 |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 474 | } |
| 475 | |
| 476 | // padToBlockSize calculates the needed padding block, if any, for a payload. |
| 477 | // On exit, prefix aliases payload and extends to the end of the last full |
| 478 | // block of payload. finalBlock is a fresh slice which contains the contents of |
| 479 | // any suffix of payload as well as the needed padding to make finalBlock a |
| 480 | // full block. |
Adam Langley | 80842bd | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 481 | func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 482 | overrun := len(payload) % blockSize |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 483 | prefix = payload[:len(payload)-overrun] |
Adam Langley | 80842bd | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 484 | |
| 485 | paddingLen := blockSize - overrun |
| 486 | finalSize := blockSize |
| 487 | if config.Bugs.MaxPadding { |
| 488 | for paddingLen+blockSize <= 256 { |
| 489 | paddingLen += blockSize |
| 490 | } |
| 491 | finalSize = 256 |
| 492 | } |
| 493 | finalBlock = make([]byte, finalSize) |
| 494 | for i := range finalBlock { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 495 | finalBlock[i] = byte(paddingLen - 1) |
| 496 | } |
Adam Langley | 80842bd | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 497 | if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 { |
| 498 | finalBlock[overrun] ^= 0xff |
| 499 | } |
| 500 | copy(finalBlock, payload[len(payload)-overrun:]) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 501 | return |
| 502 | } |
| 503 | |
| 504 | // encrypt encrypts and macs the data in b. |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 505 | func (hc *halfConn) encrypt(b *block, explicitIVLen int, typ recordType) (bool, alert) { |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 506 | recordHeaderLen := hc.recordHeaderLen() |
| 507 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 508 | // mac |
| 509 | if hc.mac != nil { |
David Benjamin | 8e6db49 | 2015-07-25 18:29:23 -0400 | [diff] [blame] | 510 | mac := hc.mac.MAC(hc.outDigestBuf, hc.outSeq[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] | 511 | |
| 512 | n := len(b.data) |
| 513 | b.resize(n + len(mac)) |
| 514 | copy(b.data[n:], mac) |
| 515 | hc.outDigestBuf = mac |
| 516 | } |
| 517 | |
| 518 | payload := b.data[recordHeaderLen:] |
| 519 | |
| 520 | // encrypt |
| 521 | if hc.cipher != nil { |
| 522 | switch c := hc.cipher.(type) { |
| 523 | case cipher.Stream: |
| 524 | c.XORKeyStream(payload, payload) |
David Benjamin | e9a80ff | 2015-04-07 00:46:46 -0400 | [diff] [blame] | 525 | case *tlsAead: |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 526 | payloadLen := len(b.data) - recordHeaderLen - explicitIVLen |
David Benjamin | c9ae27c | 2016-06-24 22:56:37 -0400 | [diff] [blame^] | 527 | paddingLen := 0 |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 528 | if hc.version >= VersionTLS13 { |
David Benjamin | c9ae27c | 2016-06-24 22:56:37 -0400 | [diff] [blame^] | 529 | payloadLen++ |
| 530 | paddingLen = hc.config.Bugs.RecordPadding |
| 531 | } |
| 532 | if hc.config.Bugs.OmitRecordContents { |
| 533 | payloadLen = 0 |
| 534 | } |
| 535 | b.resize(recordHeaderLen + explicitIVLen + payloadLen + paddingLen + c.Overhead()) |
| 536 | if hc.version >= VersionTLS13 { |
| 537 | if !hc.config.Bugs.OmitRecordContents { |
| 538 | b.data[payloadLen+recordHeaderLen-1] = byte(typ) |
| 539 | } |
| 540 | for i := 0; i < hc.config.Bugs.RecordPadding; i++ { |
| 541 | b.data[payloadLen+recordHeaderLen+i] = 0 |
| 542 | } |
| 543 | payloadLen += paddingLen |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 544 | } |
David Benjamin | 8e6db49 | 2015-07-25 18:29:23 -0400 | [diff] [blame] | 545 | nonce := hc.outSeq[:] |
David Benjamin | e9a80ff | 2015-04-07 00:46:46 -0400 | [diff] [blame] | 546 | if c.explicitNonce { |
| 547 | nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen] |
| 548 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 549 | payload := b.data[recordHeaderLen+explicitIVLen:] |
| 550 | payload = payload[:payloadLen] |
| 551 | |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 552 | var additionalData []byte |
| 553 | if hc.version < VersionTLS13 { |
| 554 | additionalData = make([]byte, 13) |
| 555 | copy(additionalData, hc.outSeq[:]) |
| 556 | copy(additionalData[8:], b.data[:3]) |
| 557 | additionalData[11] = byte(payloadLen >> 8) |
| 558 | additionalData[12] = byte(payloadLen) |
| 559 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 560 | |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 561 | c.Seal(payload[:0], nonce, payload, additionalData) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 562 | case cbcMode: |
| 563 | blockSize := c.BlockSize() |
| 564 | if explicitIVLen > 0 { |
| 565 | c.SetIV(payload[:explicitIVLen]) |
| 566 | payload = payload[explicitIVLen:] |
| 567 | } |
Adam Langley | 80842bd | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 568 | prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 569 | b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock)) |
| 570 | c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix) |
| 571 | c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock) |
Matt Braithwaite | af09675 | 2015-09-02 19:48:16 -0700 | [diff] [blame] | 572 | case nullCipher: |
| 573 | break |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 574 | default: |
| 575 | panic("unknown cipher type") |
| 576 | } |
| 577 | } |
| 578 | |
| 579 | // update length to include MAC and any block padding needed. |
| 580 | n := len(b.data) - recordHeaderLen |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 581 | b.data[recordHeaderLen-2] = byte(n >> 8) |
| 582 | b.data[recordHeaderLen-1] = byte(n) |
David Benjamin | 5e961c1 | 2014-11-07 01:48:35 -0500 | [diff] [blame] | 583 | hc.incSeq(true) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 584 | |
| 585 | return true, 0 |
| 586 | } |
| 587 | |
| 588 | // A block is a simple data buffer. |
| 589 | type block struct { |
| 590 | data []byte |
| 591 | off int // index for Read |
| 592 | link *block |
| 593 | } |
| 594 | |
| 595 | // resize resizes block to be n bytes, growing if necessary. |
| 596 | func (b *block) resize(n int) { |
| 597 | if n > cap(b.data) { |
| 598 | b.reserve(n) |
| 599 | } |
| 600 | b.data = b.data[0:n] |
| 601 | } |
| 602 | |
| 603 | // reserve makes sure that block contains a capacity of at least n bytes. |
| 604 | func (b *block) reserve(n int) { |
| 605 | if cap(b.data) >= n { |
| 606 | return |
| 607 | } |
| 608 | m := cap(b.data) |
| 609 | if m == 0 { |
| 610 | m = 1024 |
| 611 | } |
| 612 | for m < n { |
| 613 | m *= 2 |
| 614 | } |
| 615 | data := make([]byte, len(b.data), m) |
| 616 | copy(data, b.data) |
| 617 | b.data = data |
| 618 | } |
| 619 | |
| 620 | // readFromUntil reads from r into b until b contains at least n bytes |
| 621 | // or else returns an error. |
| 622 | func (b *block) readFromUntil(r io.Reader, n int) error { |
| 623 | // quick case |
| 624 | if len(b.data) >= n { |
| 625 | return nil |
| 626 | } |
| 627 | |
| 628 | // read until have enough. |
| 629 | b.reserve(n) |
| 630 | for { |
| 631 | m, err := r.Read(b.data[len(b.data):cap(b.data)]) |
| 632 | b.data = b.data[0 : len(b.data)+m] |
| 633 | if len(b.data) >= n { |
| 634 | // TODO(bradfitz,agl): slightly suspicious |
| 635 | // that we're throwing away r.Read's err here. |
| 636 | break |
| 637 | } |
| 638 | if err != nil { |
| 639 | return err |
| 640 | } |
| 641 | } |
| 642 | return nil |
| 643 | } |
| 644 | |
| 645 | func (b *block) Read(p []byte) (n int, err error) { |
| 646 | n = copy(p, b.data[b.off:]) |
| 647 | b.off += n |
| 648 | return |
| 649 | } |
| 650 | |
| 651 | // newBlock allocates a new block, from hc's free list if possible. |
| 652 | func (hc *halfConn) newBlock() *block { |
| 653 | b := hc.bfree |
| 654 | if b == nil { |
| 655 | return new(block) |
| 656 | } |
| 657 | hc.bfree = b.link |
| 658 | b.link = nil |
| 659 | b.resize(0) |
| 660 | return b |
| 661 | } |
| 662 | |
| 663 | // freeBlock returns a block to hc's free list. |
| 664 | // The protocol is such that each side only has a block or two on |
| 665 | // its free list at a time, so there's no need to worry about |
| 666 | // trimming the list, etc. |
| 667 | func (hc *halfConn) freeBlock(b *block) { |
| 668 | b.link = hc.bfree |
| 669 | hc.bfree = b |
| 670 | } |
| 671 | |
| 672 | // splitBlock splits a block after the first n bytes, |
| 673 | // returning a block with those n bytes and a |
| 674 | // block with the remainder. the latter may be nil. |
| 675 | func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) { |
| 676 | if len(b.data) <= n { |
| 677 | return b, nil |
| 678 | } |
| 679 | bb := hc.newBlock() |
| 680 | bb.resize(len(b.data) - n) |
| 681 | copy(bb.data, b.data[n:]) |
| 682 | b.data = b.data[0:n] |
| 683 | return b, bb |
| 684 | } |
| 685 | |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 686 | func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) { |
| 687 | if c.isDTLS { |
| 688 | return c.dtlsDoReadRecord(want) |
| 689 | } |
| 690 | |
| 691 | recordHeaderLen := tlsRecordHeaderLen |
| 692 | |
| 693 | if c.rawInput == nil { |
| 694 | c.rawInput = c.in.newBlock() |
| 695 | } |
| 696 | b := c.rawInput |
| 697 | |
| 698 | // Read header, payload. |
| 699 | if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil { |
| 700 | // RFC suggests that EOF without an alertCloseNotify is |
| 701 | // an error, but popular web sites seem to do this, |
David Benjamin | 30789da | 2015-08-29 22:56:45 -0400 | [diff] [blame] | 702 | // so we can't make it an error, outside of tests. |
| 703 | if err == io.EOF && c.config.Bugs.ExpectCloseNotify { |
| 704 | err = io.ErrUnexpectedEOF |
| 705 | } |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 706 | if e, ok := err.(net.Error); !ok || !e.Temporary() { |
| 707 | c.in.setErrorLocked(err) |
| 708 | } |
| 709 | return 0, nil, err |
| 710 | } |
| 711 | typ := recordType(b.data[0]) |
| 712 | |
| 713 | // No valid TLS record has a type of 0x80, however SSLv2 handshakes |
| 714 | // start with a uint16 length where the MSB is set and the first record |
| 715 | // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests |
| 716 | // an SSLv2 client. |
| 717 | if want == recordTypeHandshake && typ == 0x80 { |
| 718 | c.sendAlert(alertProtocolVersion) |
| 719 | return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received")) |
| 720 | } |
| 721 | |
| 722 | vers := uint16(b.data[1])<<8 | uint16(b.data[2]) |
| 723 | n := int(b.data[3])<<8 | int(b.data[4]) |
David Benjamin | bde0039 | 2016-06-21 12:19:28 -0400 | [diff] [blame] | 724 | // Alerts sent near version negotiation do not have a well-defined |
| 725 | // record-layer version prior to TLS 1.3. (In TLS 1.3, the record-layer |
| 726 | // version is irrelevant.) |
| 727 | if typ != recordTypeAlert { |
| 728 | if c.haveVers { |
| 729 | if vers != c.vers && c.vers < VersionTLS13 { |
| 730 | c.sendAlert(alertProtocolVersion) |
| 731 | return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers)) |
| 732 | } |
| 733 | } else { |
| 734 | if expect := c.config.Bugs.ExpectInitialRecordVersion; expect != 0 && vers != expect { |
| 735 | c.sendAlert(alertProtocolVersion) |
| 736 | return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect)) |
| 737 | } |
David Benjamin | 1e29a6b | 2014-12-10 02:27:24 -0500 | [diff] [blame] | 738 | } |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 739 | } |
| 740 | if n > maxCiphertext { |
| 741 | c.sendAlert(alertRecordOverflow) |
| 742 | return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n)) |
| 743 | } |
| 744 | if !c.haveVers { |
| 745 | // First message, be extra suspicious: |
| 746 | // this might not be a TLS client. |
| 747 | // Bail out before reading a full 'body', if possible. |
| 748 | // The current max version is 3.1. |
| 749 | // If the version is >= 16.0, it's probably not real. |
| 750 | // Similarly, a clientHello message encodes in |
| 751 | // well under a kilobyte. If the length is >= 12 kB, |
| 752 | // it's probably not real. |
| 753 | if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 { |
| 754 | c.sendAlert(alertUnexpectedMessage) |
| 755 | return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake")) |
| 756 | } |
| 757 | } |
| 758 | if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil { |
| 759 | if err == io.EOF { |
| 760 | err = io.ErrUnexpectedEOF |
| 761 | } |
| 762 | if e, ok := err.(net.Error); !ok || !e.Temporary() { |
| 763 | c.in.setErrorLocked(err) |
| 764 | } |
| 765 | return 0, nil, err |
| 766 | } |
| 767 | |
| 768 | // Process message. |
| 769 | b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n) |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 770 | ok, off, encTyp, err := c.in.decrypt(b) |
| 771 | if c.vers >= VersionTLS13 && c.in.cipher != nil { |
David Benjamin | c9ae27c | 2016-06-24 22:56:37 -0400 | [diff] [blame^] | 772 | if typ != recordTypeApplicationData { |
| 773 | return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: outer record type is not application data")) |
| 774 | } |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 775 | typ = encTyp |
| 776 | } |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 777 | if !ok { |
| 778 | c.in.setErrorLocked(c.sendAlert(err)) |
| 779 | } |
| 780 | b.off = off |
| 781 | return typ, b, nil |
| 782 | } |
| 783 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 784 | // readRecord reads the next TLS record from the connection |
| 785 | // and updates the record layer state. |
| 786 | // c.in.Mutex <= L; c.input == nil. |
| 787 | func (c *Conn) readRecord(want recordType) error { |
| 788 | // Caller must be in sync with connection: |
| 789 | // handshake data if handshake not yet completed, |
Adam Langley | 2ae77d2 | 2014-10-28 17:29:33 -0700 | [diff] [blame] | 790 | // else application data. |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 791 | switch want { |
| 792 | default: |
| 793 | c.sendAlert(alertInternalError) |
| 794 | return c.in.setErrorLocked(errors.New("tls: unknown record type requested")) |
| 795 | case recordTypeHandshake, recordTypeChangeCipherSpec: |
| 796 | if c.handshakeComplete { |
| 797 | c.sendAlert(alertInternalError) |
| 798 | return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete")) |
| 799 | } |
| 800 | case recordTypeApplicationData: |
David Benjamin | e58c4f5 | 2014-08-24 03:47:07 -0400 | [diff] [blame] | 801 | if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 802 | c.sendAlert(alertInternalError) |
| 803 | return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete")) |
| 804 | } |
David Benjamin | 30789da | 2015-08-29 22:56:45 -0400 | [diff] [blame] | 805 | case recordTypeAlert: |
| 806 | // Looking for a close_notify. Note: unlike a real |
| 807 | // implementation, this is not tolerant of additional records. |
| 808 | // See the documentation for ExpectCloseNotify. |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 809 | } |
| 810 | |
| 811 | Again: |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 812 | typ, b, err := c.doReadRecord(want) |
| 813 | if err != nil { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 814 | return err |
| 815 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 816 | data := b.data[b.off:] |
| 817 | if len(data) > maxPlaintext { |
| 818 | err := c.sendAlert(alertRecordOverflow) |
| 819 | c.in.freeBlock(b) |
| 820 | return c.in.setErrorLocked(err) |
| 821 | } |
| 822 | |
| 823 | switch typ { |
| 824 | default: |
| 825 | c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) |
| 826 | |
| 827 | case recordTypeAlert: |
| 828 | if len(data) != 2 { |
| 829 | c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) |
| 830 | break |
| 831 | } |
| 832 | if alert(data[1]) == alertCloseNotify { |
| 833 | c.in.setErrorLocked(io.EOF) |
| 834 | break |
| 835 | } |
| 836 | switch data[0] { |
| 837 | case alertLevelWarning: |
| 838 | // drop on the floor |
| 839 | c.in.freeBlock(b) |
| 840 | goto Again |
| 841 | case alertLevelError: |
| 842 | c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])}) |
| 843 | default: |
| 844 | c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) |
| 845 | } |
| 846 | |
| 847 | case recordTypeChangeCipherSpec: |
| 848 | if typ != want || len(data) != 1 || data[0] != 1 { |
| 849 | c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) |
| 850 | break |
| 851 | } |
Adam Langley | 80842bd | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 852 | err := c.in.changeCipherSpec(c.config) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 853 | if err != nil { |
| 854 | c.in.setErrorLocked(c.sendAlert(err.(alert))) |
| 855 | } |
| 856 | |
| 857 | case recordTypeApplicationData: |
| 858 | if typ != want { |
| 859 | c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) |
| 860 | break |
| 861 | } |
| 862 | c.input = b |
| 863 | b = nil |
| 864 | |
| 865 | case recordTypeHandshake: |
| 866 | // TODO(rsc): Should at least pick off connection close. |
| 867 | if typ != want { |
Adam Langley | 2ae77d2 | 2014-10-28 17:29:33 -0700 | [diff] [blame] | 868 | // A client might need to process a HelloRequest from |
| 869 | // the server, thus receiving a handshake message when |
David Benjamin | d9b091b | 2015-01-27 01:10:54 -0500 | [diff] [blame] | 870 | // application data is expected is ok. |
David Benjamin | 30789da | 2015-08-29 22:56:45 -0400 | [diff] [blame] | 871 | if !c.isClient || want != recordTypeApplicationData { |
Adam Langley | 2ae77d2 | 2014-10-28 17:29:33 -0700 | [diff] [blame] | 872 | return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation)) |
| 873 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 874 | } |
| 875 | c.hand.Write(data) |
| 876 | } |
| 877 | |
| 878 | if b != nil { |
| 879 | c.in.freeBlock(b) |
| 880 | } |
| 881 | return c.in.err |
| 882 | } |
| 883 | |
| 884 | // sendAlert sends a TLS alert message. |
| 885 | // c.out.Mutex <= L. |
David Benjamin | 24f346d | 2015-06-06 03:28:08 -0400 | [diff] [blame] | 886 | func (c *Conn) sendAlertLocked(level byte, err alert) error { |
| 887 | c.tmp[0] = level |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 888 | c.tmp[1] = byte(err) |
Alex Chernyakhovsky | 4cd8c43 | 2014-11-01 19:39:08 -0400 | [diff] [blame] | 889 | if c.config.Bugs.FragmentAlert { |
| 890 | c.writeRecord(recordTypeAlert, c.tmp[0:1]) |
| 891 | c.writeRecord(recordTypeAlert, c.tmp[1:2]) |
David Benjamin | 0d3a8c6 | 2016-03-11 22:25:18 -0500 | [diff] [blame] | 892 | } else if c.config.Bugs.DoubleAlert { |
| 893 | copy(c.tmp[2:4], c.tmp[0:2]) |
| 894 | c.writeRecord(recordTypeAlert, c.tmp[0:4]) |
Alex Chernyakhovsky | 4cd8c43 | 2014-11-01 19:39:08 -0400 | [diff] [blame] | 895 | } else { |
| 896 | c.writeRecord(recordTypeAlert, c.tmp[0:2]) |
| 897 | } |
David Benjamin | 24f346d | 2015-06-06 03:28:08 -0400 | [diff] [blame] | 898 | // Error alerts are fatal to the connection. |
| 899 | if level == alertLevelError { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 900 | return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err}) |
| 901 | } |
| 902 | return nil |
| 903 | } |
| 904 | |
| 905 | // sendAlert sends a TLS alert message. |
| 906 | // L < c.out.Mutex. |
| 907 | func (c *Conn) sendAlert(err alert) error { |
David Benjamin | 24f346d | 2015-06-06 03:28:08 -0400 | [diff] [blame] | 908 | level := byte(alertLevelError) |
David Benjamin | 0b7ca7d | 2016-03-10 15:44:22 -0500 | [diff] [blame] | 909 | if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertficate { |
David Benjamin | 24f346d | 2015-06-06 03:28:08 -0400 | [diff] [blame] | 910 | level = alertLevelWarning |
| 911 | } |
| 912 | return c.SendAlert(level, err) |
| 913 | } |
| 914 | |
| 915 | func (c *Conn) SendAlert(level byte, err alert) error { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 916 | c.out.Lock() |
| 917 | defer c.out.Unlock() |
David Benjamin | 24f346d | 2015-06-06 03:28:08 -0400 | [diff] [blame] | 918 | return c.sendAlertLocked(level, err) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 919 | } |
| 920 | |
David Benjamin | d86c767 | 2014-08-02 04:07:12 -0400 | [diff] [blame] | 921 | // writeV2Record writes a record for a V2ClientHello. |
| 922 | func (c *Conn) writeV2Record(data []byte) (n int, err error) { |
| 923 | record := make([]byte, 2+len(data)) |
| 924 | record[0] = uint8(len(data)>>8) | 0x80 |
| 925 | record[1] = uint8(len(data)) |
| 926 | copy(record[2:], data) |
| 927 | return c.conn.Write(record) |
| 928 | } |
| 929 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 930 | // writeRecord writes a TLS record with the given type and payload |
| 931 | // to the connection and updates the record layer state. |
| 932 | // c.out.Mutex <= L. |
| 933 | func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) { |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 934 | if c.isDTLS { |
| 935 | return c.dtlsWriteRecord(typ, data) |
| 936 | } |
| 937 | |
| 938 | recordHeaderLen := tlsRecordHeaderLen |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 939 | b := c.out.newBlock() |
David Benjamin | 9821454 | 2014-08-07 18:02:39 -0400 | [diff] [blame] | 940 | first := true |
| 941 | isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello |
David Benjamin | a8ebe22 | 2015-06-06 03:04:39 -0400 | [diff] [blame] | 942 | for len(data) > 0 || first { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 943 | m := len(data) |
David Benjamin | 2c99d28 | 2015-09-01 10:23:00 -0400 | [diff] [blame] | 944 | if m > maxPlaintext && !c.config.Bugs.SendLargeRecords { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 945 | m = maxPlaintext |
| 946 | } |
David Benjamin | 43ec06f | 2014-08-05 02:28:57 -0400 | [diff] [blame] | 947 | if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength { |
| 948 | m = c.config.Bugs.MaxHandshakeRecordLength |
David Benjamin | 9821454 | 2014-08-07 18:02:39 -0400 | [diff] [blame] | 949 | // By default, do not fragment the client_version or |
| 950 | // server_version, which are located in the first 6 |
| 951 | // bytes. |
| 952 | if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 { |
| 953 | m = 6 |
| 954 | } |
David Benjamin | 43ec06f | 2014-08-05 02:28:57 -0400 | [diff] [blame] | 955 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 956 | explicitIVLen := 0 |
| 957 | explicitIVIsSeq := false |
David Benjamin | 9821454 | 2014-08-07 18:02:39 -0400 | [diff] [blame] | 958 | first = false |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 959 | |
| 960 | var cbc cbcMode |
| 961 | if c.out.version >= VersionTLS11 { |
| 962 | var ok bool |
| 963 | if cbc, ok = c.out.cipher.(cbcMode); ok { |
| 964 | explicitIVLen = cbc.BlockSize() |
| 965 | } |
| 966 | } |
| 967 | if explicitIVLen == 0 { |
David Benjamin | e9a80ff | 2015-04-07 00:46:46 -0400 | [diff] [blame] | 968 | if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 969 | explicitIVLen = 8 |
| 970 | // The AES-GCM construction in TLS has an |
| 971 | // explicit nonce so that the nonce can be |
| 972 | // random. However, the nonce is only 8 bytes |
| 973 | // which is too small for a secure, random |
| 974 | // nonce. Therefore we use the sequence number |
| 975 | // as the nonce. |
| 976 | explicitIVIsSeq = true |
| 977 | } |
| 978 | } |
| 979 | b.resize(recordHeaderLen + explicitIVLen + m) |
| 980 | b.data[0] = byte(typ) |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 981 | if c.vers >= VersionTLS13 && c.out.cipher != nil { |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 982 | b.data[0] = byte(recordTypeApplicationData) |
David Benjamin | c9ae27c | 2016-06-24 22:56:37 -0400 | [diff] [blame^] | 983 | if outerType := c.config.Bugs.OuterRecordType; outerType != 0 { |
| 984 | b.data[0] = byte(outerType) |
| 985 | } |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 986 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 987 | vers := c.vers |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 988 | if vers == 0 || vers >= VersionTLS13 { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 989 | // Some TLS servers fail if the record version is |
| 990 | // greater than TLS 1.0 for the initial ClientHello. |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 991 | // |
| 992 | // TLS 1.3 fixes the version number in the record |
| 993 | // layer to {3, 1}. |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 994 | vers = VersionTLS10 |
| 995 | } |
| 996 | b.data[1] = byte(vers >> 8) |
| 997 | b.data[2] = byte(vers) |
| 998 | b.data[3] = byte(m >> 8) |
| 999 | b.data[4] = byte(m) |
| 1000 | if explicitIVLen > 0 { |
| 1001 | explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen] |
| 1002 | if explicitIVIsSeq { |
| 1003 | copy(explicitIV, c.out.seq[:]) |
| 1004 | } else { |
| 1005 | if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil { |
| 1006 | break |
| 1007 | } |
| 1008 | } |
| 1009 | } |
| 1010 | copy(b.data[recordHeaderLen+explicitIVLen:], data) |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 1011 | c.out.encrypt(b, explicitIVLen, typ) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1012 | _, err = c.conn.Write(b.data) |
| 1013 | if err != nil { |
| 1014 | break |
| 1015 | } |
| 1016 | n += m |
| 1017 | data = data[m:] |
| 1018 | } |
| 1019 | c.out.freeBlock(b) |
| 1020 | |
| 1021 | if typ == recordTypeChangeCipherSpec { |
Adam Langley | 80842bd | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1022 | err = c.out.changeCipherSpec(c.config) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1023 | if err != nil { |
| 1024 | // Cannot call sendAlert directly, |
| 1025 | // because we already hold c.out.Mutex. |
| 1026 | c.tmp[0] = alertLevelError |
| 1027 | c.tmp[1] = byte(err.(alert)) |
| 1028 | c.writeRecord(recordTypeAlert, c.tmp[0:2]) |
| 1029 | return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err}) |
| 1030 | } |
| 1031 | } |
| 1032 | return |
| 1033 | } |
| 1034 | |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 1035 | func (c *Conn) doReadHandshake() ([]byte, error) { |
| 1036 | if c.isDTLS { |
| 1037 | return c.dtlsDoReadHandshake() |
| 1038 | } |
| 1039 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1040 | for c.hand.Len() < 4 { |
| 1041 | if err := c.in.err; err != nil { |
| 1042 | return nil, err |
| 1043 | } |
| 1044 | if err := c.readRecord(recordTypeHandshake); err != nil { |
| 1045 | return nil, err |
| 1046 | } |
| 1047 | } |
| 1048 | |
| 1049 | data := c.hand.Bytes() |
| 1050 | n := int(data[1])<<16 | int(data[2])<<8 | int(data[3]) |
| 1051 | if n > maxHandshake { |
| 1052 | return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError)) |
| 1053 | } |
| 1054 | for c.hand.Len() < 4+n { |
| 1055 | if err := c.in.err; err != nil { |
| 1056 | return nil, err |
| 1057 | } |
| 1058 | if err := c.readRecord(recordTypeHandshake); err != nil { |
| 1059 | return nil, err |
| 1060 | } |
| 1061 | } |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 1062 | return c.hand.Next(4 + n), nil |
| 1063 | } |
| 1064 | |
| 1065 | // readHandshake reads the next handshake message from |
| 1066 | // the record layer. |
| 1067 | // c.in.Mutex < L; c.out.Mutex < L. |
| 1068 | func (c *Conn) readHandshake() (interface{}, error) { |
| 1069 | data, err := c.doReadHandshake() |
| 1070 | if err != nil { |
| 1071 | return nil, err |
| 1072 | } |
| 1073 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1074 | var m handshakeMessage |
| 1075 | switch data[0] { |
Adam Langley | 2ae77d2 | 2014-10-28 17:29:33 -0700 | [diff] [blame] | 1076 | case typeHelloRequest: |
| 1077 | m = new(helloRequestMsg) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1078 | case typeClientHello: |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 1079 | m = &clientHelloMsg{ |
| 1080 | isDTLS: c.isDTLS, |
| 1081 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1082 | case typeServerHello: |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 1083 | m = &serverHelloMsg{ |
| 1084 | isDTLS: c.isDTLS, |
| 1085 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1086 | case typeNewSessionTicket: |
| 1087 | m = new(newSessionTicketMsg) |
| 1088 | case typeCertificate: |
| 1089 | m = new(certificateMsg) |
| 1090 | case typeCertificateRequest: |
| 1091 | m = &certificateRequestMsg{ |
| 1092 | hasSignatureAndHash: c.vers >= VersionTLS12, |
| 1093 | } |
| 1094 | case typeCertificateStatus: |
| 1095 | m = new(certificateStatusMsg) |
| 1096 | case typeServerKeyExchange: |
| 1097 | m = new(serverKeyExchangeMsg) |
| 1098 | case typeServerHelloDone: |
| 1099 | m = new(serverHelloDoneMsg) |
| 1100 | case typeClientKeyExchange: |
| 1101 | m = new(clientKeyExchangeMsg) |
| 1102 | case typeCertificateVerify: |
| 1103 | m = &certificateVerifyMsg{ |
| 1104 | hasSignatureAndHash: c.vers >= VersionTLS12, |
| 1105 | } |
| 1106 | case typeNextProtocol: |
| 1107 | m = new(nextProtoMsg) |
| 1108 | case typeFinished: |
| 1109 | m = new(finishedMsg) |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 1110 | case typeHelloVerifyRequest: |
| 1111 | m = new(helloVerifyRequestMsg) |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame] | 1112 | case typeEncryptedExtensions: |
| 1113 | m = new(encryptedExtensionsMsg) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1114 | default: |
| 1115 | return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) |
| 1116 | } |
| 1117 | |
| 1118 | // The handshake message unmarshallers |
| 1119 | // expect to be able to keep references to data, |
| 1120 | // so pass in a fresh copy that won't be overwritten. |
| 1121 | data = append([]byte(nil), data...) |
| 1122 | |
| 1123 | if !m.unmarshal(data) { |
| 1124 | return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) |
| 1125 | } |
| 1126 | return m, nil |
| 1127 | } |
| 1128 | |
David Benjamin | 83f9040 | 2015-01-27 01:09:43 -0500 | [diff] [blame] | 1129 | // skipPacket processes all the DTLS records in packet. It updates |
| 1130 | // sequence number expectations but otherwise ignores them. |
| 1131 | func (c *Conn) skipPacket(packet []byte) error { |
| 1132 | for len(packet) > 0 { |
David Benjamin | 6ca9355 | 2015-08-28 16:16:25 -0400 | [diff] [blame] | 1133 | if len(packet) < 13 { |
| 1134 | return errors.New("tls: bad packet") |
| 1135 | } |
David Benjamin | 83f9040 | 2015-01-27 01:09:43 -0500 | [diff] [blame] | 1136 | // Dropped packets are completely ignored save to update |
| 1137 | // expected sequence numbers for this and the next epoch. (We |
| 1138 | // don't assert on the contents of the packets both for |
| 1139 | // simplicity and because a previous test with one shorter |
| 1140 | // timeout schedule would have done so.) |
| 1141 | epoch := packet[3:5] |
| 1142 | seq := packet[5:11] |
| 1143 | length := uint16(packet[11])<<8 | uint16(packet[12]) |
| 1144 | if bytes.Equal(c.in.seq[:2], epoch) { |
David Benjamin | 13e81fc | 2015-11-02 17:16:13 -0500 | [diff] [blame] | 1145 | if bytes.Compare(seq, c.in.seq[2:]) < 0 { |
David Benjamin | 83f9040 | 2015-01-27 01:09:43 -0500 | [diff] [blame] | 1146 | return errors.New("tls: sequence mismatch") |
| 1147 | } |
David Benjamin | 13e81fc | 2015-11-02 17:16:13 -0500 | [diff] [blame] | 1148 | copy(c.in.seq[2:], seq) |
David Benjamin | 83f9040 | 2015-01-27 01:09:43 -0500 | [diff] [blame] | 1149 | c.in.incSeq(false) |
| 1150 | } else { |
David Benjamin | 13e81fc | 2015-11-02 17:16:13 -0500 | [diff] [blame] | 1151 | if bytes.Compare(seq, c.in.nextSeq[:]) < 0 { |
David Benjamin | 83f9040 | 2015-01-27 01:09:43 -0500 | [diff] [blame] | 1152 | return errors.New("tls: sequence mismatch") |
| 1153 | } |
David Benjamin | 13e81fc | 2015-11-02 17:16:13 -0500 | [diff] [blame] | 1154 | copy(c.in.nextSeq[:], seq) |
David Benjamin | 83f9040 | 2015-01-27 01:09:43 -0500 | [diff] [blame] | 1155 | c.in.incNextSeq() |
| 1156 | } |
David Benjamin | 6ca9355 | 2015-08-28 16:16:25 -0400 | [diff] [blame] | 1157 | if len(packet) < 13+int(length) { |
| 1158 | return errors.New("tls: bad packet") |
| 1159 | } |
David Benjamin | 83f9040 | 2015-01-27 01:09:43 -0500 | [diff] [blame] | 1160 | packet = packet[13+length:] |
| 1161 | } |
| 1162 | return nil |
| 1163 | } |
| 1164 | |
| 1165 | // simulatePacketLoss simulates the loss of a handshake leg from the |
| 1166 | // peer based on the schedule in c.config.Bugs. If resendFunc is |
| 1167 | // non-nil, it is called after each simulated timeout to retransmit |
| 1168 | // handshake messages from the local end. This is used in cases where |
| 1169 | // the peer retransmits on a stale Finished rather than a timeout. |
| 1170 | func (c *Conn) simulatePacketLoss(resendFunc func()) error { |
| 1171 | if len(c.config.Bugs.TimeoutSchedule) == 0 { |
| 1172 | return nil |
| 1173 | } |
| 1174 | if !c.isDTLS { |
| 1175 | return errors.New("tls: TimeoutSchedule may only be set in DTLS") |
| 1176 | } |
| 1177 | if c.config.Bugs.PacketAdaptor == nil { |
| 1178 | return errors.New("tls: TimeoutSchedule set without PacketAdapter") |
| 1179 | } |
| 1180 | for _, timeout := range c.config.Bugs.TimeoutSchedule { |
| 1181 | // Simulate a timeout. |
| 1182 | packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout) |
| 1183 | if err != nil { |
| 1184 | return err |
| 1185 | } |
| 1186 | for _, packet := range packets { |
| 1187 | if err := c.skipPacket(packet); err != nil { |
| 1188 | return err |
| 1189 | } |
| 1190 | } |
| 1191 | if resendFunc != nil { |
| 1192 | resendFunc() |
| 1193 | } |
| 1194 | } |
| 1195 | return nil |
| 1196 | } |
| 1197 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1198 | // Write writes data to the connection. |
| 1199 | func (c *Conn) Write(b []byte) (int, error) { |
| 1200 | if err := c.Handshake(); err != nil { |
| 1201 | return 0, err |
| 1202 | } |
| 1203 | |
| 1204 | c.out.Lock() |
| 1205 | defer c.out.Unlock() |
| 1206 | |
| 1207 | if err := c.out.err; err != nil { |
| 1208 | return 0, err |
| 1209 | } |
| 1210 | |
| 1211 | if !c.handshakeComplete { |
| 1212 | return 0, alertInternalError |
| 1213 | } |
| 1214 | |
David Benjamin | 3fd1fbd | 2015-02-03 16:07:32 -0500 | [diff] [blame] | 1215 | if c.config.Bugs.SendSpuriousAlert != 0 { |
David Benjamin | 24f346d | 2015-06-06 03:28:08 -0400 | [diff] [blame] | 1216 | c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert) |
Alex Chernyakhovsky | 4cd8c43 | 2014-11-01 19:39:08 -0400 | [diff] [blame] | 1217 | } |
| 1218 | |
Adam Langley | 27a0d08 | 2015-11-03 13:34:10 -0800 | [diff] [blame] | 1219 | if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord { |
| 1220 | c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0}) |
| 1221 | } |
| 1222 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1223 | // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext |
| 1224 | // attack when using block mode ciphers due to predictable IVs. |
| 1225 | // This can be prevented by splitting each Application Data |
| 1226 | // record into two records, effectively randomizing the IV. |
| 1227 | // |
| 1228 | // http://www.openssl.org/~bodo/tls-cbc.txt |
| 1229 | // https://bugzilla.mozilla.org/show_bug.cgi?id=665814 |
| 1230 | // http://www.imperialviolet.org/2012/01/15/beastfollowup.html |
| 1231 | |
| 1232 | var m int |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 1233 | if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1234 | if _, ok := c.out.cipher.(cipher.BlockMode); ok { |
| 1235 | n, err := c.writeRecord(recordTypeApplicationData, b[:1]) |
| 1236 | if err != nil { |
| 1237 | return n, c.out.setErrorLocked(err) |
| 1238 | } |
| 1239 | m, b = 1, b[1:] |
| 1240 | } |
| 1241 | } |
| 1242 | |
| 1243 | n, err := c.writeRecord(recordTypeApplicationData, b) |
| 1244 | return n + m, c.out.setErrorLocked(err) |
| 1245 | } |
| 1246 | |
Adam Langley | 2ae77d2 | 2014-10-28 17:29:33 -0700 | [diff] [blame] | 1247 | func (c *Conn) handleRenegotiation() error { |
| 1248 | c.handshakeComplete = false |
| 1249 | if !c.isClient { |
| 1250 | panic("renegotiation should only happen for a client") |
| 1251 | } |
| 1252 | |
| 1253 | msg, err := c.readHandshake() |
| 1254 | if err != nil { |
| 1255 | return err |
| 1256 | } |
| 1257 | _, ok := msg.(*helloRequestMsg) |
| 1258 | if !ok { |
| 1259 | c.sendAlert(alertUnexpectedMessage) |
| 1260 | return alertUnexpectedMessage |
| 1261 | } |
| 1262 | |
| 1263 | return c.Handshake() |
| 1264 | } |
| 1265 | |
Adam Langley | cf2d4f4 | 2014-10-28 19:06:14 -0700 | [diff] [blame] | 1266 | func (c *Conn) Renegotiate() error { |
| 1267 | if !c.isClient { |
David Benjamin | ef5dfd2 | 2015-12-06 13:17:07 -0500 | [diff] [blame] | 1268 | helloReq := new(helloRequestMsg).marshal() |
| 1269 | if c.config.Bugs.BadHelloRequest != nil { |
| 1270 | helloReq = c.config.Bugs.BadHelloRequest |
| 1271 | } |
| 1272 | c.writeRecord(recordTypeHandshake, helloReq) |
Adam Langley | cf2d4f4 | 2014-10-28 19:06:14 -0700 | [diff] [blame] | 1273 | } |
| 1274 | |
| 1275 | c.handshakeComplete = false |
| 1276 | return c.Handshake() |
| 1277 | } |
| 1278 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1279 | // Read can be made to time out and return a net.Error with Timeout() == true |
| 1280 | // after a fixed time limit; see SetDeadline and SetReadDeadline. |
| 1281 | func (c *Conn) Read(b []byte) (n int, err error) { |
| 1282 | if err = c.Handshake(); err != nil { |
| 1283 | return |
| 1284 | } |
| 1285 | |
| 1286 | c.in.Lock() |
| 1287 | defer c.in.Unlock() |
| 1288 | |
| 1289 | // Some OpenSSL servers send empty records in order to randomize the |
| 1290 | // CBC IV. So this loop ignores a limited number of empty records. |
| 1291 | const maxConsecutiveEmptyRecords = 100 |
| 1292 | for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ { |
| 1293 | for c.input == nil && c.in.err == nil { |
| 1294 | if err := c.readRecord(recordTypeApplicationData); err != nil { |
| 1295 | // Soft error, like EAGAIN |
| 1296 | return 0, err |
| 1297 | } |
David Benjamin | d9b091b | 2015-01-27 01:10:54 -0500 | [diff] [blame] | 1298 | if c.hand.Len() > 0 { |
Adam Langley | 2ae77d2 | 2014-10-28 17:29:33 -0700 | [diff] [blame] | 1299 | // We received handshake bytes, indicating the |
David Benjamin | d9b091b | 2015-01-27 01:10:54 -0500 | [diff] [blame] | 1300 | // start of a renegotiation. |
Adam Langley | 2ae77d2 | 2014-10-28 17:29:33 -0700 | [diff] [blame] | 1301 | if err := c.handleRenegotiation(); err != nil { |
| 1302 | return 0, err |
| 1303 | } |
| 1304 | continue |
| 1305 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1306 | } |
| 1307 | if err := c.in.err; err != nil { |
| 1308 | return 0, err |
| 1309 | } |
| 1310 | |
| 1311 | n, err = c.input.Read(b) |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 1312 | if c.input.off >= len(c.input.data) || c.isDTLS { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1313 | c.in.freeBlock(c.input) |
| 1314 | c.input = nil |
| 1315 | } |
| 1316 | |
| 1317 | // If a close-notify alert is waiting, read it so that |
| 1318 | // we can return (n, EOF) instead of (n, nil), to signal |
| 1319 | // to the HTTP response reading goroutine that the |
| 1320 | // connection is now closed. This eliminates a race |
| 1321 | // where the HTTP response reading goroutine would |
| 1322 | // otherwise not observe the EOF until its next read, |
| 1323 | // by which time a client goroutine might have already |
| 1324 | // tried to reuse the HTTP connection for a new |
| 1325 | // request. |
| 1326 | // See https://codereview.appspot.com/76400046 |
| 1327 | // and http://golang.org/issue/3514 |
| 1328 | if ri := c.rawInput; ri != nil && |
| 1329 | n != 0 && err == nil && |
| 1330 | c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert { |
| 1331 | if recErr := c.readRecord(recordTypeApplicationData); recErr != nil { |
| 1332 | err = recErr // will be io.EOF on closeNotify |
| 1333 | } |
| 1334 | } |
| 1335 | |
| 1336 | if n != 0 || err != nil { |
| 1337 | return n, err |
| 1338 | } |
| 1339 | } |
| 1340 | |
| 1341 | return 0, io.ErrNoProgress |
| 1342 | } |
| 1343 | |
| 1344 | // Close closes the connection. |
| 1345 | func (c *Conn) Close() error { |
| 1346 | var alertErr error |
| 1347 | |
| 1348 | c.handshakeMutex.Lock() |
| 1349 | defer c.handshakeMutex.Unlock() |
David Benjamin | 30789da | 2015-08-29 22:56:45 -0400 | [diff] [blame] | 1350 | if c.handshakeComplete && !c.config.Bugs.NoCloseNotify { |
David Benjamin | fa214e4 | 2016-05-10 17:03:10 -0400 | [diff] [blame] | 1351 | alert := alertCloseNotify |
| 1352 | if c.config.Bugs.SendAlertOnShutdown != 0 { |
| 1353 | alert = c.config.Bugs.SendAlertOnShutdown |
| 1354 | } |
| 1355 | alertErr = c.sendAlert(alert) |
David Benjamin | 4d55961 | 2016-05-18 14:31:51 -0400 | [diff] [blame] | 1356 | // Clear local alerts when sending alerts so we continue to wait |
| 1357 | // for the peer rather than closing the socket early. |
| 1358 | if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" { |
| 1359 | alertErr = nil |
| 1360 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1361 | } |
| 1362 | |
David Benjamin | 30789da | 2015-08-29 22:56:45 -0400 | [diff] [blame] | 1363 | // Consume a close_notify from the peer if one hasn't been received |
| 1364 | // already. This avoids the peer from failing |SSL_shutdown| due to a |
| 1365 | // write failing. |
| 1366 | if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify { |
| 1367 | for c.in.error() == nil { |
| 1368 | c.readRecord(recordTypeAlert) |
| 1369 | } |
| 1370 | if c.in.error() != io.EOF { |
| 1371 | alertErr = c.in.error() |
| 1372 | } |
| 1373 | } |
| 1374 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1375 | if err := c.conn.Close(); err != nil { |
| 1376 | return err |
| 1377 | } |
| 1378 | return alertErr |
| 1379 | } |
| 1380 | |
| 1381 | // Handshake runs the client or server handshake |
| 1382 | // protocol if it has not yet been run. |
| 1383 | // Most uses of this package need not call Handshake |
| 1384 | // explicitly: the first Read or Write will call it automatically. |
| 1385 | func (c *Conn) Handshake() error { |
| 1386 | c.handshakeMutex.Lock() |
| 1387 | defer c.handshakeMutex.Unlock() |
| 1388 | if err := c.handshakeErr; err != nil { |
| 1389 | return err |
| 1390 | } |
| 1391 | if c.handshakeComplete { |
| 1392 | return nil |
| 1393 | } |
| 1394 | |
David Benjamin | 9a41d1b | 2015-05-16 01:30:09 -0400 | [diff] [blame] | 1395 | if c.isDTLS && c.config.Bugs.SendSplitAlert { |
| 1396 | c.conn.Write([]byte{ |
| 1397 | byte(recordTypeAlert), // type |
| 1398 | 0xfe, 0xff, // version |
| 1399 | 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence |
| 1400 | 0x0, 0x2, // length |
| 1401 | }) |
| 1402 | c.conn.Write([]byte{alertLevelError, byte(alertInternalError)}) |
| 1403 | } |
David Benjamin | 4cf369b | 2015-08-22 01:35:43 -0400 | [diff] [blame] | 1404 | if data := c.config.Bugs.AppDataBeforeHandshake; data != nil { |
| 1405 | c.writeRecord(recordTypeApplicationData, data) |
| 1406 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1407 | if c.isClient { |
| 1408 | c.handshakeErr = c.clientHandshake() |
| 1409 | } else { |
| 1410 | c.handshakeErr = c.serverHandshake() |
| 1411 | } |
David Benjamin | ddb9f15 | 2015-02-03 15:44:39 -0500 | [diff] [blame] | 1412 | if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType { |
| 1413 | c.writeRecord(recordType(42), []byte("invalid record")) |
| 1414 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1415 | return c.handshakeErr |
| 1416 | } |
| 1417 | |
| 1418 | // ConnectionState returns basic TLS details about the connection. |
| 1419 | func (c *Conn) ConnectionState() ConnectionState { |
| 1420 | c.handshakeMutex.Lock() |
| 1421 | defer c.handshakeMutex.Unlock() |
| 1422 | |
| 1423 | var state ConnectionState |
| 1424 | state.HandshakeComplete = c.handshakeComplete |
| 1425 | if c.handshakeComplete { |
| 1426 | state.Version = c.vers |
| 1427 | state.NegotiatedProtocol = c.clientProtocol |
| 1428 | state.DidResume = c.didResume |
| 1429 | state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback |
David Benjamin | fc7b086 | 2014-09-06 13:21:53 -0400 | [diff] [blame] | 1430 | state.NegotiatedProtocolFromALPN = c.usedALPN |
David Benjamin | c565ebb | 2015-04-03 04:06:36 -0400 | [diff] [blame] | 1431 | state.CipherSuite = c.cipherSuite.id |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1432 | state.PeerCertificates = c.peerCertificates |
| 1433 | state.VerifiedChains = c.verifiedChains |
| 1434 | state.ServerName = c.serverName |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame] | 1435 | state.ChannelID = c.channelID |
David Benjamin | ca6c826 | 2014-11-15 19:06:08 -0500 | [diff] [blame] | 1436 | state.SRTPProtectionProfile = c.srtpProtectionProfile |
Adam Langley | af0e32c | 2015-06-03 09:57:23 -0700 | [diff] [blame] | 1437 | state.TLSUnique = c.firstFinished[:] |
Paul Lietar | 4fac72e | 2015-09-09 13:44:55 +0100 | [diff] [blame] | 1438 | state.SCTList = c.sctList |
Steven Valdez | 0d62f26 | 2015-09-04 12:41:04 -0400 | [diff] [blame] | 1439 | state.ClientCertSignatureHash = c.clientCertSignatureHash |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1440 | } |
| 1441 | |
| 1442 | return state |
| 1443 | } |
| 1444 | |
| 1445 | // OCSPResponse returns the stapled OCSP response from the TLS server, if |
| 1446 | // any. (Only valid for client connections.) |
| 1447 | func (c *Conn) OCSPResponse() []byte { |
| 1448 | c.handshakeMutex.Lock() |
| 1449 | defer c.handshakeMutex.Unlock() |
| 1450 | |
| 1451 | return c.ocspResponse |
| 1452 | } |
| 1453 | |
| 1454 | // VerifyHostname checks that the peer certificate chain is valid for |
| 1455 | // connecting to host. If so, it returns nil; if not, it returns an error |
| 1456 | // describing the problem. |
| 1457 | func (c *Conn) VerifyHostname(host string) error { |
| 1458 | c.handshakeMutex.Lock() |
| 1459 | defer c.handshakeMutex.Unlock() |
| 1460 | if !c.isClient { |
| 1461 | return errors.New("tls: VerifyHostname called on TLS server connection") |
| 1462 | } |
| 1463 | if !c.handshakeComplete { |
| 1464 | return errors.New("tls: handshake has not yet been performed") |
| 1465 | } |
| 1466 | return c.peerCertificates[0].VerifyHostname(host) |
| 1467 | } |
David Benjamin | c565ebb | 2015-04-03 04:06:36 -0400 | [diff] [blame] | 1468 | |
| 1469 | // ExportKeyingMaterial exports keying material from the current connection |
| 1470 | // state, as per RFC 5705. |
| 1471 | func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) { |
| 1472 | c.handshakeMutex.Lock() |
| 1473 | defer c.handshakeMutex.Unlock() |
| 1474 | if !c.handshakeComplete { |
| 1475 | return nil, errors.New("tls: handshake has not yet been performed") |
| 1476 | } |
| 1477 | |
| 1478 | seedLen := len(c.clientRandom) + len(c.serverRandom) |
| 1479 | if useContext { |
| 1480 | seedLen += 2 + len(context) |
| 1481 | } |
| 1482 | seed := make([]byte, 0, seedLen) |
| 1483 | seed = append(seed, c.clientRandom[:]...) |
| 1484 | seed = append(seed, c.serverRandom[:]...) |
| 1485 | if useContext { |
| 1486 | seed = append(seed, byte(len(context)>>8), byte(len(context))) |
| 1487 | seed = append(seed, context...) |
| 1488 | } |
| 1489 | result := make([]byte, length) |
| 1490 | prfForVersion(c.vers, c.cipherSuite)(result, c.masterSecret[:], label, seed) |
| 1491 | return result, nil |
| 1492 | } |
David Benjamin | 3e052de | 2015-11-25 20:10:31 -0500 | [diff] [blame] | 1493 | |
| 1494 | // noRenegotiationInfo returns true if the renegotiation info extension |
| 1495 | // should be supported in the current handshake. |
| 1496 | func (c *Conn) noRenegotiationInfo() bool { |
| 1497 | if c.config.Bugs.NoRenegotiationInfo { |
| 1498 | return true |
| 1499 | } |
| 1500 | if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial { |
| 1501 | return true |
| 1502 | } |
| 1503 | if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial { |
| 1504 | return true |
| 1505 | } |
| 1506 | return false |
| 1507 | } |