wireguard.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. "bytes"
  18. "context"
  19. "fmt"
  20. stdnet "net"
  21. "net/netip"
  22. "strings"
  23. "sync"
  24. "github.com/xtls/xray-core/common"
  25. "github.com/xtls/xray-core/common/buf"
  26. "github.com/xtls/xray-core/common/log"
  27. "github.com/xtls/xray-core/common/net"
  28. "github.com/xtls/xray-core/common/protocol"
  29. "github.com/xtls/xray-core/common/session"
  30. "github.com/xtls/xray-core/common/signal"
  31. "github.com/xtls/xray-core/common/task"
  32. "github.com/xtls/xray-core/core"
  33. "github.com/xtls/xray-core/features/dns"
  34. "github.com/xtls/xray-core/features/policy"
  35. "github.com/xtls/xray-core/transport"
  36. "github.com/xtls/xray-core/transport/internet"
  37. )
  38. // Handler is an outbound connection that silently swallow the entire payload.
  39. type Handler struct {
  40. conf *DeviceConfig
  41. net Tunnel
  42. bind *netBindClient
  43. policyManager policy.Manager
  44. dns dns.Client
  45. // cached configuration
  46. ipc string
  47. endpoints []netip.Addr
  48. hasIPv4, hasIPv6 bool
  49. wgLock sync.Mutex
  50. }
  51. // New creates a new wireguard handler.
  52. func New(ctx context.Context, conf *DeviceConfig) (*Handler, error) {
  53. v := core.MustFromContext(ctx)
  54. endpoints, err := parseEndpoints(conf)
  55. if err != nil {
  56. return nil, err
  57. }
  58. hasIPv4, hasIPv6 := false, false
  59. for _, e := range endpoints {
  60. if e.Is4() {
  61. hasIPv4 = true
  62. }
  63. if e.Is6() {
  64. hasIPv6 = true
  65. }
  66. }
  67. d := v.GetFeature(dns.ClientType()).(dns.Client)
  68. return &Handler{
  69. conf: conf,
  70. policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
  71. dns: d,
  72. ipc: createIPCRequest(conf, d, hasIPv6),
  73. endpoints: endpoints,
  74. hasIPv4: hasIPv4,
  75. hasIPv6: hasIPv6,
  76. }, nil
  77. }
  78. func (h *Handler) processWireGuard(dialer internet.Dialer) (err error) {
  79. h.wgLock.Lock()
  80. defer h.wgLock.Unlock()
  81. if h.bind != nil && h.bind.dialer == dialer && h.net != nil {
  82. return nil
  83. }
  84. log.Record(&log.GeneralMessage{
  85. Severity: log.Severity_Info,
  86. Content: "switching dialer",
  87. })
  88. if h.net != nil {
  89. _ = h.net.Close()
  90. h.net = nil
  91. }
  92. if h.bind != nil {
  93. _ = h.bind.Close()
  94. h.bind = nil
  95. }
  96. // bind := conn.NewStdNetBind() // TODO: conn.Bind wrapper for dialer
  97. bind := &netBindClient{
  98. dialer: dialer,
  99. workers: int(h.conf.NumWorkers),
  100. dns: h.dns,
  101. reserved: h.conf.Reserved,
  102. }
  103. defer func() {
  104. if err != nil {
  105. _ = bind.Close()
  106. }
  107. }()
  108. h.net, err = h.makeVirtualTun(bind)
  109. if err != nil {
  110. return newError("failed to create virtual tun interface").Base(err)
  111. }
  112. h.bind = bind
  113. return nil
  114. }
  115. // Process implements OutboundHandler.Dispatch().
  116. func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
  117. outbound := session.OutboundFromContext(ctx)
  118. if outbound == nil || !outbound.Target.IsValid() {
  119. return newError("target not specified")
  120. }
  121. outbound.Name = "wireguard"
  122. inbound := session.InboundFromContext(ctx)
  123. if inbound != nil {
  124. inbound.SetCanSpliceCopy(3)
  125. }
  126. if err := h.processWireGuard(dialer); err != nil {
  127. return err
  128. }
  129. // Destination of the inner request.
  130. destination := outbound.Target
  131. command := protocol.RequestCommandTCP
  132. if destination.Network == net.Network_UDP {
  133. command = protocol.RequestCommandUDP
  134. }
  135. // resolve dns
  136. addr := destination.Address
  137. if addr.Family().IsDomain() {
  138. ips, err := h.dns.LookupIP(addr.Domain(), dns.IPOption{
  139. IPv4Enable: h.hasIPv4,
  140. IPv6Enable: h.hasIPv6,
  141. })
  142. if err != nil {
  143. return newError("failed to lookup DNS").Base(err)
  144. } else if len(ips) == 0 {
  145. return dns.ErrEmptyResponse
  146. }
  147. addr = net.IPAddress(ips[0])
  148. }
  149. var newCtx context.Context
  150. var newCancel context.CancelFunc
  151. if session.TimeoutOnlyFromContext(ctx) {
  152. newCtx, newCancel = context.WithCancel(context.Background())
  153. }
  154. p := h.policyManager.ForLevel(0)
  155. ctx, cancel := context.WithCancel(ctx)
  156. timer := signal.CancelAfterInactivity(ctx, func() {
  157. cancel()
  158. if newCancel != nil {
  159. newCancel()
  160. }
  161. }, p.Timeouts.ConnectionIdle)
  162. addrPort := netip.AddrPortFrom(toNetIpAddr(addr), destination.Port.Value())
  163. var requestFunc func() error
  164. var responseFunc func() error
  165. if command == protocol.RequestCommandTCP {
  166. conn, err := h.net.DialContextTCPAddrPort(ctx, addrPort)
  167. if err != nil {
  168. return newError("failed to create TCP connection").Base(err)
  169. }
  170. defer conn.Close()
  171. requestFunc = func() error {
  172. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  173. return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer))
  174. }
  175. responseFunc = func() error {
  176. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  177. return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer))
  178. }
  179. } else if command == protocol.RequestCommandUDP {
  180. conn, err := h.net.DialUDPAddrPort(netip.AddrPort{}, addrPort)
  181. if err != nil {
  182. return newError("failed to create UDP connection").Base(err)
  183. }
  184. defer conn.Close()
  185. requestFunc = func() error {
  186. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  187. return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer))
  188. }
  189. responseFunc = func() error {
  190. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  191. return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer))
  192. }
  193. }
  194. if newCtx != nil {
  195. ctx = newCtx
  196. }
  197. responseDonePost := task.OnSuccess(responseFunc, task.Close(link.Writer))
  198. if err := task.Run(ctx, requestFunc, responseDonePost); err != nil {
  199. common.Interrupt(link.Reader)
  200. common.Interrupt(link.Writer)
  201. return newError("connection ends").Base(err)
  202. }
  203. return nil
  204. }
  205. // serialize the config into an IPC request
  206. func createIPCRequest(conf *DeviceConfig, d dns.Client, resolveEndPointToV4 bool) string {
  207. var request bytes.Buffer
  208. request.WriteString(fmt.Sprintf("private_key=%s\n", conf.SecretKey))
  209. for _, peer := range conf.Peers {
  210. endpoint := peer.Endpoint
  211. host, port, err := net.SplitHostPort(endpoint)
  212. if resolveEndPointToV4 && err == nil {
  213. _, err = netip.ParseAddr(host)
  214. if err != nil {
  215. ipList, err := d.LookupIP(host, dns.IPOption{IPv4Enable: true, IPv6Enable: false})
  216. if err == nil && len(ipList) > 0 {
  217. endpoint = stdnet.JoinHostPort(ipList[0].String(), port)
  218. }
  219. }
  220. }
  221. request.WriteString(fmt.Sprintf("public_key=%s\nendpoint=%s\npersistent_keepalive_interval=%d\npreshared_key=%s\n",
  222. peer.PublicKey, endpoint, peer.KeepAlive, peer.PreSharedKey))
  223. for _, ip := range peer.AllowedIps {
  224. request.WriteString(fmt.Sprintf("allowed_ip=%s\n", ip))
  225. }
  226. }
  227. return request.String()[:request.Len()]
  228. }
  229. // convert endpoint string to netip.Addr
  230. func parseEndpoints(conf *DeviceConfig) ([]netip.Addr, error) {
  231. endpoints := make([]netip.Addr, len(conf.Endpoint))
  232. for i, str := range conf.Endpoint {
  233. var addr netip.Addr
  234. if strings.Contains(str, "/") {
  235. prefix, err := netip.ParsePrefix(str)
  236. if err != nil {
  237. return nil, err
  238. }
  239. addr = prefix.Addr()
  240. if prefix.Bits() != addr.BitLen() {
  241. return nil, newError("interface address subnet should be /32 for IPv4 and /128 for IPv6")
  242. }
  243. } else {
  244. var err error
  245. addr, err = netip.ParseAddr(str)
  246. if err != nil {
  247. return nil, err
  248. }
  249. }
  250. endpoints[i] = addr
  251. }
  252. return endpoints, nil
  253. }
  254. // creates a tun interface on netstack given a configuration
  255. func (h *Handler) makeVirtualTun(bind *netBindClient) (Tunnel, error) {
  256. t, err := CreateTun(h.endpoints, int(h.conf.Mtu))
  257. if err != nil {
  258. return nil, err
  259. }
  260. bind.dnsOption.IPv4Enable = h.hasIPv4
  261. bind.dnsOption.IPv6Enable = h.hasIPv6
  262. if err = t.BuildDevice(h.ipc, bind); err != nil {
  263. _ = t.Close()
  264. return nil, err
  265. }
  266. return t, nil
  267. }
  268. func init() {
  269. common.Must(common.RegisterConfig((*DeviceConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  270. return New(ctx, config.(*DeviceConfig))
  271. }))
  272. }