Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 1 | // Copyright 2009 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 | package main |
| 6 | |
| 7 | import ( |
| 8 | "bytes" |
| 9 | "crypto/ecdsa" |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame] | 10 | "crypto/elliptic" |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 11 | "crypto/rsa" |
| 12 | "crypto/subtle" |
| 13 | "crypto/x509" |
| 14 | "encoding/asn1" |
| 15 | "errors" |
| 16 | "fmt" |
| 17 | "io" |
David Benjamin | de620d9 | 2014-07-18 15:03:41 -0400 | [diff] [blame] | 18 | "math/big" |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 19 | "net" |
| 20 | "strconv" |
| 21 | ) |
| 22 | |
| 23 | type clientHandshakeState struct { |
David Benjamin | 83f9040 | 2015-01-27 01:09:43 -0500 | [diff] [blame] | 24 | c *Conn |
| 25 | serverHello *serverHelloMsg |
| 26 | hello *clientHelloMsg |
| 27 | suite *cipherSuite |
| 28 | finishedHash finishedHash |
| 29 | masterSecret []byte |
| 30 | session *ClientSessionState |
| 31 | finishedBytes []byte |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 32 | } |
| 33 | |
| 34 | func (c *Conn) clientHandshake() error { |
| 35 | if c.config == nil { |
| 36 | c.config = defaultConfig() |
| 37 | } |
| 38 | |
| 39 | if len(c.config.ServerName) == 0 && !c.config.InsecureSkipVerify { |
| 40 | return errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config") |
| 41 | } |
| 42 | |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 43 | c.sendHandshakeSeq = 0 |
| 44 | c.recvHandshakeSeq = 0 |
| 45 | |
David Benjamin | fa055a2 | 2014-09-15 16:51:51 -0400 | [diff] [blame] | 46 | nextProtosLength := 0 |
| 47 | for _, proto := range c.config.NextProtos { |
| 48 | if l := len(proto); l == 0 || l > 255 { |
| 49 | return errors.New("tls: invalid NextProtos value") |
| 50 | } else { |
| 51 | nextProtosLength += 1 + l |
| 52 | } |
| 53 | } |
| 54 | if nextProtosLength > 0xffff { |
| 55 | return errors.New("tls: NextProtos values too large") |
| 56 | } |
| 57 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 58 | hello := &clientHelloMsg{ |
David Benjamin | ca6c826 | 2014-11-15 19:06:08 -0500 | [diff] [blame] | 59 | isDTLS: c.isDTLS, |
| 60 | vers: c.config.maxVersion(), |
| 61 | compressionMethods: []uint8{compressionNone}, |
| 62 | random: make([]byte, 32), |
| 63 | ocspStapling: true, |
| 64 | serverName: c.config.ServerName, |
| 65 | supportedCurves: c.config.curvePreferences(), |
| 66 | supportedPoints: []uint8{pointFormatUncompressed}, |
| 67 | nextProtoNeg: len(c.config.NextProtos) > 0, |
| 68 | secureRenegotiation: []byte{}, |
| 69 | alpnProtocols: c.config.NextProtos, |
| 70 | duplicateExtension: c.config.Bugs.DuplicateExtension, |
| 71 | channelIDSupported: c.config.ChannelID != nil, |
| 72 | npnLast: c.config.Bugs.SwapNPNAndALPN, |
| 73 | extendedMasterSecret: c.config.maxVersion() >= VersionTLS10, |
| 74 | srtpProtectionProfiles: c.config.SRTPProtectionProfiles, |
| 75 | srtpMasterKeyIdentifier: c.config.Bugs.SRTPMasterKeyIdentifer, |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 76 | } |
| 77 | |
David Benjamin | 98e882e | 2014-08-08 13:24:34 -0400 | [diff] [blame] | 78 | if c.config.Bugs.SendClientVersion != 0 { |
| 79 | hello.vers = c.config.Bugs.SendClientVersion |
| 80 | } |
| 81 | |
Adam Langley | 7571292 | 2014-10-10 16:23:43 -0700 | [diff] [blame] | 82 | if c.config.Bugs.NoExtendedMasterSecret { |
| 83 | hello.extendedMasterSecret = false |
| 84 | } |
| 85 | |
David Benjamin | 55a4364 | 2015-04-20 14:45:55 -0400 | [diff] [blame] | 86 | if c.config.Bugs.NoSupportedCurves { |
| 87 | hello.supportedCurves = nil |
| 88 | } |
| 89 | |
Adam Langley | 2ae77d2 | 2014-10-28 17:29:33 -0700 | [diff] [blame] | 90 | if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo { |
| 91 | if c.config.Bugs.BadRenegotiationInfo { |
| 92 | hello.secureRenegotiation = append(hello.secureRenegotiation, c.clientVerify...) |
| 93 | hello.secureRenegotiation[0] ^= 0x80 |
| 94 | } else { |
| 95 | hello.secureRenegotiation = c.clientVerify |
| 96 | } |
| 97 | } |
| 98 | |
David Benjamin | ca6554b | 2014-11-08 12:31:52 -0500 | [diff] [blame] | 99 | if c.config.Bugs.NoRenegotiationInfo { |
| 100 | hello.secureRenegotiation = nil |
| 101 | } |
| 102 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 103 | possibleCipherSuites := c.config.cipherSuites() |
| 104 | hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites)) |
| 105 | |
| 106 | NextCipherSuite: |
| 107 | for _, suiteId := range possibleCipherSuites { |
| 108 | for _, suite := range cipherSuites { |
| 109 | if suite.id != suiteId { |
| 110 | continue |
| 111 | } |
| 112 | // Don't advertise TLS 1.2-only cipher suites unless |
| 113 | // we're attempting TLS 1.2. |
| 114 | if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 { |
| 115 | continue |
| 116 | } |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 117 | // Don't advertise non-DTLS cipher suites on DTLS. |
| 118 | if c.isDTLS && suite.flags&suiteNoDTLS != 0 { |
| 119 | continue |
| 120 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 121 | hello.cipherSuites = append(hello.cipherSuites, suiteId) |
| 122 | continue NextCipherSuite |
| 123 | } |
| 124 | } |
| 125 | |
David Benjamin | bef270a | 2014-08-02 04:22:02 -0400 | [diff] [blame] | 126 | if c.config.Bugs.SendFallbackSCSV { |
| 127 | hello.cipherSuites = append(hello.cipherSuites, fallbackSCSV) |
| 128 | } |
| 129 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 130 | _, err := io.ReadFull(c.config.rand(), hello.random) |
| 131 | if err != nil { |
| 132 | c.sendAlert(alertInternalError) |
| 133 | return errors.New("tls: short read from Rand: " + err.Error()) |
| 134 | } |
| 135 | |
David Benjamin | 44d3eed | 2015-05-21 01:29:55 -0400 | [diff] [blame^] | 136 | if hello.vers >= VersionTLS12 && !c.config.Bugs.NoSignatureAndHashes { |
David Benjamin | 000800a | 2014-11-14 01:43:59 -0500 | [diff] [blame] | 137 | hello.signatureAndHashes = c.config.signatureAndHashesForClient() |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 138 | } |
| 139 | |
| 140 | var session *ClientSessionState |
| 141 | var cacheKey string |
| 142 | sessionCache := c.config.ClientSessionCache |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 143 | |
| 144 | if sessionCache != nil { |
David Benjamin | fe8eb9a | 2014-11-17 03:19:02 -0500 | [diff] [blame] | 145 | hello.ticketSupported = !c.config.SessionTicketsDisabled |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 146 | |
| 147 | // Try to resume a previously negotiated TLS session, if |
| 148 | // available. |
| 149 | cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config) |
| 150 | candidateSession, ok := sessionCache.Get(cacheKey) |
| 151 | if ok { |
David Benjamin | fe8eb9a | 2014-11-17 03:19:02 -0500 | [diff] [blame] | 152 | ticketOk := !c.config.SessionTicketsDisabled || candidateSession.sessionTicket == nil |
| 153 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 154 | // Check that the ciphersuite/version used for the |
| 155 | // previous session are still valid. |
| 156 | cipherSuiteOk := false |
| 157 | for _, id := range hello.cipherSuites { |
| 158 | if id == candidateSession.cipherSuite { |
| 159 | cipherSuiteOk = true |
| 160 | break |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | versOk := candidateSession.vers >= c.config.minVersion() && |
| 165 | candidateSession.vers <= c.config.maxVersion() |
David Benjamin | fe8eb9a | 2014-11-17 03:19:02 -0500 | [diff] [blame] | 166 | if ticketOk && versOk && cipherSuiteOk { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 167 | session = candidateSession |
| 168 | } |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | if session != nil { |
David Benjamin | fe8eb9a | 2014-11-17 03:19:02 -0500 | [diff] [blame] | 173 | if session.sessionTicket != nil { |
| 174 | hello.sessionTicket = session.sessionTicket |
| 175 | if c.config.Bugs.CorruptTicket { |
| 176 | hello.sessionTicket = make([]byte, len(session.sessionTicket)) |
| 177 | copy(hello.sessionTicket, session.sessionTicket) |
| 178 | if len(hello.sessionTicket) > 0 { |
| 179 | offset := 40 |
| 180 | if offset > len(hello.sessionTicket) { |
| 181 | offset = len(hello.sessionTicket) - 1 |
| 182 | } |
| 183 | hello.sessionTicket[offset] ^= 0x40 |
Adam Langley | 3831173 | 2014-10-16 19:04:35 -0700 | [diff] [blame] | 184 | } |
Adam Langley | 3831173 | 2014-10-16 19:04:35 -0700 | [diff] [blame] | 185 | } |
David Benjamin | fe8eb9a | 2014-11-17 03:19:02 -0500 | [diff] [blame] | 186 | // A random session ID is used to detect when the |
| 187 | // server accepted the ticket and is resuming a session |
| 188 | // (see RFC 5077). |
| 189 | sessionIdLen := 16 |
| 190 | if c.config.Bugs.OversizedSessionId { |
| 191 | sessionIdLen = 33 |
| 192 | } |
| 193 | hello.sessionId = make([]byte, sessionIdLen) |
| 194 | if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil { |
| 195 | c.sendAlert(alertInternalError) |
| 196 | return errors.New("tls: short read from Rand: " + err.Error()) |
| 197 | } |
| 198 | } else { |
| 199 | hello.sessionId = session.sessionId |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 200 | } |
| 201 | } |
| 202 | |
David Benjamin | d86c767 | 2014-08-02 04:07:12 -0400 | [diff] [blame] | 203 | var helloBytes []byte |
| 204 | if c.config.Bugs.SendV2ClientHello { |
David Benjamin | 94d701b | 2014-11-30 13:54:41 -0500 | [diff] [blame] | 205 | // Test that the peer left-pads random. |
| 206 | hello.random[0] = 0 |
David Benjamin | d86c767 | 2014-08-02 04:07:12 -0400 | [diff] [blame] | 207 | v2Hello := &v2ClientHelloMsg{ |
| 208 | vers: hello.vers, |
| 209 | cipherSuites: hello.cipherSuites, |
| 210 | // No session resumption for V2ClientHello. |
| 211 | sessionId: nil, |
David Benjamin | 94d701b | 2014-11-30 13:54:41 -0500 | [diff] [blame] | 212 | challenge: hello.random[1:], |
David Benjamin | d86c767 | 2014-08-02 04:07:12 -0400 | [diff] [blame] | 213 | } |
| 214 | helloBytes = v2Hello.marshal() |
| 215 | c.writeV2Record(helloBytes) |
| 216 | } else { |
| 217 | helloBytes = hello.marshal() |
| 218 | c.writeRecord(recordTypeHandshake, helloBytes) |
| 219 | } |
David Benjamin | a4e6d48 | 2015-03-02 19:10:53 -0500 | [diff] [blame] | 220 | c.dtlsFlushHandshake() |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 221 | |
David Benjamin | 83f9040 | 2015-01-27 01:09:43 -0500 | [diff] [blame] | 222 | if err := c.simulatePacketLoss(nil); err != nil { |
| 223 | return err |
| 224 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 225 | msg, err := c.readHandshake() |
| 226 | if err != nil { |
| 227 | return err |
| 228 | } |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 229 | |
| 230 | if c.isDTLS { |
| 231 | helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg) |
| 232 | if ok { |
David Benjamin | 8bc38f5 | 2014-08-16 12:07:27 -0400 | [diff] [blame] | 233 | if helloVerifyRequest.vers != VersionTLS10 { |
| 234 | // Per RFC 6347, the version field in |
| 235 | // HelloVerifyRequest SHOULD be always DTLS |
| 236 | // 1.0. Enforce this for testing purposes. |
| 237 | return errors.New("dtls: bad HelloVerifyRequest version") |
| 238 | } |
| 239 | |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 240 | hello.raw = nil |
| 241 | hello.cookie = helloVerifyRequest.cookie |
| 242 | helloBytes = hello.marshal() |
| 243 | c.writeRecord(recordTypeHandshake, helloBytes) |
David Benjamin | a4e6d48 | 2015-03-02 19:10:53 -0500 | [diff] [blame] | 244 | c.dtlsFlushHandshake() |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 245 | |
David Benjamin | 83f9040 | 2015-01-27 01:09:43 -0500 | [diff] [blame] | 246 | if err := c.simulatePacketLoss(nil); err != nil { |
| 247 | return err |
| 248 | } |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 249 | msg, err = c.readHandshake() |
| 250 | if err != nil { |
| 251 | return err |
| 252 | } |
| 253 | } |
| 254 | } |
| 255 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 256 | serverHello, ok := msg.(*serverHelloMsg) |
| 257 | if !ok { |
| 258 | c.sendAlert(alertUnexpectedMessage) |
| 259 | return unexpectedMessageError(serverHello, msg) |
| 260 | } |
| 261 | |
David Benjamin | 76d8abe | 2014-08-14 16:25:34 -0400 | [diff] [blame] | 262 | c.vers, ok = c.config.mutualVersion(serverHello.vers) |
| 263 | if !ok { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 264 | c.sendAlert(alertProtocolVersion) |
| 265 | return fmt.Errorf("tls: server selected unsupported protocol version %x", serverHello.vers) |
| 266 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 267 | c.haveVers = true |
| 268 | |
| 269 | suite := mutualCipherSuite(c.config.cipherSuites(), serverHello.cipherSuite) |
| 270 | if suite == nil { |
| 271 | c.sendAlert(alertHandshakeFailure) |
| 272 | return fmt.Errorf("tls: server selected an unsupported cipher suite") |
| 273 | } |
| 274 | |
David Benjamin | ca6554b | 2014-11-08 12:31:52 -0500 | [diff] [blame] | 275 | if len(c.clientVerify) > 0 && !c.config.Bugs.NoRenegotiationInfo { |
Adam Langley | 2ae77d2 | 2014-10-28 17:29:33 -0700 | [diff] [blame] | 276 | var expectedRenegInfo []byte |
| 277 | expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...) |
| 278 | expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...) |
| 279 | if !bytes.Equal(serverHello.secureRenegotiation, expectedRenegInfo) { |
| 280 | c.sendAlert(alertHandshakeFailure) |
| 281 | return fmt.Errorf("tls: renegotiation mismatch") |
| 282 | } |
| 283 | } |
| 284 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 285 | hs := &clientHandshakeState{ |
| 286 | c: c, |
| 287 | serverHello: serverHello, |
| 288 | hello: hello, |
| 289 | suite: suite, |
| 290 | finishedHash: newFinishedHash(c.vers, suite), |
| 291 | session: session, |
| 292 | } |
| 293 | |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 294 | hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1) |
| 295 | hs.writeServerHash(hs.serverHello.marshal()) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 296 | |
David Benjamin | f3ec83d | 2014-07-21 22:42:34 -0400 | [diff] [blame] | 297 | if c.config.Bugs.EarlyChangeCipherSpec > 0 { |
| 298 | hs.establishKeys() |
| 299 | c.writeRecord(recordTypeChangeCipherSpec, []byte{1}) |
| 300 | } |
| 301 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 302 | isResume, err := hs.processServerHello() |
| 303 | if err != nil { |
| 304 | return err |
| 305 | } |
| 306 | |
| 307 | if isResume { |
David Benjamin | f3ec83d | 2014-07-21 22:42:34 -0400 | [diff] [blame] | 308 | if c.config.Bugs.EarlyChangeCipherSpec == 0 { |
| 309 | if err := hs.establishKeys(); err != nil { |
| 310 | return err |
| 311 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 312 | } |
| 313 | if err := hs.readSessionTicket(); err != nil { |
| 314 | return err |
| 315 | } |
| 316 | if err := hs.readFinished(); err != nil { |
| 317 | return err |
| 318 | } |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame] | 319 | if err := hs.sendFinished(isResume); err != nil { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 320 | return err |
| 321 | } |
| 322 | } else { |
| 323 | if err := hs.doFullHandshake(); err != nil { |
| 324 | return err |
| 325 | } |
| 326 | if err := hs.establishKeys(); err != nil { |
| 327 | return err |
| 328 | } |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame] | 329 | if err := hs.sendFinished(isResume); err != nil { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 330 | return err |
| 331 | } |
David Benjamin | 83f9040 | 2015-01-27 01:09:43 -0500 | [diff] [blame] | 332 | // Most retransmits are triggered by a timeout, but the final |
| 333 | // leg of the handshake is retransmited upon re-receiving a |
| 334 | // Finished. |
David Benjamin | b3774b9 | 2015-01-31 17:16:01 -0500 | [diff] [blame] | 335 | if err := c.simulatePacketLoss(func() { |
| 336 | c.writeRecord(recordTypeHandshake, hs.finishedBytes) |
David Benjamin | a4e6d48 | 2015-03-02 19:10:53 -0500 | [diff] [blame] | 337 | c.dtlsFlushHandshake() |
David Benjamin | b3774b9 | 2015-01-31 17:16:01 -0500 | [diff] [blame] | 338 | }); err != nil { |
David Benjamin | 83f9040 | 2015-01-27 01:09:43 -0500 | [diff] [blame] | 339 | return err |
| 340 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 341 | if err := hs.readSessionTicket(); err != nil { |
| 342 | return err |
| 343 | } |
| 344 | if err := hs.readFinished(); err != nil { |
| 345 | return err |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | if sessionCache != nil && hs.session != nil && session != hs.session { |
| 350 | sessionCache.Put(cacheKey, hs.session) |
| 351 | } |
| 352 | |
| 353 | c.didResume = isResume |
| 354 | c.handshakeComplete = true |
David Benjamin | c565ebb | 2015-04-03 04:06:36 -0400 | [diff] [blame] | 355 | c.cipherSuite = suite |
| 356 | copy(c.clientRandom[:], hs.hello.random) |
| 357 | copy(c.serverRandom[:], hs.serverHello.random) |
| 358 | copy(c.masterSecret[:], hs.masterSecret) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 359 | return nil |
| 360 | } |
| 361 | |
| 362 | func (hs *clientHandshakeState) doFullHandshake() error { |
| 363 | c := hs.c |
| 364 | |
David Benjamin | 48cae08 | 2014-10-27 01:06:24 -0400 | [diff] [blame] | 365 | var leaf *x509.Certificate |
| 366 | if hs.suite.flags&suitePSK == 0 { |
| 367 | msg, err := c.readHandshake() |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 368 | if err != nil { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 369 | return err |
| 370 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 371 | |
David Benjamin | 48cae08 | 2014-10-27 01:06:24 -0400 | [diff] [blame] | 372 | certMsg, ok := msg.(*certificateMsg) |
| 373 | if !ok || len(certMsg.certificates) == 0 { |
| 374 | c.sendAlert(alertUnexpectedMessage) |
| 375 | return unexpectedMessageError(certMsg, msg) |
| 376 | } |
| 377 | hs.writeServerHash(certMsg.marshal()) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 378 | |
David Benjamin | 48cae08 | 2014-10-27 01:06:24 -0400 | [diff] [blame] | 379 | certs := make([]*x509.Certificate, len(certMsg.certificates)) |
| 380 | for i, asn1Data := range certMsg.certificates { |
| 381 | cert, err := x509.ParseCertificate(asn1Data) |
| 382 | if err != nil { |
| 383 | c.sendAlert(alertBadCertificate) |
| 384 | return errors.New("tls: failed to parse certificate from server: " + err.Error()) |
| 385 | } |
| 386 | certs[i] = cert |
| 387 | } |
| 388 | leaf = certs[0] |
| 389 | |
| 390 | if !c.config.InsecureSkipVerify { |
| 391 | opts := x509.VerifyOptions{ |
| 392 | Roots: c.config.RootCAs, |
| 393 | CurrentTime: c.config.time(), |
| 394 | DNSName: c.config.ServerName, |
| 395 | Intermediates: x509.NewCertPool(), |
| 396 | } |
| 397 | |
| 398 | for i, cert := range certs { |
| 399 | if i == 0 { |
| 400 | continue |
| 401 | } |
| 402 | opts.Intermediates.AddCert(cert) |
| 403 | } |
| 404 | c.verifiedChains, err = leaf.Verify(opts) |
| 405 | if err != nil { |
| 406 | c.sendAlert(alertBadCertificate) |
| 407 | return err |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | switch leaf.PublicKey.(type) { |
| 412 | case *rsa.PublicKey, *ecdsa.PublicKey: |
| 413 | break |
| 414 | default: |
| 415 | c.sendAlert(alertUnsupportedCertificate) |
| 416 | return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", leaf.PublicKey) |
| 417 | } |
| 418 | |
| 419 | c.peerCertificates = certs |
| 420 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 421 | |
| 422 | if hs.serverHello.ocspStapling { |
David Benjamin | 48cae08 | 2014-10-27 01:06:24 -0400 | [diff] [blame] | 423 | msg, err := c.readHandshake() |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 424 | if err != nil { |
| 425 | return err |
| 426 | } |
| 427 | cs, ok := msg.(*certificateStatusMsg) |
| 428 | if !ok { |
| 429 | c.sendAlert(alertUnexpectedMessage) |
| 430 | return unexpectedMessageError(cs, msg) |
| 431 | } |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 432 | hs.writeServerHash(cs.marshal()) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 433 | |
| 434 | if cs.statusType == statusTypeOCSP { |
| 435 | c.ocspResponse = cs.response |
| 436 | } |
| 437 | } |
| 438 | |
David Benjamin | 48cae08 | 2014-10-27 01:06:24 -0400 | [diff] [blame] | 439 | msg, err := c.readHandshake() |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 440 | if err != nil { |
| 441 | return err |
| 442 | } |
| 443 | |
| 444 | keyAgreement := hs.suite.ka(c.vers) |
| 445 | |
| 446 | skx, ok := msg.(*serverKeyExchangeMsg) |
| 447 | if ok { |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 448 | hs.writeServerHash(skx.marshal()) |
David Benjamin | 48cae08 | 2014-10-27 01:06:24 -0400 | [diff] [blame] | 449 | err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 450 | if err != nil { |
| 451 | c.sendAlert(alertUnexpectedMessage) |
| 452 | return err |
| 453 | } |
| 454 | |
| 455 | msg, err = c.readHandshake() |
| 456 | if err != nil { |
| 457 | return err |
| 458 | } |
| 459 | } |
| 460 | |
| 461 | var chainToSend *Certificate |
| 462 | var certRequested bool |
| 463 | certReq, ok := msg.(*certificateRequestMsg) |
| 464 | if ok { |
| 465 | certRequested = true |
| 466 | |
| 467 | // RFC 4346 on the certificateAuthorities field: |
| 468 | // A list of the distinguished names of acceptable certificate |
| 469 | // authorities. These distinguished names may specify a desired |
| 470 | // distinguished name for a root CA or for a subordinate CA; |
| 471 | // thus, this message can be used to describe both known roots |
| 472 | // and a desired authorization space. If the |
| 473 | // certificate_authorities list is empty then the client MAY |
| 474 | // send any certificate of the appropriate |
| 475 | // ClientCertificateType, unless there is some external |
| 476 | // arrangement to the contrary. |
| 477 | |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 478 | hs.writeServerHash(certReq.marshal()) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 479 | |
| 480 | var rsaAvail, ecdsaAvail bool |
| 481 | for _, certType := range certReq.certificateTypes { |
| 482 | switch certType { |
David Benjamin | 7b03051 | 2014-07-08 17:30:11 -0400 | [diff] [blame] | 483 | case CertTypeRSASign: |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 484 | rsaAvail = true |
David Benjamin | 7b03051 | 2014-07-08 17:30:11 -0400 | [diff] [blame] | 485 | case CertTypeECDSASign: |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 486 | ecdsaAvail = true |
| 487 | } |
| 488 | } |
| 489 | |
| 490 | // We need to search our list of client certs for one |
| 491 | // where SignatureAlgorithm is RSA and the Issuer is in |
| 492 | // certReq.certificateAuthorities |
| 493 | findCert: |
| 494 | for i, chain := range c.config.Certificates { |
| 495 | if !rsaAvail && !ecdsaAvail { |
| 496 | continue |
| 497 | } |
| 498 | |
| 499 | for j, cert := range chain.Certificate { |
| 500 | x509Cert := chain.Leaf |
| 501 | // parse the certificate if this isn't the leaf |
| 502 | // node, or if chain.Leaf was nil |
| 503 | if j != 0 || x509Cert == nil { |
| 504 | if x509Cert, err = x509.ParseCertificate(cert); err != nil { |
| 505 | c.sendAlert(alertInternalError) |
| 506 | return errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error()) |
| 507 | } |
| 508 | } |
| 509 | |
| 510 | switch { |
| 511 | case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA: |
| 512 | case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA: |
| 513 | default: |
| 514 | continue findCert |
| 515 | } |
| 516 | |
| 517 | if len(certReq.certificateAuthorities) == 0 { |
| 518 | // they gave us an empty list, so just take the |
| 519 | // first RSA cert from c.config.Certificates |
| 520 | chainToSend = &chain |
| 521 | break findCert |
| 522 | } |
| 523 | |
| 524 | for _, ca := range certReq.certificateAuthorities { |
| 525 | if bytes.Equal(x509Cert.RawIssuer, ca) { |
| 526 | chainToSend = &chain |
| 527 | break findCert |
| 528 | } |
| 529 | } |
| 530 | } |
| 531 | } |
| 532 | |
| 533 | msg, err = c.readHandshake() |
| 534 | if err != nil { |
| 535 | return err |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | shd, ok := msg.(*serverHelloDoneMsg) |
| 540 | if !ok { |
| 541 | c.sendAlert(alertUnexpectedMessage) |
| 542 | return unexpectedMessageError(shd, msg) |
| 543 | } |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 544 | hs.writeServerHash(shd.marshal()) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 545 | |
| 546 | // If the server requested a certificate then we have to send a |
| 547 | // Certificate message, even if it's empty because we don't have a |
| 548 | // certificate to send. |
| 549 | if certRequested { |
David Benjamin | 48cae08 | 2014-10-27 01:06:24 -0400 | [diff] [blame] | 550 | certMsg := new(certificateMsg) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 551 | if chainToSend != nil { |
| 552 | certMsg.certificates = chainToSend.Certificate |
| 553 | } |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 554 | hs.writeClientHash(certMsg.marshal()) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 555 | c.writeRecord(recordTypeHandshake, certMsg.marshal()) |
| 556 | } |
| 557 | |
David Benjamin | 48cae08 | 2014-10-27 01:06:24 -0400 | [diff] [blame] | 558 | preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 559 | if err != nil { |
| 560 | c.sendAlert(alertInternalError) |
| 561 | return err |
| 562 | } |
| 563 | if ckx != nil { |
David Benjamin | f3ec83d | 2014-07-21 22:42:34 -0400 | [diff] [blame] | 564 | if c.config.Bugs.EarlyChangeCipherSpec < 2 { |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 565 | hs.writeClientHash(ckx.marshal()) |
David Benjamin | f3ec83d | 2014-07-21 22:42:34 -0400 | [diff] [blame] | 566 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 567 | c.writeRecord(recordTypeHandshake, ckx.marshal()) |
| 568 | } |
| 569 | |
Adam Langley | 7571292 | 2014-10-10 16:23:43 -0700 | [diff] [blame] | 570 | if hs.serverHello.extendedMasterSecret && c.vers >= VersionTLS10 { |
| 571 | hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash) |
| 572 | c.extendedMasterSecret = true |
| 573 | } else { |
| 574 | if c.config.Bugs.RequireExtendedMasterSecret { |
| 575 | return errors.New("tls: extended master secret required but not supported by peer") |
| 576 | } |
| 577 | hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random) |
| 578 | } |
David Benjamin | e098ec2 | 2014-08-27 23:13:20 -0400 | [diff] [blame] | 579 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 580 | if chainToSend != nil { |
| 581 | var signed []byte |
| 582 | certVerify := &certificateVerifyMsg{ |
| 583 | hasSignatureAndHash: c.vers >= VersionTLS12, |
| 584 | } |
| 585 | |
David Benjamin | 72dc783 | 2015-03-16 17:49:43 -0400 | [diff] [blame] | 586 | // Determine the hash to sign. |
| 587 | var signatureType uint8 |
| 588 | switch c.config.Certificates[0].PrivateKey.(type) { |
| 589 | case *ecdsa.PrivateKey: |
| 590 | signatureType = signatureECDSA |
| 591 | case *rsa.PrivateKey: |
| 592 | signatureType = signatureRSA |
| 593 | default: |
| 594 | c.sendAlert(alertInternalError) |
| 595 | return errors.New("unknown private key type") |
| 596 | } |
| 597 | if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences { |
| 598 | certReq.signatureAndHashes = c.config.signatureAndHashesForClient() |
| 599 | } |
| 600 | certVerify.signatureAndHash, err = hs.finishedHash.selectClientCertSignatureAlgorithm(certReq.signatureAndHashes, c.config.signatureAndHashesForClient(), signatureType) |
| 601 | if err != nil { |
| 602 | c.sendAlert(alertInternalError) |
| 603 | return err |
| 604 | } |
| 605 | digest, hashFunc, err := hs.finishedHash.hashForClientCertificate(certVerify.signatureAndHash, hs.masterSecret) |
| 606 | if err != nil { |
| 607 | c.sendAlert(alertInternalError) |
| 608 | return err |
| 609 | } |
| 610 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 611 | switch key := c.config.Certificates[0].PrivateKey.(type) { |
| 612 | case *ecdsa.PrivateKey: |
David Benjamin | de620d9 | 2014-07-18 15:03:41 -0400 | [diff] [blame] | 613 | var r, s *big.Int |
| 614 | r, s, err = ecdsa.Sign(c.config.rand(), key, digest) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 615 | if err == nil { |
| 616 | signed, err = asn1.Marshal(ecdsaSignature{r, s}) |
| 617 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 618 | case *rsa.PrivateKey: |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 619 | signed, err = rsa.SignPKCS1v15(c.config.rand(), key, hashFunc, digest) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 620 | default: |
| 621 | err = errors.New("unknown private key type") |
| 622 | } |
| 623 | if err != nil { |
| 624 | c.sendAlert(alertInternalError) |
| 625 | return errors.New("tls: failed to sign handshake with client certificate: " + err.Error()) |
| 626 | } |
| 627 | certVerify.signature = signed |
| 628 | |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 629 | hs.writeClientHash(certVerify.marshal()) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 630 | c.writeRecord(recordTypeHandshake, certVerify.marshal()) |
| 631 | } |
David Benjamin | a4e6d48 | 2015-03-02 19:10:53 -0500 | [diff] [blame] | 632 | c.dtlsFlushHandshake() |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 633 | |
David Benjamin | e098ec2 | 2014-08-27 23:13:20 -0400 | [diff] [blame] | 634 | hs.finishedHash.discardHandshakeBuffer() |
| 635 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 636 | return nil |
| 637 | } |
| 638 | |
| 639 | func (hs *clientHandshakeState) establishKeys() error { |
| 640 | c := hs.c |
| 641 | |
| 642 | clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV := |
| 643 | keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen) |
| 644 | var clientCipher, serverCipher interface{} |
| 645 | var clientHash, serverHash macFunction |
| 646 | if hs.suite.cipher != nil { |
| 647 | clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */) |
| 648 | clientHash = hs.suite.mac(c.vers, clientMAC) |
| 649 | serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */) |
| 650 | serverHash = hs.suite.mac(c.vers, serverMAC) |
| 651 | } else { |
| 652 | clientCipher = hs.suite.aead(clientKey, clientIV) |
| 653 | serverCipher = hs.suite.aead(serverKey, serverIV) |
| 654 | } |
| 655 | |
| 656 | c.in.prepareCipherSpec(c.vers, serverCipher, serverHash) |
| 657 | c.out.prepareCipherSpec(c.vers, clientCipher, clientHash) |
| 658 | return nil |
| 659 | } |
| 660 | |
| 661 | func (hs *clientHandshakeState) serverResumedSession() bool { |
| 662 | // If the server responded with the same sessionId then it means the |
| 663 | // sessionTicket is being used to resume a TLS session. |
| 664 | return hs.session != nil && hs.hello.sessionId != nil && |
| 665 | bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId) |
| 666 | } |
| 667 | |
| 668 | func (hs *clientHandshakeState) processServerHello() (bool, error) { |
| 669 | c := hs.c |
| 670 | |
| 671 | if hs.serverHello.compressionMethod != compressionNone { |
| 672 | c.sendAlert(alertUnexpectedMessage) |
| 673 | return false, errors.New("tls: server selected unsupported compression format") |
| 674 | } |
| 675 | |
David Benjamin | fa055a2 | 2014-09-15 16:51:51 -0400 | [diff] [blame] | 676 | clientDidNPN := hs.hello.nextProtoNeg |
| 677 | clientDidALPN := len(hs.hello.alpnProtocols) > 0 |
| 678 | serverHasNPN := hs.serverHello.nextProtoNeg |
| 679 | serverHasALPN := len(hs.serverHello.alpnProtocol) > 0 |
| 680 | |
| 681 | if !clientDidNPN && serverHasNPN { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 682 | c.sendAlert(alertHandshakeFailure) |
| 683 | return false, errors.New("server advertised unrequested NPN extension") |
| 684 | } |
| 685 | |
David Benjamin | fa055a2 | 2014-09-15 16:51:51 -0400 | [diff] [blame] | 686 | if !clientDidALPN && serverHasALPN { |
| 687 | c.sendAlert(alertHandshakeFailure) |
| 688 | return false, errors.New("server advertised unrequested ALPN extension") |
| 689 | } |
| 690 | |
| 691 | if serverHasNPN && serverHasALPN { |
| 692 | c.sendAlert(alertHandshakeFailure) |
| 693 | return false, errors.New("server advertised both NPN and ALPN extensions") |
| 694 | } |
| 695 | |
| 696 | if serverHasALPN { |
| 697 | c.clientProtocol = hs.serverHello.alpnProtocol |
| 698 | c.clientProtocolFallback = false |
David Benjamin | fc7b086 | 2014-09-06 13:21:53 -0400 | [diff] [blame] | 699 | c.usedALPN = true |
David Benjamin | fa055a2 | 2014-09-15 16:51:51 -0400 | [diff] [blame] | 700 | } |
| 701 | |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame] | 702 | if !hs.hello.channelIDSupported && hs.serverHello.channelIDRequested { |
| 703 | c.sendAlert(alertHandshakeFailure) |
| 704 | return false, errors.New("server advertised unrequested Channel ID extension") |
| 705 | } |
| 706 | |
David Benjamin | ca6c826 | 2014-11-15 19:06:08 -0500 | [diff] [blame] | 707 | if hs.serverHello.srtpProtectionProfile != 0 { |
| 708 | if hs.serverHello.srtpMasterKeyIdentifier != "" { |
| 709 | return false, errors.New("tls: server selected SRTP MKI value") |
| 710 | } |
| 711 | |
| 712 | found := false |
| 713 | for _, p := range c.config.SRTPProtectionProfiles { |
| 714 | if p == hs.serverHello.srtpProtectionProfile { |
| 715 | found = true |
| 716 | break |
| 717 | } |
| 718 | } |
| 719 | if !found { |
| 720 | return false, errors.New("tls: server advertised unsupported SRTP profile") |
| 721 | } |
| 722 | |
| 723 | c.srtpProtectionProfile = hs.serverHello.srtpProtectionProfile |
| 724 | } |
| 725 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 726 | if hs.serverResumedSession() { |
David Benjamin | 4b27d9f | 2015-05-12 22:42:52 -0400 | [diff] [blame] | 727 | // For test purposes, assert that the server never accepts the |
| 728 | // resumption offer on renegotiation. |
| 729 | if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego { |
| 730 | return false, errors.New("tls: server resumed session on renegotiation") |
| 731 | } |
| 732 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 733 | // Restore masterSecret and peerCerts from previous state |
| 734 | hs.masterSecret = hs.session.masterSecret |
| 735 | c.peerCertificates = hs.session.serverCertificates |
Adam Langley | 7571292 | 2014-10-10 16:23:43 -0700 | [diff] [blame] | 736 | c.extendedMasterSecret = hs.session.extendedMasterSecret |
David Benjamin | e098ec2 | 2014-08-27 23:13:20 -0400 | [diff] [blame] | 737 | hs.finishedHash.discardHandshakeBuffer() |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 738 | return true, nil |
| 739 | } |
| 740 | return false, nil |
| 741 | } |
| 742 | |
| 743 | func (hs *clientHandshakeState) readFinished() error { |
| 744 | c := hs.c |
| 745 | |
| 746 | c.readRecord(recordTypeChangeCipherSpec) |
| 747 | if err := c.in.error(); err != nil { |
| 748 | return err |
| 749 | } |
| 750 | |
| 751 | msg, err := c.readHandshake() |
| 752 | if err != nil { |
| 753 | return err |
| 754 | } |
| 755 | serverFinished, ok := msg.(*finishedMsg) |
| 756 | if !ok { |
| 757 | c.sendAlert(alertUnexpectedMessage) |
| 758 | return unexpectedMessageError(serverFinished, msg) |
| 759 | } |
| 760 | |
David Benjamin | f3ec83d | 2014-07-21 22:42:34 -0400 | [diff] [blame] | 761 | if c.config.Bugs.EarlyChangeCipherSpec == 0 { |
| 762 | verify := hs.finishedHash.serverSum(hs.masterSecret) |
| 763 | if len(verify) != len(serverFinished.verifyData) || |
| 764 | subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 { |
| 765 | c.sendAlert(alertHandshakeFailure) |
| 766 | return errors.New("tls: server's Finished message was incorrect") |
| 767 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 768 | } |
Adam Langley | 2ae77d2 | 2014-10-28 17:29:33 -0700 | [diff] [blame] | 769 | c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...) |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 770 | hs.writeServerHash(serverFinished.marshal()) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 771 | return nil |
| 772 | } |
| 773 | |
| 774 | func (hs *clientHandshakeState) readSessionTicket() error { |
David Benjamin | fe8eb9a | 2014-11-17 03:19:02 -0500 | [diff] [blame] | 775 | c := hs.c |
| 776 | |
| 777 | // Create a session with no server identifier. Either a |
| 778 | // session ID or session ticket will be attached. |
| 779 | session := &ClientSessionState{ |
| 780 | vers: c.vers, |
| 781 | cipherSuite: hs.suite.id, |
| 782 | masterSecret: hs.masterSecret, |
| 783 | handshakeHash: hs.finishedHash.server.Sum(nil), |
| 784 | serverCertificates: c.peerCertificates, |
| 785 | } |
| 786 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 787 | if !hs.serverHello.ticketSupported { |
David Benjamin | fe8eb9a | 2014-11-17 03:19:02 -0500 | [diff] [blame] | 788 | if hs.session == nil && len(hs.serverHello.sessionId) > 0 { |
| 789 | session.sessionId = hs.serverHello.sessionId |
| 790 | hs.session = session |
| 791 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 792 | return nil |
| 793 | } |
| 794 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 795 | msg, err := c.readHandshake() |
| 796 | if err != nil { |
| 797 | return err |
| 798 | } |
| 799 | sessionTicketMsg, ok := msg.(*newSessionTicketMsg) |
| 800 | if !ok { |
| 801 | c.sendAlert(alertUnexpectedMessage) |
| 802 | return unexpectedMessageError(sessionTicketMsg, msg) |
| 803 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 804 | |
David Benjamin | fe8eb9a | 2014-11-17 03:19:02 -0500 | [diff] [blame] | 805 | session.sessionTicket = sessionTicketMsg.ticket |
| 806 | hs.session = session |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 807 | |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame] | 808 | hs.writeServerHash(sessionTicketMsg.marshal()) |
| 809 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 810 | return nil |
| 811 | } |
| 812 | |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame] | 813 | func (hs *clientHandshakeState) sendFinished(isResume bool) error { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 814 | c := hs.c |
| 815 | |
David Benjamin | 86271ee | 2014-07-21 16:14:03 -0400 | [diff] [blame] | 816 | var postCCSBytes []byte |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 817 | seqno := hs.c.sendHandshakeSeq |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 818 | if hs.serverHello.nextProtoNeg { |
| 819 | nextProto := new(nextProtoMsg) |
| 820 | proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.nextProtos) |
| 821 | nextProto.proto = proto |
| 822 | c.clientProtocol = proto |
| 823 | c.clientProtocolFallback = fallback |
| 824 | |
David Benjamin | 86271ee | 2014-07-21 16:14:03 -0400 | [diff] [blame] | 825 | nextProtoBytes := nextProto.marshal() |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 826 | hs.writeHash(nextProtoBytes, seqno) |
| 827 | seqno++ |
David Benjamin | 86271ee | 2014-07-21 16:14:03 -0400 | [diff] [blame] | 828 | postCCSBytes = append(postCCSBytes, nextProtoBytes...) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 829 | } |
| 830 | |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame] | 831 | if hs.serverHello.channelIDRequested { |
| 832 | encryptedExtensions := new(encryptedExtensionsMsg) |
| 833 | if c.config.ChannelID.Curve != elliptic.P256() { |
| 834 | return fmt.Errorf("tls: Channel ID is not on P-256.") |
| 835 | } |
| 836 | var resumeHash []byte |
| 837 | if isResume { |
| 838 | resumeHash = hs.session.handshakeHash |
| 839 | } |
| 840 | r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, hs.finishedHash.hashForChannelID(resumeHash)) |
| 841 | if err != nil { |
| 842 | return err |
| 843 | } |
| 844 | channelID := make([]byte, 128) |
| 845 | writeIntPadded(channelID[0:32], c.config.ChannelID.X) |
| 846 | writeIntPadded(channelID[32:64], c.config.ChannelID.Y) |
| 847 | writeIntPadded(channelID[64:96], r) |
| 848 | writeIntPadded(channelID[96:128], s) |
| 849 | encryptedExtensions.channelID = channelID |
| 850 | |
| 851 | c.channelID = &c.config.ChannelID.PublicKey |
| 852 | |
| 853 | encryptedExtensionsBytes := encryptedExtensions.marshal() |
| 854 | hs.writeHash(encryptedExtensionsBytes, seqno) |
| 855 | seqno++ |
| 856 | postCCSBytes = append(postCCSBytes, encryptedExtensionsBytes...) |
| 857 | } |
| 858 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 859 | finished := new(finishedMsg) |
David Benjamin | f3ec83d | 2014-07-21 22:42:34 -0400 | [diff] [blame] | 860 | if c.config.Bugs.EarlyChangeCipherSpec == 2 { |
| 861 | finished.verifyData = hs.finishedHash.clientSum(nil) |
| 862 | } else { |
| 863 | finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret) |
| 864 | } |
David Benjamin | 513f0ea | 2015-04-02 19:33:31 -0400 | [diff] [blame] | 865 | if c.config.Bugs.BadFinished { |
| 866 | finished.verifyData[0]++ |
| 867 | } |
Adam Langley | 2ae77d2 | 2014-10-28 17:29:33 -0700 | [diff] [blame] | 868 | c.clientVerify = append(c.clientVerify[:0], finished.verifyData...) |
David Benjamin | 83f9040 | 2015-01-27 01:09:43 -0500 | [diff] [blame] | 869 | hs.finishedBytes = finished.marshal() |
| 870 | hs.writeHash(hs.finishedBytes, seqno) |
| 871 | postCCSBytes = append(postCCSBytes, hs.finishedBytes...) |
David Benjamin | 86271ee | 2014-07-21 16:14:03 -0400 | [diff] [blame] | 872 | |
| 873 | if c.config.Bugs.FragmentAcrossChangeCipherSpec { |
| 874 | c.writeRecord(recordTypeHandshake, postCCSBytes[:5]) |
| 875 | postCCSBytes = postCCSBytes[5:] |
| 876 | } |
David Benjamin | a4e6d48 | 2015-03-02 19:10:53 -0500 | [diff] [blame] | 877 | c.dtlsFlushHandshake() |
David Benjamin | 86271ee | 2014-07-21 16:14:03 -0400 | [diff] [blame] | 878 | |
| 879 | if !c.config.Bugs.SkipChangeCipherSpec && |
| 880 | c.config.Bugs.EarlyChangeCipherSpec == 0 { |
| 881 | c.writeRecord(recordTypeChangeCipherSpec, []byte{1}) |
| 882 | } |
| 883 | |
David Benjamin | 4189bd9 | 2015-01-25 23:52:39 -0500 | [diff] [blame] | 884 | if c.config.Bugs.AppDataAfterChangeCipherSpec != nil { |
| 885 | c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec) |
| 886 | } |
David Benjamin | dc3da93 | 2015-03-12 15:09:02 -0400 | [diff] [blame] | 887 | if c.config.Bugs.AlertAfterChangeCipherSpec != 0 { |
| 888 | c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec) |
| 889 | return errors.New("tls: simulating post-CCS alert") |
| 890 | } |
David Benjamin | 4189bd9 | 2015-01-25 23:52:39 -0500 | [diff] [blame] | 891 | |
David Benjamin | b80168e | 2015-02-08 18:30:14 -0500 | [diff] [blame] | 892 | if !c.config.Bugs.SkipFinished { |
| 893 | c.writeRecord(recordTypeHandshake, postCCSBytes) |
David Benjamin | a4e6d48 | 2015-03-02 19:10:53 -0500 | [diff] [blame] | 894 | c.dtlsFlushHandshake() |
David Benjamin | b3774b9 | 2015-01-31 17:16:01 -0500 | [diff] [blame] | 895 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 896 | return nil |
| 897 | } |
| 898 | |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 899 | func (hs *clientHandshakeState) writeClientHash(msg []byte) { |
| 900 | // writeClientHash is called before writeRecord. |
| 901 | hs.writeHash(msg, hs.c.sendHandshakeSeq) |
| 902 | } |
| 903 | |
| 904 | func (hs *clientHandshakeState) writeServerHash(msg []byte) { |
| 905 | // writeServerHash is called after readHandshake. |
| 906 | hs.writeHash(msg, hs.c.recvHandshakeSeq-1) |
| 907 | } |
| 908 | |
| 909 | func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) { |
| 910 | if hs.c.isDTLS { |
| 911 | // This is somewhat hacky. DTLS hashes a slightly different format. |
| 912 | // First, the TLS header. |
| 913 | hs.finishedHash.Write(msg[:4]) |
| 914 | // Then the sequence number and reassembled fragment offset (always 0). |
| 915 | hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0}) |
| 916 | // Then the reassembled fragment (always equal to the message length). |
| 917 | hs.finishedHash.Write(msg[1:4]) |
| 918 | // And then the message body. |
| 919 | hs.finishedHash.Write(msg[4:]) |
| 920 | } else { |
| 921 | hs.finishedHash.Write(msg) |
| 922 | } |
| 923 | } |
| 924 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 925 | // clientSessionCacheKey returns a key used to cache sessionTickets that could |
| 926 | // be used to resume previously negotiated TLS sessions with a server. |
| 927 | func clientSessionCacheKey(serverAddr net.Addr, config *Config) string { |
| 928 | if len(config.ServerName) > 0 { |
| 929 | return config.ServerName |
| 930 | } |
| 931 | return serverAddr.String() |
| 932 | } |
| 933 | |
David Benjamin | fa055a2 | 2014-09-15 16:51:51 -0400 | [diff] [blame] | 934 | // mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol |
| 935 | // given list of possible protocols and a list of the preference order. The |
| 936 | // first list must not be empty. It returns the resulting protocol and flag |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 937 | // indicating if the fallback case was reached. |
David Benjamin | fa055a2 | 2014-09-15 16:51:51 -0400 | [diff] [blame] | 938 | func mutualProtocol(protos, preferenceProtos []string) (string, bool) { |
| 939 | for _, s := range preferenceProtos { |
| 940 | for _, c := range protos { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 941 | if s == c { |
| 942 | return s, false |
| 943 | } |
| 944 | } |
| 945 | } |
| 946 | |
David Benjamin | fa055a2 | 2014-09-15 16:51:51 -0400 | [diff] [blame] | 947 | return protos[0], true |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 948 | } |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame] | 949 | |
| 950 | // writeIntPadded writes x into b, padded up with leading zeros as |
| 951 | // needed. |
| 952 | func writeIntPadded(b []byte, x *big.Int) { |
| 953 | for i := range b { |
| 954 | b[i] = 0 |
| 955 | } |
| 956 | xb := x.Bytes() |
| 957 | copy(b[len(b)-len(xb):], xb) |
| 958 | } |