socksProxy.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. /*
  2. * Copyright (c) 2015, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package psiphon
  20. import (
  21. "net"
  22. "strings"
  23. "sync"
  24. socks "github.com/Psiphon-Labs/goptlib"
  25. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  26. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  27. )
  28. // SocksProxy is a SOCKS server that accepts local host connections
  29. // and, for each connection, establishes a port forward through
  30. // the tunnel SSH client and relays traffic through the port
  31. // forward.
  32. type SocksProxy struct {
  33. config *Config
  34. tunneler Tunneler
  35. listener *socks.SocksListener
  36. serveWaitGroup *sync.WaitGroup
  37. openConns *common.Conns[net.Conn]
  38. stopListeningBroadcast chan struct{}
  39. }
  40. var _SOCKS_PROXY_TYPE = "SOCKS"
  41. // NewSocksProxy initializes a new SOCKS server. It begins listening for
  42. // connections, starts a goroutine that runs an accept loop, and returns
  43. // leaving the accept loop running.
  44. func NewSocksProxy(
  45. config *Config,
  46. tunneler Tunneler,
  47. listenIP string) (proxy *SocksProxy, err error) {
  48. listener, portInUse, err := makeLocalProxyListener(
  49. listenIP, config.LocalSocksProxyPort)
  50. if err != nil {
  51. if portInUse {
  52. NoticeSocksProxyPortInUse(config.LocalSocksProxyPort)
  53. }
  54. return nil, errors.Trace(err)
  55. }
  56. proxy = &SocksProxy{
  57. config: config,
  58. tunneler: tunneler,
  59. listener: socks.NewSocksListener(listener),
  60. serveWaitGroup: new(sync.WaitGroup),
  61. openConns: common.NewConns[net.Conn](),
  62. stopListeningBroadcast: make(chan struct{}),
  63. }
  64. proxy.serveWaitGroup.Add(1)
  65. go proxy.serve()
  66. NoticeListeningSocksProxyPort(proxy.listener.Addr().(*net.TCPAddr).Port)
  67. return proxy, nil
  68. }
  69. // Close terminates the listener and waits for the accept loop
  70. // goroutine to complete.
  71. func (proxy *SocksProxy) Close() {
  72. close(proxy.stopListeningBroadcast)
  73. proxy.listener.Close()
  74. proxy.serveWaitGroup.Wait()
  75. proxy.openConns.CloseAll()
  76. }
  77. func (proxy *SocksProxy) socksConnectionHandler(localConn *socks.SocksConn) (err error) {
  78. defer localConn.Close()
  79. defer proxy.openConns.Remove(localConn)
  80. proxy.openConns.Add(localConn)
  81. // Using downstreamConn so localConn.Close() will be called when remoteConn.Close() is called.
  82. // This ensures that the downstream client (e.g., web browser) doesn't keep waiting on the
  83. // open connection for data which will never arrive.
  84. remoteConn, err := proxy.tunneler.Dial(localConn.Req.Target, localConn)
  85. if err != nil {
  86. reason := byte(socks.SocksRepGeneralFailure)
  87. // "ssh: rejected" is the prefix of ssh.OpenChannelError
  88. // TODO: retain error type and check for ssh.OpenChannelError
  89. if strings.Contains(err.Error(), "ssh: rejected") {
  90. reason = byte(socks.SocksRepConnectionRefused)
  91. }
  92. _ = localConn.RejectReason(reason)
  93. return errors.Trace(err)
  94. }
  95. defer remoteConn.Close()
  96. err = localConn.Grant(&net.TCPAddr{IP: net.ParseIP("0.0.0.0"), Port: 0})
  97. if err != nil {
  98. return errors.Trace(err)
  99. }
  100. LocalProxyRelay(proxy.config, _SOCKS_PROXY_TYPE, localConn, remoteConn)
  101. return nil
  102. }
  103. func (proxy *SocksProxy) serve() {
  104. defer proxy.listener.Close()
  105. defer proxy.serveWaitGroup.Done()
  106. loop:
  107. for {
  108. // Note: will be interrupted by listener.Close() call made by proxy.Close()
  109. socksConnection, err := proxy.listener.AcceptSocks()
  110. // Can't check for the exact error that Close() will cause in Accept(),
  111. // (see: https://code.google.com/p/go/issues/detail?id=4373). So using an
  112. // explicit stop signal to stop gracefully.
  113. select {
  114. case <-proxy.stopListeningBroadcast:
  115. break loop
  116. default:
  117. }
  118. if err != nil {
  119. NoticeWarning("SOCKS proxy accept error: %s", err)
  120. if e, ok := err.(net.Error); ok && e.Temporary() {
  121. // Temporary error, keep running
  122. continue
  123. }
  124. // Fatal error, stop the proxy
  125. proxy.tunneler.SignalComponentFailure()
  126. break loop
  127. }
  128. go func() {
  129. err := proxy.socksConnectionHandler(socksConnection)
  130. if err != nil {
  131. NoticeLocalProxyError(_SOCKS_PROXY_TYPE, errors.Trace(err))
  132. }
  133. }()
  134. }
  135. NoticeInfo("SOCKS proxy stopped")
  136. }