socks5.go 6.4 KB

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