socks.go 7.4 KB

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