socks.go 7.9 KB

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