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