socks5.go 6.3 KB

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