handshake_server.go 34 KB

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