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