wireguard.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. //go:build with_wireguard
  2. package outbound
  3. import (
  4. "context"
  5. "encoding/base64"
  6. "encoding/hex"
  7. "fmt"
  8. "net"
  9. "strings"
  10. "github.com/sagernet/sing-box/adapter"
  11. "github.com/sagernet/sing-box/common/dialer"
  12. C "github.com/sagernet/sing-box/constant"
  13. "github.com/sagernet/sing-box/log"
  14. "github.com/sagernet/sing-box/option"
  15. "github.com/sagernet/sing-box/transport/wireguard"
  16. "github.com/sagernet/sing-tun"
  17. "github.com/sagernet/sing/common"
  18. "github.com/sagernet/sing/common/debug"
  19. E "github.com/sagernet/sing/common/exceptions"
  20. M "github.com/sagernet/sing/common/metadata"
  21. N "github.com/sagernet/sing/common/network"
  22. "github.com/sagernet/wireguard-go/device"
  23. )
  24. var (
  25. _ adapter.Outbound = (*WireGuard)(nil)
  26. _ adapter.InterfaceUpdateListener = (*WireGuard)(nil)
  27. )
  28. type WireGuard struct {
  29. myOutboundAdapter
  30. bind *wireguard.ClientBind
  31. device *device.Device
  32. tunDevice wireguard.Device
  33. }
  34. func NewWireGuard(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.WireGuardOutboundOptions) (*WireGuard, error) {
  35. outbound := &WireGuard{
  36. myOutboundAdapter: myOutboundAdapter{
  37. protocol: C.TypeWireGuard,
  38. network: options.Network.Build(),
  39. router: router,
  40. logger: logger,
  41. tag: tag,
  42. },
  43. }
  44. var reserved [3]uint8
  45. if len(options.Reserved) > 0 {
  46. if len(options.Reserved) != 3 {
  47. return nil, E.New("invalid reserved value, required 3 bytes, got ", len(options.Reserved))
  48. }
  49. copy(reserved[:], options.Reserved)
  50. }
  51. peerAddr := options.ServerOptions.Build()
  52. outbound.bind = wireguard.NewClientBind(ctx, dialer.New(router, options.DialerOptions), peerAddr, reserved)
  53. localPrefixes := common.Map(options.LocalAddress, option.ListenPrefix.Build)
  54. if len(localPrefixes) == 0 {
  55. return nil, E.New("missing local address")
  56. }
  57. var privateKey, peerPublicKey, preSharedKey string
  58. {
  59. bytes, err := base64.StdEncoding.DecodeString(options.PrivateKey)
  60. if err != nil {
  61. return nil, E.Cause(err, "decode private key")
  62. }
  63. privateKey = hex.EncodeToString(bytes)
  64. }
  65. {
  66. bytes, err := base64.StdEncoding.DecodeString(options.PeerPublicKey)
  67. if err != nil {
  68. return nil, E.Cause(err, "decode peer public key")
  69. }
  70. peerPublicKey = hex.EncodeToString(bytes)
  71. }
  72. if options.PreSharedKey != "" {
  73. bytes, err := base64.StdEncoding.DecodeString(options.PreSharedKey)
  74. if err != nil {
  75. return nil, E.Cause(err, "decode pre shared key")
  76. }
  77. preSharedKey = hex.EncodeToString(bytes)
  78. }
  79. ipcConf := "private_key=" + privateKey
  80. ipcConf += "\npublic_key=" + peerPublicKey
  81. ipcConf += "\nendpoint=" + peerAddr.String()
  82. if preSharedKey != "" {
  83. ipcConf += "\npreshared_key=" + preSharedKey
  84. }
  85. var has4, has6 bool
  86. for _, address := range localPrefixes {
  87. if address.Addr().Is4() {
  88. has4 = true
  89. } else {
  90. has6 = true
  91. }
  92. }
  93. if has4 {
  94. ipcConf += "\nallowed_ip=0.0.0.0/0"
  95. }
  96. if has6 {
  97. ipcConf += "\nallowed_ip=::/0"
  98. }
  99. mtu := options.MTU
  100. if mtu == 0 {
  101. mtu = 1408
  102. }
  103. var wireTunDevice wireguard.Device
  104. var err error
  105. if !options.SystemInterface && tun.WithGVisor {
  106. wireTunDevice, err = wireguard.NewStackDevice(localPrefixes, mtu)
  107. } else {
  108. wireTunDevice, err = wireguard.NewSystemDevice(router, options.InterfaceName, localPrefixes, mtu)
  109. }
  110. if err != nil {
  111. return nil, E.Cause(err, "create WireGuard device")
  112. }
  113. wgDevice := device.NewDevice(wireTunDevice, outbound.bind, &device.Logger{
  114. Verbosef: func(format string, args ...interface{}) {
  115. logger.Debug(fmt.Sprintf(strings.ToLower(format), args...))
  116. },
  117. Errorf: func(format string, args ...interface{}) {
  118. logger.Error(fmt.Sprintf(strings.ToLower(format), args...))
  119. },
  120. }, options.Workers)
  121. if debug.Enabled {
  122. logger.Trace("created wireguard ipc conf: \n", ipcConf)
  123. }
  124. err = wgDevice.IpcSet(ipcConf)
  125. if err != nil {
  126. return nil, E.Cause(err, "setup wireguard")
  127. }
  128. outbound.device = wgDevice
  129. outbound.tunDevice = wireTunDevice
  130. return outbound, nil
  131. }
  132. func (w *WireGuard) InterfaceUpdated() error {
  133. w.bind.Reset()
  134. return nil
  135. }
  136. func (w *WireGuard) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  137. switch network {
  138. case N.NetworkTCP:
  139. w.logger.InfoContext(ctx, "outbound connection to ", destination)
  140. case N.NetworkUDP:
  141. w.logger.InfoContext(ctx, "outbound packet connection to ", destination)
  142. }
  143. if destination.IsFqdn() {
  144. addrs, err := w.router.LookupDefault(ctx, destination.Fqdn)
  145. if err != nil {
  146. return nil, err
  147. }
  148. return N.DialSerial(ctx, w.tunDevice, network, destination, addrs)
  149. }
  150. return w.tunDevice.DialContext(ctx, network, destination)
  151. }
  152. func (w *WireGuard) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  153. w.logger.InfoContext(ctx, "outbound packet connection to ", destination)
  154. return w.tunDevice.ListenPacket(ctx, destination)
  155. }
  156. func (w *WireGuard) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
  157. return NewConnection(ctx, w, conn, metadata)
  158. }
  159. func (w *WireGuard) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
  160. return NewPacketConnection(ctx, w, conn, metadata)
  161. }
  162. func (w *WireGuard) Start() error {
  163. return w.tunDevice.Start()
  164. }
  165. func (w *WireGuard) Close() error {
  166. if w.device != nil {
  167. w.device.Close()
  168. }
  169. return common.Close(w.tunDevice)
  170. }