wireguard.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. "net/netip"
  21. "strings"
  22. "github.com/sagernet/wireguard-go/device"
  23. "github.com/xtls/xray-core/common"
  24. "github.com/xtls/xray-core/common/buf"
  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 *Net
  41. bind *netBindClient
  42. policyManager policy.Manager
  43. dns dns.Client
  44. // cached configuration
  45. ipc string
  46. endpoints []netip.Addr
  47. }
  48. // New creates a new wireguard handler.
  49. func New(ctx context.Context, conf *DeviceConfig) (*Handler, error) {
  50. v := core.MustFromContext(ctx)
  51. endpoints, err := parseEndpoints(conf)
  52. if err != nil {
  53. return nil, err
  54. }
  55. return &Handler{
  56. conf: conf,
  57. policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
  58. dns: v.GetFeature(dns.ClientType()).(dns.Client),
  59. ipc: createIPCRequest(conf),
  60. endpoints: endpoints,
  61. }, nil
  62. }
  63. // Process implements OutboundHandler.Dispatch().
  64. func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
  65. if h.bind == nil || h.bind.dialer != dialer || h.net == nil {
  66. log.Record(&log.GeneralMessage{
  67. Severity: log.Severity_Info,
  68. Content: "switching dialer",
  69. })
  70. // bind := conn.NewStdNetBind() // TODO: conn.Bind wrapper for dialer
  71. bind := &netBindClient{
  72. dialer: dialer,
  73. workers: int(h.conf.NumWorkers),
  74. dns: h.dns,
  75. }
  76. net, err := h.makeVirtualTun(bind)
  77. if err != nil {
  78. bind.Close()
  79. return newError("failed to create virtual tun interface").Base(err)
  80. }
  81. h.net = net
  82. if h.bind != nil {
  83. h.bind.Close()
  84. }
  85. h.bind = bind
  86. }
  87. outbound := session.OutboundFromContext(ctx)
  88. if outbound == nil || !outbound.Target.IsValid() {
  89. return newError("target not specified")
  90. }
  91. // Destination of the inner request.
  92. destination := outbound.Target
  93. command := protocol.RequestCommandTCP
  94. if destination.Network == net.Network_UDP {
  95. command = protocol.RequestCommandUDP
  96. }
  97. // resolve dns
  98. addr := destination.Address
  99. if addr.Family().IsDomain() {
  100. ips, err := h.dns.LookupIP(addr.Domain(), dns.IPOption{
  101. IPv4Enable: h.net.HasV4(),
  102. IPv6Enable: h.net.HasV6(),
  103. })
  104. if err != nil {
  105. return newError("failed to lookup DNS").Base(err)
  106. } else if len(ips) == 0 {
  107. return dns.ErrEmptyResponse
  108. }
  109. addr = net.IPAddress(ips[0])
  110. }
  111. p := h.policyManager.ForLevel(0)
  112. ctx, cancel := context.WithCancel(ctx)
  113. timer := signal.CancelAfterInactivity(ctx, cancel, p.Timeouts.ConnectionIdle)
  114. addrPort := netip.AddrPortFrom(toNetIpAddr(addr), destination.Port.Value())
  115. var requestFunc func() error
  116. var responseFunc func() error
  117. if command == protocol.RequestCommandTCP {
  118. conn, err := h.net.DialContextTCPAddrPort(ctx, addrPort)
  119. if err != nil {
  120. return newError("failed to create TCP connection").Base(err)
  121. }
  122. requestFunc = func() error {
  123. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  124. return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer))
  125. }
  126. responseFunc = func() error {
  127. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  128. return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer))
  129. }
  130. } else if command == protocol.RequestCommandUDP {
  131. conn, err := h.net.DialUDPAddrPort(netip.AddrPort{}, addrPort)
  132. if err != nil {
  133. return newError("failed to create UDP connection").Base(err)
  134. }
  135. requestFunc = func() error {
  136. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  137. return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer))
  138. }
  139. responseFunc = func() error {
  140. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  141. return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer))
  142. }
  143. }
  144. responseDonePost := task.OnSuccess(responseFunc, task.Close(link.Writer))
  145. if err := task.Run(ctx, requestFunc, responseDonePost); err != nil {
  146. return newError("connection ends").Base(err)
  147. }
  148. return nil
  149. }
  150. // serialize the config into an IPC request
  151. func createIPCRequest(conf *DeviceConfig) string {
  152. var request bytes.Buffer
  153. request.WriteString(fmt.Sprintf("private_key=%s\n", conf.SecretKey))
  154. for _, peer := range conf.Peers {
  155. request.WriteString(fmt.Sprintf("public_key=%s\nendpoint=%s\npersistent_keepalive_interval=%d\npreshared_key=%s\n",
  156. peer.PublicKey, peer.Endpoint, peer.KeepAlive, peer.PreSharedKey))
  157. for _, ip := range peer.AllowedIps {
  158. request.WriteString(fmt.Sprintf("allowed_ip=%s\n", ip))
  159. }
  160. }
  161. return request.String()[:request.Len()]
  162. }
  163. // convert endpoint string to netip.Addr
  164. func parseEndpoints(conf *DeviceConfig) ([]netip.Addr, error) {
  165. endpoints := make([]netip.Addr, len(conf.Endpoint))
  166. for i, str := range conf.Endpoint {
  167. var addr netip.Addr
  168. if strings.Contains(str, "/") {
  169. prefix, err := netip.ParsePrefix(str)
  170. if err != nil {
  171. return nil, err
  172. }
  173. addr = prefix.Addr()
  174. if prefix.Bits() != addr.BitLen() {
  175. return nil, newError("interface address subnet should be /32 for IPv4 and /128 for IPv6")
  176. }
  177. } else {
  178. var err error
  179. addr, err = netip.ParseAddr(str)
  180. if err != nil {
  181. return nil, err
  182. }
  183. }
  184. endpoints[i] = addr
  185. }
  186. return endpoints, nil
  187. }
  188. // creates a tun interface on netstack given a configuration
  189. func (h *Handler) makeVirtualTun(bind *netBindClient) (*Net, error) {
  190. tun, tnet, err := CreateNetTUN(h.endpoints, h.dns, int(h.conf.Mtu))
  191. if err != nil {
  192. return nil, err
  193. }
  194. bind.dnsOption.IPv4Enable = tnet.HasV4()
  195. bind.dnsOption.IPv6Enable = tnet.HasV6()
  196. // dev := device.NewDevice(tun, conn.NewDefaultBind(), nil /* device.NewLogger(device.LogLevelVerbose, "") */)
  197. dev := device.NewDevice(tun, bind, &device.Logger{
  198. Verbosef: func(format string, args ...any) {
  199. log.Record(&log.GeneralMessage{
  200. Severity: log.Severity_Debug,
  201. Content: fmt.Sprintf(format, args...),
  202. })
  203. },
  204. Errorf: func(format string, args ...any) {
  205. log.Record(&log.GeneralMessage{
  206. Severity: log.Severity_Error,
  207. Content: fmt.Sprintf(format, args...),
  208. })
  209. },
  210. }, int(h.conf.NumWorkers))
  211. err = dev.IpcSet(h.ipc)
  212. if err != nil {
  213. return nil, err
  214. }
  215. err = dev.Up()
  216. if err != nil {
  217. return nil, err
  218. }
  219. return tnet, nil
  220. }
  221. func init() {
  222. common.Must(common.RegisterConfig((*DeviceConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  223. return New(ctx, config.(*DeviceConfig))
  224. }))
  225. }