handshake_client.go 40 KB

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