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