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" |
David Benjamin | de620d9 | 2014-07-18 15:03:41 -0400 | [diff] [blame] | 9 | "crypto" |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 10 | "crypto/ecdsa" |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame^] | 11 | "crypto/elliptic" |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 12 | "crypto/rsa" |
| 13 | "crypto/subtle" |
| 14 | "crypto/x509" |
| 15 | "encoding/asn1" |
| 16 | "errors" |
| 17 | "fmt" |
| 18 | "io" |
David Benjamin | de620d9 | 2014-07-18 15:03:41 -0400 | [diff] [blame] | 19 | "math/big" |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 20 | "net" |
| 21 | "strconv" |
| 22 | ) |
| 23 | |
| 24 | type clientHandshakeState struct { |
| 25 | c *Conn |
| 26 | serverHello *serverHelloMsg |
| 27 | hello *clientHelloMsg |
| 28 | suite *cipherSuite |
| 29 | finishedHash finishedHash |
| 30 | masterSecret []byte |
| 31 | session *ClientSessionState |
| 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 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 46 | hello := &clientHelloMsg{ |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 47 | isDTLS: c.isDTLS, |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 48 | vers: c.config.maxVersion(), |
| 49 | compressionMethods: []uint8{compressionNone}, |
| 50 | random: make([]byte, 32), |
| 51 | ocspStapling: true, |
| 52 | serverName: c.config.ServerName, |
| 53 | supportedCurves: c.config.curvePreferences(), |
| 54 | supportedPoints: []uint8{pointFormatUncompressed}, |
| 55 | nextProtoNeg: len(c.config.NextProtos) > 0, |
| 56 | secureRenegotiation: true, |
David Benjamin | 35a7a44 | 2014-07-05 00:23:20 -0400 | [diff] [blame] | 57 | duplicateExtension: c.config.Bugs.DuplicateExtension, |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame^] | 58 | channelIDSupported: c.config.ChannelID != nil, |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 59 | } |
| 60 | |
David Benjamin | 98e882e | 2014-08-08 13:24:34 -0400 | [diff] [blame] | 61 | if c.config.Bugs.SendClientVersion != 0 { |
| 62 | hello.vers = c.config.Bugs.SendClientVersion |
| 63 | } |
| 64 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 65 | possibleCipherSuites := c.config.cipherSuites() |
| 66 | hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites)) |
| 67 | |
| 68 | NextCipherSuite: |
| 69 | for _, suiteId := range possibleCipherSuites { |
| 70 | for _, suite := range cipherSuites { |
| 71 | if suite.id != suiteId { |
| 72 | continue |
| 73 | } |
| 74 | // Don't advertise TLS 1.2-only cipher suites unless |
| 75 | // we're attempting TLS 1.2. |
| 76 | if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 { |
| 77 | continue |
| 78 | } |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 79 | // Don't advertise non-DTLS cipher suites on DTLS. |
| 80 | if c.isDTLS && suite.flags&suiteNoDTLS != 0 { |
| 81 | continue |
| 82 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 83 | hello.cipherSuites = append(hello.cipherSuites, suiteId) |
| 84 | continue NextCipherSuite |
| 85 | } |
| 86 | } |
| 87 | |
David Benjamin | bef270a | 2014-08-02 04:22:02 -0400 | [diff] [blame] | 88 | if c.config.Bugs.SendFallbackSCSV { |
| 89 | hello.cipherSuites = append(hello.cipherSuites, fallbackSCSV) |
| 90 | } |
| 91 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 92 | _, err := io.ReadFull(c.config.rand(), hello.random) |
| 93 | if err != nil { |
| 94 | c.sendAlert(alertInternalError) |
| 95 | return errors.New("tls: short read from Rand: " + err.Error()) |
| 96 | } |
| 97 | |
| 98 | if hello.vers >= VersionTLS12 { |
| 99 | hello.signatureAndHashes = supportedSKXSignatureAlgorithms |
| 100 | } |
| 101 | |
| 102 | var session *ClientSessionState |
| 103 | var cacheKey string |
| 104 | sessionCache := c.config.ClientSessionCache |
| 105 | if c.config.SessionTicketsDisabled { |
| 106 | sessionCache = nil |
| 107 | } |
| 108 | |
| 109 | if sessionCache != nil { |
| 110 | hello.ticketSupported = true |
| 111 | |
| 112 | // Try to resume a previously negotiated TLS session, if |
| 113 | // available. |
| 114 | cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config) |
| 115 | candidateSession, ok := sessionCache.Get(cacheKey) |
| 116 | if ok { |
| 117 | // Check that the ciphersuite/version used for the |
| 118 | // previous session are still valid. |
| 119 | cipherSuiteOk := false |
| 120 | for _, id := range hello.cipherSuites { |
| 121 | if id == candidateSession.cipherSuite { |
| 122 | cipherSuiteOk = true |
| 123 | break |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | versOk := candidateSession.vers >= c.config.minVersion() && |
| 128 | candidateSession.vers <= c.config.maxVersion() |
| 129 | if versOk && cipherSuiteOk { |
| 130 | session = candidateSession |
| 131 | } |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | if session != nil { |
| 136 | hello.sessionTicket = session.sessionTicket |
| 137 | // A random session ID is used to detect when the |
| 138 | // server accepted the ticket and is resuming a session |
| 139 | // (see RFC 5077). |
| 140 | hello.sessionId = make([]byte, 16) |
| 141 | if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil { |
| 142 | c.sendAlert(alertInternalError) |
| 143 | return errors.New("tls: short read from Rand: " + err.Error()) |
| 144 | } |
| 145 | } |
| 146 | |
David Benjamin | d86c767 | 2014-08-02 04:07:12 -0400 | [diff] [blame] | 147 | var helloBytes []byte |
| 148 | if c.config.Bugs.SendV2ClientHello { |
| 149 | v2Hello := &v2ClientHelloMsg{ |
| 150 | vers: hello.vers, |
| 151 | cipherSuites: hello.cipherSuites, |
| 152 | // No session resumption for V2ClientHello. |
| 153 | sessionId: nil, |
| 154 | challenge: hello.random, |
| 155 | } |
| 156 | helloBytes = v2Hello.marshal() |
| 157 | c.writeV2Record(helloBytes) |
| 158 | } else { |
| 159 | helloBytes = hello.marshal() |
| 160 | c.writeRecord(recordTypeHandshake, helloBytes) |
| 161 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 162 | |
| 163 | msg, err := c.readHandshake() |
| 164 | if err != nil { |
| 165 | return err |
| 166 | } |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 167 | |
| 168 | if c.isDTLS { |
| 169 | helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg) |
| 170 | if ok { |
David Benjamin | 8bc38f5 | 2014-08-16 12:07:27 -0400 | [diff] [blame] | 171 | if helloVerifyRequest.vers != VersionTLS10 { |
| 172 | // Per RFC 6347, the version field in |
| 173 | // HelloVerifyRequest SHOULD be always DTLS |
| 174 | // 1.0. Enforce this for testing purposes. |
| 175 | return errors.New("dtls: bad HelloVerifyRequest version") |
| 176 | } |
| 177 | |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 178 | hello.raw = nil |
| 179 | hello.cookie = helloVerifyRequest.cookie |
| 180 | helloBytes = hello.marshal() |
| 181 | c.writeRecord(recordTypeHandshake, helloBytes) |
| 182 | |
| 183 | msg, err = c.readHandshake() |
| 184 | if err != nil { |
| 185 | return err |
| 186 | } |
| 187 | } |
| 188 | } |
| 189 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 190 | serverHello, ok := msg.(*serverHelloMsg) |
| 191 | if !ok { |
| 192 | c.sendAlert(alertUnexpectedMessage) |
| 193 | return unexpectedMessageError(serverHello, msg) |
| 194 | } |
| 195 | |
David Benjamin | 76d8abe | 2014-08-14 16:25:34 -0400 | [diff] [blame] | 196 | c.vers, ok = c.config.mutualVersion(serverHello.vers) |
| 197 | if !ok { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 198 | c.sendAlert(alertProtocolVersion) |
| 199 | return fmt.Errorf("tls: server selected unsupported protocol version %x", serverHello.vers) |
| 200 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 201 | c.haveVers = true |
| 202 | |
| 203 | suite := mutualCipherSuite(c.config.cipherSuites(), serverHello.cipherSuite) |
| 204 | if suite == nil { |
| 205 | c.sendAlert(alertHandshakeFailure) |
| 206 | return fmt.Errorf("tls: server selected an unsupported cipher suite") |
| 207 | } |
| 208 | |
| 209 | hs := &clientHandshakeState{ |
| 210 | c: c, |
| 211 | serverHello: serverHello, |
| 212 | hello: hello, |
| 213 | suite: suite, |
| 214 | finishedHash: newFinishedHash(c.vers, suite), |
| 215 | session: session, |
| 216 | } |
| 217 | |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 218 | hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1) |
| 219 | hs.writeServerHash(hs.serverHello.marshal()) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 220 | |
David Benjamin | f3ec83d | 2014-07-21 22:42:34 -0400 | [diff] [blame] | 221 | if c.config.Bugs.EarlyChangeCipherSpec > 0 { |
| 222 | hs.establishKeys() |
| 223 | c.writeRecord(recordTypeChangeCipherSpec, []byte{1}) |
| 224 | } |
| 225 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 226 | isResume, err := hs.processServerHello() |
| 227 | if err != nil { |
| 228 | return err |
| 229 | } |
| 230 | |
| 231 | if isResume { |
David Benjamin | f3ec83d | 2014-07-21 22:42:34 -0400 | [diff] [blame] | 232 | if c.config.Bugs.EarlyChangeCipherSpec == 0 { |
| 233 | if err := hs.establishKeys(); err != nil { |
| 234 | return err |
| 235 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 236 | } |
| 237 | if err := hs.readSessionTicket(); err != nil { |
| 238 | return err |
| 239 | } |
| 240 | if err := hs.readFinished(); err != nil { |
| 241 | return err |
| 242 | } |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame^] | 243 | if err := hs.sendFinished(isResume); err != nil { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 244 | return err |
| 245 | } |
| 246 | } else { |
| 247 | if err := hs.doFullHandshake(); err != nil { |
| 248 | return err |
| 249 | } |
| 250 | if err := hs.establishKeys(); err != nil { |
| 251 | return err |
| 252 | } |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame^] | 253 | if err := hs.sendFinished(isResume); err != nil { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 254 | return err |
| 255 | } |
| 256 | if err := hs.readSessionTicket(); err != nil { |
| 257 | return err |
| 258 | } |
| 259 | if err := hs.readFinished(); err != nil { |
| 260 | return err |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | if sessionCache != nil && hs.session != nil && session != hs.session { |
| 265 | sessionCache.Put(cacheKey, hs.session) |
| 266 | } |
| 267 | |
| 268 | c.didResume = isResume |
| 269 | c.handshakeComplete = true |
| 270 | c.cipherSuite = suite.id |
| 271 | return nil |
| 272 | } |
| 273 | |
| 274 | func (hs *clientHandshakeState) doFullHandshake() error { |
| 275 | c := hs.c |
| 276 | |
| 277 | msg, err := c.readHandshake() |
| 278 | if err != nil { |
| 279 | return err |
| 280 | } |
| 281 | certMsg, ok := msg.(*certificateMsg) |
| 282 | if !ok || len(certMsg.certificates) == 0 { |
| 283 | c.sendAlert(alertUnexpectedMessage) |
| 284 | return unexpectedMessageError(certMsg, msg) |
| 285 | } |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 286 | hs.writeServerHash(certMsg.marshal()) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 287 | |
| 288 | certs := make([]*x509.Certificate, len(certMsg.certificates)) |
| 289 | for i, asn1Data := range certMsg.certificates { |
| 290 | cert, err := x509.ParseCertificate(asn1Data) |
| 291 | if err != nil { |
| 292 | c.sendAlert(alertBadCertificate) |
| 293 | return errors.New("tls: failed to parse certificate from server: " + err.Error()) |
| 294 | } |
| 295 | certs[i] = cert |
| 296 | } |
| 297 | |
| 298 | if !c.config.InsecureSkipVerify { |
| 299 | opts := x509.VerifyOptions{ |
| 300 | Roots: c.config.RootCAs, |
| 301 | CurrentTime: c.config.time(), |
| 302 | DNSName: c.config.ServerName, |
| 303 | Intermediates: x509.NewCertPool(), |
| 304 | } |
| 305 | |
| 306 | for i, cert := range certs { |
| 307 | if i == 0 { |
| 308 | continue |
| 309 | } |
| 310 | opts.Intermediates.AddCert(cert) |
| 311 | } |
| 312 | c.verifiedChains, err = certs[0].Verify(opts) |
| 313 | if err != nil { |
| 314 | c.sendAlert(alertBadCertificate) |
| 315 | return err |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | switch certs[0].PublicKey.(type) { |
| 320 | case *rsa.PublicKey, *ecdsa.PublicKey: |
| 321 | break |
| 322 | default: |
| 323 | c.sendAlert(alertUnsupportedCertificate) |
| 324 | return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey) |
| 325 | } |
| 326 | |
| 327 | c.peerCertificates = certs |
| 328 | |
| 329 | if hs.serverHello.ocspStapling { |
| 330 | msg, err = c.readHandshake() |
| 331 | if err != nil { |
| 332 | return err |
| 333 | } |
| 334 | cs, ok := msg.(*certificateStatusMsg) |
| 335 | if !ok { |
| 336 | c.sendAlert(alertUnexpectedMessage) |
| 337 | return unexpectedMessageError(cs, msg) |
| 338 | } |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 339 | hs.writeServerHash(cs.marshal()) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 340 | |
| 341 | if cs.statusType == statusTypeOCSP { |
| 342 | c.ocspResponse = cs.response |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | msg, err = c.readHandshake() |
| 347 | if err != nil { |
| 348 | return err |
| 349 | } |
| 350 | |
| 351 | keyAgreement := hs.suite.ka(c.vers) |
| 352 | |
| 353 | skx, ok := msg.(*serverKeyExchangeMsg) |
| 354 | if ok { |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 355 | hs.writeServerHash(skx.marshal()) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 356 | err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, certs[0], skx) |
| 357 | if err != nil { |
| 358 | c.sendAlert(alertUnexpectedMessage) |
| 359 | return err |
| 360 | } |
| 361 | |
| 362 | msg, err = c.readHandshake() |
| 363 | if err != nil { |
| 364 | return err |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | var chainToSend *Certificate |
| 369 | var certRequested bool |
| 370 | certReq, ok := msg.(*certificateRequestMsg) |
| 371 | if ok { |
| 372 | certRequested = true |
| 373 | |
| 374 | // RFC 4346 on the certificateAuthorities field: |
| 375 | // A list of the distinguished names of acceptable certificate |
| 376 | // authorities. These distinguished names may specify a desired |
| 377 | // distinguished name for a root CA or for a subordinate CA; |
| 378 | // thus, this message can be used to describe both known roots |
| 379 | // and a desired authorization space. If the |
| 380 | // certificate_authorities list is empty then the client MAY |
| 381 | // send any certificate of the appropriate |
| 382 | // ClientCertificateType, unless there is some external |
| 383 | // arrangement to the contrary. |
| 384 | |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 385 | hs.writeServerHash(certReq.marshal()) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 386 | |
| 387 | var rsaAvail, ecdsaAvail bool |
| 388 | for _, certType := range certReq.certificateTypes { |
| 389 | switch certType { |
David Benjamin | 7b03051 | 2014-07-08 17:30:11 -0400 | [diff] [blame] | 390 | case CertTypeRSASign: |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 391 | rsaAvail = true |
David Benjamin | 7b03051 | 2014-07-08 17:30:11 -0400 | [diff] [blame] | 392 | case CertTypeECDSASign: |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 393 | ecdsaAvail = true |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | // We need to search our list of client certs for one |
| 398 | // where SignatureAlgorithm is RSA and the Issuer is in |
| 399 | // certReq.certificateAuthorities |
| 400 | findCert: |
| 401 | for i, chain := range c.config.Certificates { |
| 402 | if !rsaAvail && !ecdsaAvail { |
| 403 | continue |
| 404 | } |
| 405 | |
| 406 | for j, cert := range chain.Certificate { |
| 407 | x509Cert := chain.Leaf |
| 408 | // parse the certificate if this isn't the leaf |
| 409 | // node, or if chain.Leaf was nil |
| 410 | if j != 0 || x509Cert == nil { |
| 411 | if x509Cert, err = x509.ParseCertificate(cert); err != nil { |
| 412 | c.sendAlert(alertInternalError) |
| 413 | return errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error()) |
| 414 | } |
| 415 | } |
| 416 | |
| 417 | switch { |
| 418 | case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA: |
| 419 | case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA: |
| 420 | default: |
| 421 | continue findCert |
| 422 | } |
| 423 | |
| 424 | if len(certReq.certificateAuthorities) == 0 { |
| 425 | // they gave us an empty list, so just take the |
| 426 | // first RSA cert from c.config.Certificates |
| 427 | chainToSend = &chain |
| 428 | break findCert |
| 429 | } |
| 430 | |
| 431 | for _, ca := range certReq.certificateAuthorities { |
| 432 | if bytes.Equal(x509Cert.RawIssuer, ca) { |
| 433 | chainToSend = &chain |
| 434 | break findCert |
| 435 | } |
| 436 | } |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | msg, err = c.readHandshake() |
| 441 | if err != nil { |
| 442 | return err |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | shd, ok := msg.(*serverHelloDoneMsg) |
| 447 | if !ok { |
| 448 | c.sendAlert(alertUnexpectedMessage) |
| 449 | return unexpectedMessageError(shd, msg) |
| 450 | } |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 451 | hs.writeServerHash(shd.marshal()) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 452 | |
| 453 | // If the server requested a certificate then we have to send a |
| 454 | // Certificate message, even if it's empty because we don't have a |
| 455 | // certificate to send. |
| 456 | if certRequested { |
| 457 | certMsg = new(certificateMsg) |
| 458 | if chainToSend != nil { |
| 459 | certMsg.certificates = chainToSend.Certificate |
| 460 | } |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 461 | hs.writeClientHash(certMsg.marshal()) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 462 | c.writeRecord(recordTypeHandshake, certMsg.marshal()) |
| 463 | } |
| 464 | |
| 465 | preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, certs[0]) |
| 466 | if err != nil { |
| 467 | c.sendAlert(alertInternalError) |
| 468 | return err |
| 469 | } |
| 470 | if ckx != nil { |
David Benjamin | f3ec83d | 2014-07-21 22:42:34 -0400 | [diff] [blame] | 471 | if c.config.Bugs.EarlyChangeCipherSpec < 2 { |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 472 | hs.writeClientHash(ckx.marshal()) |
David Benjamin | f3ec83d | 2014-07-21 22:42:34 -0400 | [diff] [blame] | 473 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 474 | c.writeRecord(recordTypeHandshake, ckx.marshal()) |
| 475 | } |
| 476 | |
| 477 | if chainToSend != nil { |
| 478 | var signed []byte |
| 479 | certVerify := &certificateVerifyMsg{ |
| 480 | hasSignatureAndHash: c.vers >= VersionTLS12, |
| 481 | } |
| 482 | |
| 483 | switch key := c.config.Certificates[0].PrivateKey.(type) { |
| 484 | case *ecdsa.PrivateKey: |
David Benjamin | de620d9 | 2014-07-18 15:03:41 -0400 | [diff] [blame] | 485 | certVerify.signatureAndHash, err = hs.finishedHash.selectClientCertSignatureAlgorithm(certReq.signatureAndHashes, signatureECDSA) |
| 486 | if err != nil { |
| 487 | break |
| 488 | } |
| 489 | var digest []byte |
| 490 | digest, _, err = hs.finishedHash.hashForClientCertificate(certVerify.signatureAndHash) |
| 491 | if err != nil { |
| 492 | break |
| 493 | } |
| 494 | var r, s *big.Int |
| 495 | r, s, err = ecdsa.Sign(c.config.rand(), key, digest) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 496 | if err == nil { |
| 497 | signed, err = asn1.Marshal(ecdsaSignature{r, s}) |
| 498 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 499 | case *rsa.PrivateKey: |
David Benjamin | de620d9 | 2014-07-18 15:03:41 -0400 | [diff] [blame] | 500 | certVerify.signatureAndHash, err = hs.finishedHash.selectClientCertSignatureAlgorithm(certReq.signatureAndHashes, signatureRSA) |
| 501 | if err != nil { |
| 502 | break |
| 503 | } |
| 504 | var digest []byte |
| 505 | var hashFunc crypto.Hash |
| 506 | digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(certVerify.signatureAndHash) |
| 507 | if err != nil { |
| 508 | break |
| 509 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 510 | signed, err = rsa.SignPKCS1v15(c.config.rand(), key, hashFunc, digest) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 511 | default: |
| 512 | err = errors.New("unknown private key type") |
| 513 | } |
| 514 | if err != nil { |
| 515 | c.sendAlert(alertInternalError) |
| 516 | return errors.New("tls: failed to sign handshake with client certificate: " + err.Error()) |
| 517 | } |
| 518 | certVerify.signature = signed |
| 519 | |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 520 | hs.writeClientHash(certVerify.marshal()) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 521 | c.writeRecord(recordTypeHandshake, certVerify.marshal()) |
| 522 | } |
| 523 | |
| 524 | hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random) |
| 525 | return nil |
| 526 | } |
| 527 | |
| 528 | func (hs *clientHandshakeState) establishKeys() error { |
| 529 | c := hs.c |
| 530 | |
| 531 | clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV := |
| 532 | keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen) |
| 533 | var clientCipher, serverCipher interface{} |
| 534 | var clientHash, serverHash macFunction |
| 535 | if hs.suite.cipher != nil { |
| 536 | clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */) |
| 537 | clientHash = hs.suite.mac(c.vers, clientMAC) |
| 538 | serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */) |
| 539 | serverHash = hs.suite.mac(c.vers, serverMAC) |
| 540 | } else { |
| 541 | clientCipher = hs.suite.aead(clientKey, clientIV) |
| 542 | serverCipher = hs.suite.aead(serverKey, serverIV) |
| 543 | } |
| 544 | |
| 545 | c.in.prepareCipherSpec(c.vers, serverCipher, serverHash) |
| 546 | c.out.prepareCipherSpec(c.vers, clientCipher, clientHash) |
| 547 | return nil |
| 548 | } |
| 549 | |
| 550 | func (hs *clientHandshakeState) serverResumedSession() bool { |
| 551 | // If the server responded with the same sessionId then it means the |
| 552 | // sessionTicket is being used to resume a TLS session. |
| 553 | return hs.session != nil && hs.hello.sessionId != nil && |
| 554 | bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId) |
| 555 | } |
| 556 | |
| 557 | func (hs *clientHandshakeState) processServerHello() (bool, error) { |
| 558 | c := hs.c |
| 559 | |
| 560 | if hs.serverHello.compressionMethod != compressionNone { |
| 561 | c.sendAlert(alertUnexpectedMessage) |
| 562 | return false, errors.New("tls: server selected unsupported compression format") |
| 563 | } |
| 564 | |
| 565 | if !hs.hello.nextProtoNeg && hs.serverHello.nextProtoNeg { |
| 566 | c.sendAlert(alertHandshakeFailure) |
| 567 | return false, errors.New("server advertised unrequested NPN extension") |
| 568 | } |
| 569 | |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame^] | 570 | if !hs.hello.channelIDSupported && hs.serverHello.channelIDRequested { |
| 571 | c.sendAlert(alertHandshakeFailure) |
| 572 | return false, errors.New("server advertised unrequested Channel ID extension") |
| 573 | } |
| 574 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 575 | if hs.serverResumedSession() { |
| 576 | // Restore masterSecret and peerCerts from previous state |
| 577 | hs.masterSecret = hs.session.masterSecret |
| 578 | c.peerCertificates = hs.session.serverCertificates |
| 579 | return true, nil |
| 580 | } |
| 581 | return false, nil |
| 582 | } |
| 583 | |
| 584 | func (hs *clientHandshakeState) readFinished() error { |
| 585 | c := hs.c |
| 586 | |
| 587 | c.readRecord(recordTypeChangeCipherSpec) |
| 588 | if err := c.in.error(); err != nil { |
| 589 | return err |
| 590 | } |
| 591 | |
| 592 | msg, err := c.readHandshake() |
| 593 | if err != nil { |
| 594 | return err |
| 595 | } |
| 596 | serverFinished, ok := msg.(*finishedMsg) |
| 597 | if !ok { |
| 598 | c.sendAlert(alertUnexpectedMessage) |
| 599 | return unexpectedMessageError(serverFinished, msg) |
| 600 | } |
| 601 | |
David Benjamin | f3ec83d | 2014-07-21 22:42:34 -0400 | [diff] [blame] | 602 | if c.config.Bugs.EarlyChangeCipherSpec == 0 { |
| 603 | verify := hs.finishedHash.serverSum(hs.masterSecret) |
| 604 | if len(verify) != len(serverFinished.verifyData) || |
| 605 | subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 { |
| 606 | c.sendAlert(alertHandshakeFailure) |
| 607 | return errors.New("tls: server's Finished message was incorrect") |
| 608 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 609 | } |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 610 | hs.writeServerHash(serverFinished.marshal()) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 611 | return nil |
| 612 | } |
| 613 | |
| 614 | func (hs *clientHandshakeState) readSessionTicket() error { |
| 615 | if !hs.serverHello.ticketSupported { |
| 616 | return nil |
| 617 | } |
| 618 | |
| 619 | c := hs.c |
| 620 | msg, err := c.readHandshake() |
| 621 | if err != nil { |
| 622 | return err |
| 623 | } |
| 624 | sessionTicketMsg, ok := msg.(*newSessionTicketMsg) |
| 625 | if !ok { |
| 626 | c.sendAlert(alertUnexpectedMessage) |
| 627 | return unexpectedMessageError(sessionTicketMsg, msg) |
| 628 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 629 | |
| 630 | hs.session = &ClientSessionState{ |
| 631 | sessionTicket: sessionTicketMsg.ticket, |
| 632 | vers: c.vers, |
| 633 | cipherSuite: hs.suite.id, |
| 634 | masterSecret: hs.masterSecret, |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame^] | 635 | handshakeHash: hs.finishedHash.server.Sum(nil), |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 636 | serverCertificates: c.peerCertificates, |
| 637 | } |
| 638 | |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame^] | 639 | hs.writeServerHash(sessionTicketMsg.marshal()) |
| 640 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 641 | return nil |
| 642 | } |
| 643 | |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame^] | 644 | func (hs *clientHandshakeState) sendFinished(isResume bool) error { |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 645 | c := hs.c |
| 646 | |
David Benjamin | 86271ee | 2014-07-21 16:14:03 -0400 | [diff] [blame] | 647 | var postCCSBytes []byte |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 648 | seqno := hs.c.sendHandshakeSeq |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 649 | if hs.serverHello.nextProtoNeg { |
| 650 | nextProto := new(nextProtoMsg) |
| 651 | proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.nextProtos) |
| 652 | nextProto.proto = proto |
| 653 | c.clientProtocol = proto |
| 654 | c.clientProtocolFallback = fallback |
| 655 | |
David Benjamin | 86271ee | 2014-07-21 16:14:03 -0400 | [diff] [blame] | 656 | nextProtoBytes := nextProto.marshal() |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 657 | hs.writeHash(nextProtoBytes, seqno) |
| 658 | seqno++ |
David Benjamin | 86271ee | 2014-07-21 16:14:03 -0400 | [diff] [blame] | 659 | postCCSBytes = append(postCCSBytes, nextProtoBytes...) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 660 | } |
| 661 | |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame^] | 662 | if hs.serverHello.channelIDRequested { |
| 663 | encryptedExtensions := new(encryptedExtensionsMsg) |
| 664 | if c.config.ChannelID.Curve != elliptic.P256() { |
| 665 | return fmt.Errorf("tls: Channel ID is not on P-256.") |
| 666 | } |
| 667 | var resumeHash []byte |
| 668 | if isResume { |
| 669 | resumeHash = hs.session.handshakeHash |
| 670 | } |
| 671 | r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, hs.finishedHash.hashForChannelID(resumeHash)) |
| 672 | if err != nil { |
| 673 | return err |
| 674 | } |
| 675 | channelID := make([]byte, 128) |
| 676 | writeIntPadded(channelID[0:32], c.config.ChannelID.X) |
| 677 | writeIntPadded(channelID[32:64], c.config.ChannelID.Y) |
| 678 | writeIntPadded(channelID[64:96], r) |
| 679 | writeIntPadded(channelID[96:128], s) |
| 680 | encryptedExtensions.channelID = channelID |
| 681 | |
| 682 | c.channelID = &c.config.ChannelID.PublicKey |
| 683 | |
| 684 | encryptedExtensionsBytes := encryptedExtensions.marshal() |
| 685 | hs.writeHash(encryptedExtensionsBytes, seqno) |
| 686 | seqno++ |
| 687 | postCCSBytes = append(postCCSBytes, encryptedExtensionsBytes...) |
| 688 | } |
| 689 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 690 | finished := new(finishedMsg) |
David Benjamin | f3ec83d | 2014-07-21 22:42:34 -0400 | [diff] [blame] | 691 | if c.config.Bugs.EarlyChangeCipherSpec == 2 { |
| 692 | finished.verifyData = hs.finishedHash.clientSum(nil) |
| 693 | } else { |
| 694 | finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret) |
| 695 | } |
David Benjamin | 86271ee | 2014-07-21 16:14:03 -0400 | [diff] [blame] | 696 | finishedBytes := finished.marshal() |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 697 | hs.writeHash(finishedBytes, seqno) |
David Benjamin | 86271ee | 2014-07-21 16:14:03 -0400 | [diff] [blame] | 698 | postCCSBytes = append(postCCSBytes, finishedBytes...) |
| 699 | |
| 700 | if c.config.Bugs.FragmentAcrossChangeCipherSpec { |
| 701 | c.writeRecord(recordTypeHandshake, postCCSBytes[:5]) |
| 702 | postCCSBytes = postCCSBytes[5:] |
| 703 | } |
| 704 | |
| 705 | if !c.config.Bugs.SkipChangeCipherSpec && |
| 706 | c.config.Bugs.EarlyChangeCipherSpec == 0 { |
| 707 | c.writeRecord(recordTypeChangeCipherSpec, []byte{1}) |
| 708 | } |
| 709 | |
| 710 | c.writeRecord(recordTypeHandshake, postCCSBytes) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 711 | return nil |
| 712 | } |
| 713 | |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 714 | func (hs *clientHandshakeState) writeClientHash(msg []byte) { |
| 715 | // writeClientHash is called before writeRecord. |
| 716 | hs.writeHash(msg, hs.c.sendHandshakeSeq) |
| 717 | } |
| 718 | |
| 719 | func (hs *clientHandshakeState) writeServerHash(msg []byte) { |
| 720 | // writeServerHash is called after readHandshake. |
| 721 | hs.writeHash(msg, hs.c.recvHandshakeSeq-1) |
| 722 | } |
| 723 | |
| 724 | func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) { |
| 725 | if hs.c.isDTLS { |
| 726 | // This is somewhat hacky. DTLS hashes a slightly different format. |
| 727 | // First, the TLS header. |
| 728 | hs.finishedHash.Write(msg[:4]) |
| 729 | // Then the sequence number and reassembled fragment offset (always 0). |
| 730 | hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0}) |
| 731 | // Then the reassembled fragment (always equal to the message length). |
| 732 | hs.finishedHash.Write(msg[1:4]) |
| 733 | // And then the message body. |
| 734 | hs.finishedHash.Write(msg[4:]) |
| 735 | } else { |
| 736 | hs.finishedHash.Write(msg) |
| 737 | } |
| 738 | } |
| 739 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 740 | // clientSessionCacheKey returns a key used to cache sessionTickets that could |
| 741 | // be used to resume previously negotiated TLS sessions with a server. |
| 742 | func clientSessionCacheKey(serverAddr net.Addr, config *Config) string { |
| 743 | if len(config.ServerName) > 0 { |
| 744 | return config.ServerName |
| 745 | } |
| 746 | return serverAddr.String() |
| 747 | } |
| 748 | |
| 749 | // mutualProtocol finds the mutual Next Protocol Negotiation protocol given the |
| 750 | // set of client and server supported protocols. The set of client supported |
| 751 | // protocols must not be empty. It returns the resulting protocol and flag |
| 752 | // indicating if the fallback case was reached. |
| 753 | func mutualProtocol(clientProtos, serverProtos []string) (string, bool) { |
| 754 | for _, s := range serverProtos { |
| 755 | for _, c := range clientProtos { |
| 756 | if s == c { |
| 757 | return s, false |
| 758 | } |
| 759 | } |
| 760 | } |
| 761 | |
| 762 | return clientProtos[0], true |
| 763 | } |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame^] | 764 | |
| 765 | // writeIntPadded writes x into b, padded up with leading zeros as |
| 766 | // needed. |
| 767 | func writeIntPadded(b []byte, x *big.Int) { |
| 768 | for i := range b { |
| 769 | b[i] = 0 |
| 770 | } |
| 771 | xb := x.Bytes() |
| 772 | copy(b[len(b)-len(xb):], xb) |
| 773 | } |