handshake_client.go 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400
  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. // [Psiphon]
  418. // Mitigate a race condition where utls.SessionTicketExtension.InitializeByUtls
  419. // mutates the shared cache entry. Only a shallow copy is required.
  420. sessionCopy := *session
  421. session = &sessionCopy
  422. // [Psiphon]
  423. // Check that version used for the previous session is still valid.
  424. versOk := false
  425. for _, v := range hello.supportedVersions {
  426. if v == session.version {
  427. versOk = true
  428. break
  429. }
  430. }
  431. if !versOk {
  432. return nil, nil, nil, nil
  433. }
  434. // Check that the cached server certificate is not expired, and that it's
  435. // valid for the ServerName. This should be ensured by the cache key, but
  436. // protect the application from a faulty ClientSessionCache implementation.
  437. if !c.config.InsecureSkipTimeVerify { // [UTLS]
  438. if c.config.time().After(session.peerCertificates[0].NotAfter) {
  439. // Expired certificate, delete the entry.
  440. c.config.ClientSessionCache.Put(cacheKey, nil)
  441. return nil, nil, nil, nil
  442. }
  443. }
  444. if !c.config.InsecureSkipVerify {
  445. if len(session.verifiedChains) == 0 {
  446. // The original connection had InsecureSkipVerify, while this doesn't.
  447. return nil, nil, nil, nil
  448. }
  449. // [UTLS SECTION START]
  450. var dnsName string
  451. if len(c.config.InsecureServerNameToVerify) == 0 {
  452. dnsName = c.config.ServerName
  453. } else if c.config.InsecureServerNameToVerify != "*" {
  454. dnsName = c.config.InsecureServerNameToVerify
  455. }
  456. if len(dnsName) > 0 {
  457. if err := session.peerCertificates[0].VerifyHostname(dnsName); err != nil {
  458. return nil, nil, nil, nil
  459. }
  460. }
  461. // [UTLS SECTION END]
  462. }
  463. if session.version != VersionTLS13 {
  464. // In TLS 1.2 the cipher suite must match the resumed session. Ensure we
  465. // are still offering it.
  466. if mutualCipherSuite(hello.cipherSuites, session.cipherSuite) == nil {
  467. return nil, nil, nil, nil
  468. }
  469. hello.sessionTicket = session.ticket
  470. return
  471. }
  472. // Check that the session ticket is not expired.
  473. if c.config.time().After(time.Unix(int64(session.useBy), 0)) {
  474. c.config.ClientSessionCache.Put(cacheKey, nil)
  475. return nil, nil, nil, nil
  476. }
  477. // In TLS 1.3 the KDF hash must match the resumed session. Ensure we
  478. // offer at least one cipher suite with that hash.
  479. cipherSuite := cipherSuiteTLS13ByID(session.cipherSuite)
  480. if cipherSuite == nil {
  481. return nil, nil, nil, nil
  482. }
  483. cipherSuiteOk := false
  484. for _, offeredID := range hello.cipherSuites {
  485. offeredSuite := cipherSuiteTLS13ByID(offeredID)
  486. if offeredSuite != nil && offeredSuite.hash == cipherSuite.hash {
  487. cipherSuiteOk = true
  488. break
  489. }
  490. }
  491. if !cipherSuiteOk {
  492. return nil, nil, nil, nil
  493. }
  494. if c.quic != nil {
  495. if c.quic.enableSessionEvents {
  496. c.quicResumeSession(session)
  497. }
  498. // For 0-RTT, the cipher suite has to match exactly, and we need to be
  499. // offering the same ALPN.
  500. if session.EarlyData && mutualCipherSuiteTLS13(hello.cipherSuites, session.cipherSuite) != nil {
  501. for _, alpn := range hello.alpnProtocols {
  502. if alpn == session.alpnProtocol {
  503. hello.earlyData = true
  504. break
  505. }
  506. }
  507. }
  508. }
  509. // Set the pre_shared_key extension. See RFC 8446, Section 4.2.11.1.
  510. ticketAge := c.config.time().Sub(time.Unix(int64(session.createdAt), 0))
  511. identity := pskIdentity{
  512. label: session.ticket,
  513. obfuscatedTicketAge: uint32(ticketAge/time.Millisecond) + session.ageAdd,
  514. }
  515. hello.pskIdentities = []pskIdentity{identity}
  516. hello.pskBinders = [][]byte{make([]byte, cipherSuite.hash.Size())}
  517. // Compute the PSK binders. See RFC 8446, Section 4.2.11.2.
  518. earlySecret = cipherSuite.extract(session.secret, nil)
  519. binderKey = cipherSuite.deriveSecret(earlySecret, resumptionBinderLabel, nil)
  520. // [UTLS SECTION START]
  521. if c.utls.sessionController != nil && !c.utls.sessionController.shouldLoadSessionWriteBinders() {
  522. return
  523. }
  524. // [UTLS SECTION END]
  525. transcript := cipherSuite.hash.New()
  526. if err := computeAndUpdatePSK(hello, binderKey, transcript, cipherSuite.finishedHash); err != nil {
  527. return nil, nil, nil, err
  528. }
  529. return
  530. }
  531. func (c *Conn) pickTLSVersion(serverHello *serverHelloMsg) error {
  532. peerVersion := serverHello.vers
  533. if serverHello.supportedVersion != 0 {
  534. peerVersion = serverHello.supportedVersion
  535. }
  536. vers, ok := c.config.mutualVersion(roleClient, []uint16{peerVersion})
  537. if !ok {
  538. c.sendAlert(alertProtocolVersion)
  539. return fmt.Errorf("tls: server selected unsupported protocol version %x", peerVersion)
  540. }
  541. c.vers = vers
  542. c.haveVers = true
  543. c.in.version = vers
  544. c.out.version = vers
  545. return nil
  546. }
  547. // Does the handshake, either a full one or resumes old session. Requires hs.c,
  548. // hs.hello, hs.serverHello, and, optionally, hs.session to be set.
  549. func (hs *clientHandshakeState) handshake() error {
  550. c := hs.c
  551. isResume, err := hs.processServerHello()
  552. if err != nil {
  553. return err
  554. }
  555. hs.finishedHash = newFinishedHash(c.vers, hs.suite)
  556. // No signatures of the handshake are needed in a resumption.
  557. // Otherwise, in a full handshake, if we don't have any certificates
  558. // configured then we will never send a CertificateVerify message and
  559. // thus no signatures are needed in that case either.
  560. if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
  561. hs.finishedHash.discardHandshakeBuffer()
  562. }
  563. if err := transcriptMsg(hs.hello, &hs.finishedHash); err != nil {
  564. return err
  565. }
  566. if err := transcriptMsg(hs.serverHello, &hs.finishedHash); err != nil {
  567. return err
  568. }
  569. c.buffering = true
  570. c.didResume = isResume
  571. if isResume {
  572. if err := hs.establishKeys(); err != nil {
  573. return err
  574. }
  575. if err := hs.readSessionTicket(); err != nil {
  576. return err
  577. }
  578. if err := hs.readFinished(c.serverFinished[:]); err != nil {
  579. return err
  580. }
  581. c.clientFinishedIsFirst = false
  582. // Make sure the connection is still being verified whether or not this
  583. // is a resumption. Resumptions currently don't reverify certificates so
  584. // they don't call verifyServerCertificate. See Issue 31641.
  585. if c.config.VerifyConnection != nil {
  586. if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
  587. c.sendAlert(alertBadCertificate)
  588. return err
  589. }
  590. }
  591. if err := hs.sendFinished(c.clientFinished[:]); err != nil {
  592. return err
  593. }
  594. if _, err := c.flush(); err != nil {
  595. return err
  596. }
  597. } else {
  598. if err := hs.doFullHandshake(); err != nil {
  599. return err
  600. }
  601. if err := hs.establishKeys(); err != nil {
  602. return err
  603. }
  604. if err := hs.sendFinished(c.clientFinished[:]); err != nil {
  605. return err
  606. }
  607. if _, err := c.flush(); err != nil {
  608. return err
  609. }
  610. c.clientFinishedIsFirst = true
  611. if err := hs.readSessionTicket(); err != nil {
  612. return err
  613. }
  614. if err := hs.readFinished(c.serverFinished[:]); err != nil {
  615. return err
  616. }
  617. }
  618. if err := hs.saveSessionTicket(); err != nil {
  619. return err
  620. }
  621. c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random)
  622. c.isHandshakeComplete.Store(true)
  623. return nil
  624. }
  625. func (hs *clientHandshakeState) pickCipherSuite() error {
  626. if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil {
  627. hs.c.sendAlert(alertHandshakeFailure)
  628. return errors.New("tls: server chose an unconfigured cipher suite")
  629. }
  630. // [UTLS SECTION BEGIN]
  631. // Disable unsupported godebug packages
  632. // if hs.c.config.CipherSuites == nil && !needFIPS() && rsaKexCiphers[hs.suite.id] {
  633. // tlsrsakex.Value() // ensure godebug is initialized
  634. // tlsrsakex.IncNonDefault()
  635. // }
  636. // if hs.c.config.CipherSuites == nil && !needFIPS() && tdesCiphers[hs.suite.id] {
  637. // tls3des.Value() // ensure godebug is initialized
  638. // tls3des.IncNonDefault()
  639. // }
  640. // [UTLS SECTION END]
  641. hs.c.cipherSuite = hs.suite.id
  642. return nil
  643. }
  644. func (hs *clientHandshakeState) doFullHandshake() error {
  645. c := hs.c
  646. msg, err := c.readHandshake(&hs.finishedHash)
  647. if err != nil {
  648. return err
  649. }
  650. certMsg, ok := msg.(*certificateMsg)
  651. if !ok || len(certMsg.certificates) == 0 {
  652. c.sendAlert(alertUnexpectedMessage)
  653. return unexpectedMessageError(certMsg, msg)
  654. }
  655. msg, err = c.readHandshake(&hs.finishedHash)
  656. if err != nil {
  657. return err
  658. }
  659. cs, ok := msg.(*certificateStatusMsg)
  660. if ok {
  661. // RFC4366 on Certificate Status Request:
  662. // The server MAY return a "certificate_status" message.
  663. if !hs.serverHello.ocspStapling {
  664. // If a server returns a "CertificateStatus" message, then the
  665. // server MUST have included an extension of type "status_request"
  666. // with empty "extension_data" in the extended server hello.
  667. c.sendAlert(alertUnexpectedMessage)
  668. return errors.New("tls: received unexpected CertificateStatus message")
  669. }
  670. c.ocspResponse = cs.response
  671. msg, err = c.readHandshake(&hs.finishedHash)
  672. if err != nil {
  673. return err
  674. }
  675. }
  676. if c.handshakes == 0 {
  677. // If this is the first handshake on a connection, process and
  678. // (optionally) verify the server's certificates.
  679. if err := c.verifyServerCertificate(certMsg.certificates); err != nil {
  680. return err
  681. }
  682. } else {
  683. // This is a renegotiation handshake. We require that the
  684. // server's identity (i.e. leaf certificate) is unchanged and
  685. // thus any previous trust decision is still valid.
  686. //
  687. // See https://mitls.org/pages/attacks/3SHAKE for the
  688. // motivation behind this requirement.
  689. if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
  690. c.sendAlert(alertBadCertificate)
  691. return errors.New("tls: server's identity changed during renegotiation")
  692. }
  693. }
  694. keyAgreement := hs.suite.ka(c.vers)
  695. skx, ok := msg.(*serverKeyExchangeMsg)
  696. if ok {
  697. err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
  698. if err != nil {
  699. c.sendAlert(alertUnexpectedMessage)
  700. return err
  701. }
  702. if len(skx.key) >= 3 && skx.key[0] == 3 /* named curve */ {
  703. c.curveID = CurveID(byteorder.BeUint16(skx.key[1:]))
  704. }
  705. msg, err = c.readHandshake(&hs.finishedHash)
  706. if err != nil {
  707. return err
  708. }
  709. }
  710. var chainToSend *Certificate
  711. var certRequested bool
  712. certReq, ok := msg.(*certificateRequestMsg)
  713. if ok {
  714. certRequested = true
  715. cri := certificateRequestInfoFromMsg(hs.ctx, c.vers, certReq)
  716. if chainToSend, err = c.getClientCertificate(cri); err != nil {
  717. c.sendAlert(alertInternalError)
  718. return err
  719. }
  720. msg, err = c.readHandshake(&hs.finishedHash)
  721. if err != nil {
  722. return err
  723. }
  724. }
  725. shd, ok := msg.(*serverHelloDoneMsg)
  726. if !ok {
  727. c.sendAlert(alertUnexpectedMessage)
  728. return unexpectedMessageError(shd, msg)
  729. }
  730. // If the server requested a certificate then we have to send a
  731. // Certificate message, even if it's empty because we don't have a
  732. // certificate to send.
  733. if certRequested {
  734. certMsg = new(certificateMsg)
  735. certMsg.certificates = chainToSend.Certificate
  736. if _, err := hs.c.writeHandshakeRecord(certMsg, &hs.finishedHash); err != nil {
  737. return err
  738. }
  739. }
  740. preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
  741. if err != nil {
  742. c.sendAlert(alertInternalError)
  743. return err
  744. }
  745. if ckx != nil {
  746. if _, err := hs.c.writeHandshakeRecord(ckx, &hs.finishedHash); err != nil {
  747. return err
  748. }
  749. }
  750. if hs.serverHello.extendedMasterSecret {
  751. c.extMasterSecret = true
  752. hs.masterSecret = extMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret,
  753. hs.finishedHash.Sum())
  754. } else {
  755. hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret,
  756. hs.hello.random, hs.serverHello.random)
  757. }
  758. if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.hello.random, hs.masterSecret); err != nil {
  759. c.sendAlert(alertInternalError)
  760. return errors.New("tls: failed to write to key log: " + err.Error())
  761. }
  762. if chainToSend != nil && len(chainToSend.Certificate) > 0 {
  763. certVerify := &certificateVerifyMsg{}
  764. key, ok := chainToSend.PrivateKey.(crypto.Signer)
  765. if !ok {
  766. c.sendAlert(alertInternalError)
  767. return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
  768. }
  769. var sigType uint8
  770. var sigHash crypto.Hash
  771. if c.vers >= VersionTLS12 {
  772. signatureAlgorithm, err := selectSignatureScheme(c.vers, chainToSend, certReq.supportedSignatureAlgorithms)
  773. if err != nil {
  774. c.sendAlert(alertIllegalParameter)
  775. return err
  776. }
  777. sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm)
  778. if err != nil {
  779. return c.sendAlert(alertInternalError)
  780. }
  781. certVerify.hasSignatureAlgorithm = true
  782. certVerify.signatureAlgorithm = signatureAlgorithm
  783. } else {
  784. sigType, sigHash, err = legacyTypeAndHashFromPublicKey(key.Public())
  785. if err != nil {
  786. c.sendAlert(alertIllegalParameter)
  787. return err
  788. }
  789. }
  790. signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash)
  791. signOpts := crypto.SignerOpts(sigHash)
  792. if sigType == signatureRSAPSS {
  793. signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
  794. }
  795. certVerify.signature, err = key.Sign(c.config.rand(), signed, signOpts)
  796. if err != nil {
  797. c.sendAlert(alertInternalError)
  798. return err
  799. }
  800. if _, err := hs.c.writeHandshakeRecord(certVerify, &hs.finishedHash); err != nil {
  801. return err
  802. }
  803. }
  804. hs.finishedHash.discardHandshakeBuffer()
  805. return nil
  806. }
  807. func (hs *clientHandshakeState) establishKeys() error {
  808. c := hs.c
  809. clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
  810. keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
  811. var clientCipher, serverCipher any
  812. var clientHash, serverHash hash.Hash
  813. if hs.suite.cipher != nil {
  814. clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
  815. clientHash = hs.suite.mac(clientMAC)
  816. serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
  817. serverHash = hs.suite.mac(serverMAC)
  818. } else {
  819. clientCipher = hs.suite.aead(clientKey, clientIV)
  820. serverCipher = hs.suite.aead(serverKey, serverIV)
  821. }
  822. c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
  823. c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
  824. return nil
  825. }
  826. func (hs *clientHandshakeState) serverResumedSession() bool {
  827. // If the server responded with the same sessionId then it means the
  828. // sessionTicket is being used to resume a TLS session.
  829. return hs.session != nil && hs.hello.sessionId != nil &&
  830. bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
  831. }
  832. func (hs *clientHandshakeState) processServerHello() (bool, error) {
  833. c := hs.c
  834. if err := hs.pickCipherSuite(); err != nil {
  835. return false, err
  836. }
  837. if hs.serverHello.compressionMethod != compressionNone {
  838. c.sendAlert(alertUnexpectedMessage)
  839. return false, errors.New("tls: server selected unsupported compression format")
  840. }
  841. if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
  842. c.secureRenegotiation = true
  843. if len(hs.serverHello.secureRenegotiation) != 0 {
  844. c.sendAlert(alertHandshakeFailure)
  845. return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
  846. }
  847. }
  848. if c.handshakes > 0 && c.secureRenegotiation {
  849. var expectedSecureRenegotiation [24]byte
  850. copy(expectedSecureRenegotiation[:], c.clientFinished[:])
  851. copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
  852. if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
  853. c.sendAlert(alertHandshakeFailure)
  854. return false, errors.New("tls: incorrect renegotiation extension contents")
  855. }
  856. }
  857. if err := checkALPN(hs.hello.alpnProtocols, hs.serverHello.alpnProtocol, false); err != nil {
  858. c.sendAlert(alertUnsupportedExtension)
  859. return false, err
  860. }
  861. c.clientProtocol = hs.serverHello.alpnProtocol
  862. c.scts = hs.serverHello.scts
  863. if !hs.serverResumedSession() {
  864. return false, nil
  865. }
  866. if hs.session.version != c.vers {
  867. c.sendAlert(alertHandshakeFailure)
  868. return false, errors.New("tls: server resumed a session with a different version")
  869. }
  870. if hs.session.cipherSuite != hs.suite.id {
  871. c.sendAlert(alertHandshakeFailure)
  872. return false, errors.New("tls: server resumed a session with a different cipher suite")
  873. }
  874. // RFC 7627, Section 5.3
  875. if hs.session.extMasterSecret != hs.serverHello.extendedMasterSecret {
  876. c.sendAlert(alertHandshakeFailure)
  877. return false, errors.New("tls: server resumed a session with a different EMS extension")
  878. }
  879. // Restore master secret and certificates from previous state
  880. hs.masterSecret = hs.session.secret
  881. c.extMasterSecret = hs.session.extMasterSecret
  882. c.peerCertificates = hs.session.peerCertificates
  883. c.activeCertHandles = hs.c.activeCertHandles
  884. c.verifiedChains = hs.session.verifiedChains
  885. c.ocspResponse = hs.session.ocspResponse
  886. // Let the ServerHello SCTs override the session SCTs from the original
  887. // connection, if any are provided
  888. if len(c.scts) == 0 && len(hs.session.scts) != 0 {
  889. c.scts = hs.session.scts
  890. }
  891. return true, nil
  892. }
  893. // checkALPN ensure that the server's choice of ALPN protocol is compatible with
  894. // the protocols that we advertised in the Client Hello.
  895. func checkALPN(clientProtos []string, serverProto string, quic bool) error {
  896. if serverProto == "" {
  897. if quic && len(clientProtos) > 0 {
  898. // RFC 9001, Section 8.1
  899. return errors.New("tls: server did not select an ALPN protocol")
  900. }
  901. return nil
  902. }
  903. if len(clientProtos) == 0 {
  904. return errors.New("tls: server advertised unrequested ALPN extension")
  905. }
  906. for _, proto := range clientProtos {
  907. if proto == serverProto {
  908. return nil
  909. }
  910. }
  911. return errors.New("tls: server selected unadvertised ALPN protocol")
  912. }
  913. func (hs *clientHandshakeState) readFinished(out []byte) error {
  914. c := hs.c
  915. if err := c.readChangeCipherSpec(); err != nil {
  916. return err
  917. }
  918. // finishedMsg is included in the transcript, but not until after we
  919. // check the client version, since the state before this message was
  920. // sent is used during verification.
  921. msg, err := c.readHandshake(nil)
  922. if err != nil {
  923. return err
  924. }
  925. serverFinished, ok := msg.(*finishedMsg)
  926. if !ok {
  927. c.sendAlert(alertUnexpectedMessage)
  928. return unexpectedMessageError(serverFinished, msg)
  929. }
  930. verify := hs.finishedHash.serverSum(hs.masterSecret)
  931. if len(verify) != len(serverFinished.verifyData) ||
  932. subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
  933. c.sendAlert(alertHandshakeFailure)
  934. return errors.New("tls: server's Finished message was incorrect")
  935. }
  936. if err := transcriptMsg(serverFinished, &hs.finishedHash); err != nil {
  937. return err
  938. }
  939. copy(out, verify)
  940. return nil
  941. }
  942. func (hs *clientHandshakeState) readSessionTicket() error {
  943. if !hs.serverHello.ticketSupported {
  944. return nil
  945. }
  946. c := hs.c
  947. if !hs.hello.ticketSupported {
  948. c.sendAlert(alertIllegalParameter)
  949. return errors.New("tls: server sent unrequested session ticket")
  950. }
  951. msg, err := c.readHandshake(&hs.finishedHash)
  952. if err != nil {
  953. return err
  954. }
  955. sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
  956. if !ok {
  957. c.sendAlert(alertUnexpectedMessage)
  958. return unexpectedMessageError(sessionTicketMsg, msg)
  959. }
  960. hs.ticket = sessionTicketMsg.ticket
  961. return nil
  962. }
  963. func (hs *clientHandshakeState) saveSessionTicket() error {
  964. if hs.ticket == nil {
  965. return nil
  966. }
  967. c := hs.c
  968. cacheKey := c.clientSessionCacheKey()
  969. if cacheKey == "" {
  970. return nil
  971. }
  972. session := c.sessionState()
  973. session.secret = hs.masterSecret
  974. session.ticket = hs.ticket
  975. cs := &ClientSessionState{session: session}
  976. // [UTLS SECTION BEGIN]
  977. // By skipping saving to ClientSessionCache when it is not set in the Config,
  978. // it allows TLS 1.2 connections to be established while client actively advertises
  979. // session_ticket extension, without modifying configs from previous tagged versions.
  980. if c.config.ClientSessionCache != nil {
  981. c.config.ClientSessionCache.Put(cacheKey, cs)
  982. }
  983. // [UTLS SECTION END]
  984. return nil
  985. }
  986. func (hs *clientHandshakeState) sendFinished(out []byte) error {
  987. c := hs.c
  988. if err := c.writeChangeCipherRecord(); err != nil {
  989. return err
  990. }
  991. finished := new(finishedMsg)
  992. finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
  993. if _, err := hs.c.writeHandshakeRecord(finished, &hs.finishedHash); err != nil {
  994. return err
  995. }
  996. copy(out, finished.verifyData)
  997. return nil
  998. }
  999. // defaultMaxRSAKeySize is the maximum RSA key size in bits that we are willing
  1000. // to verify the signatures of during a TLS handshake.
  1001. const defaultMaxRSAKeySize = 8192
  1002. // var tlsmaxrsasize = godebug.New("tlsmaxrsasize") // [UTLS] unused
  1003. func checkKeySize(n int) (max int, ok bool) {
  1004. // [UTLS SECTION BEGIN]
  1005. // Disabled unsupported godebug packages
  1006. // if v := tlsmaxrsasize.Value(); v != "" {
  1007. // if max, err := strconv.Atoi(v); err == nil {
  1008. // if (n <= max) != (n <= defaultMaxRSAKeySize) {
  1009. // tlsmaxrsasize.IncNonDefault()
  1010. // }
  1011. // return max, n <= max
  1012. // }
  1013. // }
  1014. // [UTLS SECTION END]
  1015. return defaultMaxRSAKeySize, n <= defaultMaxRSAKeySize
  1016. }
  1017. // verifyServerCertificate parses and verifies the provided chain, setting
  1018. // c.verifiedChains and c.peerCertificates or sending the appropriate alert.
  1019. func (c *Conn) verifyServerCertificate(certificates [][]byte) error {
  1020. activeHandles := make([]*activeCert, len(certificates))
  1021. certs := make([]*x509.Certificate, len(certificates))
  1022. for i, asn1Data := range certificates {
  1023. cert, err := globalCertCache.newCert(asn1Data)
  1024. if err != nil {
  1025. c.sendAlert(alertBadCertificate)
  1026. return errors.New("tls: failed to parse certificate from server: " + err.Error())
  1027. }
  1028. if cert.cert.PublicKeyAlgorithm == x509.RSA {
  1029. n := cert.cert.PublicKey.(*rsa.PublicKey).N.BitLen()
  1030. if max, ok := checkKeySize(n); !ok {
  1031. c.sendAlert(alertBadCertificate)
  1032. return fmt.Errorf("tls: server sent certificate containing RSA key larger than %d bits", max)
  1033. }
  1034. }
  1035. activeHandles[i] = cert
  1036. certs[i] = cert.cert
  1037. }
  1038. echRejected := c.config.EncryptedClientHelloConfigList != nil && !c.echAccepted
  1039. if echRejected {
  1040. if c.config.EncryptedClientHelloRejectionVerify != nil {
  1041. if err := c.config.EncryptedClientHelloRejectionVerify(c.connectionStateLocked()); err != nil {
  1042. c.sendAlert(alertBadCertificate)
  1043. return err
  1044. }
  1045. } else {
  1046. opts := x509.VerifyOptions{
  1047. Roots: c.config.RootCAs,
  1048. CurrentTime: c.config.time(),
  1049. DNSName: c.serverName,
  1050. Intermediates: x509.NewCertPool(),
  1051. }
  1052. for _, cert := range certs[1:] {
  1053. opts.Intermediates.AddCert(cert)
  1054. }
  1055. var err error
  1056. c.verifiedChains, err = certs[0].Verify(opts)
  1057. if err != nil {
  1058. c.sendAlert(alertBadCertificate)
  1059. return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err}
  1060. }
  1061. }
  1062. } else if !c.config.InsecureSkipVerify {
  1063. opts := x509.VerifyOptions{
  1064. Roots: c.config.RootCAs,
  1065. CurrentTime: c.config.time(),
  1066. // DNSName: c.config.ServerName, // [UTLS]
  1067. Intermediates: x509.NewCertPool(),
  1068. }
  1069. // [UTLS SECTION BEGIN]
  1070. if c.config.InsecureSkipTimeVerify {
  1071. opts.CurrentTime = certs[0].NotAfter
  1072. }
  1073. if len(c.config.InsecureServerNameToVerify) == 0 {
  1074. opts.DNSName = c.config.ServerName
  1075. } else if c.config.InsecureServerNameToVerify != "*" {
  1076. opts.DNSName = c.config.InsecureServerNameToVerify
  1077. }
  1078. // [UTLS SECTION END]
  1079. for _, cert := range certs[1:] {
  1080. opts.Intermediates.AddCert(cert)
  1081. }
  1082. var err error
  1083. c.verifiedChains, err = certs[0].Verify(opts)
  1084. if err != nil {
  1085. c.sendAlert(alertBadCertificate)
  1086. return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err}
  1087. }
  1088. }
  1089. switch certs[0].PublicKey.(type) {
  1090. case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
  1091. break
  1092. default:
  1093. c.sendAlert(alertUnsupportedCertificate)
  1094. return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
  1095. }
  1096. c.activeCertHandles = activeHandles
  1097. c.peerCertificates = certs
  1098. if c.config.VerifyPeerCertificate != nil && !echRejected {
  1099. if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
  1100. c.sendAlert(alertBadCertificate)
  1101. return err
  1102. }
  1103. }
  1104. if c.config.VerifyConnection != nil && !echRejected {
  1105. if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
  1106. c.sendAlert(alertBadCertificate)
  1107. return err
  1108. }
  1109. }
  1110. return nil
  1111. }
  1112. // certificateRequestInfoFromMsg generates a CertificateRequestInfo from a TLS
  1113. // <= 1.2 CertificateRequest, making an effort to fill in missing information.
  1114. func certificateRequestInfoFromMsg(ctx context.Context, vers uint16, certReq *certificateRequestMsg) *CertificateRequestInfo {
  1115. cri := &CertificateRequestInfo{
  1116. AcceptableCAs: certReq.certificateAuthorities,
  1117. Version: vers,
  1118. ctx: ctx,
  1119. }
  1120. var rsaAvail, ecAvail bool
  1121. for _, certType := range certReq.certificateTypes {
  1122. switch certType {
  1123. case certTypeRSASign:
  1124. rsaAvail = true
  1125. case certTypeECDSASign:
  1126. ecAvail = true
  1127. }
  1128. }
  1129. if !certReq.hasSignatureAlgorithm {
  1130. // Prior to TLS 1.2, signature schemes did not exist. In this case we
  1131. // make up a list based on the acceptable certificate types, to help
  1132. // GetClientCertificate and SupportsCertificate select the right certificate.
  1133. // The hash part of the SignatureScheme is a lie here, because
  1134. // TLS 1.0 and 1.1 always use MD5+SHA1 for RSA and SHA1 for ECDSA.
  1135. switch {
  1136. case rsaAvail && ecAvail:
  1137. cri.SignatureSchemes = []SignatureScheme{
  1138. ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
  1139. PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
  1140. }
  1141. case rsaAvail:
  1142. cri.SignatureSchemes = []SignatureScheme{
  1143. PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
  1144. }
  1145. case ecAvail:
  1146. cri.SignatureSchemes = []SignatureScheme{
  1147. ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
  1148. }
  1149. }
  1150. return cri
  1151. }
  1152. // Filter the signature schemes based on the certificate types.
  1153. // See RFC 5246, Section 7.4.4 (where it calls this "somewhat complicated").
  1154. cri.SignatureSchemes = make([]SignatureScheme, 0, len(certReq.supportedSignatureAlgorithms))
  1155. for _, sigScheme := range certReq.supportedSignatureAlgorithms {
  1156. sigType, _, err := typeAndHashFromSignatureScheme(sigScheme)
  1157. if err != nil {
  1158. continue
  1159. }
  1160. switch sigType {
  1161. case signatureECDSA, signatureEd25519:
  1162. if ecAvail {
  1163. cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
  1164. }
  1165. case signatureRSAPSS, signaturePKCS1v15:
  1166. if rsaAvail {
  1167. cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
  1168. }
  1169. }
  1170. }
  1171. return cri
  1172. }
  1173. func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, error) {
  1174. if c.config.GetClientCertificate != nil {
  1175. return c.config.GetClientCertificate(cri)
  1176. }
  1177. for _, chain := range c.config.Certificates {
  1178. if err := cri.SupportsCertificate(&chain); err != nil {
  1179. continue
  1180. }
  1181. return &chain, nil
  1182. }
  1183. // No acceptable certificate found. Don't send a certificate.
  1184. return new(Certificate), nil
  1185. }
  1186. // clientSessionCacheKey returns a key used to cache sessionTickets that could
  1187. // be used to resume previously negotiated TLS sessions with a server.
  1188. func (c *Conn) clientSessionCacheKey() string {
  1189. if len(c.config.ServerName) > 0 {
  1190. return c.config.ServerName
  1191. }
  1192. if c.conn != nil {
  1193. return c.conn.RemoteAddr().String()
  1194. }
  1195. return ""
  1196. }
  1197. // hostnameInSNI converts name into an appropriate hostname for SNI.
  1198. // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
  1199. // See RFC 6066, Section 3.
  1200. func hostnameInSNI(name string) string {
  1201. host := name
  1202. if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
  1203. host = host[1 : len(host)-1]
  1204. }
  1205. if i := strings.LastIndex(host, "%"); i > 0 {
  1206. host = host[:i]
  1207. }
  1208. if net.ParseIP(host) != nil {
  1209. return ""
  1210. }
  1211. for len(name) > 0 && name[len(name)-1] == '.' {
  1212. name = name[:len(name)-1]
  1213. }
  1214. return name
  1215. }
  1216. func computeAndUpdatePSK(m *clientHelloMsg, binderKey []byte, transcript hash.Hash, finishedHash func([]byte, hash.Hash) []byte) error {
  1217. helloBytes, err := m.marshalWithoutBinders()
  1218. if err != nil {
  1219. return err
  1220. }
  1221. transcript.Write(helloBytes)
  1222. pskBinders := [][]byte{finishedHash(binderKey, transcript)}
  1223. return m.updateBinders(pskBinders)
  1224. }