client_wireguard.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. package service
  2. import (
  3. "net/netip"
  4. "strconv"
  5. "strings"
  6. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  7. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  8. wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
  9. )
  10. const defaultWireguardBase = "10.0.0.0/24"
  11. func keepAliveStr(seconds int) string {
  12. if seconds <= 0 {
  13. return ""
  14. }
  15. return strconv.Itoa(seconds)
  16. }
  17. func wireguardHostAddr(s string) netip.Addr {
  18. s = strings.TrimSpace(s)
  19. if s == "" {
  20. return netip.Addr{}
  21. }
  22. if p, err := netip.ParsePrefix(s); err == nil {
  23. return p.Addr()
  24. }
  25. if a, err := netip.ParseAddr(s); err == nil {
  26. return a
  27. }
  28. return netip.Addr{}
  29. }
  30. func wireguardAllocationBase(used []string, fallback string) string {
  31. for _, u := range used {
  32. a := wireguardHostAddr(u)
  33. if !a.IsValid() || !a.Is4() || a.IsUnspecified() {
  34. continue
  35. }
  36. if p, err := a.Prefix(24); err == nil {
  37. return p.String()
  38. }
  39. }
  40. return fallback
  41. }
  42. // allocateWireguardAddress returns the first free /32 host address in base that
  43. // is not already present in used. The server holds the first host (.1), so
  44. // allocation starts at the second host (.2).
  45. func allocateWireguardAddress(used []string, base string) (string, error) {
  46. if base == "" {
  47. base = defaultWireguardBase
  48. }
  49. prefix, err := netip.ParsePrefix(base)
  50. if err != nil {
  51. return "", err
  52. }
  53. taken := make(map[netip.Addr]struct{}, len(used))
  54. for _, u := range used {
  55. if a := wireguardHostAddr(u); a.IsValid() {
  56. taken[a] = struct{}{}
  57. }
  58. }
  59. addr := prefix.Masked().Addr().Next().Next()
  60. for prefix.Contains(addr) {
  61. if _, ok := taken[addr]; !ok {
  62. return addr.String() + "/32", nil
  63. }
  64. addr = addr.Next()
  65. }
  66. return "", common.NewError("wireguard: no free address available in", base)
  67. }
  68. // defaultWireguardClients fills in blank WireGuard credentials for newly added
  69. // clients: a generated keypair when none was provided, a derived public key when
  70. // only a private key was given, and a unique tunnel address allocated from the
  71. // inbound's subnet. It mutates both the typed clients and the parallel raw client
  72. // maps that get persisted into the inbound settings. Existing values are never
  73. // overwritten, so editing a client never rotates its keys.
  74. func defaultWireguardClients(existing, clients []model.Client, interfaceClients []any) error {
  75. used := make([]string, 0)
  76. for i := range existing {
  77. used = append(used, existing[i].AllowedIPs...)
  78. }
  79. base := wireguardAllocationBase(used, defaultWireguardBase)
  80. for i := range clients {
  81. c := &clients[i]
  82. if c.PrivateKey == "" && c.PublicKey == "" {
  83. priv, pub, err := wgutil.GenerateWireguardKeypair()
  84. if err != nil {
  85. return err
  86. }
  87. c.PrivateKey = priv
  88. c.PublicKey = pub
  89. } else if c.PublicKey == "" && c.PrivateKey != "" {
  90. pub, err := wgutil.PublicKeyFromPrivate(c.PrivateKey)
  91. if err != nil {
  92. return err
  93. }
  94. c.PublicKey = pub
  95. }
  96. if len(c.AllowedIPs) == 0 {
  97. addr, err := allocateWireguardAddress(used, base)
  98. if err != nil {
  99. return err
  100. }
  101. c.AllowedIPs = []string{addr}
  102. }
  103. used = append(used, c.AllowedIPs...)
  104. if i < len(interfaceClients) {
  105. if m, ok := interfaceClients[i].(map[string]any); ok {
  106. m["privateKey"] = c.PrivateKey
  107. m["publicKey"] = c.PublicKey
  108. m["allowedIPs"] = c.AllowedIPs
  109. if c.PreSharedKey != "" {
  110. m["preSharedKey"] = c.PreSharedKey
  111. }
  112. if c.KeepAlive > 0 {
  113. m["keepAlive"] = c.KeepAlive
  114. }
  115. interfaceClients[i] = m
  116. }
  117. }
  118. }
  119. return nil
  120. }