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