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