wireguard.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. reserved: h.conf.Reserved,
  76. }
  77. net, err := h.makeVirtualTun(bind)
  78. if err != nil {
  79. bind.Close()
  80. return newError("failed to create virtual tun interface").Base(err)
  81. }
  82. h.net = net
  83. if h.bind != nil {
  84. h.bind.Close()
  85. }
  86. h.bind = bind
  87. }
  88. outbound := session.OutboundFromContext(ctx)
  89. if outbound == nil || !outbound.Target.IsValid() {
  90. return newError("target not specified")
  91. }
  92. // Destination of the inner request.
  93. destination := outbound.Target
  94. command := protocol.RequestCommandTCP
  95. if destination.Network == net.Network_UDP {
  96. command = protocol.RequestCommandUDP
  97. }
  98. // resolve dns
  99. addr := destination.Address
  100. if addr.Family().IsDomain() {
  101. ips, err := h.dns.LookupIP(addr.Domain(), dns.IPOption{
  102. IPv4Enable: h.net.HasV4(),
  103. IPv6Enable: h.net.HasV6(),
  104. })
  105. if err != nil {
  106. return newError("failed to lookup DNS").Base(err)
  107. } else if len(ips) == 0 {
  108. return dns.ErrEmptyResponse
  109. }
  110. addr = net.IPAddress(ips[0])
  111. }
  112. var newCtx context.Context
  113. var newCancel context.CancelFunc
  114. if session.TimeoutOnlyFromContext(ctx) {
  115. newCtx, newCancel = context.WithCancel(context.Background())
  116. }
  117. p := h.policyManager.ForLevel(0)
  118. ctx, cancel := context.WithCancel(ctx)
  119. timer := signal.CancelAfterInactivity(ctx, func() {
  120. cancel()
  121. if newCancel != nil {
  122. newCancel()
  123. }
  124. }, p.Timeouts.ConnectionIdle)
  125. addrPort := netip.AddrPortFrom(toNetIpAddr(addr), destination.Port.Value())
  126. var requestFunc func() error
  127. var responseFunc func() error
  128. if command == protocol.RequestCommandTCP {
  129. conn, err := h.net.DialContextTCPAddrPort(ctx, addrPort)
  130. if err != nil {
  131. return newError("failed to create TCP connection").Base(err)
  132. }
  133. requestFunc = func() error {
  134. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  135. return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer))
  136. }
  137. responseFunc = func() error {
  138. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  139. return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer))
  140. }
  141. } else if command == protocol.RequestCommandUDP {
  142. conn, err := h.net.DialUDPAddrPort(netip.AddrPort{}, addrPort)
  143. if err != nil {
  144. return newError("failed to create UDP connection").Base(err)
  145. }
  146. requestFunc = func() error {
  147. defer timer.SetTimeout(p.Timeouts.DownlinkOnly)
  148. return buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer))
  149. }
  150. responseFunc = func() error {
  151. defer timer.SetTimeout(p.Timeouts.UplinkOnly)
  152. return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer))
  153. }
  154. }
  155. if newCtx != nil {
  156. ctx = newCtx
  157. }
  158. responseDonePost := task.OnSuccess(responseFunc, task.Close(link.Writer))
  159. if err := task.Run(ctx, requestFunc, responseDonePost); err != nil {
  160. return newError("connection ends").Base(err)
  161. }
  162. return nil
  163. }
  164. // serialize the config into an IPC request
  165. func createIPCRequest(conf *DeviceConfig) string {
  166. var request bytes.Buffer
  167. request.WriteString(fmt.Sprintf("private_key=%s\n", conf.SecretKey))
  168. for _, peer := range conf.Peers {
  169. request.WriteString(fmt.Sprintf("public_key=%s\nendpoint=%s\npersistent_keepalive_interval=%d\npreshared_key=%s\n",
  170. peer.PublicKey, peer.Endpoint, peer.KeepAlive, peer.PreSharedKey))
  171. for _, ip := range peer.AllowedIps {
  172. request.WriteString(fmt.Sprintf("allowed_ip=%s\n", ip))
  173. }
  174. }
  175. return request.String()[:request.Len()]
  176. }
  177. // convert endpoint string to netip.Addr
  178. func parseEndpoints(conf *DeviceConfig) ([]netip.Addr, error) {
  179. endpoints := make([]netip.Addr, len(conf.Endpoint))
  180. for i, str := range conf.Endpoint {
  181. var addr netip.Addr
  182. if strings.Contains(str, "/") {
  183. prefix, err := netip.ParsePrefix(str)
  184. if err != nil {
  185. return nil, err
  186. }
  187. addr = prefix.Addr()
  188. if prefix.Bits() != addr.BitLen() {
  189. return nil, newError("interface address subnet should be /32 for IPv4 and /128 for IPv6")
  190. }
  191. } else {
  192. var err error
  193. addr, err = netip.ParseAddr(str)
  194. if err != nil {
  195. return nil, err
  196. }
  197. }
  198. endpoints[i] = addr
  199. }
  200. return endpoints, nil
  201. }
  202. // creates a tun interface on netstack given a configuration
  203. func (h *Handler) makeVirtualTun(bind *netBindClient) (*Net, error) {
  204. tun, tnet, err := CreateNetTUN(h.endpoints, h.dns, int(h.conf.Mtu))
  205. if err != nil {
  206. return nil, err
  207. }
  208. bind.dnsOption.IPv4Enable = tnet.HasV4()
  209. bind.dnsOption.IPv6Enable = tnet.HasV6()
  210. // dev := device.NewDevice(tun, conn.NewDefaultBind(), nil /* device.NewLogger(device.LogLevelVerbose, "") */)
  211. dev := device.NewDevice(tun, bind, &device.Logger{
  212. Verbosef: func(format string, args ...any) {
  213. log.Record(&log.GeneralMessage{
  214. Severity: log.Severity_Debug,
  215. Content: fmt.Sprintf(format, args...),
  216. })
  217. },
  218. Errorf: func(format string, args ...any) {
  219. log.Record(&log.GeneralMessage{
  220. Severity: log.Severity_Error,
  221. Content: fmt.Sprintf(format, args...),
  222. })
  223. },
  224. }, int(h.conf.NumWorkers))
  225. err = dev.IpcSet(h.ipc)
  226. if err != nil {
  227. return nil, err
  228. }
  229. err = dev.Up()
  230. if err != nil {
  231. return nil, err
  232. }
  233. return tnet, nil
  234. }
  235. func init() {
  236. common.Must(common.RegisterConfig((*DeviceConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  237. return New(ctx, config.(*DeviceConfig))
  238. }))
  239. }