client.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. package quic
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/tls"
  6. "errors"
  7. "fmt"
  8. "net"
  9. "sync"
  10. "github.com/bifurcation/mint"
  11. "github.com/lucas-clemente/quic-go/internal/handshake"
  12. "github.com/lucas-clemente/quic-go/internal/protocol"
  13. "github.com/lucas-clemente/quic-go/internal/utils"
  14. "github.com/lucas-clemente/quic-go/internal/wire"
  15. "github.com/lucas-clemente/quic-go/qerr"
  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. // [Psiphon]
  123. packetHandlers, err := getMultiplexer().AddConn(pconn, config.ConnectionIDLength)
  124. if err != nil {
  125. return nil, err
  126. }
  127. c, err := newClient(pconn, remoteAddr, config, tlsConf, host, packetHandlers.Remove, createdPacketConn)
  128. if err != nil {
  129. return nil, err
  130. }
  131. c.packetHandlers = packetHandlers
  132. if err := c.dial(ctx); err != nil {
  133. return nil, err
  134. }
  135. return c.session, nil
  136. }
  137. func newClient(
  138. pconn net.PacketConn,
  139. remoteAddr net.Addr,
  140. config *Config,
  141. tlsConf *tls.Config,
  142. host string,
  143. closeCallback func(protocol.ConnectionID),
  144. createdPacketConn bool,
  145. ) (*client, error) {
  146. if tlsConf == nil {
  147. tlsConf = &tls.Config{}
  148. }
  149. if tlsConf.ServerName == "" {
  150. var err error
  151. tlsConf.ServerName, _, err = net.SplitHostPort(host)
  152. if err != nil {
  153. return nil, err
  154. }
  155. }
  156. // check that all versions are actually supported
  157. if config != nil {
  158. for _, v := range config.Versions {
  159. if !protocol.IsValidVersion(v) {
  160. return nil, fmt.Errorf("%s is not a valid QUIC version", v)
  161. }
  162. }
  163. }
  164. onClose := func(protocol.ConnectionID) {}
  165. if closeCallback != nil {
  166. onClose = closeCallback
  167. }
  168. c := &client{
  169. conn: &conn{pconn: pconn, currentAddr: remoteAddr},
  170. createdPacketConn: createdPacketConn,
  171. tlsConf: tlsConf,
  172. config: config,
  173. version: config.Versions[0],
  174. handshakeChan: make(chan struct{}),
  175. closeCallback: onClose,
  176. logger: utils.DefaultLogger.WithPrefix("client"),
  177. }
  178. return c, c.generateConnectionIDs()
  179. }
  180. // populateClientConfig populates fields in the quic.Config with their default values, if none are set
  181. // it may be called with nil
  182. func populateClientConfig(config *Config, createdPacketConn bool) *Config {
  183. if config == nil {
  184. config = &Config{}
  185. }
  186. versions := config.Versions
  187. if len(versions) == 0 {
  188. versions = protocol.SupportedVersions
  189. }
  190. handshakeTimeout := protocol.DefaultHandshakeTimeout
  191. if config.HandshakeTimeout != 0 {
  192. handshakeTimeout = config.HandshakeTimeout
  193. }
  194. idleTimeout := protocol.DefaultIdleTimeout
  195. if config.IdleTimeout != 0 {
  196. idleTimeout = config.IdleTimeout
  197. }
  198. maxReceiveStreamFlowControlWindow := config.MaxReceiveStreamFlowControlWindow
  199. if maxReceiveStreamFlowControlWindow == 0 {
  200. maxReceiveStreamFlowControlWindow = protocol.DefaultMaxReceiveStreamFlowControlWindowClient
  201. }
  202. maxReceiveConnectionFlowControlWindow := config.MaxReceiveConnectionFlowControlWindow
  203. if maxReceiveConnectionFlowControlWindow == 0 {
  204. maxReceiveConnectionFlowControlWindow = protocol.DefaultMaxReceiveConnectionFlowControlWindowClient
  205. }
  206. maxIncomingStreams := config.MaxIncomingStreams
  207. if maxIncomingStreams == 0 {
  208. maxIncomingStreams = protocol.DefaultMaxIncomingStreams
  209. } else if maxIncomingStreams < 0 {
  210. maxIncomingStreams = 0
  211. }
  212. maxIncomingUniStreams := config.MaxIncomingUniStreams
  213. if maxIncomingUniStreams == 0 {
  214. maxIncomingUniStreams = protocol.DefaultMaxIncomingUniStreams
  215. } else if maxIncomingUniStreams < 0 {
  216. maxIncomingUniStreams = 0
  217. }
  218. connIDLen := config.ConnectionIDLength
  219. if connIDLen == 0 && !createdPacketConn {
  220. connIDLen = protocol.DefaultConnectionIDLength
  221. }
  222. for _, v := range versions {
  223. if v == protocol.Version44 {
  224. connIDLen = 0
  225. }
  226. }
  227. return &Config{
  228. Versions: versions,
  229. HandshakeTimeout: handshakeTimeout,
  230. IdleTimeout: idleTimeout,
  231. RequestConnectionIDOmission: config.RequestConnectionIDOmission,
  232. ConnectionIDLength: connIDLen,
  233. MaxReceiveStreamFlowControlWindow: maxReceiveStreamFlowControlWindow,
  234. MaxReceiveConnectionFlowControlWindow: maxReceiveConnectionFlowControlWindow,
  235. MaxIncomingStreams: maxIncomingStreams,
  236. MaxIncomingUniStreams: maxIncomingUniStreams,
  237. KeepAlive: config.KeepAlive,
  238. }
  239. }
  240. func (c *client) generateConnectionIDs() error {
  241. connIDLen := protocol.ConnectionIDLenGQUIC
  242. if c.version.UsesTLS() {
  243. connIDLen = c.config.ConnectionIDLength
  244. }
  245. srcConnID, err := generateConnectionID(connIDLen)
  246. if err != nil {
  247. return err
  248. }
  249. destConnID := srcConnID
  250. if c.version.UsesTLS() {
  251. destConnID, err = generateConnectionIDForInitial()
  252. if err != nil {
  253. return err
  254. }
  255. }
  256. c.srcConnID = srcConnID
  257. c.destConnID = destConnID
  258. if c.version == protocol.Version44 {
  259. c.srcConnID = nil
  260. }
  261. return nil
  262. }
  263. func (c *client) dial(ctx context.Context) error {
  264. 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)
  265. var err error
  266. if c.version.UsesTLS() {
  267. err = c.dialTLS(ctx)
  268. } else {
  269. err = c.dialGQUIC(ctx)
  270. }
  271. return err
  272. }
  273. func (c *client) dialGQUIC(ctx context.Context) error {
  274. if err := c.createNewGQUICSession(); err != nil {
  275. return err
  276. }
  277. err := c.establishSecureConnection(ctx)
  278. if err == errCloseSessionForNewVersion {
  279. return c.dial(ctx)
  280. }
  281. return err
  282. }
  283. func (c *client) dialTLS(ctx context.Context) error {
  284. params := &handshake.TransportParameters{
  285. StreamFlowControlWindow: protocol.ReceiveStreamFlowControlWindow,
  286. ConnectionFlowControlWindow: protocol.ReceiveConnectionFlowControlWindow,
  287. IdleTimeout: c.config.IdleTimeout,
  288. OmitConnectionID: c.config.RequestConnectionIDOmission,
  289. MaxBidiStreams: uint16(c.config.MaxIncomingStreams),
  290. MaxUniStreams: uint16(c.config.MaxIncomingUniStreams),
  291. DisableMigration: true,
  292. }
  293. extHandler := handshake.NewExtensionHandlerClient(params, c.initialVersion, c.config.Versions, c.version, c.logger)
  294. mintConf, err := tlsToMintConfig(c.tlsConf, protocol.PerspectiveClient)
  295. if err != nil {
  296. return err
  297. }
  298. mintConf.ExtensionHandler = extHandler
  299. c.mintConf = mintConf
  300. if err := c.createNewTLSSession(extHandler.GetPeerParams(), c.version); err != nil {
  301. return err
  302. }
  303. err = c.establishSecureConnection(ctx)
  304. if err == errCloseSessionForRetry || err == errCloseSessionForNewVersion {
  305. return c.dial(ctx)
  306. }
  307. return err
  308. }
  309. // establishSecureConnection runs the session, and tries to establish a secure connection
  310. // It returns:
  311. // - errCloseSessionForNewVersion when the server sends a version negotiation packet
  312. // - handshake.ErrCloseSessionForRetry when the server performs a stateless retry (for IETF QUIC)
  313. // - any other error that might occur
  314. // - when the connection is secure (for gQUIC), or forward-secure (for IETF QUIC)
  315. func (c *client) establishSecureConnection(ctx context.Context) error {
  316. errorChan := make(chan error, 1)
  317. go func() {
  318. err := c.session.run() // returns as soon as the session is closed
  319. if err != errCloseSessionForRetry && err != errCloseSessionForNewVersion && c.createdPacketConn {
  320. c.conn.Close()
  321. }
  322. errorChan <- err
  323. }()
  324. select {
  325. case <-ctx.Done():
  326. // The session will send a PeerGoingAway error to the server.
  327. c.session.Close()
  328. return ctx.Err()
  329. case err := <-errorChan:
  330. return err
  331. case <-c.handshakeChan:
  332. // handshake successfully completed
  333. return nil
  334. }
  335. }
  336. func (c *client) handlePacket(p *receivedPacket) {
  337. if err := c.handlePacketImpl(p); err != nil {
  338. c.logger.Errorf("error handling packet: %s", err)
  339. }
  340. }
  341. func (c *client) handlePacketImpl(p *receivedPacket) error {
  342. c.mutex.Lock()
  343. defer c.mutex.Unlock()
  344. // handle Version Negotiation Packets
  345. if p.header.IsVersionNegotiation {
  346. err := c.handleVersionNegotiationPacket(p.header)
  347. if err != nil {
  348. c.session.destroy(err)
  349. }
  350. // version negotiation packets have no payload
  351. return err
  352. }
  353. if !c.version.UsesIETFHeaderFormat() {
  354. connID := p.header.DestConnectionID
  355. // reject packets with truncated connection id if we didn't request truncation
  356. if !c.config.RequestConnectionIDOmission && connID.Len() == 0 {
  357. return errors.New("received packet with truncated connection ID, but didn't request truncation")
  358. }
  359. // reject packets with the wrong connection ID
  360. if connID.Len() > 0 && !connID.Equal(c.srcConnID) {
  361. return fmt.Errorf("received a packet with an unexpected connection ID (%s, expected %s)", connID, c.srcConnID)
  362. }
  363. if p.header.ResetFlag {
  364. return c.handlePublicReset(p)
  365. }
  366. } else {
  367. // reject packets with the wrong connection ID
  368. if !p.header.DestConnectionID.Equal(c.srcConnID) {
  369. return fmt.Errorf("received a packet with an unexpected connection ID (%s, expected %s)", p.header.DestConnectionID, c.srcConnID)
  370. }
  371. }
  372. if p.header.IsLongHeader {
  373. switch p.header.Type {
  374. case protocol.PacketTypeRetry:
  375. c.handleRetryPacket(p.header)
  376. return nil
  377. case protocol.PacketTypeHandshake, protocol.PacketType0RTT:
  378. default:
  379. return fmt.Errorf("Received unsupported packet type: %s", p.header.Type)
  380. }
  381. }
  382. // this is the first packet we are receiving
  383. // since it is not a Version Negotiation Packet, this means the server supports the suggested version
  384. if !c.versionNegotiated {
  385. c.versionNegotiated = true
  386. }
  387. c.session.handlePacket(p)
  388. return nil
  389. }
  390. func (c *client) handlePublicReset(p *receivedPacket) error {
  391. cr := c.conn.RemoteAddr()
  392. // check if the remote address and the connection ID match
  393. // otherwise this might be an attacker trying to inject a PUBLIC_RESET to kill the connection
  394. if cr.Network() != p.remoteAddr.Network() || cr.String() != p.remoteAddr.String() || !p.header.DestConnectionID.Equal(c.srcConnID) {
  395. return errors.New("Received a spoofed Public Reset")
  396. }
  397. pr, err := wire.ParsePublicReset(bytes.NewReader(p.data))
  398. if err != nil {
  399. return fmt.Errorf("Received a Public Reset. An error occurred parsing the packet: %s", err)
  400. }
  401. c.session.closeRemote(qerr.Error(qerr.PublicReset, fmt.Sprintf("Received a Public Reset for packet number %#x", pr.RejectedPacketNumber)))
  402. c.logger.Infof("Received Public Reset, rejected packet number: %#x", pr.RejectedPacketNumber)
  403. return nil
  404. }
  405. func (c *client) handleVersionNegotiationPacket(hdr *wire.Header) error {
  406. // ignore delayed / duplicated version negotiation packets
  407. if c.receivedVersionNegotiationPacket || c.versionNegotiated {
  408. c.logger.Debugf("Received a delayed Version Negotiation Packet.")
  409. return nil
  410. }
  411. for _, v := range hdr.SupportedVersions {
  412. if v == c.version {
  413. // the version negotiation packet contains the version that we offered
  414. // this might be a packet sent by an attacker (or by a terribly broken server implementation)
  415. // ignore it
  416. return nil
  417. }
  418. }
  419. c.logger.Infof("Received a Version Negotiation Packet. Supported Versions: %s", hdr.SupportedVersions)
  420. newVersion, ok := protocol.ChooseSupportedVersion(c.config.Versions, hdr.SupportedVersions)
  421. if !ok {
  422. return qerr.InvalidVersion
  423. }
  424. c.receivedVersionNegotiationPacket = true
  425. c.negotiatedVersions = hdr.SupportedVersions
  426. // switch to negotiated version
  427. c.initialVersion = c.version
  428. c.version = newVersion
  429. if err := c.generateConnectionIDs(); err != nil {
  430. return err
  431. }
  432. c.logger.Infof("Switching to QUIC version %s. New connection ID: %s", newVersion, c.destConnID)
  433. c.session.destroy(errCloseSessionForNewVersion)
  434. return nil
  435. }
  436. func (c *client) handleRetryPacket(hdr *wire.Header) {
  437. c.logger.Debugf("<- Received Retry")
  438. hdr.Log(c.logger)
  439. if !hdr.OrigDestConnectionID.Equal(c.destConnID) {
  440. c.logger.Debugf("Ignoring spoofed Retry. Original Destination Connection ID: %s, expected: %s", hdr.OrigDestConnectionID, c.destConnID)
  441. return
  442. }
  443. if hdr.SrcConnectionID.Equal(c.destConnID) {
  444. c.logger.Debugf("Ignoring Retry, since the server didn't change the Source Connection ID.")
  445. return
  446. }
  447. // If a token is already set, this means that we already received a Retry from the server.
  448. // Ignore this Retry packet.
  449. if len(c.token) > 0 {
  450. c.logger.Debugf("Ignoring Retry, since a Retry was already received.")
  451. return
  452. }
  453. c.destConnID = hdr.SrcConnectionID
  454. c.token = hdr.Token
  455. c.session.destroy(errCloseSessionForRetry)
  456. }
  457. func (c *client) createNewGQUICSession() error {
  458. c.mutex.Lock()
  459. defer c.mutex.Unlock()
  460. runner := &runner{
  461. onHandshakeCompleteImpl: func(_ Session) { close(c.handshakeChan) },
  462. removeConnectionIDImpl: c.closeCallback,
  463. }
  464. sess, err := newClientSession(
  465. c.conn,
  466. runner,
  467. c.version,
  468. c.destConnID,
  469. c.srcConnID,
  470. c.tlsConf,
  471. c.config,
  472. c.initialVersion,
  473. c.negotiatedVersions,
  474. c.logger,
  475. )
  476. if err != nil {
  477. return err
  478. }
  479. c.session = sess
  480. c.packetHandlers.Add(c.srcConnID, c)
  481. if c.config.RequestConnectionIDOmission {
  482. c.packetHandlers.Add(protocol.ConnectionID{}, c)
  483. }
  484. return nil
  485. }
  486. func (c *client) createNewTLSSession(
  487. paramsChan <-chan handshake.TransportParameters,
  488. version protocol.VersionNumber,
  489. ) error {
  490. c.mutex.Lock()
  491. defer c.mutex.Unlock()
  492. runner := &runner{
  493. onHandshakeCompleteImpl: func(_ Session) { close(c.handshakeChan) },
  494. removeConnectionIDImpl: c.closeCallback,
  495. }
  496. sess, err := newTLSClientSession(
  497. c.conn,
  498. runner,
  499. c.token,
  500. c.destConnID,
  501. c.srcConnID,
  502. c.config,
  503. c.mintConf,
  504. paramsChan,
  505. 1,
  506. c.logger,
  507. c.version,
  508. )
  509. if err != nil {
  510. return err
  511. }
  512. c.session = sess
  513. c.packetHandlers.Add(c.srcConnID, c)
  514. return nil
  515. }
  516. func (c *client) Close() error {
  517. c.mutex.Lock()
  518. defer c.mutex.Unlock()
  519. if c.session == nil {
  520. return nil
  521. }
  522. return c.session.Close()
  523. }
  524. func (c *client) destroy(e error) {
  525. c.mutex.Lock()
  526. defer c.mutex.Unlock()
  527. if c.session == nil {
  528. return
  529. }
  530. c.session.destroy(e)
  531. }
  532. func (c *client) GetVersion() protocol.VersionNumber {
  533. c.mutex.Lock()
  534. v := c.version
  535. c.mutex.Unlock()
  536. return v
  537. }
  538. func (c *client) GetPerspective() protocol.Perspective {
  539. return protocol.PerspectiveClient
  540. }