socks.go 7.9 KB

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