handshake_client.go 36 KB

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