sock5.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. package lib
  2. import (
  3. "encoding/binary"
  4. "errors"
  5. "io"
  6. "log"
  7. "net"
  8. "strconv"
  9. "strings"
  10. )
  11. const (
  12. ipV4 = 1
  13. domainName = 3
  14. ipV6 = 4
  15. connectMethod = 1
  16. bindMethod = 2
  17. associateMethod = 3
  18. // The maximum packet size of any udp Associate packet, based on ethernet's max size,
  19. // minus the IP and UDP headers. IPv4 has a 20 byte header, UDP adds an
  20. // additional 4 bytes. This is a total overhead of 24 bytes. Ethernet's
  21. // max packet size is 1500 bytes, 1500 - 24 = 1476.
  22. maxUDPPacketSize = 1476
  23. )
  24. const (
  25. succeeded uint8 = iota
  26. serverFailure
  27. notAllowed
  28. networkUnreachable
  29. hostUnreachable
  30. connectionRefused
  31. ttlExpired
  32. commandNotSupported
  33. addrTypeNotSupported
  34. )
  35. const (
  36. UserPassAuth = uint8(2)
  37. userAuthVersion = uint8(1)
  38. authSuccess = uint8(0)
  39. authFailure = uint8(1)
  40. )
  41. type Sock5ModeServer struct {
  42. bridge *Tunnel
  43. httpPort int
  44. u string //用户名
  45. p string //密码
  46. enCompress int
  47. deCompress int
  48. isVerify bool
  49. listener net.Listener
  50. vKey string
  51. }
  52. func (s *Sock5ModeServer) handleRequest(c net.Conn) {
  53. /*
  54. The SOCKS request is formed as follows:
  55. +----+-----+-------+------+----------+----------+
  56. |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
  57. +----+-----+-------+------+----------+----------+
  58. | 1 | 1 | X'00' | 1 | Variable | 2 |
  59. +----+-----+-------+------+----------+----------+
  60. */
  61. header := make([]byte, 3)
  62. _, err := io.ReadFull(c, header)
  63. if err != nil {
  64. log.Println("illegal request", err)
  65. c.Close()
  66. return
  67. }
  68. switch header[1] {
  69. case connectMethod:
  70. s.handleConnect(c)
  71. case bindMethod:
  72. s.handleBind(c)
  73. case associateMethod:
  74. s.handleUDP(c)
  75. default:
  76. s.sendReply(c, commandNotSupported)
  77. c.Close()
  78. }
  79. }
  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. func (s *Sock5ModeServer) doConnect(c net.Conn, command uint8) (proxyConn *Conn, err error) {
  98. addrType := make([]byte, 1)
  99. c.Read(addrType)
  100. var host string
  101. switch addrType[0] {
  102. case ipV4:
  103. ipv4 := make(net.IP, net.IPv4len)
  104. c.Read(ipv4)
  105. host = ipv4.String()
  106. case ipV6:
  107. ipv6 := make(net.IP, net.IPv6len)
  108. c.Read(ipv6)
  109. host = ipv6.String()
  110. case domainName:
  111. var domainLen uint8
  112. binary.Read(c, binary.BigEndian, &domainLen)
  113. domain := make([]byte, domainLen)
  114. c.Read(domain)
  115. host = string(domain)
  116. default:
  117. s.sendReply(c, addrTypeNotSupported)
  118. err = errors.New("Address type not supported")
  119. return nil, err
  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. client := s.bridge.GetTunnel(getverifyval(s.vKey),s.enCompress,s.deCompress)
  126. s.sendReply(c, succeeded)
  127. var ltype string
  128. if command == associateMethod {
  129. ltype = CONN_UDP
  130. } else {
  131. ltype = CONN_TCP
  132. }
  133. _, err = client.WriteHost(ltype, addr)
  134. return client, nil
  135. }
  136. func (s *Sock5ModeServer) handleConnect(c net.Conn) {
  137. proxyConn, err := s.doConnect(c, connectMethod)
  138. if err != nil {
  139. log.Println(err)
  140. c.Close()
  141. } else {
  142. go relay(proxyConn, NewConn(c), s.enCompress)
  143. go relay(NewConn(c), proxyConn, s.deCompress)
  144. }
  145. }
  146. // passive mode
  147. func (s *Sock5ModeServer) handleBind(c net.Conn) {
  148. }
  149. func (s *Sock5ModeServer) handleUDP(c net.Conn) {
  150. log.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. log.Println("does not support fragmentation, drop")
  164. dummy := make([]byte, maxUDPPacketSize)
  165. c.Read(dummy)
  166. }
  167. proxyConn, err := s.doConnect(c, associateMethod)
  168. if err != nil {
  169. c.Close()
  170. } else {
  171. go relay(proxyConn, NewConn(c), s.enCompress)
  172. go relay(NewConn(c), proxyConn, s.deCompress)
  173. }
  174. }
  175. func (s *Sock5ModeServer) handleNewConn(c net.Conn) {
  176. buf := make([]byte, 2)
  177. if _, err := io.ReadFull(c, buf); err != nil {
  178. log.Println("negotiation err", err)
  179. c.Close()
  180. return
  181. }
  182. if version := buf[0]; version != 5 {
  183. log.Println("only support socks5, request from: ", c.RemoteAddr())
  184. c.Close()
  185. return
  186. }
  187. nMethods := buf[1]
  188. methods := make([]byte, nMethods)
  189. if len, err := c.Read(methods); len != int(nMethods) || err != nil {
  190. log.Println("wrong method")
  191. c.Close()
  192. return
  193. }
  194. if s.isVerify {
  195. buf[1] = UserPassAuth
  196. c.Write(buf)
  197. if err := s.Auth(c); err != nil {
  198. c.Close()
  199. log.Println("验证失败:", err)
  200. return
  201. }
  202. } else {
  203. buf[1] = 0
  204. c.Write(buf)
  205. }
  206. s.handleRequest(c)
  207. }
  208. func (s *Sock5ModeServer) Auth(c net.Conn) error {
  209. header := []byte{0, 0}
  210. if _, err := io.ReadAtLeast(c, header, 2); err != nil {
  211. return err
  212. }
  213. if header[0] != userAuthVersion {
  214. return errors.New("验证方式不被支持")
  215. }
  216. userLen := int(header[1])
  217. user := make([]byte, userLen)
  218. if _, err := io.ReadAtLeast(c, user, userLen); err != nil {
  219. return err
  220. }
  221. if _, err := c.Read(header[:1]); err != nil {
  222. return errors.New("密码长度获取错误")
  223. }
  224. passLen := int(header[0])
  225. pass := make([]byte, passLen)
  226. if _, err := io.ReadAtLeast(c, pass, passLen); err != nil {
  227. return err
  228. }
  229. if string(pass) == s.p && string(user) == s.u {
  230. if _, err := c.Write([]byte{userAuthVersion, authSuccess}); err != nil {
  231. return err
  232. }
  233. return nil
  234. } else {
  235. if _, err := c.Write([]byte{userAuthVersion, authFailure}); err != nil {
  236. return err
  237. }
  238. return errors.New("验证不通过")
  239. }
  240. return errors.New("未知错误")
  241. }
  242. func (s *Sock5ModeServer) Start() error {
  243. s.listener, err = net.Listen("tcp", ":"+strconv.Itoa(s.httpPort))
  244. if err != nil {
  245. return err
  246. }
  247. for {
  248. conn, err := s.listener.Accept()
  249. if err != nil {
  250. if strings.Contains(err.Error(), "use of closed network connection") {
  251. break
  252. }
  253. log.Fatal("accept error: ", err)
  254. }
  255. go s.handleNewConn(conn)
  256. }
  257. return nil
  258. }
  259. func (s *Sock5ModeServer) Close() error {
  260. return s.listener.Close()
  261. }
  262. func NewSock5ModeServer(httpPort int, u, p string, brige *Tunnel, enCompress int, deCompress int, vKey string) *Sock5ModeServer {
  263. s := new(Sock5ModeServer)
  264. s.httpPort = httpPort
  265. s.bridge = brige
  266. if u != "" && p != "" {
  267. s.isVerify = true
  268. s.u = u
  269. s.p = p
  270. } else {
  271. s.isVerify = false
  272. }
  273. s.enCompress = enCompress
  274. s.deCompress = deCompress
  275. s.vKey = vKey
  276. return s
  277. }