server.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. package socks
  2. import (
  3. "context"
  4. goerrors "errors"
  5. "io"
  6. "time"
  7. "github.com/xtls/xray-core/common"
  8. "github.com/xtls/xray-core/common/buf"
  9. "github.com/xtls/xray-core/common/errors"
  10. "github.com/xtls/xray-core/common/log"
  11. "github.com/xtls/xray-core/common/net"
  12. "github.com/xtls/xray-core/common/protocol"
  13. udp_proto "github.com/xtls/xray-core/common/protocol/udp"
  14. "github.com/xtls/xray-core/common/session"
  15. "github.com/xtls/xray-core/core"
  16. "github.com/xtls/xray-core/features/policy"
  17. "github.com/xtls/xray-core/features/routing"
  18. "github.com/xtls/xray-core/proxy"
  19. "github.com/xtls/xray-core/proxy/http"
  20. "github.com/xtls/xray-core/transport"
  21. "github.com/xtls/xray-core/transport/internet/stat"
  22. "github.com/xtls/xray-core/transport/internet/udp"
  23. )
  24. // Server is a SOCKS 5 proxy server
  25. type Server struct {
  26. config *ServerConfig
  27. policyManager policy.Manager
  28. cone bool
  29. udpFilter *UDPFilter
  30. httpServer *http.Server
  31. }
  32. // NewServer creates a new Server object.
  33. func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
  34. v := core.MustFromContext(ctx)
  35. s := &Server{
  36. config: config,
  37. policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
  38. cone: ctx.Value("cone").(bool),
  39. }
  40. httpConfig := &http.ServerConfig{
  41. UserLevel: config.UserLevel,
  42. }
  43. if config.AuthType == AuthType_PASSWORD {
  44. httpConfig.Accounts = config.Accounts
  45. s.udpFilter = new(UDPFilter) // We only use this when auth is enabled
  46. }
  47. s.httpServer, _ = http.NewServer(ctx, httpConfig)
  48. return s, nil
  49. }
  50. func (s *Server) policy() policy.Session {
  51. config := s.config
  52. p := s.policyManager.ForLevel(config.UserLevel)
  53. return p
  54. }
  55. // Network implements proxy.Inbound.
  56. func (s *Server) Network() []net.Network {
  57. list := []net.Network{net.Network_TCP}
  58. if s.config.UdpEnabled {
  59. list = append(list, net.Network_UDP)
  60. }
  61. return list
  62. }
  63. // Process implements proxy.Inbound.
  64. func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Connection, dispatcher routing.Dispatcher) error {
  65. inbound := session.InboundFromContext(ctx)
  66. inbound.Name = "socks"
  67. inbound.CanSpliceCopy = 2
  68. inbound.User = &protocol.MemoryUser{
  69. Level: s.config.UserLevel,
  70. }
  71. if !proxy.IsRAWTransportWithoutSecurity(conn) {
  72. inbound.CanSpliceCopy = 3
  73. }
  74. switch network {
  75. case net.Network_TCP:
  76. firstbyte := make([]byte, 1)
  77. if n, err := conn.Read(firstbyte); n == 0 {
  78. if goerrors.Is(err, io.EOF) {
  79. errors.LogInfo(ctx, "Connection closed immediately, likely health check connection")
  80. return nil
  81. }
  82. return errors.New("failed to read from connection").Base(err)
  83. }
  84. if firstbyte[0] != 5 && firstbyte[0] != 4 { // Check if it is Socks5/4/4a
  85. errors.LogDebug(ctx, "Not Socks request, try to parse as HTTP request")
  86. return s.httpServer.ProcessWithFirstbyte(ctx, network, conn, dispatcher, firstbyte...)
  87. }
  88. return s.processTCP(ctx, conn, dispatcher, firstbyte)
  89. case net.Network_UDP:
  90. return s.handleUDPPayload(ctx, conn, dispatcher)
  91. default:
  92. return errors.New("unknown network: ", network)
  93. }
  94. }
  95. func (s *Server) processTCP(ctx context.Context, conn stat.Connection, dispatcher routing.Dispatcher, firstbyte []byte) error {
  96. plcy := s.policy()
  97. if err := conn.SetReadDeadline(time.Now().Add(plcy.Timeouts.Handshake)); err != nil {
  98. errors.LogInfoInner(ctx, err, "failed to set deadline")
  99. }
  100. inbound := session.InboundFromContext(ctx)
  101. if inbound == nil || !inbound.Gateway.IsValid() {
  102. return errors.New("inbound gateway not specified")
  103. }
  104. svrSession := &ServerSession{
  105. config: s.config,
  106. address: inbound.Gateway.Address,
  107. port: inbound.Gateway.Port,
  108. localAddress: net.IPAddress(conn.LocalAddr().(*net.TCPAddr).IP),
  109. }
  110. // Firstbyte is for forwarded conn from SOCKS inbound
  111. // Because it needs first byte to choose protocol
  112. // We need to add it back
  113. reader := &buf.BufferedReader{
  114. Reader: buf.NewReader(conn),
  115. Buffer: buf.MultiBuffer{buf.FromBytes(firstbyte)},
  116. }
  117. request, err := svrSession.Handshake(reader, conn)
  118. if err != nil {
  119. if inbound.Source.IsValid() {
  120. log.Record(&log.AccessMessage{
  121. From: inbound.Source,
  122. To: "",
  123. Status: log.AccessRejected,
  124. Reason: err,
  125. })
  126. }
  127. return errors.New("failed to read request").Base(err)
  128. }
  129. if request.User != nil {
  130. inbound.User.Email = request.User.Email
  131. }
  132. if err := conn.SetReadDeadline(time.Time{}); err != nil {
  133. errors.LogInfoInner(ctx, err, "failed to clear deadline")
  134. }
  135. if request.Command == protocol.RequestCommandTCP {
  136. dest := request.Destination()
  137. errors.LogInfo(ctx, "TCP Connect request to ", dest)
  138. if inbound.Source.IsValid() {
  139. ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
  140. From: inbound.Source,
  141. To: dest,
  142. Status: log.AccessAccepted,
  143. Reason: "",
  144. })
  145. }
  146. if inbound.CanSpliceCopy == 2 {
  147. inbound.CanSpliceCopy = 1
  148. }
  149. if err := dispatcher.DispatchLink(ctx, dest, &transport.Link{
  150. Reader: reader,
  151. Writer: buf.NewWriter(conn)},
  152. ); err != nil {
  153. return errors.New("failed to dispatch request").Base(err)
  154. }
  155. return nil
  156. }
  157. if request.Command == protocol.RequestCommandUDP {
  158. if s.udpFilter != nil {
  159. s.udpFilter.Add(conn.RemoteAddr())
  160. }
  161. return s.handleUDP(conn)
  162. }
  163. return nil
  164. }
  165. func (*Server) handleUDP(c io.Reader) error {
  166. // The TCP connection closes after this method returns. We need to wait until
  167. // the client closes it.
  168. return common.Error2(io.Copy(buf.DiscardBytes, c))
  169. }
  170. func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dispatcher routing.Dispatcher) error {
  171. if s.udpFilter != nil && !s.udpFilter.Check(conn.RemoteAddr()) {
  172. errors.LogDebug(ctx, "Unauthorized UDP access from ", conn.RemoteAddr().String())
  173. return nil
  174. }
  175. udpServer := udp.NewDispatcher(dispatcher, func(ctx context.Context, packet *udp_proto.Packet) {
  176. payload := packet.Payload
  177. errors.LogDebug(ctx, "writing back UDP response with ", payload.Len(), " bytes")
  178. request := protocol.RequestHeaderFromContext(ctx)
  179. if request == nil {
  180. payload.Release()
  181. return
  182. }
  183. if payload.UDP != nil {
  184. request = &protocol.RequestHeader{
  185. User: request.User,
  186. Address: payload.UDP.Address,
  187. Port: payload.UDP.Port,
  188. }
  189. }
  190. udpMessage, err := EncodeUDPPacket(request, payload.Bytes())
  191. payload.Release()
  192. if err != nil {
  193. errors.LogWarningInner(ctx, err, "failed to write UDP response")
  194. return
  195. }
  196. conn.Write(udpMessage.Bytes())
  197. udpMessage.Release()
  198. })
  199. defer udpServer.RemoveRay()
  200. inbound := session.InboundFromContext(ctx)
  201. if inbound != nil && inbound.Source.IsValid() {
  202. errors.LogInfo(ctx, "client UDP connection from ", inbound.Source)
  203. }
  204. var dest *net.Destination
  205. reader := buf.NewPacketReader(conn)
  206. for {
  207. mpayload, err := reader.ReadMultiBuffer()
  208. if err != nil {
  209. return err
  210. }
  211. for _, payload := range mpayload {
  212. request, err := DecodeUDPPacket(payload)
  213. if err != nil {
  214. errors.LogInfoInner(ctx, err, "failed to parse UDP request")
  215. payload.Release()
  216. continue
  217. }
  218. if payload.IsEmpty() {
  219. payload.Release()
  220. continue
  221. }
  222. destination := request.Destination()
  223. currentPacketCtx := ctx
  224. errors.LogDebug(ctx, "send packet to ", destination, " with ", payload.Len(), " bytes")
  225. if inbound != nil && inbound.Source.IsValid() {
  226. currentPacketCtx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
  227. From: inbound.Source,
  228. To: destination,
  229. Status: log.AccessAccepted,
  230. Reason: "",
  231. })
  232. }
  233. payload.UDP = &destination
  234. if !s.cone || dest == nil {
  235. dest = &destination
  236. }
  237. currentPacketCtx = protocol.ContextWithRequestHeader(currentPacketCtx, request)
  238. udpServer.Dispatch(currentPacketCtx, *dest, payload)
  239. }
  240. }
  241. }
  242. func init() {
  243. common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  244. return NewServer(ctx, config.(*ServerConfig))
  245. }))
  246. }