socks.go 7.8 KB

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