handshake_client.go 42 KB

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