wireguard.go 4.8 KB

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