client.go 17 KB

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