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: |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 526 | contentTypeLen := 0 |
| 527 | if hc.version >= VersionTLS13 { |
| 528 | contentTypeLen = 1 |
| 529 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 530 | payloadLen := len(b.data) - recordHeaderLen - explicitIVLen |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 531 | b.resize(len(b.data) + contentTypeLen + c.Overhead()) |
| 532 | if hc.version >= VersionTLS13 { |
| 533 | b.data[payloadLen+recordHeaderLen] = byte(typ) |
| 534 | payloadLen += 1 |
| 535 | // TODO(nharper): Add ProtocolBugs to add |
| 536 | // padding. |
| 537 | } |
David Benjamin | 8e6db49 | 2015-07-25 18:29:23 -0400 | [diff] [blame] | 538 | nonce := hc.outSeq[:] |
David Benjamin | e9a80ff | 2015-04-07 00:46:46 -0400 | [diff] [blame] | 539 | if c.explicitNonce { |
| 540 | nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen] |
| 541 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 542 | payload := b.data[recordHeaderLen+explicitIVLen:] |
| 543 | payload = payload[:payloadLen] |
| 544 | |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 545 | var additionalData []byte |
| 546 | if hc.version < VersionTLS13 { |
| 547 | additionalData = make([]byte, 13) |
| 548 | copy(additionalData, hc.outSeq[:]) |
| 549 | copy(additionalData[8:], b.data[:3]) |
| 550 | additionalData[11] = byte(payloadLen >> 8) |
| 551 | additionalData[12] = byte(payloadLen) |
| 552 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 553 | |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 554 | c.Seal(payload[:0], nonce, payload, additionalData) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 555 | case cbcMode: |
| 556 | blockSize := c.BlockSize() |
| 557 | if explicitIVLen > 0 { |
| 558 | c.SetIV(payload[:explicitIVLen]) |
| 559 | payload = payload[explicitIVLen:] |
| 560 | } |
Adam Langley | 80842bd | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 561 | prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 562 | b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock)) |
| 563 | c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix) |
| 564 | c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock) |
Matt Braithwaite | af09675 | 2015-09-02 19:48:16 -0700 | [diff] [blame] | 565 | case nullCipher: |
| 566 | break |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 567 | default: |
| 568 | panic("unknown cipher type") |
| 569 | } |
| 570 | } |
| 571 | |
| 572 | // update length to include MAC and any block padding needed. |
| 573 | n := len(b.data) - recordHeaderLen |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 574 | b.data[recordHeaderLen-2] = byte(n >> 8) |
| 575 | b.data[recordHeaderLen-1] = byte(n) |
David Benjamin | 5e961c1 | 2014-11-07 01:48:35 -0500 | [diff] [blame] | 576 | hc.incSeq(true) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 577 | |
| 578 | return true, 0 |
| 579 | } |
| 580 | |
| 581 | // A block is a simple data buffer. |
| 582 | type block struct { |
| 583 | data []byte |
| 584 | off int // index for Read |
| 585 | link *block |
| 586 | } |
| 587 | |
| 588 | // resize resizes block to be n bytes, growing if necessary. |
| 589 | func (b *block) resize(n int) { |
| 590 | if n > cap(b.data) { |
| 591 | b.reserve(n) |
| 592 | } |
| 593 | b.data = b.data[0:n] |
| 594 | } |
| 595 | |
| 596 | // reserve makes sure that block contains a capacity of at least n bytes. |
| 597 | func (b *block) reserve(n int) { |
| 598 | if cap(b.data) >= n { |
| 599 | return |
| 600 | } |
| 601 | m := cap(b.data) |
| 602 | if m == 0 { |
| 603 | m = 1024 |
| 604 | } |
| 605 | for m < n { |
| 606 | m *= 2 |
| 607 | } |
| 608 | data := make([]byte, len(b.data), m) |
| 609 | copy(data, b.data) |
| 610 | b.data = data |
| 611 | } |
| 612 | |
| 613 | // readFromUntil reads from r into b until b contains at least n bytes |
| 614 | // or else returns an error. |
| 615 | func (b *block) readFromUntil(r io.Reader, n int) error { |
| 616 | // quick case |
| 617 | if len(b.data) >= n { |
| 618 | return nil |
| 619 | } |
| 620 | |
| 621 | // read until have enough. |
| 622 | b.reserve(n) |
| 623 | for { |
| 624 | m, err := r.Read(b.data[len(b.data):cap(b.data)]) |
| 625 | b.data = b.data[0 : len(b.data)+m] |
| 626 | if len(b.data) >= n { |
| 627 | // TODO(bradfitz,agl): slightly suspicious |
| 628 | // that we're throwing away r.Read's err here. |
| 629 | break |
| 630 | } |
| 631 | if err != nil { |
| 632 | return err |
| 633 | } |
| 634 | } |
| 635 | return nil |
| 636 | } |
| 637 | |
| 638 | func (b *block) Read(p []byte) (n int, err error) { |
| 639 | n = copy(p, b.data[b.off:]) |
| 640 | b.off += n |
| 641 | return |
| 642 | } |
| 643 | |
| 644 | // newBlock allocates a new block, from hc's free list if possible. |
| 645 | func (hc *halfConn) newBlock() *block { |
| 646 | b := hc.bfree |
| 647 | if b == nil { |
| 648 | return new(block) |
| 649 | } |
| 650 | hc.bfree = b.link |
| 651 | b.link = nil |
| 652 | b.resize(0) |
| 653 | return b |
| 654 | } |
| 655 | |
| 656 | // freeBlock returns a block to hc's free list. |
| 657 | // The protocol is such that each side only has a block or two on |
| 658 | // its free list at a time, so there's no need to worry about |
| 659 | // trimming the list, etc. |
| 660 | func (hc *halfConn) freeBlock(b *block) { |
| 661 | b.link = hc.bfree |
| 662 | hc.bfree = b |
| 663 | } |
| 664 | |
| 665 | // splitBlock splits a block after the first n bytes, |
| 666 | // returning a block with those n bytes and a |
| 667 | // block with the remainder. the latter may be nil. |
| 668 | func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) { |
| 669 | if len(b.data) <= n { |
| 670 | return b, nil |
| 671 | } |
| 672 | bb := hc.newBlock() |
| 673 | bb.resize(len(b.data) - n) |
| 674 | copy(bb.data, b.data[n:]) |
| 675 | b.data = b.data[0:n] |
| 676 | return b, bb |
| 677 | } |
| 678 | |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 679 | func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) { |
| 680 | if c.isDTLS { |
| 681 | return c.dtlsDoReadRecord(want) |
| 682 | } |
| 683 | |
| 684 | recordHeaderLen := tlsRecordHeaderLen |
| 685 | |
| 686 | if c.rawInput == nil { |
| 687 | c.rawInput = c.in.newBlock() |
| 688 | } |
| 689 | b := c.rawInput |
| 690 | |
| 691 | // Read header, payload. |
| 692 | if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil { |
| 693 | // RFC suggests that EOF without an alertCloseNotify is |
| 694 | // an error, but popular web sites seem to do this, |
David Benjamin | 30789da | 2015-08-29 22:56:45 -0400 | [diff] [blame] | 695 | // so we can't make it an error, outside of tests. |
| 696 | if err == io.EOF && c.config.Bugs.ExpectCloseNotify { |
| 697 | err = io.ErrUnexpectedEOF |
| 698 | } |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 699 | if e, ok := err.(net.Error); !ok || !e.Temporary() { |
| 700 | c.in.setErrorLocked(err) |
| 701 | } |
| 702 | return 0, nil, err |
| 703 | } |
| 704 | typ := recordType(b.data[0]) |
| 705 | |
| 706 | // No valid TLS record has a type of 0x80, however SSLv2 handshakes |
| 707 | // start with a uint16 length where the MSB is set and the first record |
| 708 | // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests |
| 709 | // an SSLv2 client. |
| 710 | if want == recordTypeHandshake && typ == 0x80 { |
| 711 | c.sendAlert(alertProtocolVersion) |
| 712 | return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received")) |
| 713 | } |
| 714 | |
| 715 | vers := uint16(b.data[1])<<8 | uint16(b.data[2]) |
| 716 | n := int(b.data[3])<<8 | int(b.data[4]) |
David Benjamin | bde0039 | 2016-06-21 12:19:28 -0400 | [diff] [blame^] | 717 | // Alerts sent near version negotiation do not have a well-defined |
| 718 | // record-layer version prior to TLS 1.3. (In TLS 1.3, the record-layer |
| 719 | // version is irrelevant.) |
| 720 | if typ != recordTypeAlert { |
| 721 | if c.haveVers { |
| 722 | if vers != c.vers && c.vers < VersionTLS13 { |
| 723 | c.sendAlert(alertProtocolVersion) |
| 724 | return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers)) |
| 725 | } |
| 726 | } else { |
| 727 | if expect := c.config.Bugs.ExpectInitialRecordVersion; expect != 0 && vers != expect { |
| 728 | c.sendAlert(alertProtocolVersion) |
| 729 | return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect)) |
| 730 | } |
David Benjamin | 1e29a6b | 2014-12-10 02:27:24 -0500 | [diff] [blame] | 731 | } |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 732 | } |
| 733 | if n > maxCiphertext { |
| 734 | c.sendAlert(alertRecordOverflow) |
| 735 | return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n)) |
| 736 | } |
| 737 | if !c.haveVers { |
| 738 | // First message, be extra suspicious: |
| 739 | // this might not be a TLS client. |
| 740 | // Bail out before reading a full 'body', if possible. |
| 741 | // The current max version is 3.1. |
| 742 | // If the version is >= 16.0, it's probably not real. |
| 743 | // Similarly, a clientHello message encodes in |
| 744 | // well under a kilobyte. If the length is >= 12 kB, |
| 745 | // it's probably not real. |
| 746 | if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 { |
| 747 | c.sendAlert(alertUnexpectedMessage) |
| 748 | return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake")) |
| 749 | } |
| 750 | } |
| 751 | if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil { |
| 752 | if err == io.EOF { |
| 753 | err = io.ErrUnexpectedEOF |
| 754 | } |
| 755 | if e, ok := err.(net.Error); !ok || !e.Temporary() { |
| 756 | c.in.setErrorLocked(err) |
| 757 | } |
| 758 | return 0, nil, err |
| 759 | } |
| 760 | |
| 761 | // Process message. |
| 762 | b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n) |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 763 | ok, off, encTyp, err := c.in.decrypt(b) |
| 764 | if c.vers >= VersionTLS13 && c.in.cipher != nil { |
| 765 | // TODO(nharper): Check that outer type (typ) is |
| 766 | // application data. |
| 767 | typ = encTyp |
| 768 | } |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 769 | if !ok { |
| 770 | c.in.setErrorLocked(c.sendAlert(err)) |
| 771 | } |
| 772 | b.off = off |
| 773 | return typ, b, nil |
| 774 | } |
| 775 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 776 | // readRecord reads the next TLS record from the connection |
| 777 | // and updates the record layer state. |
| 778 | // c.in.Mutex <= L; c.input == nil. |
| 779 | func (c *Conn) readRecord(want recordType) error { |
| 780 | // Caller must be in sync with connection: |
| 781 | // handshake data if handshake not yet completed, |
Adam Langley | 2ae77d2 | 2014-10-28 17:29:33 -0700 | [diff] [blame] | 782 | // else application data. |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 783 | switch want { |
| 784 | default: |
| 785 | c.sendAlert(alertInternalError) |
| 786 | return c.in.setErrorLocked(errors.New("tls: unknown record type requested")) |
| 787 | case recordTypeHandshake, recordTypeChangeCipherSpec: |
| 788 | if c.handshakeComplete { |
| 789 | c.sendAlert(alertInternalError) |
| 790 | return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete")) |
| 791 | } |
| 792 | case recordTypeApplicationData: |
David Benjamin | e58c4f5 | 2014-08-24 03:47:07 -0400 | [diff] [blame] | 793 | if !c.handshakeComplete && !c.config.Bugs.ExpectFalseStart { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 794 | c.sendAlert(alertInternalError) |
| 795 | return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete")) |
| 796 | } |
David Benjamin | 30789da | 2015-08-29 22:56:45 -0400 | [diff] [blame] | 797 | case recordTypeAlert: |
| 798 | // Looking for a close_notify. Note: unlike a real |
| 799 | // implementation, this is not tolerant of additional records. |
| 800 | // See the documentation for ExpectCloseNotify. |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 801 | } |
| 802 | |
| 803 | Again: |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 804 | typ, b, err := c.doReadRecord(want) |
| 805 | if err != nil { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 806 | return err |
| 807 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 808 | data := b.data[b.off:] |
| 809 | if len(data) > maxPlaintext { |
| 810 | err := c.sendAlert(alertRecordOverflow) |
| 811 | c.in.freeBlock(b) |
| 812 | return c.in.setErrorLocked(err) |
| 813 | } |
| 814 | |
| 815 | switch typ { |
| 816 | default: |
| 817 | c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) |
| 818 | |
| 819 | case recordTypeAlert: |
| 820 | if len(data) != 2 { |
| 821 | c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) |
| 822 | break |
| 823 | } |
| 824 | if alert(data[1]) == alertCloseNotify { |
| 825 | c.in.setErrorLocked(io.EOF) |
| 826 | break |
| 827 | } |
| 828 | switch data[0] { |
| 829 | case alertLevelWarning: |
| 830 | // drop on the floor |
| 831 | c.in.freeBlock(b) |
| 832 | goto Again |
| 833 | case alertLevelError: |
| 834 | c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])}) |
| 835 | default: |
| 836 | c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) |
| 837 | } |
| 838 | |
| 839 | case recordTypeChangeCipherSpec: |
| 840 | if typ != want || len(data) != 1 || data[0] != 1 { |
| 841 | c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) |
| 842 | break |
| 843 | } |
Adam Langley | 80842bd | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 844 | err := c.in.changeCipherSpec(c.config) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 845 | if err != nil { |
| 846 | c.in.setErrorLocked(c.sendAlert(err.(alert))) |
| 847 | } |
| 848 | |
| 849 | case recordTypeApplicationData: |
| 850 | if typ != want { |
| 851 | c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) |
| 852 | break |
| 853 | } |
| 854 | c.input = b |
| 855 | b = nil |
| 856 | |
| 857 | case recordTypeHandshake: |
| 858 | // TODO(rsc): Should at least pick off connection close. |
| 859 | if typ != want { |
Adam Langley | 2ae77d2 | 2014-10-28 17:29:33 -0700 | [diff] [blame] | 860 | // A client might need to process a HelloRequest from |
| 861 | // the server, thus receiving a handshake message when |
David Benjamin | d9b091b | 2015-01-27 01:10:54 -0500 | [diff] [blame] | 862 | // application data is expected is ok. |
David Benjamin | 30789da | 2015-08-29 22:56:45 -0400 | [diff] [blame] | 863 | if !c.isClient || want != recordTypeApplicationData { |
Adam Langley | 2ae77d2 | 2014-10-28 17:29:33 -0700 | [diff] [blame] | 864 | return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation)) |
| 865 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 866 | } |
| 867 | c.hand.Write(data) |
| 868 | } |
| 869 | |
| 870 | if b != nil { |
| 871 | c.in.freeBlock(b) |
| 872 | } |
| 873 | return c.in.err |
| 874 | } |
| 875 | |
| 876 | // sendAlert sends a TLS alert message. |
| 877 | // c.out.Mutex <= L. |
David Benjamin | 24f346d | 2015-06-06 03:28:08 -0400 | [diff] [blame] | 878 | func (c *Conn) sendAlertLocked(level byte, err alert) error { |
| 879 | c.tmp[0] = level |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 880 | c.tmp[1] = byte(err) |
Alex Chernyakhovsky | 4cd8c43 | 2014-11-01 19:39:08 -0400 | [diff] [blame] | 881 | if c.config.Bugs.FragmentAlert { |
| 882 | c.writeRecord(recordTypeAlert, c.tmp[0:1]) |
| 883 | c.writeRecord(recordTypeAlert, c.tmp[1:2]) |
David Benjamin | 0d3a8c6 | 2016-03-11 22:25:18 -0500 | [diff] [blame] | 884 | } else if c.config.Bugs.DoubleAlert { |
| 885 | copy(c.tmp[2:4], c.tmp[0:2]) |
| 886 | c.writeRecord(recordTypeAlert, c.tmp[0:4]) |
Alex Chernyakhovsky | 4cd8c43 | 2014-11-01 19:39:08 -0400 | [diff] [blame] | 887 | } else { |
| 888 | c.writeRecord(recordTypeAlert, c.tmp[0:2]) |
| 889 | } |
David Benjamin | 24f346d | 2015-06-06 03:28:08 -0400 | [diff] [blame] | 890 | // Error alerts are fatal to the connection. |
| 891 | if level == alertLevelError { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 892 | return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err}) |
| 893 | } |
| 894 | return nil |
| 895 | } |
| 896 | |
| 897 | // sendAlert sends a TLS alert message. |
| 898 | // L < c.out.Mutex. |
| 899 | func (c *Conn) sendAlert(err alert) error { |
David Benjamin | 24f346d | 2015-06-06 03:28:08 -0400 | [diff] [blame] | 900 | level := byte(alertLevelError) |
David Benjamin | 0b7ca7d | 2016-03-10 15:44:22 -0500 | [diff] [blame] | 901 | if err == alertNoRenegotiation || err == alertCloseNotify || err == alertNoCertficate { |
David Benjamin | 24f346d | 2015-06-06 03:28:08 -0400 | [diff] [blame] | 902 | level = alertLevelWarning |
| 903 | } |
| 904 | return c.SendAlert(level, err) |
| 905 | } |
| 906 | |
| 907 | func (c *Conn) SendAlert(level byte, err alert) error { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 908 | c.out.Lock() |
| 909 | defer c.out.Unlock() |
David Benjamin | 24f346d | 2015-06-06 03:28:08 -0400 | [diff] [blame] | 910 | return c.sendAlertLocked(level, err) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 911 | } |
| 912 | |
David Benjamin | d86c767 | 2014-08-02 04:07:12 -0400 | [diff] [blame] | 913 | // writeV2Record writes a record for a V2ClientHello. |
| 914 | func (c *Conn) writeV2Record(data []byte) (n int, err error) { |
| 915 | record := make([]byte, 2+len(data)) |
| 916 | record[0] = uint8(len(data)>>8) | 0x80 |
| 917 | record[1] = uint8(len(data)) |
| 918 | copy(record[2:], data) |
| 919 | return c.conn.Write(record) |
| 920 | } |
| 921 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 922 | // writeRecord writes a TLS record with the given type and payload |
| 923 | // to the connection and updates the record layer state. |
| 924 | // c.out.Mutex <= L. |
| 925 | func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) { |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 926 | if c.isDTLS { |
| 927 | return c.dtlsWriteRecord(typ, data) |
| 928 | } |
| 929 | |
| 930 | recordHeaderLen := tlsRecordHeaderLen |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 931 | b := c.out.newBlock() |
David Benjamin | 9821454 | 2014-08-07 18:02:39 -0400 | [diff] [blame] | 932 | first := true |
| 933 | isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello |
David Benjamin | a8ebe22 | 2015-06-06 03:04:39 -0400 | [diff] [blame] | 934 | for len(data) > 0 || first { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 935 | m := len(data) |
David Benjamin | 2c99d28 | 2015-09-01 10:23:00 -0400 | [diff] [blame] | 936 | if m > maxPlaintext && !c.config.Bugs.SendLargeRecords { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 937 | m = maxPlaintext |
| 938 | } |
David Benjamin | 43ec06f | 2014-08-05 02:28:57 -0400 | [diff] [blame] | 939 | if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength { |
| 940 | m = c.config.Bugs.MaxHandshakeRecordLength |
David Benjamin | 9821454 | 2014-08-07 18:02:39 -0400 | [diff] [blame] | 941 | // By default, do not fragment the client_version or |
| 942 | // server_version, which are located in the first 6 |
| 943 | // bytes. |
| 944 | if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 { |
| 945 | m = 6 |
| 946 | } |
David Benjamin | 43ec06f | 2014-08-05 02:28:57 -0400 | [diff] [blame] | 947 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 948 | explicitIVLen := 0 |
| 949 | explicitIVIsSeq := false |
David Benjamin | 9821454 | 2014-08-07 18:02:39 -0400 | [diff] [blame] | 950 | first = false |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 951 | |
| 952 | var cbc cbcMode |
| 953 | if c.out.version >= VersionTLS11 { |
| 954 | var ok bool |
| 955 | if cbc, ok = c.out.cipher.(cbcMode); ok { |
| 956 | explicitIVLen = cbc.BlockSize() |
| 957 | } |
| 958 | } |
| 959 | if explicitIVLen == 0 { |
David Benjamin | e9a80ff | 2015-04-07 00:46:46 -0400 | [diff] [blame] | 960 | if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 961 | explicitIVLen = 8 |
| 962 | // The AES-GCM construction in TLS has an |
| 963 | // explicit nonce so that the nonce can be |
| 964 | // random. However, the nonce is only 8 bytes |
| 965 | // which is too small for a secure, random |
| 966 | // nonce. Therefore we use the sequence number |
| 967 | // as the nonce. |
| 968 | explicitIVIsSeq = true |
| 969 | } |
| 970 | } |
| 971 | b.resize(recordHeaderLen + explicitIVLen + m) |
| 972 | b.data[0] = byte(typ) |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 973 | if c.vers >= VersionTLS13 && c.out.cipher != nil { |
| 974 | // TODO(nharper): Add a ProtocolBugs to skip this. |
| 975 | b.data[0] = byte(recordTypeApplicationData) |
| 976 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 977 | vers := c.vers |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 978 | if vers == 0 || vers >= VersionTLS13 { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 979 | // Some TLS servers fail if the record version is |
| 980 | // greater than TLS 1.0 for the initial ClientHello. |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 981 | // |
| 982 | // TLS 1.3 fixes the version number in the record |
| 983 | // layer to {3, 1}. |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 984 | vers = VersionTLS10 |
| 985 | } |
| 986 | b.data[1] = byte(vers >> 8) |
| 987 | b.data[2] = byte(vers) |
| 988 | b.data[3] = byte(m >> 8) |
| 989 | b.data[4] = byte(m) |
| 990 | if explicitIVLen > 0 { |
| 991 | explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen] |
| 992 | if explicitIVIsSeq { |
| 993 | copy(explicitIV, c.out.seq[:]) |
| 994 | } else { |
| 995 | if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil { |
| 996 | break |
| 997 | } |
| 998 | } |
| 999 | } |
| 1000 | copy(b.data[recordHeaderLen+explicitIVLen:], data) |
Nick Harper | 1fd39d8 | 2016-06-14 18:14:35 -0700 | [diff] [blame] | 1001 | c.out.encrypt(b, explicitIVLen, typ) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1002 | _, err = c.conn.Write(b.data) |
| 1003 | if err != nil { |
| 1004 | break |
| 1005 | } |
| 1006 | n += m |
| 1007 | data = data[m:] |
| 1008 | } |
| 1009 | c.out.freeBlock(b) |
| 1010 | |
| 1011 | if typ == recordTypeChangeCipherSpec { |
Adam Langley | 80842bd | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1012 | err = c.out.changeCipherSpec(c.config) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1013 | if err != nil { |
| 1014 | // Cannot call sendAlert directly, |
| 1015 | // because we already hold c.out.Mutex. |
| 1016 | c.tmp[0] = alertLevelError |
| 1017 | c.tmp[1] = byte(err.(alert)) |
| 1018 | c.writeRecord(recordTypeAlert, c.tmp[0:2]) |
| 1019 | return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err}) |
| 1020 | } |
| 1021 | } |
| 1022 | return |
| 1023 | } |
| 1024 | |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 1025 | func (c *Conn) doReadHandshake() ([]byte, error) { |
| 1026 | if c.isDTLS { |
| 1027 | return c.dtlsDoReadHandshake() |
| 1028 | } |
| 1029 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1030 | for c.hand.Len() < 4 { |
| 1031 | if err := c.in.err; err != nil { |
| 1032 | return nil, err |
| 1033 | } |
| 1034 | if err := c.readRecord(recordTypeHandshake); err != nil { |
| 1035 | return nil, err |
| 1036 | } |
| 1037 | } |
| 1038 | |
| 1039 | data := c.hand.Bytes() |
| 1040 | n := int(data[1])<<16 | int(data[2])<<8 | int(data[3]) |
| 1041 | if n > maxHandshake { |
| 1042 | return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError)) |
| 1043 | } |
| 1044 | for c.hand.Len() < 4+n { |
| 1045 | if err := c.in.err; err != nil { |
| 1046 | return nil, err |
| 1047 | } |
| 1048 | if err := c.readRecord(recordTypeHandshake); err != nil { |
| 1049 | return nil, err |
| 1050 | } |
| 1051 | } |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 1052 | return c.hand.Next(4 + n), nil |
| 1053 | } |
| 1054 | |
| 1055 | // readHandshake reads the next handshake message from |
| 1056 | // the record layer. |
| 1057 | // c.in.Mutex < L; c.out.Mutex < L. |
| 1058 | func (c *Conn) readHandshake() (interface{}, error) { |
| 1059 | data, err := c.doReadHandshake() |
| 1060 | if err != nil { |
| 1061 | return nil, err |
| 1062 | } |
| 1063 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1064 | var m handshakeMessage |
| 1065 | switch data[0] { |
Adam Langley | 2ae77d2 | 2014-10-28 17:29:33 -0700 | [diff] [blame] | 1066 | case typeHelloRequest: |
| 1067 | m = new(helloRequestMsg) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1068 | case typeClientHello: |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 1069 | m = &clientHelloMsg{ |
| 1070 | isDTLS: c.isDTLS, |
| 1071 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1072 | case typeServerHello: |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 1073 | m = &serverHelloMsg{ |
| 1074 | isDTLS: c.isDTLS, |
| 1075 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1076 | case typeNewSessionTicket: |
| 1077 | m = new(newSessionTicketMsg) |
| 1078 | case typeCertificate: |
| 1079 | m = new(certificateMsg) |
| 1080 | case typeCertificateRequest: |
| 1081 | m = &certificateRequestMsg{ |
| 1082 | hasSignatureAndHash: c.vers >= VersionTLS12, |
| 1083 | } |
| 1084 | case typeCertificateStatus: |
| 1085 | m = new(certificateStatusMsg) |
| 1086 | case typeServerKeyExchange: |
| 1087 | m = new(serverKeyExchangeMsg) |
| 1088 | case typeServerHelloDone: |
| 1089 | m = new(serverHelloDoneMsg) |
| 1090 | case typeClientKeyExchange: |
| 1091 | m = new(clientKeyExchangeMsg) |
| 1092 | case typeCertificateVerify: |
| 1093 | m = &certificateVerifyMsg{ |
| 1094 | hasSignatureAndHash: c.vers >= VersionTLS12, |
| 1095 | } |
| 1096 | case typeNextProtocol: |
| 1097 | m = new(nextProtoMsg) |
| 1098 | case typeFinished: |
| 1099 | m = new(finishedMsg) |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 1100 | case typeHelloVerifyRequest: |
| 1101 | m = new(helloVerifyRequestMsg) |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame] | 1102 | case typeEncryptedExtensions: |
| 1103 | m = new(encryptedExtensionsMsg) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1104 | default: |
| 1105 | return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) |
| 1106 | } |
| 1107 | |
| 1108 | // The handshake message unmarshallers |
| 1109 | // expect to be able to keep references to data, |
| 1110 | // so pass in a fresh copy that won't be overwritten. |
| 1111 | data = append([]byte(nil), data...) |
| 1112 | |
| 1113 | if !m.unmarshal(data) { |
| 1114 | return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) |
| 1115 | } |
| 1116 | return m, nil |
| 1117 | } |
| 1118 | |
David Benjamin | 83f9040 | 2015-01-27 01:09:43 -0500 | [diff] [blame] | 1119 | // skipPacket processes all the DTLS records in packet. It updates |
| 1120 | // sequence number expectations but otherwise ignores them. |
| 1121 | func (c *Conn) skipPacket(packet []byte) error { |
| 1122 | for len(packet) > 0 { |
David Benjamin | 6ca9355 | 2015-08-28 16:16:25 -0400 | [diff] [blame] | 1123 | if len(packet) < 13 { |
| 1124 | return errors.New("tls: bad packet") |
| 1125 | } |
David Benjamin | 83f9040 | 2015-01-27 01:09:43 -0500 | [diff] [blame] | 1126 | // Dropped packets are completely ignored save to update |
| 1127 | // expected sequence numbers for this and the next epoch. (We |
| 1128 | // don't assert on the contents of the packets both for |
| 1129 | // simplicity and because a previous test with one shorter |
| 1130 | // timeout schedule would have done so.) |
| 1131 | epoch := packet[3:5] |
| 1132 | seq := packet[5:11] |
| 1133 | length := uint16(packet[11])<<8 | uint16(packet[12]) |
| 1134 | if bytes.Equal(c.in.seq[:2], epoch) { |
David Benjamin | 13e81fc | 2015-11-02 17:16:13 -0500 | [diff] [blame] | 1135 | if bytes.Compare(seq, c.in.seq[2:]) < 0 { |
David Benjamin | 83f9040 | 2015-01-27 01:09:43 -0500 | [diff] [blame] | 1136 | return errors.New("tls: sequence mismatch") |
| 1137 | } |
David Benjamin | 13e81fc | 2015-11-02 17:16:13 -0500 | [diff] [blame] | 1138 | copy(c.in.seq[2:], seq) |
David Benjamin | 83f9040 | 2015-01-27 01:09:43 -0500 | [diff] [blame] | 1139 | c.in.incSeq(false) |
| 1140 | } else { |
David Benjamin | 13e81fc | 2015-11-02 17:16:13 -0500 | [diff] [blame] | 1141 | if bytes.Compare(seq, c.in.nextSeq[:]) < 0 { |
David Benjamin | 83f9040 | 2015-01-27 01:09:43 -0500 | [diff] [blame] | 1142 | return errors.New("tls: sequence mismatch") |
| 1143 | } |
David Benjamin | 13e81fc | 2015-11-02 17:16:13 -0500 | [diff] [blame] | 1144 | copy(c.in.nextSeq[:], seq) |
David Benjamin | 83f9040 | 2015-01-27 01:09:43 -0500 | [diff] [blame] | 1145 | c.in.incNextSeq() |
| 1146 | } |
David Benjamin | 6ca9355 | 2015-08-28 16:16:25 -0400 | [diff] [blame] | 1147 | if len(packet) < 13+int(length) { |
| 1148 | return errors.New("tls: bad packet") |
| 1149 | } |
David Benjamin | 83f9040 | 2015-01-27 01:09:43 -0500 | [diff] [blame] | 1150 | packet = packet[13+length:] |
| 1151 | } |
| 1152 | return nil |
| 1153 | } |
| 1154 | |
| 1155 | // simulatePacketLoss simulates the loss of a handshake leg from the |
| 1156 | // peer based on the schedule in c.config.Bugs. If resendFunc is |
| 1157 | // non-nil, it is called after each simulated timeout to retransmit |
| 1158 | // handshake messages from the local end. This is used in cases where |
| 1159 | // the peer retransmits on a stale Finished rather than a timeout. |
| 1160 | func (c *Conn) simulatePacketLoss(resendFunc func()) error { |
| 1161 | if len(c.config.Bugs.TimeoutSchedule) == 0 { |
| 1162 | return nil |
| 1163 | } |
| 1164 | if !c.isDTLS { |
| 1165 | return errors.New("tls: TimeoutSchedule may only be set in DTLS") |
| 1166 | } |
| 1167 | if c.config.Bugs.PacketAdaptor == nil { |
| 1168 | return errors.New("tls: TimeoutSchedule set without PacketAdapter") |
| 1169 | } |
| 1170 | for _, timeout := range c.config.Bugs.TimeoutSchedule { |
| 1171 | // Simulate a timeout. |
| 1172 | packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout) |
| 1173 | if err != nil { |
| 1174 | return err |
| 1175 | } |
| 1176 | for _, packet := range packets { |
| 1177 | if err := c.skipPacket(packet); err != nil { |
| 1178 | return err |
| 1179 | } |
| 1180 | } |
| 1181 | if resendFunc != nil { |
| 1182 | resendFunc() |
| 1183 | } |
| 1184 | } |
| 1185 | return nil |
| 1186 | } |
| 1187 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1188 | // Write writes data to the connection. |
| 1189 | func (c *Conn) Write(b []byte) (int, error) { |
| 1190 | if err := c.Handshake(); err != nil { |
| 1191 | return 0, err |
| 1192 | } |
| 1193 | |
| 1194 | c.out.Lock() |
| 1195 | defer c.out.Unlock() |
| 1196 | |
| 1197 | if err := c.out.err; err != nil { |
| 1198 | return 0, err |
| 1199 | } |
| 1200 | |
| 1201 | if !c.handshakeComplete { |
| 1202 | return 0, alertInternalError |
| 1203 | } |
| 1204 | |
David Benjamin | 3fd1fbd | 2015-02-03 16:07:32 -0500 | [diff] [blame] | 1205 | if c.config.Bugs.SendSpuriousAlert != 0 { |
David Benjamin | 24f346d | 2015-06-06 03:28:08 -0400 | [diff] [blame] | 1206 | c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert) |
Alex Chernyakhovsky | 4cd8c43 | 2014-11-01 19:39:08 -0400 | [diff] [blame] | 1207 | } |
| 1208 | |
Adam Langley | 27a0d08 | 2015-11-03 13:34:10 -0800 | [diff] [blame] | 1209 | if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord { |
| 1210 | c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0}) |
| 1211 | } |
| 1212 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1213 | // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext |
| 1214 | // attack when using block mode ciphers due to predictable IVs. |
| 1215 | // This can be prevented by splitting each Application Data |
| 1216 | // record into two records, effectively randomizing the IV. |
| 1217 | // |
| 1218 | // http://www.openssl.org/~bodo/tls-cbc.txt |
| 1219 | // https://bugzilla.mozilla.org/show_bug.cgi?id=665814 |
| 1220 | // http://www.imperialviolet.org/2012/01/15/beastfollowup.html |
| 1221 | |
| 1222 | var m int |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 1223 | if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1224 | if _, ok := c.out.cipher.(cipher.BlockMode); ok { |
| 1225 | n, err := c.writeRecord(recordTypeApplicationData, b[:1]) |
| 1226 | if err != nil { |
| 1227 | return n, c.out.setErrorLocked(err) |
| 1228 | } |
| 1229 | m, b = 1, b[1:] |
| 1230 | } |
| 1231 | } |
| 1232 | |
| 1233 | n, err := c.writeRecord(recordTypeApplicationData, b) |
| 1234 | return n + m, c.out.setErrorLocked(err) |
| 1235 | } |
| 1236 | |
Adam Langley | 2ae77d2 | 2014-10-28 17:29:33 -0700 | [diff] [blame] | 1237 | func (c *Conn) handleRenegotiation() error { |
| 1238 | c.handshakeComplete = false |
| 1239 | if !c.isClient { |
| 1240 | panic("renegotiation should only happen for a client") |
| 1241 | } |
| 1242 | |
| 1243 | msg, err := c.readHandshake() |
| 1244 | if err != nil { |
| 1245 | return err |
| 1246 | } |
| 1247 | _, ok := msg.(*helloRequestMsg) |
| 1248 | if !ok { |
| 1249 | c.sendAlert(alertUnexpectedMessage) |
| 1250 | return alertUnexpectedMessage |
| 1251 | } |
| 1252 | |
| 1253 | return c.Handshake() |
| 1254 | } |
| 1255 | |
Adam Langley | cf2d4f4 | 2014-10-28 19:06:14 -0700 | [diff] [blame] | 1256 | func (c *Conn) Renegotiate() error { |
| 1257 | if !c.isClient { |
David Benjamin | ef5dfd2 | 2015-12-06 13:17:07 -0500 | [diff] [blame] | 1258 | helloReq := new(helloRequestMsg).marshal() |
| 1259 | if c.config.Bugs.BadHelloRequest != nil { |
| 1260 | helloReq = c.config.Bugs.BadHelloRequest |
| 1261 | } |
| 1262 | c.writeRecord(recordTypeHandshake, helloReq) |
Adam Langley | cf2d4f4 | 2014-10-28 19:06:14 -0700 | [diff] [blame] | 1263 | } |
| 1264 | |
| 1265 | c.handshakeComplete = false |
| 1266 | return c.Handshake() |
| 1267 | } |
| 1268 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1269 | // Read can be made to time out and return a net.Error with Timeout() == true |
| 1270 | // after a fixed time limit; see SetDeadline and SetReadDeadline. |
| 1271 | func (c *Conn) Read(b []byte) (n int, err error) { |
| 1272 | if err = c.Handshake(); err != nil { |
| 1273 | return |
| 1274 | } |
| 1275 | |
| 1276 | c.in.Lock() |
| 1277 | defer c.in.Unlock() |
| 1278 | |
| 1279 | // Some OpenSSL servers send empty records in order to randomize the |
| 1280 | // CBC IV. So this loop ignores a limited number of empty records. |
| 1281 | const maxConsecutiveEmptyRecords = 100 |
| 1282 | for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ { |
| 1283 | for c.input == nil && c.in.err == nil { |
| 1284 | if err := c.readRecord(recordTypeApplicationData); err != nil { |
| 1285 | // Soft error, like EAGAIN |
| 1286 | return 0, err |
| 1287 | } |
David Benjamin | d9b091b | 2015-01-27 01:10:54 -0500 | [diff] [blame] | 1288 | if c.hand.Len() > 0 { |
Adam Langley | 2ae77d2 | 2014-10-28 17:29:33 -0700 | [diff] [blame] | 1289 | // We received handshake bytes, indicating the |
David Benjamin | d9b091b | 2015-01-27 01:10:54 -0500 | [diff] [blame] | 1290 | // start of a renegotiation. |
Adam Langley | 2ae77d2 | 2014-10-28 17:29:33 -0700 | [diff] [blame] | 1291 | if err := c.handleRenegotiation(); err != nil { |
| 1292 | return 0, err |
| 1293 | } |
| 1294 | continue |
| 1295 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1296 | } |
| 1297 | if err := c.in.err; err != nil { |
| 1298 | return 0, err |
| 1299 | } |
| 1300 | |
| 1301 | n, err = c.input.Read(b) |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 1302 | if c.input.off >= len(c.input.data) || c.isDTLS { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1303 | c.in.freeBlock(c.input) |
| 1304 | c.input = nil |
| 1305 | } |
| 1306 | |
| 1307 | // If a close-notify alert is waiting, read it so that |
| 1308 | // we can return (n, EOF) instead of (n, nil), to signal |
| 1309 | // to the HTTP response reading goroutine that the |
| 1310 | // connection is now closed. This eliminates a race |
| 1311 | // where the HTTP response reading goroutine would |
| 1312 | // otherwise not observe the EOF until its next read, |
| 1313 | // by which time a client goroutine might have already |
| 1314 | // tried to reuse the HTTP connection for a new |
| 1315 | // request. |
| 1316 | // See https://codereview.appspot.com/76400046 |
| 1317 | // and http://golang.org/issue/3514 |
| 1318 | if ri := c.rawInput; ri != nil && |
| 1319 | n != 0 && err == nil && |
| 1320 | c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert { |
| 1321 | if recErr := c.readRecord(recordTypeApplicationData); recErr != nil { |
| 1322 | err = recErr // will be io.EOF on closeNotify |
| 1323 | } |
| 1324 | } |
| 1325 | |
| 1326 | if n != 0 || err != nil { |
| 1327 | return n, err |
| 1328 | } |
| 1329 | } |
| 1330 | |
| 1331 | return 0, io.ErrNoProgress |
| 1332 | } |
| 1333 | |
| 1334 | // Close closes the connection. |
| 1335 | func (c *Conn) Close() error { |
| 1336 | var alertErr error |
| 1337 | |
| 1338 | c.handshakeMutex.Lock() |
| 1339 | defer c.handshakeMutex.Unlock() |
David Benjamin | 30789da | 2015-08-29 22:56:45 -0400 | [diff] [blame] | 1340 | if c.handshakeComplete && !c.config.Bugs.NoCloseNotify { |
David Benjamin | fa214e4 | 2016-05-10 17:03:10 -0400 | [diff] [blame] | 1341 | alert := alertCloseNotify |
| 1342 | if c.config.Bugs.SendAlertOnShutdown != 0 { |
| 1343 | alert = c.config.Bugs.SendAlertOnShutdown |
| 1344 | } |
| 1345 | alertErr = c.sendAlert(alert) |
David Benjamin | 4d55961 | 2016-05-18 14:31:51 -0400 | [diff] [blame] | 1346 | // Clear local alerts when sending alerts so we continue to wait |
| 1347 | // for the peer rather than closing the socket early. |
| 1348 | if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" { |
| 1349 | alertErr = nil |
| 1350 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1351 | } |
| 1352 | |
David Benjamin | 30789da | 2015-08-29 22:56:45 -0400 | [diff] [blame] | 1353 | // Consume a close_notify from the peer if one hasn't been received |
| 1354 | // already. This avoids the peer from failing |SSL_shutdown| due to a |
| 1355 | // write failing. |
| 1356 | if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify { |
| 1357 | for c.in.error() == nil { |
| 1358 | c.readRecord(recordTypeAlert) |
| 1359 | } |
| 1360 | if c.in.error() != io.EOF { |
| 1361 | alertErr = c.in.error() |
| 1362 | } |
| 1363 | } |
| 1364 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1365 | if err := c.conn.Close(); err != nil { |
| 1366 | return err |
| 1367 | } |
| 1368 | return alertErr |
| 1369 | } |
| 1370 | |
| 1371 | // Handshake runs the client or server handshake |
| 1372 | // protocol if it has not yet been run. |
| 1373 | // Most uses of this package need not call Handshake |
| 1374 | // explicitly: the first Read or Write will call it automatically. |
| 1375 | func (c *Conn) Handshake() error { |
| 1376 | c.handshakeMutex.Lock() |
| 1377 | defer c.handshakeMutex.Unlock() |
| 1378 | if err := c.handshakeErr; err != nil { |
| 1379 | return err |
| 1380 | } |
| 1381 | if c.handshakeComplete { |
| 1382 | return nil |
| 1383 | } |
| 1384 | |
David Benjamin | 9a41d1b | 2015-05-16 01:30:09 -0400 | [diff] [blame] | 1385 | if c.isDTLS && c.config.Bugs.SendSplitAlert { |
| 1386 | c.conn.Write([]byte{ |
| 1387 | byte(recordTypeAlert), // type |
| 1388 | 0xfe, 0xff, // version |
| 1389 | 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence |
| 1390 | 0x0, 0x2, // length |
| 1391 | }) |
| 1392 | c.conn.Write([]byte{alertLevelError, byte(alertInternalError)}) |
| 1393 | } |
David Benjamin | 4cf369b | 2015-08-22 01:35:43 -0400 | [diff] [blame] | 1394 | if data := c.config.Bugs.AppDataBeforeHandshake; data != nil { |
| 1395 | c.writeRecord(recordTypeApplicationData, data) |
| 1396 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1397 | if c.isClient { |
| 1398 | c.handshakeErr = c.clientHandshake() |
| 1399 | } else { |
| 1400 | c.handshakeErr = c.serverHandshake() |
| 1401 | } |
David Benjamin | ddb9f15 | 2015-02-03 15:44:39 -0500 | [diff] [blame] | 1402 | if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType { |
| 1403 | c.writeRecord(recordType(42), []byte("invalid record")) |
| 1404 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1405 | return c.handshakeErr |
| 1406 | } |
| 1407 | |
| 1408 | // ConnectionState returns basic TLS details about the connection. |
| 1409 | func (c *Conn) ConnectionState() ConnectionState { |
| 1410 | c.handshakeMutex.Lock() |
| 1411 | defer c.handshakeMutex.Unlock() |
| 1412 | |
| 1413 | var state ConnectionState |
| 1414 | state.HandshakeComplete = c.handshakeComplete |
| 1415 | if c.handshakeComplete { |
| 1416 | state.Version = c.vers |
| 1417 | state.NegotiatedProtocol = c.clientProtocol |
| 1418 | state.DidResume = c.didResume |
| 1419 | state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback |
David Benjamin | fc7b086 | 2014-09-06 13:21:53 -0400 | [diff] [blame] | 1420 | state.NegotiatedProtocolFromALPN = c.usedALPN |
David Benjamin | c565ebb | 2015-04-03 04:06:36 -0400 | [diff] [blame] | 1421 | state.CipherSuite = c.cipherSuite.id |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1422 | state.PeerCertificates = c.peerCertificates |
| 1423 | state.VerifiedChains = c.verifiedChains |
| 1424 | state.ServerName = c.serverName |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame] | 1425 | state.ChannelID = c.channelID |
David Benjamin | ca6c826 | 2014-11-15 19:06:08 -0500 | [diff] [blame] | 1426 | state.SRTPProtectionProfile = c.srtpProtectionProfile |
Adam Langley | af0e32c | 2015-06-03 09:57:23 -0700 | [diff] [blame] | 1427 | state.TLSUnique = c.firstFinished[:] |
Paul Lietar | 4fac72e | 2015-09-09 13:44:55 +0100 | [diff] [blame] | 1428 | state.SCTList = c.sctList |
Steven Valdez | 0d62f26 | 2015-09-04 12:41:04 -0400 | [diff] [blame] | 1429 | state.ClientCertSignatureHash = c.clientCertSignatureHash |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1430 | } |
| 1431 | |
| 1432 | return state |
| 1433 | } |
| 1434 | |
| 1435 | // OCSPResponse returns the stapled OCSP response from the TLS server, if |
| 1436 | // any. (Only valid for client connections.) |
| 1437 | func (c *Conn) OCSPResponse() []byte { |
| 1438 | c.handshakeMutex.Lock() |
| 1439 | defer c.handshakeMutex.Unlock() |
| 1440 | |
| 1441 | return c.ocspResponse |
| 1442 | } |
| 1443 | |
| 1444 | // VerifyHostname checks that the peer certificate chain is valid for |
| 1445 | // connecting to host. If so, it returns nil; if not, it returns an error |
| 1446 | // describing the problem. |
| 1447 | func (c *Conn) VerifyHostname(host string) error { |
| 1448 | c.handshakeMutex.Lock() |
| 1449 | defer c.handshakeMutex.Unlock() |
| 1450 | if !c.isClient { |
| 1451 | return errors.New("tls: VerifyHostname called on TLS server connection") |
| 1452 | } |
| 1453 | if !c.handshakeComplete { |
| 1454 | return errors.New("tls: handshake has not yet been performed") |
| 1455 | } |
| 1456 | return c.peerCertificates[0].VerifyHostname(host) |
| 1457 | } |
David Benjamin | c565ebb | 2015-04-03 04:06:36 -0400 | [diff] [blame] | 1458 | |
| 1459 | // ExportKeyingMaterial exports keying material from the current connection |
| 1460 | // state, as per RFC 5705. |
| 1461 | func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) { |
| 1462 | c.handshakeMutex.Lock() |
| 1463 | defer c.handshakeMutex.Unlock() |
| 1464 | if !c.handshakeComplete { |
| 1465 | return nil, errors.New("tls: handshake has not yet been performed") |
| 1466 | } |
| 1467 | |
| 1468 | seedLen := len(c.clientRandom) + len(c.serverRandom) |
| 1469 | if useContext { |
| 1470 | seedLen += 2 + len(context) |
| 1471 | } |
| 1472 | seed := make([]byte, 0, seedLen) |
| 1473 | seed = append(seed, c.clientRandom[:]...) |
| 1474 | seed = append(seed, c.serverRandom[:]...) |
| 1475 | if useContext { |
| 1476 | seed = append(seed, byte(len(context)>>8), byte(len(context))) |
| 1477 | seed = append(seed, context...) |
| 1478 | } |
| 1479 | result := make([]byte, length) |
| 1480 | prfForVersion(c.vers, c.cipherSuite)(result, c.masterSecret[:], label, seed) |
| 1481 | return result, nil |
| 1482 | } |
David Benjamin | 3e052de | 2015-11-25 20:10:31 -0500 | [diff] [blame] | 1483 | |
| 1484 | // noRenegotiationInfo returns true if the renegotiation info extension |
| 1485 | // should be supported in the current handshake. |
| 1486 | func (c *Conn) noRenegotiationInfo() bool { |
| 1487 | if c.config.Bugs.NoRenegotiationInfo { |
| 1488 | return true |
| 1489 | } |
| 1490 | if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial { |
| 1491 | return true |
| 1492 | } |
| 1493 | if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial { |
| 1494 | return true |
| 1495 | } |
| 1496 | return false |
| 1497 | } |