handshake_client.go 34 KB

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