wireguard.go 4.8 KB

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