client.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. package gquic
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/tls"
  6. "errors"
  7. "fmt"
  8. "net"
  9. "sync"
  10. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic/gquic-go/internal/handshake"
  11. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic/gquic-go/internal/protocol"
  12. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic/gquic-go/internal/utils"
  13. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic/gquic-go/internal/wire"
  14. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic/gquic-go/qerr"
  15. "github.com/bifurcation/mint"
  16. )
  17. type client struct {
  18. mutex sync.Mutex
  19. conn connection
  20. // If the client is created with DialAddr, we create a packet conn.
  21. // If it is started with Dial, we take a packet conn as a parameter.
  22. createdPacketConn bool
  23. packetHandlers packetHandlerManager
  24. token []byte
  25. versionNegotiated bool // has the server accepted our version
  26. receivedVersionNegotiationPacket bool
  27. negotiatedVersions []protocol.VersionNumber // the list of versions from the version negotiation packet
  28. tlsConf *tls.Config
  29. mintConf *mint.Config
  30. config *Config
  31. srcConnID protocol.ConnectionID
  32. destConnID protocol.ConnectionID
  33. initialVersion protocol.VersionNumber
  34. version protocol.VersionNumber
  35. handshakeChan chan struct{}
  36. closeCallback func(protocol.ConnectionID)
  37. session quicSession
  38. logger utils.Logger
  39. }
  40. var _ packetHandler = &client{}
  41. var (
  42. // make it possible to mock connection ID generation in the tests
  43. generateConnectionID = protocol.GenerateConnectionID
  44. generateConnectionIDForInitial = protocol.GenerateConnectionIDForInitial
  45. errCloseSessionForNewVersion = errors.New("closing session in order to recreate it with a new version")
  46. errCloseSessionForRetry = errors.New("closing session in response to a stateless retry")
  47. )
  48. // DialAddr establishes a new QUIC connection to a server.
  49. // The hostname for SNI is taken from the given address.
  50. func DialAddr(
  51. addr string,
  52. tlsConf *tls.Config,
  53. config *Config,
  54. ) (Session, error) {
  55. return DialAddrContext(context.Background(), addr, tlsConf, config)
  56. }
  57. // DialAddrContext establishes a new QUIC connection to a server using the provided context.
  58. // The hostname for SNI is taken from the given address.
  59. func DialAddrContext(
  60. ctx context.Context,
  61. addr string,
  62. tlsConf *tls.Config,
  63. config *Config,
  64. ) (Session, error) {
  65. udpAddr, err := net.ResolveUDPAddr("udp", addr)
  66. if err != nil {
  67. return nil, err
  68. }
  69. udpConn, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4zero, Port: 0})
  70. if err != nil {
  71. return nil, err
  72. }
  73. return dialContext(ctx, udpConn, udpAddr, addr, tlsConf, config, true)
  74. }
  75. // Dial establishes a new QUIC connection to a server using a net.PacketConn.
  76. // The host parameter is used for SNI.
  77. func Dial(
  78. pconn net.PacketConn,
  79. remoteAddr net.Addr,
  80. host string,
  81. tlsConf *tls.Config,
  82. config *Config,
  83. ) (Session, error) {
  84. return DialContext(context.Background(), pconn, remoteAddr, host, tlsConf, config)
  85. }
  86. // DialContext establishes a new QUIC connection to a server using a net.PacketConn using the provided context.
  87. // The host parameter is used for SNI.
  88. func DialContext(
  89. ctx context.Context,
  90. pconn net.PacketConn,
  91. remoteAddr net.Addr,
  92. host string,
  93. tlsConf *tls.Config,
  94. config *Config,
  95. ) (Session, error) {
  96. return dialContext(ctx, pconn, remoteAddr, host, tlsConf, config, false)
  97. }
  98. func dialContext(
  99. ctx context.Context,
  100. pconn net.PacketConn,
  101. remoteAddr net.Addr,
  102. host string,
  103. tlsConf *tls.Config,
  104. config *Config,
  105. createdPacketConn bool,
  106. ) (Session, error) {
  107. // [Psiphon]
  108. // We call DialContext as we need to create a custom net.PacketConn.
  109. // There is one custom net.PacketConn per QUIC connection, which
  110. // satisfies the gQUIC 44 constraint.
  111. config = populateClientConfig(config, true)
  112. /*
  113. config = populateClientConfig(config, createdPacketConn)
  114. if !createdPacketConn {
  115. for _, v := range config.Versions {
  116. if v == protocol.Version44 {
  117. return nil, errors.New("Cannot multiplex connections using gQUIC 44, see https://groups.google.com/a/chromium.org/forum/#!topic/proto-quic/pE9NlLLjizE. Please disable gQUIC 44 in the quic.Config, or use DialAddr")
  118. }
  119. }
  120. }
  121. }
  122. */
  123. // [Psiphon]
  124. packetHandlers, err := getMultiplexer().AddConn(pconn, config.ConnectionIDLength)
  125. if err != nil {
  126. return nil, err
  127. }
  128. c, err := newClient(pconn, remoteAddr, config, tlsConf, host, packetHandlers.Remove, createdPacketConn)
  129. if err != nil {
  130. return nil, err
  131. }
  132. c.packetHandlers = packetHandlers
  133. if err := c.dial(ctx); err != nil {
  134. return nil, err
  135. }
  136. return c.session, nil
  137. }
  138. func newClient(
  139. pconn net.PacketConn,
  140. remoteAddr net.Addr,
  141. config *Config,
  142. tlsConf *tls.Config,
  143. host string,
  144. closeCallback func(protocol.ConnectionID),
  145. createdPacketConn bool,
  146. ) (*client, error) {
  147. if tlsConf == nil {
  148. tlsConf = &tls.Config{}
  149. }
  150. if tlsConf.ServerName == "" {
  151. var err error
  152. tlsConf.ServerName, _, err = net.SplitHostPort(host)
  153. if err != nil {
  154. return nil, err
  155. }
  156. }
  157. // check that all versions are actually supported
  158. if config != nil {
  159. for _, v := range config.Versions {
  160. if !protocol.IsValidVersion(v) {
  161. return nil, fmt.Errorf("%s is not a valid QUIC version", v)
  162. }
  163. }
  164. }
  165. onClose := func(protocol.ConnectionID) {}
  166. if closeCallback != nil {
  167. onClose = closeCallback
  168. }
  169. c := &client{
  170. conn: &conn{pconn: pconn, currentAddr: remoteAddr},
  171. createdPacketConn: createdPacketConn,
  172. tlsConf: tlsConf,
  173. config: config,
  174. version: config.Versions[0],
  175. handshakeChan: make(chan struct{}),
  176. closeCallback: onClose,
  177. logger: utils.DefaultLogger.WithPrefix("client"),
  178. }
  179. return c, c.generateConnectionIDs()
  180. }
  181. // populateClientConfig populates fields in the quic.Config with their default values, if none are set
  182. // it may be called with nil
  183. func populateClientConfig(config *Config, createdPacketConn bool) *Config {
  184. if config == nil {
  185. config = &Config{}
  186. }
  187. versions := config.Versions
  188. if len(versions) == 0 {
  189. versions = protocol.SupportedVersions
  190. }
  191. handshakeTimeout := protocol.DefaultHandshakeTimeout
  192. if config.HandshakeTimeout != 0 {
  193. handshakeTimeout = config.HandshakeTimeout
  194. }
  195. idleTimeout := protocol.DefaultIdleTimeout
  196. if config.IdleTimeout != 0 {
  197. idleTimeout = config.IdleTimeout
  198. }
  199. maxReceiveStreamFlowControlWindow := config.MaxReceiveStreamFlowControlWindow
  200. if maxReceiveStreamFlowControlWindow == 0 {
  201. maxReceiveStreamFlowControlWindow = protocol.DefaultMaxReceiveStreamFlowControlWindowClient
  202. }
  203. maxReceiveConnectionFlowControlWindow := config.MaxReceiveConnectionFlowControlWindow
  204. if maxReceiveConnectionFlowControlWindow == 0 {
  205. maxReceiveConnectionFlowControlWindow = protocol.DefaultMaxReceiveConnectionFlowControlWindowClient
  206. }
  207. maxIncomingStreams := config.MaxIncomingStreams
  208. if maxIncomingStreams == 0 {
  209. maxIncomingStreams = protocol.DefaultMaxIncomingStreams
  210. } else if maxIncomingStreams < 0 {
  211. maxIncomingStreams = 0
  212. }
  213. maxIncomingUniStreams := config.MaxIncomingUniStreams
  214. if maxIncomingUniStreams == 0 {
  215. maxIncomingUniStreams = protocol.DefaultMaxIncomingUniStreams
  216. } else if maxIncomingUniStreams < 0 {
  217. maxIncomingUniStreams = 0
  218. }
  219. connIDLen := config.ConnectionIDLength
  220. if connIDLen == 0 && !createdPacketConn {
  221. connIDLen = protocol.DefaultConnectionIDLength
  222. }
  223. for _, v := range versions {
  224. if v == protocol.Version44 {
  225. connIDLen = 0
  226. }
  227. }
  228. return &Config{
  229. Versions: versions,
  230. HandshakeTimeout: handshakeTimeout,
  231. IdleTimeout: idleTimeout,
  232. RequestConnectionIDOmission: config.RequestConnectionIDOmission,
  233. ConnectionIDLength: connIDLen,
  234. MaxReceiveStreamFlowControlWindow: maxReceiveStreamFlowControlWindow,
  235. MaxReceiveConnectionFlowControlWindow: maxReceiveConnectionFlowControlWindow,
  236. MaxIncomingStreams: maxIncomingStreams,
  237. MaxIncomingUniStreams: maxIncomingUniStreams,
  238. KeepAlive: config.KeepAlive,
  239. }
  240. }
  241. func (c *client) generateConnectionIDs() error {
  242. connIDLen := protocol.ConnectionIDLenGQUIC
  243. if c.version.UsesTLS() {
  244. connIDLen = c.config.ConnectionIDLength
  245. }
  246. srcConnID, err := generateConnectionID(connIDLen)
  247. if err != nil {
  248. return err
  249. }
  250. destConnID := srcConnID
  251. if c.version.UsesTLS() {
  252. destConnID, err = generateConnectionIDForInitial()
  253. if err != nil {
  254. return err
  255. }
  256. }
  257. c.srcConnID = srcConnID
  258. c.destConnID = destConnID
  259. if c.version == protocol.Version44 {
  260. c.srcConnID = nil
  261. }
  262. return nil
  263. }
  264. func (c *client) dial(ctx context.Context) error {
  265. c.logger.Infof("Starting new connection to %s (%s -> %s), source connection ID %s, destination connection ID %s, version %s", c.tlsConf.ServerName, c.conn.LocalAddr(), c.conn.RemoteAddr(), c.srcConnID, c.destConnID, c.version)
  266. var err error
  267. if c.version.UsesTLS() {
  268. err = c.dialTLS(ctx)
  269. } else {
  270. err = c.dialGQUIC(ctx)
  271. }
  272. return err
  273. }
  274. func (c *client) dialGQUIC(ctx context.Context) error {
  275. if err := c.createNewGQUICSession(); err != nil {
  276. return err
  277. }
  278. err := c.establishSecureConnection(ctx)
  279. if err == errCloseSessionForNewVersion {
  280. return c.dial(ctx)
  281. }
  282. return err
  283. }
  284. func (c *client) dialTLS(ctx context.Context) error {
  285. params := &handshake.TransportParameters{
  286. StreamFlowControlWindow: protocol.ReceiveStreamFlowControlWindow,
  287. ConnectionFlowControlWindow: protocol.ReceiveConnectionFlowControlWindow,
  288. IdleTimeout: c.config.IdleTimeout,
  289. OmitConnectionID: c.config.RequestConnectionIDOmission,
  290. MaxBidiStreams: uint16(c.config.MaxIncomingStreams),
  291. MaxUniStreams: uint16(c.config.MaxIncomingUniStreams),
  292. DisableMigration: true,
  293. }
  294. extHandler := handshake.NewExtensionHandlerClient(params, c.initialVersion, c.config.Versions, c.version, c.logger)
  295. mintConf, err := tlsToMintConfig(c.tlsConf, protocol.PerspectiveClient)
  296. if err != nil {
  297. return err
  298. }
  299. mintConf.ExtensionHandler = extHandler
  300. c.mintConf = mintConf
  301. if err := c.createNewTLSSession(extHandler.GetPeerParams(), c.version); err != nil {
  302. return err
  303. }
  304. err = c.establishSecureConnection(ctx)
  305. if err == errCloseSessionForRetry || err == errCloseSessionForNewVersion {
  306. return c.dial(ctx)
  307. }
  308. return err
  309. }
  310. // establishSecureConnection runs the session, and tries to establish a secure connection
  311. // It returns:
  312. // - errCloseSessionForNewVersion when the server sends a version negotiation packet
  313. // - handshake.ErrCloseSessionForRetry when the server performs a stateless retry (for IETF QUIC)
  314. // - any other error that might occur
  315. // - when the connection is secure (for gQUIC), or forward-secure (for IETF QUIC)
  316. func (c *client) establishSecureConnection(ctx context.Context) error {
  317. errorChan := make(chan error, 1)
  318. go func() {
  319. err := c.session.run() // returns as soon as the session is closed
  320. if err != errCloseSessionForRetry && err != errCloseSessionForNewVersion && c.createdPacketConn {
  321. c.conn.Close()
  322. }
  323. errorChan <- err
  324. }()
  325. select {
  326. case <-ctx.Done():
  327. // The session will send a PeerGoingAway error to the server.
  328. c.session.Close()
  329. return ctx.Err()
  330. case err := <-errorChan:
  331. return err
  332. case <-c.handshakeChan:
  333. // handshake successfully completed
  334. return nil
  335. }
  336. }
  337. func (c *client) handlePacket(p *receivedPacket) {
  338. if err := c.handlePacketImpl(p); err != nil {
  339. c.logger.Errorf("error handling packet: %s", err)
  340. }
  341. }
  342. func (c *client) handlePacketImpl(p *receivedPacket) error {
  343. c.mutex.Lock()
  344. defer c.mutex.Unlock()
  345. // handle Version Negotiation Packets
  346. if p.header.IsVersionNegotiation {
  347. err := c.handleVersionNegotiationPacket(p.header)
  348. if err != nil {
  349. c.session.destroy(err)
  350. }
  351. // version negotiation packets have no payload
  352. return err
  353. }
  354. if !c.version.UsesIETFHeaderFormat() {
  355. connID := p.header.DestConnectionID
  356. // reject packets with truncated connection id if we didn't request truncation
  357. if !c.config.RequestConnectionIDOmission && connID.Len() == 0 {
  358. return errors.New("received packet with truncated connection ID, but didn't request truncation")
  359. }
  360. // reject packets with the wrong connection ID
  361. if connID.Len() > 0 && !connID.Equal(c.srcConnID) {
  362. return fmt.Errorf("received a packet with an unexpected connection ID (%s, expected %s)", connID, c.srcConnID)
  363. }
  364. if p.header.ResetFlag {
  365. return c.handlePublicReset(p)
  366. }
  367. } else {
  368. // reject packets with the wrong connection ID
  369. if !p.header.DestConnectionID.Equal(c.srcConnID) {
  370. return fmt.Errorf("received a packet with an unexpected connection ID (%s, expected %s)", p.header.DestConnectionID, c.srcConnID)
  371. }
  372. }
  373. if p.header.IsLongHeader {
  374. switch p.header.Type {
  375. case protocol.PacketTypeRetry:
  376. c.handleRetryPacket(p.header)
  377. return nil
  378. case protocol.PacketTypeHandshake, protocol.PacketType0RTT:
  379. // [Psiphon]
  380. // The fix in https://github.com/lucas-clemente/quic-go/commit/386b77f422028fe86aae7ae9c017ca2c692c8184 must
  381. // also be applied here.
  382. case protocol.PacketTypeInitial:
  383. if p.header.Version == protocol.Version44 {
  384. break
  385. }
  386. fallthrough
  387. // [Psiphon]
  388. default:
  389. return fmt.Errorf("Received unsupported packet type: %s", p.header.Type)
  390. }
  391. }
  392. // this is the first packet we are receiving
  393. // since it is not a Version Negotiation Packet, this means the server supports the suggested version
  394. if !c.versionNegotiated {
  395. c.versionNegotiated = true
  396. }
  397. c.session.handlePacket(p)
  398. return nil
  399. }
  400. func (c *client) handlePublicReset(p *receivedPacket) error {
  401. cr := c.conn.RemoteAddr()
  402. // check if the remote address and the connection ID match
  403. // otherwise this might be an attacker trying to inject a PUBLIC_RESET to kill the connection
  404. if cr.Network() != p.remoteAddr.Network() || cr.String() != p.remoteAddr.String() || !p.header.DestConnectionID.Equal(c.srcConnID) {
  405. return errors.New("Received a spoofed Public Reset")
  406. }
  407. pr, err := wire.ParsePublicReset(bytes.NewReader(p.data))
  408. if err != nil {
  409. return fmt.Errorf("Received a Public Reset. An error occurred parsing the packet: %s", err)
  410. }
  411. c.session.closeRemote(qerr.Error(qerr.PublicReset, fmt.Sprintf("Received a Public Reset for packet number %#x", pr.RejectedPacketNumber)))
  412. c.logger.Infof("Received Public Reset, rejected packet number: %#x", pr.RejectedPacketNumber)
  413. return nil
  414. }
  415. func (c *client) handleVersionNegotiationPacket(hdr *wire.Header) error {
  416. // ignore delayed / duplicated version negotiation packets
  417. if c.receivedVersionNegotiationPacket || c.versionNegotiated {
  418. c.logger.Debugf("Received a delayed Version Negotiation Packet.")
  419. return nil
  420. }
  421. for _, v := range hdr.SupportedVersions {
  422. if v == c.version {
  423. // the version negotiation packet contains the version that we offered
  424. // this might be a packet sent by an attacker (or by a terribly broken server implementation)
  425. // ignore it
  426. return nil
  427. }
  428. }
  429. c.logger.Infof("Received a Version Negotiation Packet. Supported Versions: %s", hdr.SupportedVersions)
  430. newVersion, ok := protocol.ChooseSupportedVersion(c.config.Versions, hdr.SupportedVersions)
  431. if !ok {
  432. return qerr.InvalidVersion
  433. }
  434. c.receivedVersionNegotiationPacket = true
  435. c.negotiatedVersions = hdr.SupportedVersions
  436. // switch to negotiated version
  437. c.initialVersion = c.version
  438. c.version = newVersion
  439. if err := c.generateConnectionIDs(); err != nil {
  440. return err
  441. }
  442. c.logger.Infof("Switching to QUIC version %s. New connection ID: %s", newVersion, c.destConnID)
  443. c.session.destroy(errCloseSessionForNewVersion)
  444. return nil
  445. }
  446. func (c *client) handleRetryPacket(hdr *wire.Header) {
  447. c.logger.Debugf("<- Received Retry")
  448. hdr.Log(c.logger)
  449. if !hdr.OrigDestConnectionID.Equal(c.destConnID) {
  450. c.logger.Debugf("Ignoring spoofed Retry. Original Destination Connection ID: %s, expected: %s", hdr.OrigDestConnectionID, c.destConnID)
  451. return
  452. }
  453. if hdr.SrcConnectionID.Equal(c.destConnID) {
  454. c.logger.Debugf("Ignoring Retry, since the server didn't change the Source Connection ID.")
  455. return
  456. }
  457. // If a token is already set, this means that we already received a Retry from the server.
  458. // Ignore this Retry packet.
  459. if len(c.token) > 0 {
  460. c.logger.Debugf("Ignoring Retry, since a Retry was already received.")
  461. return
  462. }
  463. c.destConnID = hdr.SrcConnectionID
  464. c.token = hdr.Token
  465. c.session.destroy(errCloseSessionForRetry)
  466. }
  467. func (c *client) createNewGQUICSession() error {
  468. c.mutex.Lock()
  469. defer c.mutex.Unlock()
  470. runner := &runner{
  471. onHandshakeCompleteImpl: func(_ Session) { close(c.handshakeChan) },
  472. removeConnectionIDImpl: c.closeCallback,
  473. }
  474. sess, err := newClientSession(
  475. c.conn,
  476. runner,
  477. c.version,
  478. c.destConnID,
  479. c.srcConnID,
  480. c.tlsConf,
  481. c.config,
  482. c.initialVersion,
  483. c.negotiatedVersions,
  484. c.logger,
  485. )
  486. if err != nil {
  487. return err
  488. }
  489. c.session = sess
  490. c.packetHandlers.Add(c.srcConnID, c)
  491. if c.config.RequestConnectionIDOmission {
  492. c.packetHandlers.Add(protocol.ConnectionID{}, c)
  493. }
  494. return nil
  495. }
  496. func (c *client) createNewTLSSession(
  497. paramsChan <-chan handshake.TransportParameters,
  498. version protocol.VersionNumber,
  499. ) error {
  500. c.mutex.Lock()
  501. defer c.mutex.Unlock()
  502. runner := &runner{
  503. onHandshakeCompleteImpl: func(_ Session) { close(c.handshakeChan) },
  504. removeConnectionIDImpl: c.closeCallback,
  505. }
  506. sess, err := newTLSClientSession(
  507. c.conn,
  508. runner,
  509. c.token,
  510. c.destConnID,
  511. c.srcConnID,
  512. c.config,
  513. c.mintConf,
  514. paramsChan,
  515. 1,
  516. c.logger,
  517. c.version,
  518. )
  519. if err != nil {
  520. return err
  521. }
  522. c.session = sess
  523. c.packetHandlers.Add(c.srcConnID, c)
  524. return nil
  525. }
  526. func (c *client) Close() error {
  527. c.mutex.Lock()
  528. defer c.mutex.Unlock()
  529. if c.session == nil {
  530. return nil
  531. }
  532. return c.session.Close()
  533. }
  534. func (c *client) destroy(e error) {
  535. c.mutex.Lock()
  536. defer c.mutex.Unlock()
  537. if c.session == nil {
  538. return
  539. }
  540. c.session.destroy(e)
  541. }
  542. func (c *client) GetVersion() protocol.VersionNumber {
  543. c.mutex.Lock()
  544. v := c.version
  545. c.mutex.Unlock()
  546. return v
  547. }
  548. func (c *client) GetPerspective() protocol.Perspective {
  549. return protocol.PerspectiveClient
  550. }