socks.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. package socks
  2. import (
  3. "errors"
  4. "io"
  5. "net"
  6. "sync"
  7. "time"
  8. "github.com/v2ray/v2ray-core/app"
  9. "github.com/v2ray/v2ray-core/common/alloc"
  10. "github.com/v2ray/v2ray-core/common/log"
  11. v2net "github.com/v2ray/v2ray-core/common/net"
  12. "github.com/v2ray/v2ray-core/common/retry"
  13. proxyerrors "github.com/v2ray/v2ray-core/proxy/common/errors"
  14. jsonconfig "github.com/v2ray/v2ray-core/proxy/socks/config/json"
  15. "github.com/v2ray/v2ray-core/proxy/socks/protocol"
  16. )
  17. var (
  18. UnsupportedSocksCommand = errors.New("Unsupported socks command.")
  19. UnsupportedAuthMethod = errors.New("Unsupported auth method.")
  20. )
  21. // SocksServer is a SOCKS 5 proxy server
  22. type SocksServer struct {
  23. accepting bool
  24. dispatcher app.PacketDispatcher
  25. config *jsonconfig.SocksConfig
  26. }
  27. func NewSocksServer(dispatcher app.PacketDispatcher, config *jsonconfig.SocksConfig) *SocksServer {
  28. return &SocksServer{
  29. dispatcher: dispatcher,
  30. config: config,
  31. }
  32. }
  33. func (this *SocksServer) Listen(port uint16) error {
  34. listener, err := net.ListenTCP("tcp", &net.TCPAddr{
  35. IP: []byte{0, 0, 0, 0},
  36. Port: int(port),
  37. Zone: "",
  38. })
  39. if err != nil {
  40. log.Error("Socks failed to listen on port %d: %v", port, err)
  41. return err
  42. }
  43. this.accepting = true
  44. go this.AcceptConnections(listener)
  45. if this.config.UDPEnabled {
  46. this.ListenUDP(port)
  47. }
  48. return nil
  49. }
  50. func (this *SocksServer) AcceptConnections(listener *net.TCPListener) {
  51. for this.accepting {
  52. retry.Timed(100 /* times */, 100 /* ms */).On(func() error {
  53. connection, err := listener.AcceptTCP()
  54. if err != nil {
  55. log.Error("Socks failed to accept new connection %v", err)
  56. return err
  57. }
  58. go this.HandleConnection(connection)
  59. return nil
  60. })
  61. }
  62. }
  63. func (this *SocksServer) HandleConnection(connection *net.TCPConn) error {
  64. defer connection.Close()
  65. reader := v2net.NewTimeOutReader(120, connection)
  66. auth, auth4, err := protocol.ReadAuthentication(reader)
  67. if err != nil && err != protocol.Socks4Downgrade {
  68. log.Error("Socks failed to read authentication: %v", err)
  69. return err
  70. }
  71. if err != nil && err == protocol.Socks4Downgrade {
  72. return this.handleSocks4(reader, connection, auth4)
  73. } else {
  74. return this.handleSocks5(reader, connection, auth)
  75. }
  76. }
  77. func (this *SocksServer) handleSocks5(reader *v2net.TimeOutReader, writer io.Writer, auth protocol.Socks5AuthenticationRequest) error {
  78. expectedAuthMethod := protocol.AuthNotRequired
  79. if this.config.IsPassword() {
  80. expectedAuthMethod = protocol.AuthUserPass
  81. }
  82. if !auth.HasAuthMethod(expectedAuthMethod) {
  83. authResponse := protocol.NewAuthenticationResponse(protocol.AuthNoMatchingMethod)
  84. err := protocol.WriteAuthentication(writer, authResponse)
  85. if err != nil {
  86. log.Error("Socks failed to write authentication: %v", err)
  87. return err
  88. }
  89. log.Warning("Socks client doesn't support allowed any auth methods.")
  90. return UnsupportedAuthMethod
  91. }
  92. authResponse := protocol.NewAuthenticationResponse(expectedAuthMethod)
  93. err := protocol.WriteAuthentication(writer, authResponse)
  94. if err != nil {
  95. log.Error("Socks failed to write authentication: %v", err)
  96. return err
  97. }
  98. if this.config.IsPassword() {
  99. upRequest, err := protocol.ReadUserPassRequest(reader)
  100. if err != nil {
  101. log.Error("Socks failed to read username and password: %v", err)
  102. return err
  103. }
  104. status := byte(0)
  105. if !this.config.HasAccount(upRequest.Username(), upRequest.Password()) {
  106. status = byte(0xFF)
  107. }
  108. upResponse := protocol.NewSocks5UserPassResponse(status)
  109. err = protocol.WriteUserPassResponse(writer, upResponse)
  110. if err != nil {
  111. log.Error("Socks failed to write user pass response: %v", err)
  112. return err
  113. }
  114. if status != byte(0) {
  115. log.Warning("Invalid user account: %s", upRequest.AuthDetail())
  116. return proxyerrors.InvalidAuthentication
  117. }
  118. }
  119. request, err := protocol.ReadRequest(reader)
  120. if err != nil {
  121. log.Error("Socks failed to read request: %v", err)
  122. return err
  123. }
  124. if request.Command == protocol.CmdUdpAssociate && this.config.UDPEnabled {
  125. return this.handleUDP(reader, writer)
  126. }
  127. if request.Command == protocol.CmdBind || request.Command == protocol.CmdUdpAssociate {
  128. response := protocol.NewSocks5Response()
  129. response.Error = protocol.ErrorCommandNotSupported
  130. response.Port = uint16(0)
  131. response.SetIPv4([]byte{0, 0, 0, 0})
  132. responseBuffer := alloc.NewSmallBuffer().Clear()
  133. response.Write(responseBuffer)
  134. _, err = writer.Write(responseBuffer.Value)
  135. responseBuffer.Release()
  136. if err != nil {
  137. log.Error("Socks failed to write response: %v", err)
  138. return err
  139. }
  140. log.Warning("Unsupported socks command %d", request.Command)
  141. return UnsupportedSocksCommand
  142. }
  143. response := protocol.NewSocks5Response()
  144. response.Error = protocol.ErrorSuccess
  145. // Some SOCKS software requires a value other than dest. Let's fake one:
  146. response.Port = uint16(1717)
  147. response.SetIPv4([]byte{0, 0, 0, 0})
  148. responseBuffer := alloc.NewSmallBuffer().Clear()
  149. response.Write(responseBuffer)
  150. _, err = writer.Write(responseBuffer.Value)
  151. responseBuffer.Release()
  152. if err != nil {
  153. log.Error("Socks failed to write response: %v", err)
  154. return err
  155. }
  156. dest := request.Destination()
  157. data, err := v2net.ReadFrom(reader, nil)
  158. if err != nil {
  159. return err
  160. }
  161. packet := v2net.NewPacket(dest, data, true)
  162. this.transport(reader, writer, packet)
  163. return nil
  164. }
  165. func (this *SocksServer) handleUDP(reader *v2net.TimeOutReader, writer io.Writer) error {
  166. response := protocol.NewSocks5Response()
  167. response.Error = protocol.ErrorSuccess
  168. udpAddr := this.getUDPAddr()
  169. response.Port = udpAddr.Port().Value()
  170. switch {
  171. case udpAddr.IsIPv4():
  172. response.SetIPv4(udpAddr.IP())
  173. case udpAddr.IsIPv6():
  174. response.SetIPv6(udpAddr.IP())
  175. case udpAddr.IsDomain():
  176. response.SetDomain(udpAddr.Domain())
  177. }
  178. responseBuffer := alloc.NewSmallBuffer().Clear()
  179. response.Write(responseBuffer)
  180. _, err := writer.Write(responseBuffer.Value)
  181. responseBuffer.Release()
  182. if err != nil {
  183. log.Error("Socks failed to write response: %v", err)
  184. return err
  185. }
  186. reader.SetTimeOut(300) /* 5 minutes */
  187. v2net.ReadFrom(reader, nil) // Just in case of anything left in the socket
  188. // The TCP connection closes after this method returns. We need to wait until
  189. // the client closes it.
  190. // TODO: get notified from UDP part
  191. <-time.After(5 * time.Minute)
  192. return nil
  193. }
  194. func (this *SocksServer) handleSocks4(reader io.Reader, writer io.Writer, auth protocol.Socks4AuthenticationRequest) error {
  195. result := protocol.Socks4RequestGranted
  196. if auth.Command == protocol.CmdBind {
  197. result = protocol.Socks4RequestRejected
  198. }
  199. socks4Response := protocol.NewSocks4AuthenticationResponse(result, auth.Port, auth.IP[:])
  200. responseBuffer := alloc.NewSmallBuffer().Clear()
  201. socks4Response.Write(responseBuffer)
  202. writer.Write(responseBuffer.Value)
  203. responseBuffer.Release()
  204. if result == protocol.Socks4RequestRejected {
  205. log.Warning("Unsupported socks 4 command %d", auth.Command)
  206. return UnsupportedSocksCommand
  207. }
  208. dest := v2net.NewTCPDestination(v2net.IPAddress(auth.IP[:], auth.Port))
  209. data, err := v2net.ReadFrom(reader, nil)
  210. if err != nil {
  211. return err
  212. }
  213. packet := v2net.NewPacket(dest, data, true)
  214. this.transport(reader, writer, packet)
  215. return nil
  216. }
  217. func (this *SocksServer) transport(reader io.Reader, writer io.Writer, firstPacket v2net.Packet) {
  218. ray := this.dispatcher.DispatchToOutbound(firstPacket)
  219. input := ray.InboundInput()
  220. output := ray.InboundOutput()
  221. var inputFinish, outputFinish sync.Mutex
  222. inputFinish.Lock()
  223. outputFinish.Lock()
  224. go func() {
  225. v2net.ReaderToChan(input, reader)
  226. inputFinish.Unlock()
  227. close(input)
  228. }()
  229. go func() {
  230. v2net.ChanToWriter(writer, output)
  231. outputFinish.Unlock()
  232. }()
  233. outputFinish.Lock()
  234. }