handshake_client.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  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. "context"
  8. "crypto"
  9. "crypto/ecdh"
  10. "crypto/ecdsa"
  11. "crypto/ed25519"
  12. "crypto/rsa"
  13. "crypto/subtle"
  14. "crypto/x509"
  15. "errors"
  16. "fmt"
  17. "hash"
  18. "io"
  19. "net"
  20. "strings"
  21. "time"
  22. )
  23. type clientHandshakeState struct {
  24. c *Conn
  25. ctx context.Context
  26. serverHello *serverHelloMsg
  27. hello *clientHelloMsg
  28. suite *cipherSuite
  29. finishedHash finishedHash
  30. masterSecret []byte
  31. session *SessionState // the session being resumed
  32. ticket []byte // a fresh ticket received during this handshake
  33. }
  34. var testingOnlyForceClientHelloSignatureAlgorithms []SignatureScheme
  35. func (c *Conn) makeClientHello() (*clientHelloMsg, *ecdh.PrivateKey, error) {
  36. config := c.config
  37. if len(config.ServerName) == 0 && !config.InsecureSkipVerify {
  38. return nil, nil, errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
  39. }
  40. nextProtosLength := 0
  41. for _, proto := range config.NextProtos {
  42. if l := len(proto); l == 0 || l > 255 {
  43. return nil, nil, errors.New("tls: invalid NextProtos value")
  44. } else {
  45. nextProtosLength += 1 + l
  46. }
  47. }
  48. if nextProtosLength > 0xffff {
  49. return nil, nil, errors.New("tls: NextProtos values too large")
  50. }
  51. supportedVersions := config.supportedVersions(roleClient)
  52. if len(supportedVersions) == 0 {
  53. return nil, nil, errors.New("tls: no supported versions satisfy MinVersion and MaxVersion")
  54. }
  55. clientHelloVersion := config.maxSupportedVersion(roleClient)
  56. // The version at the beginning of the ClientHello was capped at TLS 1.2
  57. // for compatibility reasons. The supported_versions extension is used
  58. // to negotiate versions now. See RFC 8446, Section 4.2.1.
  59. if clientHelloVersion > VersionTLS12 {
  60. clientHelloVersion = VersionTLS12
  61. }
  62. hello := &clientHelloMsg{
  63. vers: clientHelloVersion,
  64. compressionMethods: []uint8{compressionNone},
  65. random: make([]byte, 32),
  66. extendedMasterSecret: true,
  67. ocspStapling: true,
  68. scts: true,
  69. serverName: hostnameInSNI(config.ServerName),
  70. supportedCurves: config.curvePreferences(),
  71. supportedPoints: []uint8{pointFormatUncompressed},
  72. secureRenegotiationSupported: true,
  73. alpnProtocols: config.NextProtos,
  74. supportedVersions: supportedVersions,
  75. }
  76. // [Psiphon]
  77. // TODO! is extraConfig check necessary/
  78. if c.config != nil {
  79. hello.PRNG = c.config.ClientHelloPRNG
  80. if c.config.GetClientHelloRandom != nil {
  81. helloRandom, err := c.config.GetClientHelloRandom()
  82. if err == nil && len(helloRandom) != 32 {
  83. err = errors.New("invalid length")
  84. }
  85. if err != nil {
  86. return nil, nil, errors.New("tls: GetClientHelloRandom failed: " + err.Error())
  87. }
  88. copy(hello.random, helloRandom)
  89. }
  90. }
  91. if c.handshakes > 0 {
  92. hello.secureRenegotiation = c.clientFinished[:]
  93. }
  94. preferenceOrder := cipherSuitesPreferenceOrder
  95. if !hasAESGCMHardwareSupport {
  96. preferenceOrder = cipherSuitesPreferenceOrderNoAES
  97. }
  98. configCipherSuites := config.cipherSuites()
  99. hello.cipherSuites = make([]uint16, 0, len(configCipherSuites))
  100. for _, suiteId := range preferenceOrder {
  101. suite := mutualCipherSuite(configCipherSuites, suiteId)
  102. if suite == nil {
  103. continue
  104. }
  105. // Don't advertise TLS 1.2-only cipher suites unless
  106. // we're attempting TLS 1.2.
  107. if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
  108. continue
  109. }
  110. hello.cipherSuites = append(hello.cipherSuites, suiteId)
  111. }
  112. // [Psiphon]
  113. // TODO! is config != nil check necessary?
  114. var err error
  115. if c.config == nil || c.config.GetClientHelloRandom == nil {
  116. _, err := io.ReadFull(config.rand(), hello.random)
  117. if err != nil {
  118. return nil, nil, errors.New("tls: short read from Rand: " + err.Error())
  119. }
  120. }
  121. // A random session ID is used to detect when the server accepted a ticket
  122. // and is resuming a session (see RFC 5077). In TLS 1.3, it's always set as
  123. // a compatibility measure (see RFC 8446, Section 4.1.2).
  124. //
  125. // The session ID is not set for QUIC connections (see RFC 9001, Section 8.4).
  126. if c.quic == nil {
  127. hello.sessionId = make([]byte, 32)
  128. if _, err := io.ReadFull(config.rand(), hello.sessionId); err != nil {
  129. return nil, nil, errors.New("tls: short read from Rand: " + err.Error())
  130. }
  131. }
  132. if hello.vers >= VersionTLS12 {
  133. hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
  134. }
  135. if testingOnlyForceClientHelloSignatureAlgorithms != nil {
  136. hello.supportedSignatureAlgorithms = testingOnlyForceClientHelloSignatureAlgorithms
  137. }
  138. var key *ecdh.PrivateKey
  139. if hello.supportedVersions[0] == VersionTLS13 {
  140. // Reset the list of ciphers when the client only supports TLS 1.3.
  141. if len(hello.supportedVersions) == 1 {
  142. hello.cipherSuites = nil
  143. }
  144. if needFIPS() {
  145. hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13FIPS...)
  146. } else if hasAESGCMHardwareSupport {
  147. hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13...)
  148. } else {
  149. hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13NoAES...)
  150. }
  151. curveID := config.curvePreferences()[0]
  152. if _, ok := curveForCurveID(curveID); !ok {
  153. return nil, nil, errors.New("tls: CurvePreferences includes unsupported curve")
  154. }
  155. key, err = generateECDHEKey(config.rand(), curveID)
  156. if err != nil {
  157. return nil, nil, err
  158. }
  159. hello.keyShares = []keyShare{{group: curveID, data: key.PublicKey().Bytes()}}
  160. }
  161. if c.quic != nil {
  162. p, err := c.quicGetTransportParameters()
  163. if err != nil {
  164. return nil, nil, err
  165. }
  166. if p == nil {
  167. p = []byte{}
  168. }
  169. hello.quicTransportParameters = p
  170. }
  171. return hello, key, nil
  172. }
  173. func (c *Conn) clientHandshake(ctx context.Context) (err error) {
  174. if c.config == nil {
  175. c.config = defaultConfig()
  176. }
  177. // This may be a renegotiation handshake, in which case some fields
  178. // need to be reset.
  179. c.didResume = false
  180. hello, ecdheKey, err := c.makeClientHello()
  181. if err != nil {
  182. return err
  183. }
  184. c.serverName = hello.serverName
  185. session, earlySecret, binderKey, err := c.loadSession(hello)
  186. if err != nil {
  187. return err
  188. }
  189. if session != nil {
  190. defer func() {
  191. // If we got a handshake failure when resuming a session, throw away
  192. // the session ticket. See RFC 5077, Section 3.2.
  193. //
  194. // RFC 8446 makes no mention of dropping tickets on failure, but it
  195. // does require servers to abort on invalid binders, so we need to
  196. // delete tickets to recover from a corrupted PSK.
  197. if err != nil {
  198. if cacheKey := c.clientSessionCacheKey(); cacheKey != "" {
  199. c.config.ClientSessionCache.Put(cacheKey, nil)
  200. }
  201. }
  202. }()
  203. }
  204. if _, err := c.writeHandshakeRecord(hello, nil); err != nil {
  205. return err
  206. }
  207. if hello.earlyData {
  208. suite := cipherSuiteTLS13ByID(session.cipherSuite)
  209. transcript := suite.hash.New()
  210. if err := transcriptMsg(hello, transcript); err != nil {
  211. return err
  212. }
  213. earlyTrafficSecret := suite.deriveSecret(earlySecret, clientEarlyTrafficLabel, transcript)
  214. c.quicSetWriteSecret(QUICEncryptionLevelEarly, suite.id, earlyTrafficSecret)
  215. }
  216. // serverHelloMsg is not included in the transcript
  217. msg, err := c.readHandshake(nil)
  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. if err := c.pickTLSVersion(serverHello); err != nil {
  227. return err
  228. }
  229. // If we are negotiating a protocol version that's lower than what we
  230. // support, check for the server downgrade canaries.
  231. // See RFC 8446, Section 4.1.3.
  232. maxVers := c.config.maxSupportedVersion(roleClient)
  233. tls12Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS12
  234. tls11Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS11
  235. if maxVers == VersionTLS13 && c.vers <= VersionTLS12 && (tls12Downgrade || tls11Downgrade) ||
  236. maxVers == VersionTLS12 && c.vers <= VersionTLS11 && tls11Downgrade {
  237. c.sendAlert(alertIllegalParameter)
  238. return errors.New("tls: downgrade attempt detected, possibly due to a MitM attack or a broken middlebox")
  239. }
  240. if c.vers == VersionTLS13 {
  241. hs := &clientHandshakeStateTLS13{
  242. c: c,
  243. ctx: ctx,
  244. serverHello: serverHello,
  245. hello: hello,
  246. ecdheKey: ecdheKey,
  247. session: session,
  248. earlySecret: earlySecret,
  249. binderKey: binderKey,
  250. }
  251. // In TLS 1.3, session tickets are delivered after the handshake.
  252. return hs.handshake()
  253. }
  254. hs := &clientHandshakeState{
  255. c: c,
  256. ctx: ctx,
  257. serverHello: serverHello,
  258. hello: hello,
  259. session: session,
  260. }
  261. if err := hs.handshake(); err != nil {
  262. return err
  263. }
  264. return nil
  265. }
  266. func (c *Conn) loadSession(hello *clientHelloMsg) (
  267. session *SessionState, earlySecret, binderKey []byte, err error) {
  268. if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
  269. return nil, nil, nil, nil
  270. }
  271. hello.ticketSupported = true
  272. if hello.supportedVersions[0] == VersionTLS13 {
  273. // Require DHE on resumption as it guarantees forward secrecy against
  274. // compromise of the session ticket key. See RFC 8446, Section 4.2.9.
  275. hello.pskModes = []uint8{pskModeDHE}
  276. }
  277. // Session resumption is not allowed if renegotiating because
  278. // renegotiation is primarily used to allow a client to send a client
  279. // certificate, which would be skipped if session resumption occurred.
  280. if c.handshakes != 0 {
  281. return nil, nil, nil, nil
  282. }
  283. // Try to resume a previously negotiated TLS session, if available.
  284. cacheKey := c.clientSessionCacheKey()
  285. if cacheKey == "" {
  286. return nil, nil, nil, nil
  287. }
  288. cs, ok := c.config.ClientSessionCache.Get(cacheKey)
  289. if !ok || cs == nil {
  290. return nil, nil, nil, nil
  291. }
  292. session = cs.session
  293. // Check that version used for the previous session is still valid.
  294. versOk := false
  295. for _, v := range hello.supportedVersions {
  296. if v == session.version {
  297. versOk = true
  298. break
  299. }
  300. }
  301. if !versOk {
  302. return nil, nil, nil, nil
  303. }
  304. // Check that the cached server certificate is not expired, and that it's
  305. // valid for the ServerName. This should be ensured by the cache key, but
  306. // protect the application from a faulty ClientSessionCache implementation.
  307. if c.config.time().After(session.peerCertificates[0].NotAfter) {
  308. // Expired certificate, delete the entry.
  309. c.config.ClientSessionCache.Put(cacheKey, nil)
  310. return nil, nil, nil, nil
  311. }
  312. if !c.config.InsecureSkipVerify {
  313. if len(session.verifiedChains) == 0 {
  314. // The original connection had InsecureSkipVerify, while this doesn't.
  315. return nil, nil, nil, nil
  316. }
  317. if err := session.peerCertificates[0].VerifyHostname(c.config.ServerName); err != nil {
  318. return nil, nil, nil, nil
  319. }
  320. }
  321. if session.version != VersionTLS13 {
  322. // In TLS 1.2 the cipher suite must match the resumed session. Ensure we
  323. // are still offering it.
  324. if mutualCipherSuite(hello.cipherSuites, session.cipherSuite) == nil {
  325. return nil, nil, nil, nil
  326. }
  327. hello.sessionTicket = cs.ticket
  328. return
  329. }
  330. // Check that the session ticket is not expired.
  331. if c.config.time().After(time.Unix(int64(session.useBy), 0)) {
  332. c.config.ClientSessionCache.Put(cacheKey, nil)
  333. return nil, nil, nil, nil
  334. }
  335. // In TLS 1.3 the KDF hash must match the resumed session. Ensure we
  336. // offer at least one cipher suite with that hash.
  337. cipherSuite := cipherSuiteTLS13ByID(session.cipherSuite)
  338. if cipherSuite == nil {
  339. return nil, nil, nil, nil
  340. }
  341. cipherSuiteOk := false
  342. for _, offeredID := range hello.cipherSuites {
  343. offeredSuite := cipherSuiteTLS13ByID(offeredID)
  344. if offeredSuite != nil && offeredSuite.hash == cipherSuite.hash {
  345. cipherSuiteOk = true
  346. break
  347. }
  348. }
  349. if !cipherSuiteOk {
  350. return nil, nil, nil, nil
  351. }
  352. if c.quic != nil && session.EarlyData {
  353. // For 0-RTT, the cipher suite has to match exactly, and we need to be
  354. // offering the same ALPN.
  355. if mutualCipherSuiteTLS13(hello.cipherSuites, session.cipherSuite) != nil {
  356. for _, alpn := range hello.alpnProtocols {
  357. if alpn == session.alpnProtocol {
  358. hello.earlyData = true
  359. break
  360. }
  361. }
  362. }
  363. }
  364. // Set the pre_shared_key extension. See RFC 8446, Section 4.2.11.1.
  365. ticketAge := c.config.time().Sub(time.Unix(int64(session.createdAt), 0))
  366. identity := pskIdentity{
  367. label: cs.ticket,
  368. obfuscatedTicketAge: uint32(ticketAge/time.Millisecond) + session.ageAdd,
  369. }
  370. hello.pskIdentities = []pskIdentity{identity}
  371. hello.pskBinders = [][]byte{make([]byte, cipherSuite.hash.Size())}
  372. // Compute the PSK binders. See RFC 8446, Section 4.2.11.2.
  373. earlySecret = cipherSuite.extract(session.secret, nil)
  374. binderKey = cipherSuite.deriveSecret(earlySecret, resumptionBinderLabel, nil)
  375. transcript := cipherSuite.hash.New()
  376. helloBytes, err := hello.marshalWithoutBinders()
  377. if err != nil {
  378. return nil, nil, nil, err
  379. }
  380. transcript.Write(helloBytes)
  381. pskBinders := [][]byte{cipherSuite.finishedHash(binderKey, transcript)}
  382. if err := hello.updateBinders(pskBinders); err != nil {
  383. return nil, nil, nil, err
  384. }
  385. return
  386. }
  387. func (c *Conn) pickTLSVersion(serverHello *serverHelloMsg) error {
  388. peerVersion := serverHello.vers
  389. if serverHello.supportedVersion != 0 {
  390. peerVersion = serverHello.supportedVersion
  391. }
  392. vers, ok := c.config.mutualVersion(roleClient, []uint16{peerVersion})
  393. if !ok {
  394. c.sendAlert(alertProtocolVersion)
  395. return fmt.Errorf("tls: server selected unsupported protocol version %x", peerVersion)
  396. }
  397. c.vers = vers
  398. c.haveVers = true
  399. c.in.version = vers
  400. c.out.version = vers
  401. return nil
  402. }
  403. // Does the handshake, either a full one or resumes old session. Requires hs.c,
  404. // hs.hello, hs.serverHello, and, optionally, hs.session to be set.
  405. func (hs *clientHandshakeState) handshake() error {
  406. c := hs.c
  407. isResume, err := hs.processServerHello()
  408. if err != nil {
  409. return err
  410. }
  411. hs.finishedHash = newFinishedHash(c.vers, hs.suite)
  412. // No signatures of the handshake are needed in a resumption.
  413. // Otherwise, in a full handshake, if we don't have any certificates
  414. // configured then we will never send a CertificateVerify message and
  415. // thus no signatures are needed in that case either.
  416. if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
  417. hs.finishedHash.discardHandshakeBuffer()
  418. }
  419. if err := transcriptMsg(hs.hello, &hs.finishedHash); err != nil {
  420. return err
  421. }
  422. if err := transcriptMsg(hs.serverHello, &hs.finishedHash); err != nil {
  423. return err
  424. }
  425. c.buffering = true
  426. c.didResume = isResume
  427. if isResume {
  428. if err := hs.establishKeys(); err != nil {
  429. return err
  430. }
  431. if err := hs.readSessionTicket(); err != nil {
  432. return err
  433. }
  434. if err := hs.readFinished(c.serverFinished[:]); err != nil {
  435. return err
  436. }
  437. c.clientFinishedIsFirst = false
  438. // Make sure the connection is still being verified whether or not this
  439. // is a resumption. Resumptions currently don't reverify certificates so
  440. // they don't call verifyServerCertificate. See Issue 31641.
  441. if c.config.VerifyConnection != nil {
  442. if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
  443. c.sendAlert(alertBadCertificate)
  444. return err
  445. }
  446. }
  447. if err := hs.sendFinished(c.clientFinished[:]); err != nil {
  448. return err
  449. }
  450. if _, err := c.flush(); err != nil {
  451. return err
  452. }
  453. } else {
  454. if err := hs.doFullHandshake(); err != nil {
  455. return err
  456. }
  457. if err := hs.establishKeys(); err != nil {
  458. return err
  459. }
  460. if err := hs.sendFinished(c.clientFinished[:]); err != nil {
  461. return err
  462. }
  463. if _, err := c.flush(); err != nil {
  464. return err
  465. }
  466. c.clientFinishedIsFirst = true
  467. if err := hs.readSessionTicket(); err != nil {
  468. return err
  469. }
  470. if err := hs.readFinished(c.serverFinished[:]); err != nil {
  471. return err
  472. }
  473. }
  474. if err := hs.saveSessionTicket(); err != nil {
  475. return err
  476. }
  477. c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random)
  478. c.isHandshakeComplete.Store(true)
  479. return nil
  480. }
  481. func (hs *clientHandshakeState) pickCipherSuite() error {
  482. if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil {
  483. hs.c.sendAlert(alertHandshakeFailure)
  484. return errors.New("tls: server chose an unconfigured cipher suite")
  485. }
  486. hs.c.cipherSuite = hs.suite.id
  487. return nil
  488. }
  489. func (hs *clientHandshakeState) doFullHandshake() error {
  490. c := hs.c
  491. msg, err := c.readHandshake(&hs.finishedHash)
  492. if err != nil {
  493. return err
  494. }
  495. certMsg, ok := msg.(*certificateMsg)
  496. if !ok || len(certMsg.certificates) == 0 {
  497. c.sendAlert(alertUnexpectedMessage)
  498. return unexpectedMessageError(certMsg, msg)
  499. }
  500. msg, err = c.readHandshake(&hs.finishedHash)
  501. if err != nil {
  502. return err
  503. }
  504. cs, ok := msg.(*certificateStatusMsg)
  505. if ok {
  506. // RFC4366 on Certificate Status Request:
  507. // The server MAY return a "certificate_status" message.
  508. if !hs.serverHello.ocspStapling {
  509. // If a server returns a "CertificateStatus" message, then the
  510. // server MUST have included an extension of type "status_request"
  511. // with empty "extension_data" in the extended server hello.
  512. c.sendAlert(alertUnexpectedMessage)
  513. return errors.New("tls: received unexpected CertificateStatus message")
  514. }
  515. c.ocspResponse = cs.response
  516. msg, err = c.readHandshake(&hs.finishedHash)
  517. if err != nil {
  518. return err
  519. }
  520. }
  521. if c.handshakes == 0 {
  522. // If this is the first handshake on a connection, process and
  523. // (optionally) verify the server's certificates.
  524. if err := c.verifyServerCertificate(certMsg.certificates); err != nil {
  525. return err
  526. }
  527. } else {
  528. // This is a renegotiation handshake. We require that the
  529. // server's identity (i.e. leaf certificate) is unchanged and
  530. // thus any previous trust decision is still valid.
  531. //
  532. // See https://mitls.org/pages/attacks/3SHAKE for the
  533. // motivation behind this requirement.
  534. if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
  535. c.sendAlert(alertBadCertificate)
  536. return errors.New("tls: server's identity changed during renegotiation")
  537. }
  538. }
  539. keyAgreement := hs.suite.ka(c.vers)
  540. skx, ok := msg.(*serverKeyExchangeMsg)
  541. if ok {
  542. err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
  543. if err != nil {
  544. c.sendAlert(alertUnexpectedMessage)
  545. return err
  546. }
  547. msg, err = c.readHandshake(&hs.finishedHash)
  548. if err != nil {
  549. return err
  550. }
  551. }
  552. var chainToSend *Certificate
  553. var certRequested bool
  554. certReq, ok := msg.(*certificateRequestMsg)
  555. if ok {
  556. certRequested = true
  557. cri := certificateRequestInfoFromMsg(hs.ctx, c.vers, certReq)
  558. if chainToSend, err = c.getClientCertificate(cri); err != nil {
  559. c.sendAlert(alertInternalError)
  560. return err
  561. }
  562. msg, err = c.readHandshake(&hs.finishedHash)
  563. if err != nil {
  564. return err
  565. }
  566. }
  567. shd, ok := msg.(*serverHelloDoneMsg)
  568. if !ok {
  569. c.sendAlert(alertUnexpectedMessage)
  570. return unexpectedMessageError(shd, msg)
  571. }
  572. // If the server requested a certificate then we have to send a
  573. // Certificate message, even if it's empty because we don't have a
  574. // certificate to send.
  575. if certRequested {
  576. certMsg = new(certificateMsg)
  577. certMsg.certificates = chainToSend.Certificate
  578. if _, err := hs.c.writeHandshakeRecord(certMsg, &hs.finishedHash); err != nil {
  579. return err
  580. }
  581. }
  582. preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
  583. if err != nil {
  584. c.sendAlert(alertInternalError)
  585. return err
  586. }
  587. if ckx != nil {
  588. if _, err := hs.c.writeHandshakeRecord(ckx, &hs.finishedHash); err != nil {
  589. return err
  590. }
  591. }
  592. if hs.serverHello.extendedMasterSecret {
  593. c.extMasterSecret = true
  594. hs.masterSecret = extMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret,
  595. hs.finishedHash.Sum())
  596. } else {
  597. hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret,
  598. hs.hello.random, hs.serverHello.random)
  599. }
  600. if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.hello.random, hs.masterSecret); err != nil {
  601. c.sendAlert(alertInternalError)
  602. return errors.New("tls: failed to write to key log: " + err.Error())
  603. }
  604. if chainToSend != nil && len(chainToSend.Certificate) > 0 {
  605. certVerify := &certificateVerifyMsg{}
  606. key, ok := chainToSend.PrivateKey.(crypto.Signer)
  607. if !ok {
  608. c.sendAlert(alertInternalError)
  609. return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
  610. }
  611. var sigType uint8
  612. var sigHash crypto.Hash
  613. if c.vers >= VersionTLS12 {
  614. signatureAlgorithm, err := selectSignatureScheme(c.vers, chainToSend, certReq.supportedSignatureAlgorithms)
  615. if err != nil {
  616. c.sendAlert(alertIllegalParameter)
  617. return err
  618. }
  619. sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm)
  620. if err != nil {
  621. return c.sendAlert(alertInternalError)
  622. }
  623. certVerify.hasSignatureAlgorithm = true
  624. certVerify.signatureAlgorithm = signatureAlgorithm
  625. } else {
  626. sigType, sigHash, err = legacyTypeAndHashFromPublicKey(key.Public())
  627. if err != nil {
  628. c.sendAlert(alertIllegalParameter)
  629. return err
  630. }
  631. }
  632. signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash)
  633. signOpts := crypto.SignerOpts(sigHash)
  634. if sigType == signatureRSAPSS {
  635. signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
  636. }
  637. certVerify.signature, err = key.Sign(c.config.rand(), signed, signOpts)
  638. if err != nil {
  639. c.sendAlert(alertInternalError)
  640. return err
  641. }
  642. if _, err := hs.c.writeHandshakeRecord(certVerify, &hs.finishedHash); err != nil {
  643. return err
  644. }
  645. }
  646. hs.finishedHash.discardHandshakeBuffer()
  647. return nil
  648. }
  649. func (hs *clientHandshakeState) establishKeys() error {
  650. c := hs.c
  651. clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
  652. keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
  653. var clientCipher, serverCipher any
  654. var clientHash, serverHash hash.Hash
  655. if hs.suite.cipher != nil {
  656. clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
  657. clientHash = hs.suite.mac(clientMAC)
  658. serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
  659. serverHash = hs.suite.mac(serverMAC)
  660. } else {
  661. clientCipher = hs.suite.aead(clientKey, clientIV)
  662. serverCipher = hs.suite.aead(serverKey, serverIV)
  663. }
  664. c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
  665. c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
  666. return nil
  667. }
  668. func (hs *clientHandshakeState) serverResumedSession() bool {
  669. // If the server responded with the same sessionId then it means the
  670. // sessionTicket is being used to resume a TLS session.
  671. return hs.session != nil && hs.hello.sessionId != nil &&
  672. bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
  673. }
  674. func (hs *clientHandshakeState) processServerHello() (bool, error) {
  675. c := hs.c
  676. if err := hs.pickCipherSuite(); err != nil {
  677. return false, err
  678. }
  679. if hs.serverHello.compressionMethod != compressionNone {
  680. c.sendAlert(alertUnexpectedMessage)
  681. return false, errors.New("tls: server selected unsupported compression format")
  682. }
  683. if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
  684. c.secureRenegotiation = true
  685. if len(hs.serverHello.secureRenegotiation) != 0 {
  686. c.sendAlert(alertHandshakeFailure)
  687. return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
  688. }
  689. }
  690. if c.handshakes > 0 && c.secureRenegotiation {
  691. var expectedSecureRenegotiation [24]byte
  692. copy(expectedSecureRenegotiation[:], c.clientFinished[:])
  693. copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
  694. if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
  695. c.sendAlert(alertHandshakeFailure)
  696. return false, errors.New("tls: incorrect renegotiation extension contents")
  697. }
  698. }
  699. if err := checkALPN(hs.hello.alpnProtocols, hs.serverHello.alpnProtocol, false); err != nil {
  700. c.sendAlert(alertUnsupportedExtension)
  701. return false, err
  702. }
  703. c.clientProtocol = hs.serverHello.alpnProtocol
  704. c.scts = hs.serverHello.scts
  705. if !hs.serverResumedSession() {
  706. return false, nil
  707. }
  708. if hs.session.version != c.vers {
  709. c.sendAlert(alertHandshakeFailure)
  710. return false, errors.New("tls: server resumed a session with a different version")
  711. }
  712. if hs.session.cipherSuite != hs.suite.id {
  713. c.sendAlert(alertHandshakeFailure)
  714. return false, errors.New("tls: server resumed a session with a different cipher suite")
  715. }
  716. // RFC 7627, Section 5.3
  717. if hs.session.extMasterSecret != hs.serverHello.extendedMasterSecret {
  718. c.sendAlert(alertHandshakeFailure)
  719. return false, errors.New("tls: server resumed a session with a different EMS extension")
  720. }
  721. // Restore master secret and certificates from previous state
  722. hs.masterSecret = hs.session.secret
  723. c.extMasterSecret = hs.session.extMasterSecret
  724. c.peerCertificates = hs.session.peerCertificates
  725. c.activeCertHandles = hs.c.activeCertHandles
  726. c.verifiedChains = hs.session.verifiedChains
  727. c.ocspResponse = hs.session.ocspResponse
  728. // Let the ServerHello SCTs override the session SCTs from the original
  729. // connection, if any are provided
  730. if len(c.scts) == 0 && len(hs.session.scts) != 0 {
  731. c.scts = hs.session.scts
  732. }
  733. return true, nil
  734. }
  735. // checkALPN ensure that the server's choice of ALPN protocol is compatible with
  736. // the protocols that we advertised in the Client Hello.
  737. func checkALPN(clientProtos []string, serverProto string, quic bool) error {
  738. if serverProto == "" {
  739. if quic && len(clientProtos) > 0 {
  740. // RFC 9001, Section 8.1
  741. return errors.New("tls: server did not select an ALPN protocol")
  742. }
  743. return nil
  744. }
  745. if len(clientProtos) == 0 {
  746. return errors.New("tls: server advertised unrequested ALPN extension")
  747. }
  748. for _, proto := range clientProtos {
  749. if proto == serverProto {
  750. return nil
  751. }
  752. }
  753. return errors.New("tls: server selected unadvertised ALPN protocol")
  754. }
  755. func (hs *clientHandshakeState) readFinished(out []byte) error {
  756. c := hs.c
  757. if err := c.readChangeCipherSpec(); err != nil {
  758. return err
  759. }
  760. // finishedMsg is included in the transcript, but not until after we
  761. // check the client version, since the state before this message was
  762. // sent is used during verification.
  763. msg, err := c.readHandshake(nil)
  764. if err != nil {
  765. return err
  766. }
  767. serverFinished, ok := msg.(*finishedMsg)
  768. if !ok {
  769. c.sendAlert(alertUnexpectedMessage)
  770. return unexpectedMessageError(serverFinished, msg)
  771. }
  772. verify := hs.finishedHash.serverSum(hs.masterSecret)
  773. if len(verify) != len(serverFinished.verifyData) ||
  774. subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
  775. c.sendAlert(alertHandshakeFailure)
  776. return errors.New("tls: server's Finished message was incorrect")
  777. }
  778. if err := transcriptMsg(serverFinished, &hs.finishedHash); err != nil {
  779. return err
  780. }
  781. copy(out, verify)
  782. return nil
  783. }
  784. func (hs *clientHandshakeState) readSessionTicket() error {
  785. if !hs.serverHello.ticketSupported {
  786. return nil
  787. }
  788. c := hs.c
  789. if !hs.hello.ticketSupported {
  790. c.sendAlert(alertIllegalParameter)
  791. return errors.New("tls: server sent unrequested session ticket")
  792. }
  793. msg, err := c.readHandshake(&hs.finishedHash)
  794. if err != nil {
  795. return err
  796. }
  797. sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
  798. if !ok {
  799. c.sendAlert(alertUnexpectedMessage)
  800. return unexpectedMessageError(sessionTicketMsg, msg)
  801. }
  802. hs.ticket = sessionTicketMsg.ticket
  803. return nil
  804. }
  805. func (hs *clientHandshakeState) saveSessionTicket() error {
  806. if hs.ticket == nil {
  807. return nil
  808. }
  809. c := hs.c
  810. cacheKey := c.clientSessionCacheKey()
  811. if cacheKey == "" {
  812. return nil
  813. }
  814. session, err := c.sessionState()
  815. if err != nil {
  816. return err
  817. }
  818. session.secret = hs.masterSecret
  819. cs := &ClientSessionState{ticket: hs.ticket, session: session}
  820. c.config.ClientSessionCache.Put(cacheKey, cs)
  821. return nil
  822. }
  823. func (hs *clientHandshakeState) sendFinished(out []byte) error {
  824. c := hs.c
  825. if err := c.writeChangeCipherRecord(); err != nil {
  826. return err
  827. }
  828. finished := new(finishedMsg)
  829. finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
  830. if _, err := hs.c.writeHandshakeRecord(finished, &hs.finishedHash); err != nil {
  831. return err
  832. }
  833. copy(out, finished.verifyData)
  834. return nil
  835. }
  836. // defaultMaxRSAKeySize is the maximum RSA key size in bits that we are willing
  837. // to verify the signatures of during a TLS handshake.
  838. const defaultMaxRSAKeySize = 8192
  839. func checkKeySize(n int) (max int, ok bool) {
  840. return defaultMaxRSAKeySize, n <= defaultMaxRSAKeySize
  841. }
  842. // verifyServerCertificate parses and verifies the provided chain, setting
  843. // c.verifiedChains and c.peerCertificates or sending the appropriate alert.
  844. func (c *Conn) verifyServerCertificate(certificates [][]byte) error {
  845. activeHandles := make([]*activeCert, len(certificates))
  846. certs := make([]*x509.Certificate, len(certificates))
  847. for i, asn1Data := range certificates {
  848. cert, err := globalCertCache.newCert(asn1Data)
  849. if err != nil {
  850. c.sendAlert(alertBadCertificate)
  851. return errors.New("tls: failed to parse certificate from server: " + err.Error())
  852. }
  853. if cert.cert.PublicKeyAlgorithm == x509.RSA {
  854. n := cert.cert.PublicKey.(*rsa.PublicKey).N.BitLen()
  855. if max, ok := checkKeySize(n); !ok {
  856. c.sendAlert(alertBadCertificate)
  857. return fmt.Errorf("tls: server sent certificate containing RSA key larger than %d bits", max)
  858. }
  859. }
  860. activeHandles[i] = cert
  861. certs[i] = cert.cert
  862. }
  863. if !c.config.InsecureSkipVerify {
  864. opts := x509.VerifyOptions{
  865. Roots: c.config.RootCAs,
  866. CurrentTime: c.config.time(),
  867. DNSName: c.config.ServerName,
  868. Intermediates: x509.NewCertPool(),
  869. }
  870. for _, cert := range certs[1:] {
  871. opts.Intermediates.AddCert(cert)
  872. }
  873. var err error
  874. c.verifiedChains, err = certs[0].Verify(opts)
  875. if err != nil {
  876. c.sendAlert(alertBadCertificate)
  877. return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err}
  878. }
  879. }
  880. switch certs[0].PublicKey.(type) {
  881. case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
  882. break
  883. default:
  884. c.sendAlert(alertUnsupportedCertificate)
  885. return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
  886. }
  887. c.activeCertHandles = activeHandles
  888. c.peerCertificates = certs
  889. if c.config.VerifyPeerCertificate != nil {
  890. if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
  891. c.sendAlert(alertBadCertificate)
  892. return err
  893. }
  894. }
  895. if c.config.VerifyConnection != nil {
  896. if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
  897. c.sendAlert(alertBadCertificate)
  898. return err
  899. }
  900. }
  901. return nil
  902. }
  903. // certificateRequestInfoFromMsg generates a CertificateRequestInfo from a TLS
  904. // <= 1.2 CertificateRequest, making an effort to fill in missing information.
  905. func certificateRequestInfoFromMsg(ctx context.Context, vers uint16, certReq *certificateRequestMsg) *CertificateRequestInfo {
  906. cri := &CertificateRequestInfo{
  907. AcceptableCAs: certReq.certificateAuthorities,
  908. Version: vers,
  909. ctx: ctx,
  910. }
  911. var rsaAvail, ecAvail bool
  912. for _, certType := range certReq.certificateTypes {
  913. switch certType {
  914. case certTypeRSASign:
  915. rsaAvail = true
  916. case certTypeECDSASign:
  917. ecAvail = true
  918. }
  919. }
  920. if !certReq.hasSignatureAlgorithm {
  921. // Prior to TLS 1.2, signature schemes did not exist. In this case we
  922. // make up a list based on the acceptable certificate types, to help
  923. // GetClientCertificate and SupportsCertificate select the right certificate.
  924. // The hash part of the SignatureScheme is a lie here, because
  925. // TLS 1.0 and 1.1 always use MD5+SHA1 for RSA and SHA1 for ECDSA.
  926. switch {
  927. case rsaAvail && ecAvail:
  928. cri.SignatureSchemes = []SignatureScheme{
  929. ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
  930. PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
  931. }
  932. case rsaAvail:
  933. cri.SignatureSchemes = []SignatureScheme{
  934. PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
  935. }
  936. case ecAvail:
  937. cri.SignatureSchemes = []SignatureScheme{
  938. ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
  939. }
  940. }
  941. return cri
  942. }
  943. // Filter the signature schemes based on the certificate types.
  944. // See RFC 5246, Section 7.4.4 (where it calls this "somewhat complicated").
  945. cri.SignatureSchemes = make([]SignatureScheme, 0, len(certReq.supportedSignatureAlgorithms))
  946. for _, sigScheme := range certReq.supportedSignatureAlgorithms {
  947. sigType, _, err := typeAndHashFromSignatureScheme(sigScheme)
  948. if err != nil {
  949. continue
  950. }
  951. switch sigType {
  952. case signatureECDSA, signatureEd25519:
  953. if ecAvail {
  954. cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
  955. }
  956. case signatureRSAPSS, signaturePKCS1v15:
  957. if rsaAvail {
  958. cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
  959. }
  960. }
  961. }
  962. return cri
  963. }
  964. func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, error) {
  965. if c.config.GetClientCertificate != nil {
  966. return c.config.GetClientCertificate(cri)
  967. }
  968. for _, chain := range c.config.Certificates {
  969. if err := cri.SupportsCertificate(&chain); err != nil {
  970. continue
  971. }
  972. return &chain, nil
  973. }
  974. // No acceptable certificate found. Don't send a certificate.
  975. return new(Certificate), nil
  976. }
  977. // clientSessionCacheKey returns a key used to cache sessionTickets that could
  978. // be used to resume previously negotiated TLS sessions with a server.
  979. func (c *Conn) clientSessionCacheKey() string {
  980. if len(c.config.ServerName) > 0 {
  981. return c.config.ServerName
  982. }
  983. if c.conn != nil {
  984. return c.conn.RemoteAddr().String()
  985. }
  986. return ""
  987. }
  988. // hostnameInSNI converts name into an appropriate hostname for SNI.
  989. // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
  990. // See RFC 6066, Section 3.
  991. func hostnameInSNI(name string) string {
  992. host := name
  993. if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
  994. host = host[1 : len(host)-1]
  995. }
  996. if i := strings.LastIndex(host, "%"); i > 0 {
  997. host = host[:i]
  998. }
  999. if net.ParseIP(host) != nil {
  1000. return ""
  1001. }
  1002. for len(name) > 0 && name[len(name)-1] == '.' {
  1003. name = name[:len(name)-1]
  1004. }
  1005. return name
  1006. }