socks.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. package protocol
  2. import (
  3. "encoding/binary"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "github.com/v2ray/v2ray-core/common/log"
  8. v2net "github.com/v2ray/v2ray-core/common/net"
  9. )
  10. const (
  11. socksVersion = byte(0x05)
  12. socks4Version = byte(0x04)
  13. AuthNotRequired = byte(0x00)
  14. AuthGssApi = byte(0x01)
  15. AuthUserPass = byte(0x02)
  16. AuthNoMatchingMethod = byte(0xFF)
  17. Socks4RequestGranted = byte(90)
  18. Socks4RequestRejected = byte(91)
  19. )
  20. var (
  21. ErrorSocksVersion4 = errors.New("Using SOCKS version 4.")
  22. )
  23. // Authentication request header of Socks5 protocol
  24. type Socks5AuthenticationRequest struct {
  25. version byte
  26. nMethods byte
  27. authMethods [256]byte
  28. }
  29. type Socks4AuthenticationRequest struct {
  30. Version byte
  31. Command byte
  32. Port uint16
  33. IP [4]byte
  34. }
  35. func (request *Socks5AuthenticationRequest) HasAuthMethod(method byte) bool {
  36. for i := 0; i < int(request.nMethods); i++ {
  37. if request.authMethods[i] == method {
  38. return true
  39. }
  40. }
  41. return false
  42. }
  43. func ReadAuthentication(reader io.Reader) (auth Socks5AuthenticationRequest, auth4 Socks4AuthenticationRequest, err error) {
  44. buffer := make([]byte, 256)
  45. nBytes, err := reader.Read(buffer)
  46. if err != nil {
  47. log.Error("Failed to read socks authentication: %v", err)
  48. return
  49. }
  50. if nBytes < 2 {
  51. err = fmt.Errorf("Expected 2 bytes read, but actaully %d bytes read", nBytes)
  52. return
  53. }
  54. if buffer[0] == socks4Version {
  55. auth4.Version = buffer[0]
  56. auth4.Command = buffer[1]
  57. auth4.Port = binary.BigEndian.Uint16(buffer[2:4])
  58. copy(auth4.IP[:], buffer[4:8])
  59. err = ErrorSocksVersion4
  60. return
  61. }
  62. auth.version = buffer[0]
  63. if auth.version != socksVersion {
  64. err = fmt.Errorf("Unknown SOCKS version %d", auth.version)
  65. return
  66. }
  67. auth.nMethods = buffer[1]
  68. if auth.nMethods <= 0 {
  69. err = fmt.Errorf("Zero length of authentication methods")
  70. return
  71. }
  72. if nBytes-2 != int(auth.nMethods) {
  73. err = fmt.Errorf("Unmatching number of auth methods, expecting %d, but got %d", auth.nMethods, nBytes)
  74. return
  75. }
  76. copy(auth.authMethods[:], buffer[2:nBytes])
  77. return
  78. }
  79. type Socks5AuthenticationResponse struct {
  80. version byte
  81. authMethod byte
  82. }
  83. type Socks4AuthenticationResponse struct {
  84. result byte
  85. port uint16
  86. ip []byte
  87. }
  88. func NewAuthenticationResponse(authMethod byte) *Socks5AuthenticationResponse {
  89. return &Socks5AuthenticationResponse{
  90. version: socksVersion,
  91. authMethod: authMethod,
  92. }
  93. }
  94. func NewSocks4AuthenticationResponse(result byte, port uint16, ip []byte) *Socks4AuthenticationResponse {
  95. return &Socks4AuthenticationResponse{
  96. result: result,
  97. port: port,
  98. ip: ip,
  99. }
  100. }
  101. func WriteAuthentication(writer io.Writer, r *Socks5AuthenticationResponse) error {
  102. _, err := writer.Write([]byte{r.version, r.authMethod})
  103. return err
  104. }
  105. func WriteSocks4AuthenticationResponse(writer io.Writer, r *Socks4AuthenticationResponse) error {
  106. buffer := make([]byte, 8)
  107. // buffer[0] is always 0
  108. buffer[1] = r.result
  109. binary.BigEndian.PutUint16(buffer[2:4], r.port)
  110. copy(buffer[4:], r.ip)
  111. _, err := writer.Write(buffer)
  112. return err
  113. }
  114. type Socks5UserPassRequest struct {
  115. version byte
  116. username string
  117. password string
  118. }
  119. func (request Socks5UserPassRequest) IsValid(username string, password string) bool {
  120. return request.username == username && request.password == password
  121. }
  122. func ReadUserPassRequest(reader io.Reader) (request Socks5UserPassRequest, err error) {
  123. buffer := make([]byte, 256)
  124. _, err = reader.Read(buffer[0:2])
  125. if err != nil {
  126. return
  127. }
  128. request.version = buffer[0]
  129. nUsername := buffer[1]
  130. nBytes, err := reader.Read(buffer[:nUsername])
  131. if err != nil {
  132. return
  133. }
  134. request.username = string(buffer[:nBytes])
  135. _, err = reader.Read(buffer[0:1])
  136. if err != nil {
  137. return
  138. }
  139. nPassword := buffer[0]
  140. nBytes, err = reader.Read(buffer[:nPassword])
  141. if err != nil {
  142. return
  143. }
  144. request.password = string(buffer[:nBytes])
  145. return
  146. }
  147. type Socks5UserPassResponse struct {
  148. version byte
  149. status byte
  150. }
  151. func NewSocks5UserPassResponse(status byte) Socks5UserPassResponse {
  152. return Socks5UserPassResponse{
  153. version: socksVersion,
  154. status: status,
  155. }
  156. }
  157. func WriteUserPassResponse(writer io.Writer, response Socks5UserPassResponse) error {
  158. _, err := writer.Write([]byte{response.version, response.status})
  159. return err
  160. }
  161. const (
  162. AddrTypeIPv4 = byte(0x01)
  163. AddrTypeIPv6 = byte(0x04)
  164. AddrTypeDomain = byte(0x03)
  165. CmdConnect = byte(0x01)
  166. CmdBind = byte(0x02)
  167. CmdUdpAssociate = byte(0x03)
  168. )
  169. type Socks5Request struct {
  170. Version byte
  171. Command byte
  172. AddrType byte
  173. IPv4 [4]byte
  174. Domain string
  175. IPv6 [16]byte
  176. Port uint16
  177. }
  178. func ReadRequest(reader io.Reader) (request *Socks5Request, err error) {
  179. buffer := make([]byte, 4)
  180. nBytes, err := reader.Read(buffer)
  181. if err != nil {
  182. return
  183. }
  184. if nBytes < len(buffer) {
  185. err = fmt.Errorf("Unable to read request.")
  186. return
  187. }
  188. request = &Socks5Request{
  189. Version: buffer[0],
  190. Command: buffer[1],
  191. // buffer[2] is a reserved field
  192. AddrType: buffer[3],
  193. }
  194. switch request.AddrType {
  195. case AddrTypeIPv4:
  196. nBytes, err = reader.Read(request.IPv4[:])
  197. if err != nil {
  198. return
  199. }
  200. if nBytes != 4 {
  201. err = fmt.Errorf("Unable to read IPv4 address.")
  202. return
  203. }
  204. case AddrTypeDomain:
  205. buffer = make([]byte, 256)
  206. nBytes, err = reader.Read(buffer[0:1])
  207. if err != nil {
  208. return
  209. }
  210. domainLength := buffer[0]
  211. nBytes, err = reader.Read(buffer[:domainLength])
  212. if err != nil {
  213. return
  214. }
  215. if nBytes != int(domainLength) {
  216. err = fmt.Errorf("Unable to read domain with %d bytes, expecting %d bytes", nBytes, domainLength)
  217. return
  218. }
  219. request.Domain = string(buffer[:domainLength])
  220. case AddrTypeIPv6:
  221. nBytes, err = reader.Read(request.IPv6[:])
  222. if err != nil {
  223. return
  224. }
  225. if nBytes != 16 {
  226. err = fmt.Errorf("Unable to read IPv4 address.")
  227. return
  228. }
  229. default:
  230. err = fmt.Errorf("Unexpected address type %d", request.AddrType)
  231. return
  232. }
  233. buffer = make([]byte, 2)
  234. nBytes, err = reader.Read(buffer)
  235. if err != nil {
  236. return
  237. }
  238. if nBytes != 2 {
  239. err = fmt.Errorf("Unable to read port.")
  240. return
  241. }
  242. request.Port = binary.BigEndian.Uint16(buffer)
  243. return
  244. }
  245. func (request *Socks5Request) Destination() v2net.Address {
  246. switch request.AddrType {
  247. case AddrTypeIPv4:
  248. return v2net.IPAddress(request.IPv4[:], request.Port)
  249. case AddrTypeIPv6:
  250. return v2net.IPAddress(request.IPv6[:], request.Port)
  251. case AddrTypeDomain:
  252. return v2net.DomainAddress(request.Domain, request.Port)
  253. default:
  254. panic("Unknown address type")
  255. }
  256. }
  257. const (
  258. ErrorSuccess = byte(0x00)
  259. ErrorGeneralFailure = byte(0x01)
  260. ErrorConnectionNotAllowed = byte(0x02)
  261. ErrorNetworkUnreachable = byte(0x03)
  262. ErrorHostUnUnreachable = byte(0x04)
  263. ErrorConnectionRefused = byte(0x05)
  264. ErrorTTLExpired = byte(0x06)
  265. ErrorCommandNotSupported = byte(0x07)
  266. ErrorAddressTypeNotSupported = byte(0x08)
  267. )
  268. type Socks5Response struct {
  269. Version byte
  270. Error byte
  271. AddrType byte
  272. IPv4 [4]byte
  273. Domain string
  274. IPv6 [16]byte
  275. Port uint16
  276. }
  277. func NewSocks5Response() *Socks5Response {
  278. return &Socks5Response{
  279. Version: socksVersion,
  280. }
  281. }
  282. func (r *Socks5Response) SetIPv4(ipv4 []byte) {
  283. r.AddrType = AddrTypeIPv4
  284. copy(r.IPv4[:], ipv4)
  285. }
  286. func (r *Socks5Response) SetIPv6(ipv6 []byte) {
  287. r.AddrType = AddrTypeIPv6
  288. copy(r.IPv6[:], ipv6)
  289. }
  290. func (r *Socks5Response) SetDomain(domain string) {
  291. r.AddrType = AddrTypeDomain
  292. r.Domain = domain
  293. }
  294. func (r *Socks5Response) toBytes() []byte {
  295. buffer := make([]byte, 0, 300)
  296. buffer = append(buffer, r.Version)
  297. buffer = append(buffer, r.Error)
  298. buffer = append(buffer, 0x00) // reserved
  299. buffer = append(buffer, r.AddrType)
  300. switch r.AddrType {
  301. case 0x01:
  302. buffer = append(buffer, r.IPv4[:]...)
  303. case 0x03:
  304. buffer = append(buffer, byte(len(r.Domain)))
  305. buffer = append(buffer, []byte(r.Domain)...)
  306. case 0x04:
  307. buffer = append(buffer, r.IPv6[:]...)
  308. }
  309. portBuffer := make([]byte, 2)
  310. binary.BigEndian.PutUint16(portBuffer, r.Port)
  311. buffer = append(buffer, portBuffer...)
  312. return buffer
  313. }
  314. func WriteResponse(writer io.Writer, response *Socks5Response) error {
  315. _, err := writer.Write(response.toBytes())
  316. return err
  317. }