socks.go 8.0 KB

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