handshake_server.go 34 KB

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