socks.go 7.9 KB

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