handshake_client.go 27 KB

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