socks5.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. package server
  2. import (
  3. "encoding/binary"
  4. "errors"
  5. "github.com/cnlh/nps/bridge"
  6. "github.com/cnlh/nps/lib/common"
  7. "github.com/cnlh/nps/lib/conn"
  8. "github.com/cnlh/nps/lib/file"
  9. "github.com/cnlh/nps/lib/lg"
  10. "io"
  11. "net"
  12. "strconv"
  13. "strings"
  14. )
  15. const (
  16. ipV4 = 1
  17. domainName = 3
  18. ipV6 = 4
  19. connectMethod = 1
  20. bindMethod = 2
  21. associateMethod = 3
  22. // The maximum packet size of any udp Associate packet, based on ethernet's max size,
  23. // minus the IP and UDP headers. IPv4 has a 20 byte header, UDP adds an
  24. // additional 4 bytes. This is a total overhead of 24 bytes. Ethernet's
  25. // max packet size is 1500 bytes, 1500 - 24 = 1476.
  26. maxUDPPacketSize = 1476
  27. )
  28. const (
  29. succeeded uint8 = iota
  30. serverFailure
  31. notAllowed
  32. networkUnreachable
  33. hostUnreachable
  34. connectionRefused
  35. ttlExpired
  36. commandNotSupported
  37. addrTypeNotSupported
  38. )
  39. const (
  40. UserPassAuth = uint8(2)
  41. userAuthVersion = uint8(1)
  42. authSuccess = uint8(0)
  43. authFailure = uint8(1)
  44. )
  45. type Sock5ModeServer struct {
  46. server
  47. isVerify bool
  48. listener net.Listener
  49. }
  50. //req
  51. func (s *Sock5ModeServer) handleRequest(c net.Conn) {
  52. /*
  53. The SOCKS request is formed as follows:
  54. +----+-----+-------+------+----------+----------+
  55. |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
  56. +----+-----+-------+------+----------+----------+
  57. | 1 | 1 | X'00' | 1 | Variable | 2 |
  58. +----+-----+-------+------+----------+----------+
  59. */
  60. header := make([]byte, 3)
  61. _, err := io.ReadFull(c, header)
  62. if err != nil {
  63. lg.Println("illegal request", err)
  64. c.Close()
  65. return
  66. }
  67. switch header[1] {
  68. case connectMethod:
  69. s.handleConnect(c)
  70. case bindMethod:
  71. s.handleBind(c)
  72. case associateMethod:
  73. s.handleUDP(c)
  74. default:
  75. s.sendReply(c, commandNotSupported)
  76. c.Close()
  77. }
  78. }
  79. //reply
  80. func (s *Sock5ModeServer) sendReply(c net.Conn, rep uint8) {
  81. reply := []byte{
  82. 5,
  83. rep,
  84. 0,
  85. 1,
  86. }
  87. localAddr := c.LocalAddr().String()
  88. localHost, localPort, _ := net.SplitHostPort(localAddr)
  89. ipBytes := net.ParseIP(localHost).To4()
  90. nPort, _ := strconv.Atoi(localPort)
  91. reply = append(reply, ipBytes...)
  92. portBytes := make([]byte, 2)
  93. binary.BigEndian.PutUint16(portBytes, uint16(nPort))
  94. reply = append(reply, portBytes...)
  95. c.Write(reply)
  96. }
  97. //do conn
  98. func (s *Sock5ModeServer) doConnect(c net.Conn, command uint8) {
  99. addrType := make([]byte, 1)
  100. c.Read(addrType)
  101. var host string
  102. switch addrType[0] {
  103. case ipV4:
  104. ipv4 := make(net.IP, net.IPv4len)
  105. c.Read(ipv4)
  106. host = ipv4.String()
  107. case ipV6:
  108. ipv6 := make(net.IP, net.IPv6len)
  109. c.Read(ipv6)
  110. host = ipv6.String()
  111. case domainName:
  112. var domainLen uint8
  113. binary.Read(c, binary.BigEndian, &domainLen)
  114. domain := make([]byte, domainLen)
  115. c.Read(domain)
  116. host = string(domain)
  117. default:
  118. s.sendReply(c, addrTypeNotSupported)
  119. return
  120. }
  121. var port uint16
  122. binary.Read(c, binary.BigEndian, &port)
  123. // connect to host
  124. addr := net.JoinHostPort(host, strconv.Itoa(int(port)))
  125. var ltype string
  126. if command == associateMethod {
  127. ltype = common.CONN_UDP
  128. } else {
  129. ltype = common.CONN_TCP
  130. }
  131. link := conn.NewLink(s.task.Client.GetId(), ltype, addr, s.config.CompressEncode, s.config.CompressDecode, s.config.Crypt, conn.NewConn(c), s.task.Flow, nil, s.task.Client.Rate, nil)
  132. if tunnel, err := s.bridge.SendLinkInfo(s.task.Client.Id, link); err != nil {
  133. c.Close()
  134. return
  135. } else {
  136. s.sendReply(c, succeeded)
  137. s.linkCopy(link, conn.NewConn(c), nil, tunnel, s.task.Flow)
  138. }
  139. return
  140. }
  141. //conn
  142. func (s *Sock5ModeServer) handleConnect(c net.Conn) {
  143. s.doConnect(c, connectMethod)
  144. }
  145. // passive mode
  146. func (s *Sock5ModeServer) handleBind(c net.Conn) {
  147. }
  148. //udp
  149. func (s *Sock5ModeServer) handleUDP(c net.Conn) {
  150. lg.Println("UDP Associate")
  151. /*
  152. +----+------+------+----------+----------+----------+
  153. |RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA |
  154. +----+------+------+----------+----------+----------+
  155. | 2 | 1 | 1 | Variable | 2 | Variable |
  156. +----+------+------+----------+----------+----------+
  157. */
  158. buf := make([]byte, 3)
  159. c.Read(buf)
  160. // relay udp datagram silently, without any notification to the requesting client
  161. if buf[2] != 0 {
  162. // does not support fragmentation, drop it
  163. lg.Println("does not support fragmentation, drop")
  164. dummy := make([]byte, maxUDPPacketSize)
  165. c.Read(dummy)
  166. }
  167. s.doConnect(c, associateMethod)
  168. }
  169. //new conn
  170. func (s *Sock5ModeServer) handleConn(c net.Conn) {
  171. buf := make([]byte, 2)
  172. if _, err := io.ReadFull(c, buf); err != nil {
  173. lg.Println("negotiation err", err)
  174. c.Close()
  175. return
  176. }
  177. if version := buf[0]; version != 5 {
  178. lg.Println("only support socks5, request from: ", c.RemoteAddr())
  179. c.Close()
  180. return
  181. }
  182. nMethods := buf[1]
  183. methods := make([]byte, nMethods)
  184. if len, err := c.Read(methods); len != int(nMethods) || err != nil {
  185. lg.Println("wrong method")
  186. c.Close()
  187. return
  188. }
  189. if s.isVerify {
  190. buf[1] = UserPassAuth
  191. c.Write(buf)
  192. if err := s.Auth(c); err != nil {
  193. c.Close()
  194. lg.Println("验证失败:", err)
  195. return
  196. }
  197. } else {
  198. buf[1] = 0
  199. c.Write(buf)
  200. }
  201. s.handleRequest(c)
  202. }
  203. //socks5 auth
  204. func (s *Sock5ModeServer) Auth(c net.Conn) error {
  205. header := []byte{0, 0}
  206. if _, err := io.ReadAtLeast(c, header, 2); err != nil {
  207. return err
  208. }
  209. if header[0] != userAuthVersion {
  210. return errors.New("验证方式不被支持")
  211. }
  212. userLen := int(header[1])
  213. user := make([]byte, userLen)
  214. if _, err := io.ReadAtLeast(c, user, userLen); err != nil {
  215. return err
  216. }
  217. if _, err := c.Read(header[:1]); err != nil {
  218. return errors.New("密码长度获取错误")
  219. }
  220. passLen := int(header[0])
  221. pass := make([]byte, passLen)
  222. if _, err := io.ReadAtLeast(c, pass, passLen); err != nil {
  223. return err
  224. }
  225. if string(pass) == s.config.U && string(user) == s.config.P {
  226. if _, err := c.Write([]byte{userAuthVersion, authSuccess}); err != nil {
  227. return err
  228. }
  229. return nil
  230. } else {
  231. if _, err := c.Write([]byte{userAuthVersion, authFailure}); err != nil {
  232. return err
  233. }
  234. return errors.New("验证不通过")
  235. }
  236. return errors.New("未知错误")
  237. }
  238. //start
  239. func (s *Sock5ModeServer) Start() error {
  240. var err error
  241. s.listener, err = net.Listen("tcp", ":"+strconv.Itoa(s.task.TcpPort))
  242. if err != nil {
  243. return err
  244. }
  245. for {
  246. conn, err := s.listener.Accept()
  247. if err != nil {
  248. if strings.Contains(err.Error(), "use of closed network connection") {
  249. break
  250. }
  251. lg.Fatalln("accept error: ", err)
  252. }
  253. if !s.ResetConfig() {
  254. conn.Close()
  255. continue
  256. }
  257. go s.handleConn(conn)
  258. }
  259. return nil
  260. }
  261. //close
  262. func (s *Sock5ModeServer) Close() error {
  263. return s.listener.Close()
  264. }
  265. //new
  266. func NewSock5ModeServer(bridge *bridge.Bridge, task *file.Tunnel) *Sock5ModeServer {
  267. s := new(Sock5ModeServer)
  268. s.bridge = bridge
  269. s.task = task
  270. s.config = file.DeepCopyConfig(task.Config)
  271. if s.config.U != "" && s.config.P != "" {
  272. s.isVerify = true
  273. } else {
  274. s.isVerify = false
  275. }
  276. return s
  277. }