handshake_server.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206
  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. // [Psiphon]
  574. // *TODO* write a reason why this is commented out.
  575. // // TLS 1.2 tickets don't natively have a lifetime, but we want to avoid
  576. // // re-wrapping the same master secret in different tickets over and over for
  577. // // too long, weakening forward secrecy.
  578. // createdAt := time.Unix(int64(sessionState.createdAt), 0)
  579. // if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
  580. // return nil
  581. // }
  582. // [Psiphon]
  583. // Skip ticket lifetime check when using obfuscated session tickets.
  584. if !c.config.UseObfuscatedSessionTickets {
  585. // TLS 1.2 tickets don't natively have a lifetime, but we want to avoid
  586. // re-wrapping the same master secret in different tickets over and over for
  587. // too long, weakening forward secrecy.
  588. createdAt := time.Unix(int64(sessionState.createdAt), 0)
  589. if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
  590. return nil
  591. }
  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. // *TODO* write a reason why this is commented out.
  631. // if !sessionState.extMasterSecret && hs.clientHello.extendedMasterSecret {
  632. // return nil
  633. // }
  634. // [Psiphon]
  635. // When using obfuscated session tickets, the client-generated session ticket
  636. // state never uses EMS. ClientHellos vary in EMS support. So, in this mode,
  637. // skip this check to ensure the obfuscated session tickets are not
  638. // rejected.
  639. if !c.config.UseObfuscatedSessionTickets {
  640. if !sessionState.extMasterSecret && hs.clientHello.extendedMasterSecret {
  641. return nil
  642. }
  643. }
  644. if sessionState.extMasterSecret && !hs.clientHello.extendedMasterSecret {
  645. // Aborting is somewhat harsh, but it's a MUST and it would indicate a
  646. // weird downgrade in client capabilities.
  647. return errors.New("tls: session supported extended_master_secret but client does not")
  648. }
  649. c.peerCertificates = sessionState.peerCertificates
  650. c.ocspResponse = sessionState.ocspResponse
  651. c.scts = sessionState.scts
  652. c.verifiedChains = sessionState.verifiedChains
  653. c.extMasterSecret = sessionState.extMasterSecret
  654. hs.sessionState = sessionState
  655. hs.suite = suite
  656. c.didResume = true
  657. return nil
  658. }
  659. func (hs *serverHandshakeState) doResumeHandshake() error {
  660. c := hs.c
  661. hs.hello.cipherSuite = hs.suite.id
  662. c.cipherSuite = hs.suite.id
  663. // We echo the client's session ID in the ServerHello to let it know
  664. // that we're doing a resumption.
  665. hs.hello.sessionId = hs.clientHello.sessionId
  666. // We always send a new session ticket, even if it wraps the same master
  667. // secret and it's potentially encrypted with the same key, to help the
  668. // client avoid cross-connection tracking from a network observer.
  669. hs.hello.ticketSupported = true
  670. hs.finishedHash = newFinishedHash(c.vers, hs.suite)
  671. hs.finishedHash.discardHandshakeBuffer()
  672. if err := transcriptMsg(hs.clientHello, &hs.finishedHash); err != nil {
  673. return err
  674. }
  675. if _, err := hs.c.writeHandshakeRecord(hs.hello, &hs.finishedHash); err != nil {
  676. return err
  677. }
  678. if c.config.VerifyConnection != nil {
  679. if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
  680. c.sendAlert(alertBadCertificate)
  681. return err
  682. }
  683. }
  684. hs.masterSecret = hs.sessionState.secret
  685. return nil
  686. }
  687. func (hs *serverHandshakeState) doFullHandshake() error {
  688. c := hs.c
  689. if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
  690. hs.hello.ocspStapling = true
  691. }
  692. hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled
  693. hs.hello.cipherSuite = hs.suite.id
  694. hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite)
  695. if c.config.ClientAuth == NoClientCert {
  696. // No need to keep a full record of the handshake if client
  697. // certificates won't be used.
  698. hs.finishedHash.discardHandshakeBuffer()
  699. }
  700. if err := transcriptMsg(hs.clientHello, &hs.finishedHash); err != nil {
  701. return err
  702. }
  703. if _, err := hs.c.writeHandshakeRecord(hs.hello, &hs.finishedHash); err != nil {
  704. return err
  705. }
  706. certMsg := new(certificateMsg)
  707. certMsg.certificates = hs.cert.Certificate
  708. if _, err := hs.c.writeHandshakeRecord(certMsg, &hs.finishedHash); err != nil {
  709. return err
  710. }
  711. if hs.hello.ocspStapling {
  712. certStatus := new(certificateStatusMsg)
  713. certStatus.response = hs.cert.OCSPStaple
  714. if _, err := hs.c.writeHandshakeRecord(certStatus, &hs.finishedHash); err != nil {
  715. return err
  716. }
  717. }
  718. keyAgreement := hs.suite.ka(c.vers)
  719. skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.cert, hs.clientHello, hs.hello)
  720. if err != nil {
  721. c.sendAlert(alertHandshakeFailure)
  722. return err
  723. }
  724. if skx != nil {
  725. if _, err := hs.c.writeHandshakeRecord(skx, &hs.finishedHash); err != nil {
  726. return err
  727. }
  728. }
  729. var certReq *certificateRequestMsg
  730. if c.config.ClientAuth >= RequestClientCert {
  731. // Request a client certificate
  732. certReq = new(certificateRequestMsg)
  733. certReq.certificateTypes = []byte{
  734. byte(certTypeRSASign),
  735. byte(certTypeECDSASign),
  736. }
  737. if c.vers >= VersionTLS12 {
  738. certReq.hasSignatureAlgorithm = true
  739. certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
  740. }
  741. // An empty list of certificateAuthorities signals to
  742. // the client that it may send any certificate in response
  743. // to our request. When we know the CAs we trust, then
  744. // we can send them down, so that the client can choose
  745. // an appropriate certificate to give to us.
  746. if c.config.ClientCAs != nil {
  747. certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
  748. }
  749. if _, err := hs.c.writeHandshakeRecord(certReq, &hs.finishedHash); err != nil {
  750. return err
  751. }
  752. }
  753. helloDone := new(serverHelloDoneMsg)
  754. if _, err := hs.c.writeHandshakeRecord(helloDone, &hs.finishedHash); err != nil {
  755. return err
  756. }
  757. if _, err := c.flush(); err != nil {
  758. return err
  759. }
  760. var pub crypto.PublicKey // public key for client auth, if any
  761. msg, err := c.readHandshake(&hs.finishedHash)
  762. if err != nil {
  763. return err
  764. }
  765. // If we requested a client certificate, then the client must send a
  766. // certificate message, even if it's empty.
  767. if c.config.ClientAuth >= RequestClientCert {
  768. certMsg, ok := msg.(*certificateMsg)
  769. if !ok {
  770. c.sendAlert(alertUnexpectedMessage)
  771. return unexpectedMessageError(certMsg, msg)
  772. }
  773. if err := c.processCertsFromClient(Certificate{
  774. Certificate: certMsg.certificates,
  775. }); err != nil {
  776. return err
  777. }
  778. if len(certMsg.certificates) != 0 {
  779. pub = c.peerCertificates[0].PublicKey
  780. }
  781. msg, err = c.readHandshake(&hs.finishedHash)
  782. if err != nil {
  783. return err
  784. }
  785. }
  786. if c.config.VerifyConnection != nil {
  787. if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
  788. c.sendAlert(alertBadCertificate)
  789. return err
  790. }
  791. }
  792. // Get client key exchange
  793. ckx, ok := msg.(*clientKeyExchangeMsg)
  794. if !ok {
  795. c.sendAlert(alertUnexpectedMessage)
  796. return unexpectedMessageError(ckx, msg)
  797. }
  798. preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.cert, ckx, c.vers)
  799. if err != nil {
  800. c.sendAlert(alertHandshakeFailure)
  801. return err
  802. }
  803. if hs.hello.extendedMasterSecret {
  804. c.extMasterSecret = true
  805. hs.masterSecret = extMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret,
  806. hs.finishedHash.Sum())
  807. } else {
  808. hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret,
  809. hs.clientHello.random, hs.hello.random)
  810. }
  811. if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.clientHello.random, hs.masterSecret); err != nil {
  812. c.sendAlert(alertInternalError)
  813. return err
  814. }
  815. // If we received a client cert in response to our certificate request message,
  816. // the client will send us a certificateVerifyMsg immediately after the
  817. // clientKeyExchangeMsg. This message is a digest of all preceding
  818. // handshake-layer messages that is signed using the private key corresponding
  819. // to the client's certificate. This allows us to verify that the client is in
  820. // possession of the private key of the certificate.
  821. if len(c.peerCertificates) > 0 {
  822. // certificateVerifyMsg is included in the transcript, but not until
  823. // after we verify the handshake signature, since the state before
  824. // this message was sent is used.
  825. msg, err = c.readHandshake(nil)
  826. if err != nil {
  827. return err
  828. }
  829. certVerify, ok := msg.(*certificateVerifyMsg)
  830. if !ok {
  831. c.sendAlert(alertUnexpectedMessage)
  832. return unexpectedMessageError(certVerify, msg)
  833. }
  834. var sigType uint8
  835. var sigHash crypto.Hash
  836. if c.vers >= VersionTLS12 {
  837. if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, certReq.supportedSignatureAlgorithms) {
  838. c.sendAlert(alertIllegalParameter)
  839. return errors.New("tls: client certificate used with invalid signature algorithm")
  840. }
  841. sigType, sigHash, err = typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
  842. if err != nil {
  843. return c.sendAlert(alertInternalError)
  844. }
  845. } else {
  846. sigType, sigHash, err = legacyTypeAndHashFromPublicKey(pub)
  847. if err != nil {
  848. c.sendAlert(alertIllegalParameter)
  849. return err
  850. }
  851. }
  852. signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash)
  853. if err := verifyHandshakeSignature(sigType, pub, sigHash, signed, certVerify.signature); err != nil {
  854. c.sendAlert(alertDecryptError)
  855. return errors.New("tls: invalid signature by the client certificate: " + err.Error())
  856. }
  857. if err := transcriptMsg(certVerify, &hs.finishedHash); err != nil {
  858. return err
  859. }
  860. }
  861. hs.finishedHash.discardHandshakeBuffer()
  862. return nil
  863. }
  864. func (hs *serverHandshakeState) establishKeys() error {
  865. c := hs.c
  866. clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
  867. keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
  868. var clientCipher, serverCipher any
  869. var clientHash, serverHash hash.Hash
  870. if hs.suite.aead == nil {
  871. clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
  872. clientHash = hs.suite.mac(clientMAC)
  873. serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
  874. serverHash = hs.suite.mac(serverMAC)
  875. } else {
  876. clientCipher = hs.suite.aead(clientKey, clientIV)
  877. serverCipher = hs.suite.aead(serverKey, serverIV)
  878. }
  879. c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
  880. c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
  881. return nil
  882. }
  883. func (hs *serverHandshakeState) readFinished(out []byte) error {
  884. c := hs.c
  885. if err := c.readChangeCipherSpec(); err != nil {
  886. return err
  887. }
  888. // finishedMsg is included in the transcript, but not until after we
  889. // check the client version, since the state before this message was
  890. // sent is used during verification.
  891. msg, err := c.readHandshake(nil)
  892. if err != nil {
  893. return err
  894. }
  895. clientFinished, ok := msg.(*finishedMsg)
  896. if !ok {
  897. c.sendAlert(alertUnexpectedMessage)
  898. return unexpectedMessageError(clientFinished, msg)
  899. }
  900. verify := hs.finishedHash.clientSum(hs.masterSecret)
  901. if len(verify) != len(clientFinished.verifyData) ||
  902. subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
  903. c.sendAlert(alertHandshakeFailure)
  904. return errors.New("tls: client's Finished message is incorrect")
  905. }
  906. if err := transcriptMsg(clientFinished, &hs.finishedHash); err != nil {
  907. return err
  908. }
  909. copy(out, verify)
  910. return nil
  911. }
  912. func (hs *serverHandshakeState) sendSessionTicket() error {
  913. if !hs.hello.ticketSupported {
  914. return nil
  915. }
  916. c := hs.c
  917. m := new(newSessionTicketMsg)
  918. state, err := c.sessionState()
  919. if err != nil {
  920. return err
  921. }
  922. state.secret = hs.masterSecret
  923. if hs.sessionState != nil {
  924. // If this is re-wrapping an old key, then keep
  925. // the original time it was created.
  926. state.createdAt = hs.sessionState.createdAt
  927. }
  928. if c.config.WrapSession != nil {
  929. m.ticket, err = c.config.WrapSession(c.connectionStateLocked(), state)
  930. if err != nil {
  931. return err
  932. }
  933. } else {
  934. stateBytes, err := state.Bytes()
  935. if err != nil {
  936. return err
  937. }
  938. m.ticket, err = c.config.encryptTicket(stateBytes, c.ticketKeys)
  939. if err != nil {
  940. return err
  941. }
  942. }
  943. if _, err := hs.c.writeHandshakeRecord(m, &hs.finishedHash); err != nil {
  944. return err
  945. }
  946. return nil
  947. }
  948. func (hs *serverHandshakeState) sendFinished(out []byte) error {
  949. c := hs.c
  950. if err := c.writeChangeCipherRecord(); err != nil {
  951. return err
  952. }
  953. finished := new(finishedMsg)
  954. finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
  955. if _, err := hs.c.writeHandshakeRecord(finished, &hs.finishedHash); err != nil {
  956. return err
  957. }
  958. copy(out, finished.verifyData)
  959. return nil
  960. }
  961. // processCertsFromClient takes a chain of client certificates either from a
  962. // Certificates message and verifies them.
  963. func (c *Conn) processCertsFromClient(certificate Certificate) error {
  964. certificates := certificate.Certificate
  965. certs := make([]*x509.Certificate, len(certificates))
  966. var err error
  967. for i, asn1Data := range certificates {
  968. if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
  969. c.sendAlert(alertBadCertificate)
  970. return errors.New("tls: failed to parse client certificate: " + err.Error())
  971. }
  972. if certs[i].PublicKeyAlgorithm == x509.RSA {
  973. n := certs[i].PublicKey.(*rsa.PublicKey).N.BitLen()
  974. if max, ok := checkKeySize(n); !ok {
  975. c.sendAlert(alertBadCertificate)
  976. return fmt.Errorf("tls: client sent certificate containing RSA key larger than %d bits", max)
  977. }
  978. }
  979. }
  980. if len(certs) == 0 && requiresClientCert(c.config.ClientAuth) {
  981. if c.vers == VersionTLS13 {
  982. c.sendAlert(alertCertificateRequired)
  983. } else {
  984. c.sendAlert(alertBadCertificate)
  985. }
  986. return errors.New("tls: client didn't provide a certificate")
  987. }
  988. if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
  989. opts := x509.VerifyOptions{
  990. Roots: c.config.ClientCAs,
  991. CurrentTime: c.config.time(),
  992. Intermediates: x509.NewCertPool(),
  993. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
  994. }
  995. for _, cert := range certs[1:] {
  996. opts.Intermediates.AddCert(cert)
  997. }
  998. chains, err := certs[0].Verify(opts)
  999. if err != nil {
  1000. var errCertificateInvalid x509.CertificateInvalidError
  1001. if errors.As(err, &x509.UnknownAuthorityError{}) {
  1002. c.sendAlert(alertUnknownCA)
  1003. } else if errors.As(err, &errCertificateInvalid) && errCertificateInvalid.Reason == x509.Expired {
  1004. c.sendAlert(alertCertificateExpired)
  1005. } else {
  1006. c.sendAlert(alertBadCertificate)
  1007. }
  1008. return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err}
  1009. }
  1010. c.verifiedChains = chains
  1011. }
  1012. c.peerCertificates = certs
  1013. c.ocspResponse = certificate.OCSPStaple
  1014. c.scts = certificate.SignedCertificateTimestamps
  1015. if len(certs) > 0 {
  1016. switch certs[0].PublicKey.(type) {
  1017. case *ecdsa.PublicKey, *rsa.PublicKey, ed25519.PublicKey:
  1018. default:
  1019. c.sendAlert(alertUnsupportedCertificate)
  1020. return fmt.Errorf("tls: client certificate contains an unsupported public key of type %T", certs[0].PublicKey)
  1021. }
  1022. }
  1023. if c.config.VerifyPeerCertificate != nil {
  1024. if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
  1025. c.sendAlert(alertBadCertificate)
  1026. return err
  1027. }
  1028. }
  1029. return nil
  1030. }
  1031. func clientHelloInfo(ctx context.Context, c *Conn, clientHello *clientHelloMsg) *ClientHelloInfo {
  1032. supportedVersions := clientHello.supportedVersions
  1033. if len(clientHello.supportedVersions) == 0 {
  1034. supportedVersions = supportedVersionsFromMax(clientHello.vers)
  1035. }
  1036. return &ClientHelloInfo{
  1037. CipherSuites: clientHello.cipherSuites,
  1038. ServerName: clientHello.serverName,
  1039. SupportedCurves: clientHello.supportedCurves,
  1040. SupportedPoints: clientHello.supportedPoints,
  1041. SignatureSchemes: clientHello.supportedSignatureAlgorithms,
  1042. SupportedProtos: clientHello.alpnProtocols,
  1043. SupportedVersions: supportedVersions,
  1044. Conn: c.conn,
  1045. config: c.config,
  1046. ctx: ctx,
  1047. }
  1048. }