handshake_client.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  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. package tls
  5. import (
  6. "bytes"
  7. "crypto"
  8. "crypto/rand"
  9. "crypto/sha256"
  10. "math/big"
  11. "crypto/ecdsa"
  12. "crypto/rsa"
  13. "crypto/subtle"
  14. "crypto/x509"
  15. "errors"
  16. "fmt"
  17. "io"
  18. "net"
  19. "strconv"
  20. "strings"
  21. )
  22. type clientHandshakeState struct {
  23. c *Conn
  24. serverHello *serverHelloMsg
  25. hello *clientHelloMsg
  26. suite *cipherSuite
  27. finishedHash finishedHash
  28. masterSecret []byte
  29. session *ClientSessionState
  30. }
  31. // c.out.Mutex <= L; c.handshakeMutex <= L.
  32. func (c *Conn) clientHandshake() error {
  33. if c.config == nil {
  34. c.config = defaultConfig()
  35. }
  36. // This may be a renegotiation handshake, in which case some fields
  37. // need to be reset.
  38. c.didResume = false
  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. nextProtosLength := 0
  43. for _, proto := range c.config.NextProtos {
  44. if l := len(proto); l == 0 || l > 255 {
  45. return errors.New("tls: invalid NextProtos value")
  46. } else {
  47. nextProtosLength += 1 + l
  48. }
  49. }
  50. if nextProtosLength > 0xffff {
  51. return errors.New("tls: NextProtos values too large")
  52. }
  53. hello := &clientHelloMsg{
  54. vers: c.config.maxVersion(),
  55. compressionMethods: []uint8{compressionNone},
  56. random: make([]byte, 32),
  57. ocspStapling: true,
  58. scts: true,
  59. serverName: hostnameInSNI(c.config.ServerName),
  60. supportedCurves: c.config.curvePreferences(),
  61. supportedPoints: []uint8{pointFormatUncompressed},
  62. nextProtoNeg: len(c.config.NextProtos) > 0,
  63. secureRenegotiationSupported: true,
  64. alpnProtocols: c.config.NextProtos,
  65. }
  66. if c.handshakes > 0 {
  67. hello.secureRenegotiation = c.clientFinished[:]
  68. }
  69. possibleCipherSuites := c.config.cipherSuites()
  70. hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
  71. NextCipherSuite:
  72. for _, suiteId := range possibleCipherSuites {
  73. for _, suite := range cipherSuites {
  74. if suite.id != suiteId {
  75. continue
  76. }
  77. // Don't advertise TLS 1.2-only cipher suites unless
  78. // we're attempting TLS 1.2.
  79. if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
  80. continue
  81. }
  82. hello.cipherSuites = append(hello.cipherSuites, suiteId)
  83. continue NextCipherSuite
  84. }
  85. }
  86. _, err := io.ReadFull(c.config.rand(), hello.random)
  87. if err != nil {
  88. c.sendAlert(alertInternalError)
  89. return errors.New("tls: short read from Rand: " + err.Error())
  90. }
  91. if hello.vers >= VersionTLS12 {
  92. hello.signatureAndHashes = supportedSignatureAlgorithms
  93. }
  94. var session *ClientSessionState
  95. var cacheKey string
  96. sessionCache := c.config.ClientSessionCache
  97. if c.config.SessionTicketsDisabled {
  98. sessionCache = nil
  99. }
  100. if sessionCache != nil {
  101. hello.ticketSupported = true
  102. }
  103. // Session resumption is not allowed if renegotiating because
  104. // renegotiation is primarily used to allow a client to send a client
  105. // certificate, which would be skipped if session resumption occurred.
  106. if sessionCache != nil && c.handshakes == 0 {
  107. // Try to resume a previously negotiated TLS session, if
  108. // available.
  109. cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
  110. candidateSession, ok := sessionCache.Get(cacheKey)
  111. if ok {
  112. // Check that the ciphersuite/version used for the
  113. // previous session are still valid.
  114. cipherSuiteOk := false
  115. for _, id := range hello.cipherSuites {
  116. if id == candidateSession.cipherSuite {
  117. cipherSuiteOk = true
  118. break
  119. }
  120. }
  121. versOk := candidateSession.vers >= c.config.minVersion() &&
  122. candidateSession.vers <= c.config.maxVersion()
  123. if versOk && cipherSuiteOk {
  124. session = candidateSession
  125. }
  126. }
  127. }
  128. if session != nil {
  129. hello.sessionTicket = session.sessionTicket
  130. // A random session ID is used to detect when the
  131. // server accepted the ticket and is resuming a session
  132. // (see RFC 5077).
  133. hello.sessionId = make([]byte, 16)
  134. if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
  135. c.sendAlert(alertInternalError)
  136. return errors.New("tls: short read from Rand: " + err.Error())
  137. }
  138. }
  139. // [Psiphon]
  140. // Re-configure extensions as required for EmulateChrome.
  141. if c.config.EmulateChrome {
  142. hello.emulateChrome = true
  143. // Sanity check that expected and required configuration is present
  144. if hello.vers != VersionTLS12 ||
  145. len(hello.compressionMethods) != 1 ||
  146. hello.compressionMethods[0] != compressionNone ||
  147. !hello.ticketSupported ||
  148. !hello.ocspStapling ||
  149. !hello.scts ||
  150. len(hello.supportedPoints) != 1 ||
  151. hello.supportedPoints[0] != pointFormatUncompressed ||
  152. !hello.secureRenegotiationSupported {
  153. return errors.New("tls: unexpected configuration for EmulateChrome")
  154. }
  155. hello.supportedCurves = []CurveID{
  156. CurveID(randomGREASEValue()),
  157. X25519,
  158. CurveP256, // secp256r1
  159. CurveP384, // secp384r1
  160. }
  161. hello.cipherSuites = []uint16{
  162. randomGREASEValue(),
  163. TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  164. TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  165. TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  166. TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  167. TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  168. TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  169. // TODO: remove these soon
  170. // See: https://github.com/google/boringssl/commit/2e839244b078205ff677ada3fb83cf9d60ef055b
  171. TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_OLD,
  172. TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_OLD,
  173. TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  174. TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  175. TLS_RSA_WITH_AES_128_GCM_SHA256,
  176. TLS_RSA_WITH_AES_256_GCM_SHA384,
  177. TLS_RSA_WITH_AES_128_CBC_SHA,
  178. TLS_RSA_WITH_AES_256_CBC_SHA,
  179. TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  180. }
  181. // From: https://github.com/google/boringssl/blob/7d7554b6b3c79e707e25521e61e066ce2b996e4c/ssl/t1_lib.c#L442
  182. // TODO: handle RSA-PSS (0x08)
  183. hello.signatureAndHashes = []signatureAndHash{
  184. {hashSHA256, signatureECDSA},
  185. {0x08, 0x04},
  186. {hashSHA256, signatureRSA},
  187. {hashSHA384, signatureECDSA},
  188. {0x08, 0x05},
  189. {hashSHA384, signatureRSA},
  190. {0x08, 0x06},
  191. {hashSHA512, signatureRSA},
  192. {hashSHA1, signatureRSA},
  193. }
  194. hello.nextProtoNeg = false
  195. hello.alpnProtocols = []string{"h2", "http/1.1"}
  196. // The extended master secret and channel ID extensions
  197. // code is from:
  198. //
  199. // https://github.com/google/boringssl/tree/master/ssl/test/runner
  200. // https://github.com/google/boringssl/blob/master/LICENSE
  201. hello.extendedMasterSecretSupported = true
  202. hello.channelIDSupported = true
  203. // TODO: implement actual support, in case negotiated
  204. // https://github.com/google/boringssl/commit/d30a990850457657e3209cb0c27fbe89b3df7ad2
  205. // In BoringSSL, the session ID is a SHA256 digest of the
  206. // session ticket:
  207. // https://github.com/google/boringssl/blob/33fe4a0d1406f423e7424ea7367e1d1a51c2edc1/ssl/handshake_client.c#L1901-L1908
  208. if session != nil {
  209. hello.sessionTicket = session.sessionTicket
  210. sessionId := sha256.Sum256(session.sessionTicket)
  211. hello.sessionId = sessionId[:]
  212. }
  213. }
  214. if _, err := c.writeRecord(recordTypeHandshake, hello.marshal()); err != nil {
  215. return err
  216. }
  217. msg, err := c.readHandshake()
  218. if err != nil {
  219. return err
  220. }
  221. serverHello, ok := msg.(*serverHelloMsg)
  222. if !ok {
  223. c.sendAlert(alertUnexpectedMessage)
  224. return unexpectedMessageError(serverHello, msg)
  225. }
  226. vers, ok := c.config.mutualVersion(serverHello.vers)
  227. if !ok || vers < VersionTLS10 {
  228. // TLS 1.0 is the minimum version supported as a client.
  229. c.sendAlert(alertProtocolVersion)
  230. return fmt.Errorf("tls: server selected unsupported protocol version %x", serverHello.vers)
  231. }
  232. c.vers = vers
  233. c.haveVers = true
  234. suite := mutualCipherSuite(hello.cipherSuites, serverHello.cipherSuite)
  235. if suite == nil {
  236. c.sendAlert(alertHandshakeFailure)
  237. return errors.New("tls: server chose an unconfigured cipher suite")
  238. }
  239. hs := &clientHandshakeState{
  240. c: c,
  241. serverHello: serverHello,
  242. hello: hello,
  243. suite: suite,
  244. finishedHash: newFinishedHash(c.vers, suite),
  245. session: session,
  246. }
  247. isResume, err := hs.processServerHello()
  248. if err != nil {
  249. return err
  250. }
  251. // No signatures of the handshake are needed in a resumption.
  252. // Otherwise, in a full handshake, if we don't have any certificates
  253. // configured then we will never send a CertificateVerify message and
  254. // thus no signatures are needed in that case either.
  255. if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
  256. hs.finishedHash.discardHandshakeBuffer()
  257. }
  258. hs.finishedHash.Write(hs.hello.marshal())
  259. hs.finishedHash.Write(hs.serverHello.marshal())
  260. c.buffering = true
  261. if isResume {
  262. if err := hs.establishKeys(); err != nil {
  263. return err
  264. }
  265. if err := hs.readSessionTicket(); err != nil {
  266. return err
  267. }
  268. if err := hs.readFinished(c.serverFinished[:]); err != nil {
  269. return err
  270. }
  271. c.clientFinishedIsFirst = false
  272. if err := hs.sendFinished(c.clientFinished[:]); err != nil {
  273. return err
  274. }
  275. if _, err := c.flush(); err != nil {
  276. return err
  277. }
  278. } else {
  279. if err := hs.doFullHandshake(); err != nil {
  280. return err
  281. }
  282. if err := hs.establishKeys(); err != nil {
  283. return err
  284. }
  285. if err := hs.sendFinished(c.clientFinished[:]); err != nil {
  286. return err
  287. }
  288. if _, err := c.flush(); err != nil {
  289. return err
  290. }
  291. c.clientFinishedIsFirst = true
  292. if err := hs.readSessionTicket(); err != nil {
  293. return err
  294. }
  295. if err := hs.readFinished(c.serverFinished[:]); err != nil {
  296. return err
  297. }
  298. }
  299. if sessionCache != nil && hs.session != nil && session != hs.session {
  300. sessionCache.Put(cacheKey, hs.session)
  301. }
  302. c.didResume = isResume
  303. c.handshakeComplete = true
  304. c.cipherSuite = suite.id
  305. return nil
  306. }
  307. func randomGREASEValue() uint16 {
  308. values := []uint16{0x0A0A, 0x1A1A, 0x2A2A, 0x3A3A, 0x4A4A, 0x5A5A, 0x6A6A, 0x7A7A, 0x8A8A, 0x9A9A, 0xAAAA, 0xBABA, 0xCACA, 0xDADA, 0xEAEA, 0xFAFA}
  309. i, _ := rand.Int(rand.Reader, big.NewInt(int64(len(values))))
  310. return values[int(i.Int64())]
  311. }
  312. func (hs *clientHandshakeState) doFullHandshake() error {
  313. c := hs.c
  314. msg, err := c.readHandshake()
  315. if err != nil {
  316. return err
  317. }
  318. certMsg, ok := msg.(*certificateMsg)
  319. if !ok || len(certMsg.certificates) == 0 {
  320. c.sendAlert(alertUnexpectedMessage)
  321. return unexpectedMessageError(certMsg, msg)
  322. }
  323. hs.finishedHash.Write(certMsg.marshal())
  324. if c.handshakes == 0 {
  325. // If this is the first handshake on a connection, process and
  326. // (optionally) verify the server's certificates.
  327. certs := make([]*x509.Certificate, len(certMsg.certificates))
  328. for i, asn1Data := range certMsg.certificates {
  329. cert, err := x509.ParseCertificate(asn1Data)
  330. if err != nil {
  331. c.sendAlert(alertBadCertificate)
  332. return errors.New("tls: failed to parse certificate from server: " + err.Error())
  333. }
  334. certs[i] = cert
  335. }
  336. if !c.config.InsecureSkipVerify {
  337. opts := x509.VerifyOptions{
  338. Roots: c.config.RootCAs,
  339. CurrentTime: c.config.time(),
  340. DNSName: c.config.ServerName,
  341. Intermediates: x509.NewCertPool(),
  342. }
  343. for i, cert := range certs {
  344. if i == 0 {
  345. continue
  346. }
  347. opts.Intermediates.AddCert(cert)
  348. }
  349. c.verifiedChains, err = certs[0].Verify(opts)
  350. if err != nil {
  351. c.sendAlert(alertBadCertificate)
  352. return err
  353. }
  354. }
  355. if c.config.VerifyPeerCertificate != nil {
  356. if err := c.config.VerifyPeerCertificate(certMsg.certificates, c.verifiedChains); err != nil {
  357. c.sendAlert(alertBadCertificate)
  358. return err
  359. }
  360. }
  361. switch certs[0].PublicKey.(type) {
  362. case *rsa.PublicKey, *ecdsa.PublicKey:
  363. break
  364. default:
  365. c.sendAlert(alertUnsupportedCertificate)
  366. return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
  367. }
  368. c.peerCertificates = certs
  369. } else {
  370. // This is a renegotiation handshake. We require that the
  371. // server's identity (i.e. leaf certificate) is unchanged and
  372. // thus any previous trust decision is still valid.
  373. //
  374. // See https://mitls.org/pages/attacks/3SHAKE for the
  375. // motivation behind this requirement.
  376. if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
  377. c.sendAlert(alertBadCertificate)
  378. return errors.New("tls: server's identity changed during renegotiation")
  379. }
  380. }
  381. if hs.serverHello.ocspStapling {
  382. msg, err = c.readHandshake()
  383. if err != nil {
  384. return err
  385. }
  386. cs, ok := msg.(*certificateStatusMsg)
  387. if !ok {
  388. c.sendAlert(alertUnexpectedMessage)
  389. return unexpectedMessageError(cs, msg)
  390. }
  391. hs.finishedHash.Write(cs.marshal())
  392. if cs.statusType == statusTypeOCSP {
  393. c.ocspResponse = cs.response
  394. }
  395. }
  396. msg, err = c.readHandshake()
  397. if err != nil {
  398. return err
  399. }
  400. keyAgreement := hs.suite.ka(c.vers)
  401. skx, ok := msg.(*serverKeyExchangeMsg)
  402. if ok {
  403. hs.finishedHash.Write(skx.marshal())
  404. err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
  405. if err != nil {
  406. c.sendAlert(alertUnexpectedMessage)
  407. return err
  408. }
  409. msg, err = c.readHandshake()
  410. if err != nil {
  411. return err
  412. }
  413. }
  414. var chainToSend *Certificate
  415. var certRequested bool
  416. certReq, ok := msg.(*certificateRequestMsg)
  417. if ok {
  418. certRequested = true
  419. hs.finishedHash.Write(certReq.marshal())
  420. if chainToSend, err = hs.getCertificate(certReq); err != nil {
  421. c.sendAlert(alertInternalError)
  422. return err
  423. }
  424. msg, err = c.readHandshake()
  425. if err != nil {
  426. return err
  427. }
  428. }
  429. shd, ok := msg.(*serverHelloDoneMsg)
  430. if !ok {
  431. c.sendAlert(alertUnexpectedMessage)
  432. return unexpectedMessageError(shd, msg)
  433. }
  434. hs.finishedHash.Write(shd.marshal())
  435. // If the server requested a certificate then we have to send a
  436. // Certificate message, even if it's empty because we don't have a
  437. // certificate to send.
  438. if certRequested {
  439. certMsg = new(certificateMsg)
  440. certMsg.certificates = chainToSend.Certificate
  441. hs.finishedHash.Write(certMsg.marshal())
  442. if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
  443. return err
  444. }
  445. }
  446. preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
  447. if err != nil {
  448. c.sendAlert(alertInternalError)
  449. return err
  450. }
  451. if ckx != nil {
  452. hs.finishedHash.Write(ckx.marshal())
  453. if _, err := c.writeRecord(recordTypeHandshake, ckx.marshal()); err != nil {
  454. return err
  455. }
  456. }
  457. if chainToSend != nil && len(chainToSend.Certificate) > 0 {
  458. certVerify := &certificateVerifyMsg{
  459. hasSignatureAndHash: c.vers >= VersionTLS12,
  460. }
  461. key, ok := chainToSend.PrivateKey.(crypto.Signer)
  462. if !ok {
  463. c.sendAlert(alertInternalError)
  464. return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
  465. }
  466. var signatureType uint8
  467. switch key.Public().(type) {
  468. case *ecdsa.PublicKey:
  469. signatureType = signatureECDSA
  470. case *rsa.PublicKey:
  471. signatureType = signatureRSA
  472. default:
  473. c.sendAlert(alertInternalError)
  474. return fmt.Errorf("tls: failed to sign handshake with client certificate: unknown client certificate key type: %T", key)
  475. }
  476. certVerify.signatureAndHash, err = hs.finishedHash.selectClientCertSignatureAlgorithm(certReq.signatureAndHashes, signatureType)
  477. if err != nil {
  478. c.sendAlert(alertInternalError)
  479. return err
  480. }
  481. digest, hashFunc, err := hs.finishedHash.hashForClientCertificate(certVerify.signatureAndHash, hs.masterSecret)
  482. if err != nil {
  483. c.sendAlert(alertInternalError)
  484. return err
  485. }
  486. certVerify.signature, err = key.Sign(c.config.rand(), digest, hashFunc)
  487. if err != nil {
  488. c.sendAlert(alertInternalError)
  489. return err
  490. }
  491. hs.finishedHash.Write(certVerify.marshal())
  492. if _, err := c.writeRecord(recordTypeHandshake, certVerify.marshal()); err != nil {
  493. return err
  494. }
  495. }
  496. // [Psiphon]
  497. // extended master secret implementation from https://github.com/google/boringssl/commit/7571292eaca1745f3ecda2374ba1e8163b58c3b5
  498. if hs.serverHello.extendedMasterSecret && c.config.EmulateChrome {
  499. hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
  500. c.extendedMasterSecret = true
  501. } else {
  502. hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
  503. }
  504. if err := c.config.writeKeyLog(hs.hello.random, hs.masterSecret); err != nil {
  505. c.sendAlert(alertInternalError)
  506. return errors.New("tls: failed to write to key log: " + err.Error())
  507. }
  508. hs.finishedHash.discardHandshakeBuffer()
  509. return nil
  510. }
  511. func (hs *clientHandshakeState) establishKeys() error {
  512. c := hs.c
  513. clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
  514. keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
  515. var clientCipher, serverCipher interface{}
  516. var clientHash, serverHash macFunction
  517. if hs.suite.cipher != nil {
  518. clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
  519. clientHash = hs.suite.mac(c.vers, clientMAC)
  520. serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
  521. serverHash = hs.suite.mac(c.vers, serverMAC)
  522. } else {
  523. clientCipher = hs.suite.aead(clientKey, clientIV)
  524. serverCipher = hs.suite.aead(serverKey, serverIV)
  525. }
  526. c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
  527. c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
  528. return nil
  529. }
  530. func (hs *clientHandshakeState) serverResumedSession() bool {
  531. // If the server responded with the same sessionId then it means the
  532. // sessionTicket is being used to resume a TLS session.
  533. return hs.session != nil && hs.hello.sessionId != nil &&
  534. bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
  535. }
  536. func (hs *clientHandshakeState) processServerHello() (bool, error) {
  537. c := hs.c
  538. if hs.serverHello.compressionMethod != compressionNone {
  539. c.sendAlert(alertUnexpectedMessage)
  540. return false, errors.New("tls: server selected unsupported compression format")
  541. }
  542. if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
  543. c.secureRenegotiation = true
  544. if len(hs.serverHello.secureRenegotiation) != 0 {
  545. c.sendAlert(alertHandshakeFailure)
  546. return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
  547. }
  548. }
  549. if c.handshakes > 0 && c.secureRenegotiation {
  550. var expectedSecureRenegotiation [24]byte
  551. copy(expectedSecureRenegotiation[:], c.clientFinished[:])
  552. copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
  553. if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
  554. c.sendAlert(alertHandshakeFailure)
  555. return false, errors.New("tls: incorrect renegotiation extension contents")
  556. }
  557. }
  558. clientDidNPN := hs.hello.nextProtoNeg
  559. clientDidALPN := len(hs.hello.alpnProtocols) > 0
  560. serverHasNPN := hs.serverHello.nextProtoNeg
  561. serverHasALPN := len(hs.serverHello.alpnProtocol) > 0
  562. if !clientDidNPN && serverHasNPN {
  563. c.sendAlert(alertHandshakeFailure)
  564. return false, errors.New("tls: server advertised unrequested NPN extension")
  565. }
  566. if !clientDidALPN && serverHasALPN {
  567. c.sendAlert(alertHandshakeFailure)
  568. return false, errors.New("tls: server advertised unrequested ALPN extension")
  569. }
  570. if serverHasNPN && serverHasALPN {
  571. c.sendAlert(alertHandshakeFailure)
  572. return false, errors.New("tls: server advertised both NPN and ALPN extensions")
  573. }
  574. if serverHasALPN {
  575. c.clientProtocol = hs.serverHello.alpnProtocol
  576. c.clientProtocolFallback = false
  577. }
  578. c.scts = hs.serverHello.scts
  579. if !hs.serverResumedSession() {
  580. return false, nil
  581. }
  582. if hs.session.vers != c.vers {
  583. c.sendAlert(alertHandshakeFailure)
  584. return false, errors.New("tls: server resumed a session with a different version")
  585. }
  586. if hs.session.cipherSuite != hs.suite.id {
  587. c.sendAlert(alertHandshakeFailure)
  588. return false, errors.New("tls: server resumed a session with a different cipher suite")
  589. }
  590. // Restore masterSecret and peerCerts from previous state
  591. hs.masterSecret = hs.session.masterSecret
  592. c.peerCertificates = hs.session.serverCertificates
  593. c.verifiedChains = hs.session.verifiedChains
  594. // [Psiphon]
  595. c.extendedMasterSecret = hs.session.extendedMasterSecret
  596. return true, nil
  597. }
  598. func (hs *clientHandshakeState) readFinished(out []byte) error {
  599. c := hs.c
  600. c.readRecord(recordTypeChangeCipherSpec)
  601. if c.in.err != nil {
  602. return c.in.err
  603. }
  604. msg, err := c.readHandshake()
  605. if err != nil {
  606. return err
  607. }
  608. serverFinished, ok := msg.(*finishedMsg)
  609. if !ok {
  610. c.sendAlert(alertUnexpectedMessage)
  611. return unexpectedMessageError(serverFinished, msg)
  612. }
  613. verify := hs.finishedHash.serverSum(hs.masterSecret)
  614. if len(verify) != len(serverFinished.verifyData) ||
  615. subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
  616. c.sendAlert(alertHandshakeFailure)
  617. return errors.New("tls: server's Finished message was incorrect")
  618. }
  619. hs.finishedHash.Write(serverFinished.marshal())
  620. copy(out, verify)
  621. return nil
  622. }
  623. func (hs *clientHandshakeState) readSessionTicket() error {
  624. if !hs.serverHello.ticketSupported {
  625. return nil
  626. }
  627. c := hs.c
  628. msg, err := c.readHandshake()
  629. if err != nil {
  630. return err
  631. }
  632. sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
  633. if !ok {
  634. c.sendAlert(alertUnexpectedMessage)
  635. return unexpectedMessageError(sessionTicketMsg, msg)
  636. }
  637. hs.finishedHash.Write(sessionTicketMsg.marshal())
  638. hs.session = &ClientSessionState{
  639. sessionTicket: sessionTicketMsg.ticket,
  640. vers: c.vers,
  641. cipherSuite: hs.suite.id,
  642. masterSecret: hs.masterSecret,
  643. serverCertificates: c.peerCertificates,
  644. verifiedChains: c.verifiedChains,
  645. }
  646. return nil
  647. }
  648. func (hs *clientHandshakeState) sendFinished(out []byte) error {
  649. c := hs.c
  650. if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
  651. return err
  652. }
  653. if hs.serverHello.nextProtoNeg {
  654. nextProto := new(nextProtoMsg)
  655. proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.nextProtos)
  656. nextProto.proto = proto
  657. c.clientProtocol = proto
  658. c.clientProtocolFallback = fallback
  659. hs.finishedHash.Write(nextProto.marshal())
  660. if _, err := c.writeRecord(recordTypeHandshake, nextProto.marshal()); err != nil {
  661. return err
  662. }
  663. }
  664. finished := new(finishedMsg)
  665. finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
  666. hs.finishedHash.Write(finished.marshal())
  667. if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
  668. return err
  669. }
  670. copy(out, finished.verifyData)
  671. return nil
  672. }
  673. // tls11SignatureSchemes contains the signature schemes that we synthesise for
  674. // a TLS <= 1.1 connection, based on the supported certificate types.
  675. var tls11SignatureSchemes = []SignatureScheme{ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1}
  676. const (
  677. // tls11SignatureSchemesNumECDSA is the number of initial elements of
  678. // tls11SignatureSchemes that use ECDSA.
  679. tls11SignatureSchemesNumECDSA = 3
  680. // tls11SignatureSchemesNumRSA is the number of trailing elements of
  681. // tls11SignatureSchemes that use RSA.
  682. tls11SignatureSchemesNumRSA = 4
  683. )
  684. func (hs *clientHandshakeState) getCertificate(certReq *certificateRequestMsg) (*Certificate, error) {
  685. c := hs.c
  686. var rsaAvail, ecdsaAvail bool
  687. for _, certType := range certReq.certificateTypes {
  688. switch certType {
  689. case certTypeRSASign:
  690. rsaAvail = true
  691. case certTypeECDSASign:
  692. ecdsaAvail = true
  693. }
  694. }
  695. if c.config.GetClientCertificate != nil {
  696. var signatureSchemes []SignatureScheme
  697. if !certReq.hasSignatureAndHash {
  698. // Prior to TLS 1.2, the signature schemes were not
  699. // included in the certificate request message. In this
  700. // case we use a plausible list based on the acceptable
  701. // certificate types.
  702. signatureSchemes = tls11SignatureSchemes
  703. if !ecdsaAvail {
  704. signatureSchemes = signatureSchemes[tls11SignatureSchemesNumECDSA:]
  705. }
  706. if !rsaAvail {
  707. signatureSchemes = signatureSchemes[:len(signatureSchemes)-tls11SignatureSchemesNumRSA]
  708. }
  709. } else {
  710. signatureSchemes = make([]SignatureScheme, 0, len(certReq.signatureAndHashes))
  711. for _, sah := range certReq.signatureAndHashes {
  712. signatureSchemes = append(signatureSchemes, SignatureScheme(sah.hash)<<8+SignatureScheme(sah.signature))
  713. }
  714. }
  715. return c.config.GetClientCertificate(&CertificateRequestInfo{
  716. AcceptableCAs: certReq.certificateAuthorities,
  717. SignatureSchemes: signatureSchemes,
  718. })
  719. }
  720. // RFC 4346 on the certificateAuthorities field: A list of the
  721. // distinguished names of acceptable certificate authorities.
  722. // These distinguished names may specify a desired
  723. // distinguished name for a root CA or for a subordinate CA;
  724. // thus, this message can be used to describe both known roots
  725. // and a desired authorization space. If the
  726. // certificate_authorities list is empty then the client MAY
  727. // send any certificate of the appropriate
  728. // ClientCertificateType, unless there is some external
  729. // arrangement to the contrary.
  730. // We need to search our list of client certs for one
  731. // where SignatureAlgorithm is acceptable to the server and the
  732. // Issuer is in certReq.certificateAuthorities
  733. findCert:
  734. for i, chain := range c.config.Certificates {
  735. if !rsaAvail && !ecdsaAvail {
  736. continue
  737. }
  738. for j, cert := range chain.Certificate {
  739. x509Cert := chain.Leaf
  740. // parse the certificate if this isn't the leaf
  741. // node, or if chain.Leaf was nil
  742. if j != 0 || x509Cert == nil {
  743. var err error
  744. if x509Cert, err = x509.ParseCertificate(cert); err != nil {
  745. c.sendAlert(alertInternalError)
  746. return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
  747. }
  748. }
  749. switch {
  750. case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
  751. case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
  752. default:
  753. continue findCert
  754. }
  755. if len(certReq.certificateAuthorities) == 0 {
  756. // they gave us an empty list, so just take the
  757. // first cert from c.config.Certificates
  758. return &chain, nil
  759. }
  760. for _, ca := range certReq.certificateAuthorities {
  761. if bytes.Equal(x509Cert.RawIssuer, ca) {
  762. return &chain, nil
  763. }
  764. }
  765. }
  766. }
  767. // No acceptable certificate found. Don't send a certificate.
  768. return new(Certificate), nil
  769. }
  770. // clientSessionCacheKey returns a key used to cache sessionTickets that could
  771. // be used to resume previously negotiated TLS sessions with a server.
  772. func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
  773. if len(config.ServerName) > 0 {
  774. return config.ServerName
  775. }
  776. return serverAddr.String()
  777. }
  778. // mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
  779. // given list of possible protocols and a list of the preference order. The
  780. // first list must not be empty. It returns the resulting protocol and flag
  781. // indicating if the fallback case was reached.
  782. func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
  783. for _, s := range preferenceProtos {
  784. for _, c := range protos {
  785. if s == c {
  786. return s, false
  787. }
  788. }
  789. }
  790. return protos[0], true
  791. }
  792. // hostnameInSNI converts name into an approriate hostname for SNI.
  793. // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
  794. // See https://tools.ietf.org/html/rfc6066#section-3.
  795. func hostnameInSNI(name string) string {
  796. host := name
  797. if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
  798. host = host[1 : len(host)-1]
  799. }
  800. if i := strings.LastIndex(host, "%"); i > 0 {
  801. host = host[:i]
  802. }
  803. if net.ParseIP(host) != nil {
  804. return ""
  805. }
  806. if len(name) > 0 && name[len(name)-1] == '.' {
  807. name = name[:len(name)-1]
  808. }
  809. return name
  810. }