client.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. /*
  2. Some of codes are copied from https://github.com/octeep/wireproxy, license below.
  3. Copyright (c) 2022 Wind T.F. Wong <[email protected]>
  4. Permission to use, copy, modify, and distribute this software for any
  5. purpose with or without fee is hereby granted, provided that the above
  6. copyright notice and this permission notice appear in all copies.
  7. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  10. ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  12. ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  13. OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. */
  15. package wireguard
  16. import (
  17. "context"
  18. "fmt"
  19. "net/netip"
  20. "strings"
  21. "sync"
  22. "github.com/xtls/xray-core/common"
  23. "github.com/xtls/xray-core/common/buf"
  24. "github.com/xtls/xray-core/common/dice"
  25. "github.com/xtls/xray-core/common/log"
  26. "github.com/xtls/xray-core/common/net"
  27. "github.com/xtls/xray-core/common/protocol"
  28. "github.com/xtls/xray-core/common/session"
  29. "github.com/xtls/xray-core/common/signal"
  30. "github.com/xtls/xray-core/common/task"
  31. "github.com/xtls/xray-core/core"
  32. "github.com/xtls/xray-core/features/dns"
  33. "github.com/xtls/xray-core/features/policy"
  34. "github.com/xtls/xray-core/transport"
  35. "github.com/xtls/xray-core/transport/internet"
  36. )
  37. // Handler is an outbound connection that silently swallow the entire payload.
  38. type Handler struct {
  39. conf *DeviceConfig
  40. net Tunnel
  41. bind *netBindClient
  42. policyManager policy.Manager
  43. dns dns.Client
  44. // cached configuration
  45. endpoints []netip.Addr
  46. hasIPv4, hasIPv6 bool
  47. wgLock sync.Mutex
  48. }
  49. // New creates a new wireguard handler.
  50. func New(ctx context.Context, conf *DeviceConfig) (*Handler, error) {
  51. v := core.MustFromContext(ctx)
  52. endpoints, hasIPv4, hasIPv6, err := parseEndpoints(conf)
  53. if err != nil {
  54. return nil, err
  55. }
  56. d := v.GetFeature(dns.ClientType()).(dns.Client)
  57. return &Handler{
  58. conf: conf,
  59. policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
  60. dns: d,
  61. endpoints: endpoints,
  62. hasIPv4: hasIPv4,
  63. hasIPv6: hasIPv6,
  64. }, nil
  65. }
  66. func (h *Handler) processWireGuard(dialer internet.Dialer) (err error) {
  67. h.wgLock.Lock()
  68. defer h.wgLock.Unlock()
  69. if h.bind != nil && h.bind.dialer == dialer && h.net != nil {
  70. return nil
  71. }
  72. log.Record(&log.GeneralMessage{
  73. Severity: log.Severity_Info,
  74. Content: "switching dialer",
  75. })
  76. if h.net != nil {
  77. _ = h.net.Close()
  78. h.net = nil
  79. }
  80. if h.bind != nil {
  81. _ = h.bind.Close()
  82. h.bind = nil
  83. }
  84. // bind := conn.NewStdNetBind() // TODO: conn.Bind wrapper for dialer
  85. bind := &netBindClient{
  86. netBind: netBind{
  87. dns: h.dns,
  88. dnsOption: dns.IPOption{
  89. IPv4Enable: h.hasIPv4,
  90. IPv6Enable: h.hasIPv6,
  91. },
  92. workers: int(h.conf.NumWorkers),
  93. },
  94. dialer: dialer,
  95. reserved: h.conf.Reserved,
  96. }
  97. defer func() {
  98. if err != nil {
  99. _ = bind.Close()
  100. }
  101. }()
  102. h.net, err = h.makeVirtualTun(bind)
  103. if err != nil {
  104. return newError("failed to create virtual tun interface").Base(err)
  105. }
  106. h.bind = bind
  107. return nil
  108. }
  109. // Process implements OutboundHandler.Dispatch().
  110. func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
  111. outbound := session.OutboundFromContext(ctx)
  112. if outbound == nil || !outbound.Target.IsValid() {
  113. return newError("target not specified")
  114. }
  115. outbound.Name = "wireguard"
  116. inbound := session.InboundFromContext(ctx)
  117. if inbound != nil {
  118. inbound.SetCanSpliceCopy(3)
  119. }
  120. if err := h.processWireGuard(dialer); err != nil {
  121. return err
  122. }
  123. // Destination of the inner request.
  124. destination := outbound.Target
  125. command := protocol.RequestCommandTCP
  126. if destination.Network == net.Network_UDP {
  127. command = protocol.RequestCommandUDP
  128. }
  129. // resolve dns
  130. addr := destination.Address
  131. if addr.Family().IsDomain() {
  132. ips, err := h.dns.LookupIP(addr.Domain(), dns.IPOption{
  133. IPv4Enable: h.hasIPv4 && h.conf.preferIP4(),
  134. IPv6Enable: h.hasIPv6 && h.conf.preferIP6(),
  135. })
  136. { // Resolve fallback
  137. if (len(ips) == 0 || err != nil) && h.conf.hasFallback() {
  138. ips, err = h.dns.LookupIP(addr.Domain(), dns.IPOption{
  139. IPv4Enable: h.hasIPv4 && h.conf.fallbackIP4(),
  140. IPv6Enable: h.hasIPv6 && h.conf.fallbackIP6(),
  141. })
  142. }
  143. }
  144. if err != nil {
  145. return newError("failed to lookup DNS").Base(err)
  146. } else if len(ips) == 0 {
  147. return dns.ErrEmptyResponse
  148. }
  149. addr = net.IPAddress(ips[dice.Roll(len(ips))])
  150. }
  151. var newCtx context.Context
  152. var newCancel context.CancelFunc
  153. if session.TimeoutOnlyFromContext(ctx) {
  154. newCtx, newCancel = context.WithCancel(context.Background())
  155. }
  156. p := h.policyManager.ForLevel(0)
  157. ctx, cancel := context.WithCancel(ctx)
  158. timer := signal.CancelAfterInactivity(ctx, func() {
  159. cancel()
  160. if newCancel != nil {
  161. newCancel()
  162. }
  163. }, p.Timeouts.ConnectionIdle)
  164. addrPort := netip.AddrPortFrom(toNetIpAddr(addr), destination.Port.Value())
  165. var requestFunc func() error
  166. var responseFunc func() error
  167. if command == protocol.RequestCommandTCP {
  168. conn, err := h.net.DialContextTCPAddrPort(ctx, addrPort)
  169. if err != nil {
  170. return newError("failed to create TCP connection").Base(err)
  171. }
  172. defer conn.Close()
  173. requestFunc = func() error {
  174. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  175. return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer))
  176. }
  177. responseFunc = func() error {
  178. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  179. return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer))
  180. }
  181. } else if command == protocol.RequestCommandUDP {
  182. conn, err := h.net.DialUDPAddrPort(netip.AddrPort{}, addrPort)
  183. if err != nil {
  184. return newError("failed to create UDP connection").Base(err)
  185. }
  186. defer conn.Close()
  187. requestFunc = func() error {
  188. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  189. return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer))
  190. }
  191. responseFunc = func() error {
  192. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  193. return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer))
  194. }
  195. }
  196. if newCtx != nil {
  197. ctx = newCtx
  198. }
  199. responseDonePost := task.OnSuccess(responseFunc, task.Close(link.Writer))
  200. if err := task.Run(ctx, requestFunc, responseDonePost); err != nil {
  201. common.Interrupt(link.Reader)
  202. common.Interrupt(link.Writer)
  203. return newError("connection ends").Base(err)
  204. }
  205. return nil
  206. }
  207. // creates a tun interface on netstack given a configuration
  208. func (h *Handler) makeVirtualTun(bind *netBindClient) (Tunnel, error) {
  209. t, err := h.conf.createTun()(h.endpoints, int(h.conf.Mtu), nil)
  210. if err != nil {
  211. return nil, err
  212. }
  213. bind.dnsOption.IPv4Enable = h.hasIPv4
  214. bind.dnsOption.IPv6Enable = h.hasIPv6
  215. if err = t.BuildDevice(h.createIPCRequest(bind, h.conf), bind); err != nil {
  216. _ = t.Close()
  217. return nil, err
  218. }
  219. return t, nil
  220. }
  221. // serialize the config into an IPC request
  222. func (h *Handler) createIPCRequest(bind *netBindClient, conf *DeviceConfig) string {
  223. var request strings.Builder
  224. request.WriteString(fmt.Sprintf("private_key=%s\n", conf.SecretKey))
  225. if !conf.IsClient {
  226. // placeholder, we'll handle actual port listening on Xray
  227. request.WriteString("listen_port=1337\n")
  228. }
  229. for _, peer := range conf.Peers {
  230. if peer.PublicKey != "" {
  231. request.WriteString(fmt.Sprintf("public_key=%s\n", peer.PublicKey))
  232. }
  233. if peer.PreSharedKey != "" {
  234. request.WriteString(fmt.Sprintf("preshared_key=%s\n", peer.PreSharedKey))
  235. }
  236. address, port, err := net.SplitHostPort(peer.Endpoint)
  237. if err != nil {
  238. newError("failed to split endpoint ", peer.Endpoint, " into address and port").AtError().WriteToLog()
  239. }
  240. addr := net.ParseAddress(address)
  241. if addr.Family().IsDomain() {
  242. dialerIp := bind.dialer.DestIpAddress()
  243. if dialerIp != nil {
  244. addr = net.ParseAddress(dialerIp.String())
  245. newError("createIPCRequest use dialer dest ip: ", addr).WriteToLog()
  246. } else {
  247. ips, err := h.dns.LookupIP(addr.Domain(), dns.IPOption{
  248. IPv4Enable: h.hasIPv4 && h.conf.preferIP4(),
  249. IPv6Enable: h.hasIPv6 && h.conf.preferIP6(),
  250. })
  251. { // Resolve fallback
  252. if (len(ips) == 0 || err != nil) && h.conf.hasFallback() {
  253. ips, err = h.dns.LookupIP(addr.Domain(), dns.IPOption{
  254. IPv4Enable: h.hasIPv4 && h.conf.fallbackIP4(),
  255. IPv6Enable: h.hasIPv6 && h.conf.fallbackIP6(),
  256. })
  257. }
  258. }
  259. if err != nil {
  260. newError("createIPCRequest failed to lookup DNS").Base(err).WriteToLog()
  261. } else if len(ips) == 0 {
  262. newError("createIPCRequest empty lookup DNS").WriteToLog()
  263. } else {
  264. addr = net.IPAddress(ips[dice.Roll(len(ips))])
  265. }
  266. }
  267. }
  268. if peer.Endpoint != "" {
  269. request.WriteString(fmt.Sprintf("endpoint=%s:%s\n", addr, port))
  270. }
  271. for _, ip := range peer.AllowedIps {
  272. request.WriteString(fmt.Sprintf("allowed_ip=%s\n", ip))
  273. }
  274. if peer.KeepAlive != 0 {
  275. request.WriteString(fmt.Sprintf("persistent_keepalive_interval=%d\n", peer.KeepAlive))
  276. }
  277. }
  278. return request.String()[:request.Len()]
  279. }