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