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