handshake_server.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187
  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. "time"
  20. )
  21. // serverHandshakeState contains details of a server handshake in progress.
  22. // It's discarded once the handshake has completed.
  23. type serverHandshakeState struct {
  24. c *Conn
  25. ctx context.Context
  26. clientHello *clientHelloMsg
  27. hello *serverHelloMsg
  28. suite *cipherSuite
  29. ecdheOk bool
  30. ecSignOk bool
  31. rsaDecryptOk bool
  32. rsaSignOk bool
  33. sessionState *SessionState
  34. finishedHash finishedHash
  35. masterSecret []byte
  36. cert *Certificate
  37. }
  38. // serverHandshake performs a TLS handshake as a server.
  39. func (c *Conn) serverHandshake(ctx context.Context) error {
  40. clientHello, err := c.readClientHello(ctx)
  41. // [Psiphon]
  42. // The ClientHello with the passthrough message is now available. Route the
  43. // client to passthrough based on message inspection. This code assumes the
  44. // client TCP conn has been wrapped with recorderConn, which has recorded
  45. // all bytes sent by the client, which will be replayed, byte-for-byte, to
  46. // the passthrough; as a result, passthrough clients will perform their TLS
  47. // handshake with the passthrough target, receive its certificate, and in the
  48. // case of HTTPS, receive the passthrough target's HTTP responses.
  49. //
  50. // Passthrough is also triggered if readClientHello fails. E.g., on other
  51. // invalid input cases including "tls: handshake message of length..." or if
  52. // the ClientHello is otherwise invalid. This ensures that clients sending
  53. // random data will be relayed to the passthrough and not receive a
  54. // distinguishing error response.
  55. //
  56. // The `tls` API performs handshakes on demand. E.g., the first call to
  57. // tls.Conn.Read will perform a handshake if it's not yet been performed.
  58. // Consumers such as `http` may call Read and then Close. To minimize code
  59. // changes, in the passthrough case the ownership of Conn.conn, the client
  60. // TCP conn, is transferred to the passthrough relay and a closedConn is
  61. // substituted for Conn.conn. This allows the remaining `tls` code paths to
  62. // continue reference a net.Conn, albeit one that is closed, so Reads and
  63. // Writes will fail.
  64. if c.config.PassthroughAddress != "" {
  65. doPassthrough := false
  66. if err != nil {
  67. doPassthrough = true
  68. err = fmt.Errorf("passthrough: %s", err)
  69. }
  70. clientAddr := c.conn.RemoteAddr().String()
  71. clientIP, _, _ := net.SplitHostPort(clientAddr)
  72. if !doPassthrough {
  73. if !c.config.PassthroughVerifyMessage(clientHello.random) {
  74. c.config.PassthroughLogInvalidMessage(clientIP)
  75. doPassthrough = true
  76. err = errors.New("passthrough: invalid client random")
  77. }
  78. }
  79. if !doPassthrough {
  80. if !c.config.PassthroughHistoryAddNew(
  81. clientIP, clientHello.random) {
  82. doPassthrough = true
  83. err = errors.New("passthrough: duplicate client random")
  84. }
  85. }
  86. // Call GetReadBuffer, in both passthrough and non-passthrough cases, to
  87. // stop buffering all read bytes.
  88. passthroughReadBuffer := c.conn.(*recorderConn).GetReadBuffer().Bytes()
  89. if doPassthrough {
  90. // When performing passthrough, we must exit at the "return err" below.
  91. // This is a failsafe to ensure err is always set.
  92. if err == nil {
  93. err = errors.New("passthrough: missing error")
  94. }
  95. // Modifying c.conn directly is safe only because Conn.Handshake, which
  96. // calls Conn.serverHandshake, is holding c.handshakeMutex and c.in locks,
  97. // and because of the serial nature of c.conn access during the handshake
  98. // sequence.
  99. conn := c.conn
  100. c.conn = newClosedConn(conn)
  101. go func() {
  102. // Perform the passthrough relay.
  103. //
  104. // Limitations:
  105. //
  106. // - The local TCP stack may differ from passthrough target in a
  107. // detectable way.
  108. //
  109. // - There may be detectable timing characteristics due to the network hop
  110. // to the passthrough target.
  111. //
  112. // - Application-level socket operations may produce detectable
  113. // differences (e.g., CloseWrite/FIN).
  114. //
  115. // - The dial to the passthrough, or other upstream network operations,
  116. // may fail. These errors are not logged.
  117. //
  118. // - There's no timeout on the passthrough dial and no time limit on the
  119. // passthrough relay so that the invalid client can't detect a timeout
  120. // shorter than the passthrough target; this may cause additional load.
  121. defer conn.Close()
  122. // Remove any pre-existing deadlines to ensure the passthrough
  123. // is not interrupted.
  124. _ = conn.SetDeadline(time.Time{})
  125. passthroughConn, err := net.Dial("tcp", c.config.PassthroughAddress)
  126. if err != nil {
  127. return
  128. }
  129. defer passthroughConn.Close()
  130. _, err = passthroughConn.Write(passthroughReadBuffer)
  131. if err != nil {
  132. return
  133. }
  134. // Allow garbage collection.
  135. passthroughReadBuffer = nil
  136. go func() {
  137. _, _ = io.Copy(passthroughConn, conn)
  138. passthroughConn.Close()
  139. }()
  140. _, _ = io.Copy(conn, passthroughConn)
  141. }()
  142. }
  143. }
  144. if err != nil {
  145. return err
  146. }
  147. if c.vers == VersionTLS13 {
  148. hs := serverHandshakeStateTLS13{
  149. c: c,
  150. ctx: ctx,
  151. clientHello: clientHello,
  152. }
  153. return hs.handshake()
  154. }
  155. hs := serverHandshakeState{
  156. c: c,
  157. ctx: ctx,
  158. clientHello: clientHello,
  159. }
  160. return hs.handshake()
  161. }
  162. func (hs *serverHandshakeState) handshake() error {
  163. c := hs.c
  164. if err := hs.processClientHello(); err != nil {
  165. return err
  166. }
  167. // For an overview of TLS handshaking, see RFC 5246, Section 7.3.
  168. c.buffering = true
  169. if err := hs.checkForResumption(); err != nil {
  170. return err
  171. }
  172. if hs.sessionState != nil {
  173. // The client has included a session ticket and so we do an abbreviated handshake.
  174. if err := hs.doResumeHandshake(); err != nil {
  175. return err
  176. }
  177. if err := hs.establishKeys(); err != nil {
  178. return err
  179. }
  180. if err := hs.sendSessionTicket(); err != nil {
  181. return err
  182. }
  183. if err := hs.sendFinished(c.serverFinished[:]); err != nil {
  184. return err
  185. }
  186. if _, err := c.flush(); err != nil {
  187. return err
  188. }
  189. c.clientFinishedIsFirst = false
  190. if err := hs.readFinished(nil); err != nil {
  191. return err
  192. }
  193. } else {
  194. // The client didn't include a session ticket, or it wasn't
  195. // valid so we do a full handshake.
  196. if err := hs.pickCipherSuite(); err != nil {
  197. return err
  198. }
  199. if err := hs.doFullHandshake(); err != nil {
  200. return err
  201. }
  202. if err := hs.establishKeys(); err != nil {
  203. return err
  204. }
  205. if err := hs.readFinished(c.clientFinished[:]); err != nil {
  206. return err
  207. }
  208. c.clientFinishedIsFirst = true
  209. c.buffering = true
  210. if err := hs.sendSessionTicket(); err != nil {
  211. return err
  212. }
  213. if err := hs.sendFinished(nil); err != nil {
  214. return err
  215. }
  216. if _, err := c.flush(); err != nil {
  217. return err
  218. }
  219. }
  220. c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random)
  221. c.isHandshakeComplete.Store(true)
  222. return nil
  223. }
  224. // [Psiphon]
  225. // recorderConn is a net.Conn which records all bytes read from the wrapped
  226. // conn until GetReadBuffer is called, which returns the buffered bytes and
  227. // stops recording. This is used to replay, byte-for-byte, the bytes sent by a
  228. // client when switching to passthrough.
  229. //
  230. // recorderConn operations are not safe for concurrent use and intended only
  231. // to be used in the initial phase of the TLS handshake, where the order of
  232. // operations is deterministic.
  233. type recorderConn struct {
  234. net.Conn
  235. readBuffer *bytes.Buffer
  236. }
  237. func newRecorderConn(conn net.Conn) *recorderConn {
  238. return &recorderConn{
  239. Conn: conn,
  240. readBuffer: new(bytes.Buffer),
  241. }
  242. }
  243. func (c *recorderConn) Read(p []byte) (n int, err error) {
  244. n, err = c.Conn.Read(p)
  245. if n > 0 && c.readBuffer != nil {
  246. _, _ = c.readBuffer.Write(p[:n])
  247. }
  248. return n, err
  249. }
  250. func (c *recorderConn) GetReadBuffer() *bytes.Buffer {
  251. b := c.readBuffer
  252. c.readBuffer = nil
  253. return b
  254. }
  255. func (c *recorderConn) IsRecording() bool {
  256. return c.readBuffer != nil
  257. }
  258. // [Psiphon]
  259. // closedConn is a net.Conn which behaves as if it were closed: all reads and
  260. // writes fail. This is used when switching to passthrough mode: ownership of
  261. // the invalid client conn is taken by the passthrough relay and a closedConn
  262. // replaces the network conn used by the local TLS server code path.
  263. type closedConn struct {
  264. localAddr net.Addr
  265. remoteAddr net.Addr
  266. }
  267. var closedClosedError = errors.New("closed")
  268. func newClosedConn(conn net.Conn) *closedConn {
  269. return &closedConn{
  270. localAddr: conn.LocalAddr(),
  271. remoteAddr: conn.RemoteAddr(),
  272. }
  273. }
  274. func (c *closedConn) Read(_ []byte) (int, error) {
  275. return 0, closedClosedError
  276. }
  277. func (c *closedConn) Write(_ []byte) (int, error) {
  278. return 0, closedClosedError
  279. }
  280. func (c *closedConn) Close() error {
  281. return nil
  282. }
  283. func (c *closedConn) LocalAddr() net.Addr {
  284. return c.localAddr
  285. }
  286. func (c *closedConn) RemoteAddr() net.Addr {
  287. return c.remoteAddr
  288. }
  289. func (c *closedConn) SetDeadline(_ time.Time) error {
  290. return closedClosedError
  291. }
  292. func (c *closedConn) SetReadDeadline(_ time.Time) error {
  293. return closedClosedError
  294. }
  295. func (c *closedConn) SetWriteDeadline(_ time.Time) error {
  296. return closedClosedError
  297. }
  298. // readClientHello reads a ClientHello message and selects the protocol version.
  299. func (c *Conn) readClientHello(ctx context.Context) (*clientHelloMsg, error) {
  300. // clientHelloMsg is included in the transcript, but we haven't initialized
  301. // it yet. The respective handshake functions will record it themselves.
  302. msg, err := c.readHandshake(nil)
  303. if err != nil {
  304. return nil, err
  305. }
  306. clientHello, ok := msg.(*clientHelloMsg)
  307. if !ok {
  308. c.sendAlert(alertUnexpectedMessage)
  309. return nil, unexpectedMessageError(clientHello, msg)
  310. }
  311. var configForClient *Config
  312. originalConfig := c.config
  313. if c.config.GetConfigForClient != nil {
  314. chi := clientHelloInfo(ctx, c, clientHello)
  315. if configForClient, err = c.config.GetConfigForClient(chi); err != nil {
  316. c.sendAlert(alertInternalError)
  317. return nil, err
  318. } else if configForClient != nil {
  319. c.config = configForClient
  320. }
  321. }
  322. c.ticketKeys = originalConfig.ticketKeys(configForClient)
  323. clientVersions := clientHello.supportedVersions
  324. if len(clientHello.supportedVersions) == 0 {
  325. clientVersions = supportedVersionsFromMax(clientHello.vers)
  326. }
  327. c.vers, ok = c.config.mutualVersion(roleServer, clientVersions)
  328. if !ok {
  329. c.sendAlert(alertProtocolVersion)
  330. return nil, fmt.Errorf("tls: client offered only unsupported versions: %x", clientVersions)
  331. }
  332. c.haveVers = true
  333. c.in.version = c.vers
  334. c.out.version = c.vers
  335. return clientHello, nil
  336. }
  337. func (hs *serverHandshakeState) processClientHello() error {
  338. c := hs.c
  339. hs.hello = new(serverHelloMsg)
  340. hs.hello.vers = c.vers
  341. foundCompression := false
  342. // We only support null compression, so check that the client offered it.
  343. for _, compression := range hs.clientHello.compressionMethods {
  344. if compression == compressionNone {
  345. foundCompression = true
  346. break
  347. }
  348. }
  349. if !foundCompression {
  350. c.sendAlert(alertHandshakeFailure)
  351. return errors.New("tls: client does not support uncompressed connections")
  352. }
  353. hs.hello.random = make([]byte, 32)
  354. serverRandom := hs.hello.random
  355. // Downgrade protection canaries. See RFC 8446, Section 4.1.3.
  356. maxVers := c.config.maxSupportedVersion(roleServer)
  357. if maxVers >= VersionTLS12 && c.vers < maxVers || testingOnlyForceDowngradeCanary {
  358. if c.vers == VersionTLS12 {
  359. copy(serverRandom[24:], downgradeCanaryTLS12)
  360. } else {
  361. copy(serverRandom[24:], downgradeCanaryTLS11)
  362. }
  363. serverRandom = serverRandom[:24]
  364. }
  365. _, err := io.ReadFull(c.config.rand(), serverRandom)
  366. if err != nil {
  367. c.sendAlert(alertInternalError)
  368. return err
  369. }
  370. if len(hs.clientHello.secureRenegotiation) != 0 {
  371. c.sendAlert(alertHandshakeFailure)
  372. return errors.New("tls: initial handshake had non-empty renegotiation extension")
  373. }
  374. hs.hello.extendedMasterSecret = hs.clientHello.extendedMasterSecret
  375. hs.hello.secureRenegotiationSupported = hs.clientHello.secureRenegotiationSupported
  376. hs.hello.compressionMethod = compressionNone
  377. if len(hs.clientHello.serverName) > 0 {
  378. c.serverName = hs.clientHello.serverName
  379. }
  380. selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols, false)
  381. if err != nil {
  382. c.sendAlert(alertNoApplicationProtocol)
  383. return err
  384. }
  385. hs.hello.alpnProtocol = selectedProto
  386. c.clientProtocol = selectedProto
  387. hs.cert, err = c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello))
  388. if err != nil {
  389. if err == errNoCertificates {
  390. c.sendAlert(alertUnrecognizedName)
  391. } else {
  392. c.sendAlert(alertInternalError)
  393. }
  394. return err
  395. }
  396. if hs.clientHello.scts {
  397. hs.hello.scts = hs.cert.SignedCertificateTimestamps
  398. }
  399. hs.ecdheOk = supportsECDHE(c.config, hs.clientHello.supportedCurves, hs.clientHello.supportedPoints)
  400. if hs.ecdheOk && len(hs.clientHello.supportedPoints) > 0 {
  401. // Although omitting the ec_point_formats extension is permitted, some
  402. // old OpenSSL version will refuse to handshake if not present.
  403. //
  404. // Per RFC 4492, section 5.1.2, implementations MUST support the
  405. // uncompressed point format. See golang.org/issue/31943.
  406. hs.hello.supportedPoints = []uint8{pointFormatUncompressed}
  407. }
  408. if priv, ok := hs.cert.PrivateKey.(crypto.Signer); ok {
  409. switch priv.Public().(type) {
  410. case *ecdsa.PublicKey:
  411. hs.ecSignOk = true
  412. case ed25519.PublicKey:
  413. hs.ecSignOk = true
  414. case *rsa.PublicKey:
  415. hs.rsaSignOk = true
  416. default:
  417. c.sendAlert(alertInternalError)
  418. return fmt.Errorf("tls: unsupported signing key type (%T)", priv.Public())
  419. }
  420. }
  421. if priv, ok := hs.cert.PrivateKey.(crypto.Decrypter); ok {
  422. switch priv.Public().(type) {
  423. case *rsa.PublicKey:
  424. hs.rsaDecryptOk = true
  425. default:
  426. c.sendAlert(alertInternalError)
  427. return fmt.Errorf("tls: unsupported decryption key type (%T)", priv.Public())
  428. }
  429. }
  430. return nil
  431. }
  432. // negotiateALPN picks a shared ALPN protocol that both sides support in server
  433. // preference order. If ALPN is not configured or the peer doesn't support it,
  434. // it returns "" and no error.
  435. func negotiateALPN(serverProtos, clientProtos []string, quic bool) (string, error) {
  436. if len(serverProtos) == 0 || len(clientProtos) == 0 {
  437. if quic && len(serverProtos) != 0 {
  438. // RFC 9001, Section 8.1
  439. return "", fmt.Errorf("tls: client did not request an application protocol")
  440. }
  441. return "", nil
  442. }
  443. var http11fallback bool
  444. for _, s := range serverProtos {
  445. for _, c := range clientProtos {
  446. if s == c {
  447. return s, nil
  448. }
  449. if s == "h2" && c == "http/1.1" {
  450. http11fallback = true
  451. }
  452. }
  453. }
  454. // As a special case, let http/1.1 clients connect to h2 servers as if they
  455. // didn't support ALPN. We used not to enforce protocol overlap, so over
  456. // time a number of HTTP servers were configured with only "h2", but
  457. // expected to accept connections from "http/1.1" clients. See Issue 46310.
  458. if http11fallback {
  459. return "", nil
  460. }
  461. return "", fmt.Errorf("tls: client requested unsupported application protocols (%s)", clientProtos)
  462. }
  463. // supportsECDHE returns whether ECDHE key exchanges can be used with this
  464. // pre-TLS 1.3 client.
  465. func supportsECDHE(c *Config, supportedCurves []CurveID, supportedPoints []uint8) bool {
  466. supportsCurve := false
  467. for _, curve := range supportedCurves {
  468. if c.supportsCurve(curve) {
  469. supportsCurve = true
  470. break
  471. }
  472. }
  473. supportsPointFormat := false
  474. for _, pointFormat := range supportedPoints {
  475. if pointFormat == pointFormatUncompressed {
  476. supportsPointFormat = true
  477. break
  478. }
  479. }
  480. // Per RFC 8422, Section 5.1.2, if the Supported Point Formats extension is
  481. // missing, uncompressed points are supported. If supportedPoints is empty,
  482. // the extension must be missing, as an empty extension body is rejected by
  483. // the parser. See https://go.dev/issue/49126.
  484. if len(supportedPoints) == 0 {
  485. supportsPointFormat = true
  486. }
  487. return supportsCurve && supportsPointFormat
  488. }
  489. func (hs *serverHandshakeState) pickCipherSuite() error {
  490. c := hs.c
  491. preferenceOrder := cipherSuitesPreferenceOrder
  492. if !hasAESGCMHardwareSupport || !aesgcmPreferred(hs.clientHello.cipherSuites) {
  493. preferenceOrder = cipherSuitesPreferenceOrderNoAES
  494. }
  495. configCipherSuites := c.config.cipherSuites()
  496. preferenceList := make([]uint16, 0, len(configCipherSuites))
  497. for _, suiteID := range preferenceOrder {
  498. for _, id := range configCipherSuites {
  499. if id == suiteID {
  500. preferenceList = append(preferenceList, id)
  501. break
  502. }
  503. }
  504. }
  505. hs.suite = selectCipherSuite(preferenceList, hs.clientHello.cipherSuites, hs.cipherSuiteOk)
  506. if hs.suite == nil {
  507. c.sendAlert(alertHandshakeFailure)
  508. return errors.New("tls: no cipher suite supported by both client and server")
  509. }
  510. c.cipherSuite = hs.suite.id
  511. for _, id := range hs.clientHello.cipherSuites {
  512. if id == TLS_FALLBACK_SCSV {
  513. // The client is doing a fallback connection. See RFC 7507.
  514. if hs.clientHello.vers < c.config.maxSupportedVersion(roleServer) {
  515. c.sendAlert(alertInappropriateFallback)
  516. return errors.New("tls: client using inappropriate protocol fallback")
  517. }
  518. break
  519. }
  520. }
  521. return nil
  522. }
  523. func (hs *serverHandshakeState) cipherSuiteOk(c *cipherSuite) bool {
  524. if c.flags&suiteECDHE != 0 {
  525. if !hs.ecdheOk {
  526. return false
  527. }
  528. if c.flags&suiteECSign != 0 {
  529. if !hs.ecSignOk {
  530. return false
  531. }
  532. } else if !hs.rsaSignOk {
  533. return false
  534. }
  535. } else if !hs.rsaDecryptOk {
  536. return false
  537. }
  538. if hs.c.vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
  539. return false
  540. }
  541. return true
  542. }
  543. // checkForResumption reports whether we should perform resumption on this connection.
  544. func (hs *serverHandshakeState) checkForResumption() error {
  545. c := hs.c
  546. if c.config.SessionTicketsDisabled {
  547. return nil
  548. }
  549. var sessionState *SessionState
  550. if c.config.UnwrapSession != nil {
  551. ss, err := c.config.UnwrapSession(hs.clientHello.sessionTicket, c.connectionStateLocked())
  552. if err != nil {
  553. return err
  554. }
  555. if ss == nil {
  556. return nil
  557. }
  558. sessionState = ss
  559. } else {
  560. plaintext := c.config.decryptTicket(hs.clientHello.sessionTicket, c.ticketKeys)
  561. if plaintext == nil {
  562. return nil
  563. }
  564. ss, err := ParseSessionState(plaintext)
  565. if err != nil {
  566. return nil
  567. }
  568. sessionState = ss
  569. }
  570. // TLS 1.2 tickets don't natively have a lifetime, but we want to avoid
  571. // re-wrapping the same master secret in different tickets over and over for
  572. // too long, weakening forward secrecy.
  573. createdAt := time.Unix(int64(sessionState.createdAt), 0)
  574. if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
  575. return nil
  576. }
  577. // Never resume a session for a different TLS version.
  578. if c.vers != sessionState.version {
  579. return nil
  580. }
  581. cipherSuiteOk := false
  582. // Check that the client is still offering the ciphersuite in the session.
  583. for _, id := range hs.clientHello.cipherSuites {
  584. if id == sessionState.cipherSuite {
  585. cipherSuiteOk = true
  586. break
  587. }
  588. }
  589. if !cipherSuiteOk {
  590. return nil
  591. }
  592. // Check that we also support the ciphersuite from the session.
  593. suite := selectCipherSuite([]uint16{sessionState.cipherSuite},
  594. c.config.cipherSuites(), hs.cipherSuiteOk)
  595. if suite == nil {
  596. return nil
  597. }
  598. sessionHasClientCerts := len(sessionState.peerCertificates) != 0
  599. needClientCerts := requiresClientCert(c.config.ClientAuth)
  600. if needClientCerts && !sessionHasClientCerts {
  601. return nil
  602. }
  603. if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
  604. return nil
  605. }
  606. if sessionHasClientCerts && c.config.time().After(sessionState.peerCertificates[0].NotAfter) {
  607. return nil
  608. }
  609. if sessionHasClientCerts && c.config.ClientAuth >= VerifyClientCertIfGiven &&
  610. len(sessionState.verifiedChains) == 0 {
  611. return nil
  612. }
  613. // RFC 7627, Section 5.3
  614. if !sessionState.extMasterSecret && hs.clientHello.extendedMasterSecret {
  615. return nil
  616. }
  617. // [Psiphon]
  618. // When using obfuscated session tickets, the client-generated session ticket
  619. // state never uses EMS. ClientHellos vary in EMS support. So, in this mode,
  620. // skip this check to ensure the obfuscated session tickets are not
  621. // rejected.
  622. if !c.config.UseObfuscatedSessionTickets {
  623. if !sessionState.extMasterSecret && hs.clientHello.extendedMasterSecret {
  624. return nil
  625. }
  626. }
  627. if sessionState.extMasterSecret && !hs.clientHello.extendedMasterSecret {
  628. // Aborting is somewhat harsh, but it's a MUST and it would indicate a
  629. // weird downgrade in client capabilities.
  630. return errors.New("tls: session supported extended_master_secret but client does not")
  631. }
  632. c.peerCertificates = sessionState.peerCertificates
  633. c.ocspResponse = sessionState.ocspResponse
  634. c.scts = sessionState.scts
  635. c.verifiedChains = sessionState.verifiedChains
  636. c.extMasterSecret = sessionState.extMasterSecret
  637. hs.sessionState = sessionState
  638. hs.suite = suite
  639. c.didResume = true
  640. return nil
  641. }
  642. func (hs *serverHandshakeState) doResumeHandshake() error {
  643. c := hs.c
  644. hs.hello.cipherSuite = hs.suite.id
  645. c.cipherSuite = hs.suite.id
  646. // We echo the client's session ID in the ServerHello to let it know
  647. // that we're doing a resumption.
  648. hs.hello.sessionId = hs.clientHello.sessionId
  649. // We always send a new session ticket, even if it wraps the same master
  650. // secret and it's potentially encrypted with the same key, to help the
  651. // client avoid cross-connection tracking from a network observer.
  652. hs.hello.ticketSupported = true
  653. hs.finishedHash = newFinishedHash(c.vers, hs.suite)
  654. hs.finishedHash.discardHandshakeBuffer()
  655. if err := transcriptMsg(hs.clientHello, &hs.finishedHash); err != nil {
  656. return err
  657. }
  658. if _, err := hs.c.writeHandshakeRecord(hs.hello, &hs.finishedHash); err != nil {
  659. return err
  660. }
  661. if c.config.VerifyConnection != nil {
  662. if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
  663. c.sendAlert(alertBadCertificate)
  664. return err
  665. }
  666. }
  667. hs.masterSecret = hs.sessionState.secret
  668. return nil
  669. }
  670. func (hs *serverHandshakeState) doFullHandshake() error {
  671. c := hs.c
  672. if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
  673. hs.hello.ocspStapling = true
  674. }
  675. hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled
  676. hs.hello.cipherSuite = hs.suite.id
  677. hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite)
  678. if c.config.ClientAuth == NoClientCert {
  679. // No need to keep a full record of the handshake if client
  680. // certificates won't be used.
  681. hs.finishedHash.discardHandshakeBuffer()
  682. }
  683. if err := transcriptMsg(hs.clientHello, &hs.finishedHash); err != nil {
  684. return err
  685. }
  686. if _, err := hs.c.writeHandshakeRecord(hs.hello, &hs.finishedHash); err != nil {
  687. return err
  688. }
  689. certMsg := new(certificateMsg)
  690. certMsg.certificates = hs.cert.Certificate
  691. if _, err := hs.c.writeHandshakeRecord(certMsg, &hs.finishedHash); err != nil {
  692. return err
  693. }
  694. if hs.hello.ocspStapling {
  695. certStatus := new(certificateStatusMsg)
  696. certStatus.response = hs.cert.OCSPStaple
  697. if _, err := hs.c.writeHandshakeRecord(certStatus, &hs.finishedHash); err != nil {
  698. return err
  699. }
  700. }
  701. keyAgreement := hs.suite.ka(c.vers)
  702. skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.cert, hs.clientHello, hs.hello)
  703. if err != nil {
  704. c.sendAlert(alertHandshakeFailure)
  705. return err
  706. }
  707. if skx != nil {
  708. if _, err := hs.c.writeHandshakeRecord(skx, &hs.finishedHash); err != nil {
  709. return err
  710. }
  711. }
  712. var certReq *certificateRequestMsg
  713. if c.config.ClientAuth >= RequestClientCert {
  714. // Request a client certificate
  715. certReq = new(certificateRequestMsg)
  716. certReq.certificateTypes = []byte{
  717. byte(certTypeRSASign),
  718. byte(certTypeECDSASign),
  719. }
  720. if c.vers >= VersionTLS12 {
  721. certReq.hasSignatureAlgorithm = true
  722. certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
  723. }
  724. // An empty list of certificateAuthorities signals to
  725. // the client that it may send any certificate in response
  726. // to our request. When we know the CAs we trust, then
  727. // we can send them down, so that the client can choose
  728. // an appropriate certificate to give to us.
  729. if c.config.ClientCAs != nil {
  730. certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
  731. }
  732. if _, err := hs.c.writeHandshakeRecord(certReq, &hs.finishedHash); err != nil {
  733. return err
  734. }
  735. }
  736. helloDone := new(serverHelloDoneMsg)
  737. if _, err := hs.c.writeHandshakeRecord(helloDone, &hs.finishedHash); err != nil {
  738. return err
  739. }
  740. if _, err := c.flush(); err != nil {
  741. return err
  742. }
  743. var pub crypto.PublicKey // public key for client auth, if any
  744. msg, err := c.readHandshake(&hs.finishedHash)
  745. if err != nil {
  746. return err
  747. }
  748. // If we requested a client certificate, then the client must send a
  749. // certificate message, even if it's empty.
  750. if c.config.ClientAuth >= RequestClientCert {
  751. certMsg, ok := msg.(*certificateMsg)
  752. if !ok {
  753. c.sendAlert(alertUnexpectedMessage)
  754. return unexpectedMessageError(certMsg, msg)
  755. }
  756. if err := c.processCertsFromClient(Certificate{
  757. Certificate: certMsg.certificates,
  758. }); err != nil {
  759. return err
  760. }
  761. if len(certMsg.certificates) != 0 {
  762. pub = c.peerCertificates[0].PublicKey
  763. }
  764. msg, err = c.readHandshake(&hs.finishedHash)
  765. if err != nil {
  766. return err
  767. }
  768. }
  769. if c.config.VerifyConnection != nil {
  770. if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
  771. c.sendAlert(alertBadCertificate)
  772. return err
  773. }
  774. }
  775. // Get client key exchange
  776. ckx, ok := msg.(*clientKeyExchangeMsg)
  777. if !ok {
  778. c.sendAlert(alertUnexpectedMessage)
  779. return unexpectedMessageError(ckx, msg)
  780. }
  781. preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.cert, ckx, c.vers)
  782. if err != nil {
  783. c.sendAlert(alertHandshakeFailure)
  784. return err
  785. }
  786. if hs.hello.extendedMasterSecret {
  787. c.extMasterSecret = true
  788. hs.masterSecret = extMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret,
  789. hs.finishedHash.Sum())
  790. } else {
  791. hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret,
  792. hs.clientHello.random, hs.hello.random)
  793. }
  794. if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.clientHello.random, hs.masterSecret); err != nil {
  795. c.sendAlert(alertInternalError)
  796. return err
  797. }
  798. // If we received a client cert in response to our certificate request message,
  799. // the client will send us a certificateVerifyMsg immediately after the
  800. // clientKeyExchangeMsg. This message is a digest of all preceding
  801. // handshake-layer messages that is signed using the private key corresponding
  802. // to the client's certificate. This allows us to verify that the client is in
  803. // possession of the private key of the certificate.
  804. if len(c.peerCertificates) > 0 {
  805. // certificateVerifyMsg is included in the transcript, but not until
  806. // after we verify the handshake signature, since the state before
  807. // this message was sent is used.
  808. msg, err = c.readHandshake(nil)
  809. if err != nil {
  810. return err
  811. }
  812. certVerify, ok := msg.(*certificateVerifyMsg)
  813. if !ok {
  814. c.sendAlert(alertUnexpectedMessage)
  815. return unexpectedMessageError(certVerify, msg)
  816. }
  817. var sigType uint8
  818. var sigHash crypto.Hash
  819. if c.vers >= VersionTLS12 {
  820. if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, certReq.supportedSignatureAlgorithms) {
  821. c.sendAlert(alertIllegalParameter)
  822. return errors.New("tls: client certificate used with invalid signature algorithm")
  823. }
  824. sigType, sigHash, err = typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
  825. if err != nil {
  826. return c.sendAlert(alertInternalError)
  827. }
  828. } else {
  829. sigType, sigHash, err = legacyTypeAndHashFromPublicKey(pub)
  830. if err != nil {
  831. c.sendAlert(alertIllegalParameter)
  832. return err
  833. }
  834. }
  835. signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash)
  836. if err := verifyHandshakeSignature(sigType, pub, sigHash, signed, certVerify.signature); err != nil {
  837. c.sendAlert(alertDecryptError)
  838. return errors.New("tls: invalid signature by the client certificate: " + err.Error())
  839. }
  840. if err := transcriptMsg(certVerify, &hs.finishedHash); err != nil {
  841. return err
  842. }
  843. }
  844. hs.finishedHash.discardHandshakeBuffer()
  845. return nil
  846. }
  847. func (hs *serverHandshakeState) establishKeys() error {
  848. c := hs.c
  849. clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
  850. keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
  851. var clientCipher, serverCipher any
  852. var clientHash, serverHash hash.Hash
  853. if hs.suite.aead == nil {
  854. clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
  855. clientHash = hs.suite.mac(clientMAC)
  856. serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
  857. serverHash = hs.suite.mac(serverMAC)
  858. } else {
  859. clientCipher = hs.suite.aead(clientKey, clientIV)
  860. serverCipher = hs.suite.aead(serverKey, serverIV)
  861. }
  862. c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
  863. c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
  864. return nil
  865. }
  866. func (hs *serverHandshakeState) readFinished(out []byte) error {
  867. c := hs.c
  868. if err := c.readChangeCipherSpec(); err != nil {
  869. return err
  870. }
  871. // finishedMsg is included in the transcript, but not until after we
  872. // check the client version, since the state before this message was
  873. // sent is used during verification.
  874. msg, err := c.readHandshake(nil)
  875. if err != nil {
  876. return err
  877. }
  878. clientFinished, ok := msg.(*finishedMsg)
  879. if !ok {
  880. c.sendAlert(alertUnexpectedMessage)
  881. return unexpectedMessageError(clientFinished, msg)
  882. }
  883. verify := hs.finishedHash.clientSum(hs.masterSecret)
  884. if len(verify) != len(clientFinished.verifyData) ||
  885. subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
  886. c.sendAlert(alertHandshakeFailure)
  887. return errors.New("tls: client's Finished message is incorrect")
  888. }
  889. if err := transcriptMsg(clientFinished, &hs.finishedHash); err != nil {
  890. return err
  891. }
  892. copy(out, verify)
  893. return nil
  894. }
  895. func (hs *serverHandshakeState) sendSessionTicket() error {
  896. if !hs.hello.ticketSupported {
  897. return nil
  898. }
  899. c := hs.c
  900. m := new(newSessionTicketMsg)
  901. state, err := c.sessionState()
  902. if err != nil {
  903. return err
  904. }
  905. state.secret = hs.masterSecret
  906. if hs.sessionState != nil {
  907. // If this is re-wrapping an old key, then keep
  908. // the original time it was created.
  909. state.createdAt = hs.sessionState.createdAt
  910. }
  911. if c.config.WrapSession != nil {
  912. m.ticket, err = c.config.WrapSession(c.connectionStateLocked(), state)
  913. if err != nil {
  914. return err
  915. }
  916. } else {
  917. stateBytes, err := state.Bytes()
  918. if err != nil {
  919. return err
  920. }
  921. m.ticket, err = c.config.encryptTicket(stateBytes, c.ticketKeys)
  922. if err != nil {
  923. return err
  924. }
  925. }
  926. if _, err := hs.c.writeHandshakeRecord(m, &hs.finishedHash); err != nil {
  927. return err
  928. }
  929. return nil
  930. }
  931. func (hs *serverHandshakeState) sendFinished(out []byte) error {
  932. c := hs.c
  933. if err := c.writeChangeCipherRecord(); err != nil {
  934. return err
  935. }
  936. finished := new(finishedMsg)
  937. finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
  938. if _, err := hs.c.writeHandshakeRecord(finished, &hs.finishedHash); err != nil {
  939. return err
  940. }
  941. copy(out, finished.verifyData)
  942. return nil
  943. }
  944. // processCertsFromClient takes a chain of client certificates either from a
  945. // Certificates message and verifies them.
  946. func (c *Conn) processCertsFromClient(certificate Certificate) error {
  947. certificates := certificate.Certificate
  948. certs := make([]*x509.Certificate, len(certificates))
  949. var err error
  950. for i, asn1Data := range certificates {
  951. if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
  952. c.sendAlert(alertBadCertificate)
  953. return errors.New("tls: failed to parse client certificate: " + err.Error())
  954. }
  955. if certs[i].PublicKeyAlgorithm == x509.RSA {
  956. n := certs[i].PublicKey.(*rsa.PublicKey).N.BitLen()
  957. if max, ok := checkKeySize(n); !ok {
  958. c.sendAlert(alertBadCertificate)
  959. return fmt.Errorf("tls: client sent certificate containing RSA key larger than %d bits", max)
  960. }
  961. }
  962. }
  963. if len(certs) == 0 && requiresClientCert(c.config.ClientAuth) {
  964. if c.vers == VersionTLS13 {
  965. c.sendAlert(alertCertificateRequired)
  966. } else {
  967. c.sendAlert(alertBadCertificate)
  968. }
  969. return errors.New("tls: client didn't provide a certificate")
  970. }
  971. if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
  972. opts := x509.VerifyOptions{
  973. Roots: c.config.ClientCAs,
  974. CurrentTime: c.config.time(),
  975. Intermediates: x509.NewCertPool(),
  976. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
  977. }
  978. for _, cert := range certs[1:] {
  979. opts.Intermediates.AddCert(cert)
  980. }
  981. chains, err := certs[0].Verify(opts)
  982. if err != nil {
  983. var errCertificateInvalid x509.CertificateInvalidError
  984. if errors.As(err, &x509.UnknownAuthorityError{}) {
  985. c.sendAlert(alertUnknownCA)
  986. } else if errors.As(err, &errCertificateInvalid) && errCertificateInvalid.Reason == x509.Expired {
  987. c.sendAlert(alertCertificateExpired)
  988. } else {
  989. c.sendAlert(alertBadCertificate)
  990. }
  991. return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err}
  992. }
  993. c.verifiedChains = chains
  994. }
  995. c.peerCertificates = certs
  996. c.ocspResponse = certificate.OCSPStaple
  997. c.scts = certificate.SignedCertificateTimestamps
  998. if len(certs) > 0 {
  999. switch certs[0].PublicKey.(type) {
  1000. case *ecdsa.PublicKey, *rsa.PublicKey, ed25519.PublicKey:
  1001. default:
  1002. c.sendAlert(alertUnsupportedCertificate)
  1003. return fmt.Errorf("tls: client certificate contains an unsupported public key of type %T", certs[0].PublicKey)
  1004. }
  1005. }
  1006. if c.config.VerifyPeerCertificate != nil {
  1007. if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
  1008. c.sendAlert(alertBadCertificate)
  1009. return err
  1010. }
  1011. }
  1012. return nil
  1013. }
  1014. func clientHelloInfo(ctx context.Context, c *Conn, clientHello *clientHelloMsg) *ClientHelloInfo {
  1015. supportedVersions := clientHello.supportedVersions
  1016. if len(clientHello.supportedVersions) == 0 {
  1017. supportedVersions = supportedVersionsFromMax(clientHello.vers)
  1018. }
  1019. return &ClientHelloInfo{
  1020. CipherSuites: clientHello.cipherSuites,
  1021. ServerName: clientHello.serverName,
  1022. SupportedCurves: clientHello.supportedCurves,
  1023. SupportedPoints: clientHello.supportedPoints,
  1024. SignatureSchemes: clientHello.supportedSignatureAlgorithms,
  1025. SupportedProtos: clientHello.alpnProtocols,
  1026. SupportedVersions: supportedVersions,
  1027. Conn: c.conn,
  1028. config: c.config,
  1029. ctx: ctx,
  1030. }
  1031. }