diff --git a/global/global.go b/global/global.go deleted file mode 100644 index dfbfa4a..0000000 --- a/global/global.go +++ /dev/null @@ -1 +0,0 @@ -package global diff --git a/http/api/client.go b/http/api/client.go index a606894..fcac909 100644 --- a/http/api/client.go +++ b/http/api/client.go @@ -5,8 +5,11 @@ import ( "fmt" "gitee.ltd/lxh/logger/log" "github.com/gin-gonic/gin" + "github.com/spf13/cast" + "golang.zx2c4.com/wireguard/wgctrl/wgtypes" "os" "strings" + "time" "wireguard-dashboard/client" "wireguard-dashboard/http/param" "wireguard-dashboard/model/entity" @@ -75,6 +78,84 @@ func (clients) Save(c *gin.Context) { utils.GinResponse(c).OK() } +// AssignIPAndAllowedIP +// @description: 分配客户端IP和允许访问的IP段 +// @receiver clients +// @param c +func (clients) AssignIPAndAllowedIP(c *gin.Context) { + var p param.AssignIPAndAllowedIP + if err := c.ShouldBind(&p); err != nil { + utils.GinResponse(c).FailedWithErr("参数错误", err) + return + } + + // 获取一下服务端信息,因为IP分配需要根据服务端的IP制定 + serverInfo, err := repository.Server().GetServer() + if err != nil { + utils.GinResponse(c).FailedWithErr("获取服务端信息失败", err) + return + } + + var assignIPS []string + assignIPS = append(assignIPS, serverInfo.IpScope) + switch p.Rule { + case "AUTO": + // 只获取最新的一个 + var clientInfo *entity.Client + if err = repository.Client().Order("created_at DESC").Take(&clientInfo).Error; err == nil { + if cast.ToInt64(utils.Wireguard().GetIPSuffix(clientInfo.IpAllocation)) >= 255 { + utils.GinResponse(c).FailedWithMsg("当前IP分配错误,请手动进行分配") + return + } + assignIPS = append(assignIPS, clientInfo.IpAllocation) + } + + case "RANDOM": + // 查询全部客户端不管是禁用还是没禁用的 + var clientsInfo []entity.Client + if err = repository.Client().Find(&clientsInfo).Error; err != nil { + utils.GinResponse(c).FailedWithErr("获取失败", err) + return + } + + for _, v := range clientsInfo { + assignIPS = append(assignIPS, v.IpAllocation) + } + } + + clientIP := utils.Wireguard().GenerateClientIP(serverInfo.IpScope, p.Rule, assignIPS...) + + utils.GinResponse(c).OKWithData(map[string]any{ + "clientIP": []string{fmt.Sprintf("%s/32", clientIP)}, + "serverIP": []string{serverInfo.IpScope}, + }) +} + +// GenerateKeys +// @description: 生成密钥对 +// @receiver clients +// @param c +func (clients) GenerateKeys(c *gin.Context) { + // 为空,新增 + privateKey, err := wgtypes.GeneratePrivateKey() + if err != nil { + utils.GinResponse(c).FailedWithErr("生成密钥对失败", err) + return + } + publicKey := privateKey.PublicKey().String() + presharedKey, err := wgtypes.GenerateKey() + if err != nil { + return + } + keys := template_data.Keys{ + PrivateKey: privateKey.String(), + PublicKey: publicKey, + PresharedKey: presharedKey.String(), + } + + utils.GinResponse(c).OKWithData(keys) +} + // Delete // @description: 删除客户端 // @receiver clients @@ -127,12 +208,17 @@ func (clients) Download(c *gin.Context) { return } + var serverDNS []string + if *data.UseServerDns == 1 { + serverDNS = setting.DnsServer + } + // 处理一下数据 execData := template_data.ClientConfig{ PrivateKey: keys.PrivateKey, IpAllocation: data.IpAllocation, MTU: setting.MTU, - DNS: strings.Join(setting.DnsServer, ","), + DNS: strings.Join(serverDNS, ","), PublicKey: data.Server.PublicKey, PresharedKey: keys.PresharedKey, AllowedIPS: data.AllowedIps, @@ -199,11 +285,17 @@ func (clients) GenerateQrCode(c *gin.Context) { return } + var serverDNS []string + if *data.UseServerDns == 1 { + serverDNS = setting.DnsServer + } + // 处理一下数据 execData := template_data.ClientConfig{ PrivateKey: keys.PrivateKey, IpAllocation: data.IpAllocation, MTU: setting.MTU, + DNS: strings.Join(serverDNS, ","), PublicKey: data.Server.PublicKey, PresharedKey: keys.PresharedKey, AllowedIPS: data.AllowedIps, @@ -281,7 +373,7 @@ func (clients) Status(c *gin.Context) { ipAllocation += iaip.String() + "," } ipAllocation = strings.TrimRight(ipAllocation, ",") - isOnline := p.LastHandshakeTime.Minute() < 1 + isOnline := time.Since(p.LastHandshakeTime).Minutes() < 1 data = append(data, vo.ClientStatus{ ID: clientInfo.Id, Name: clientInfo.Name, diff --git a/http/api/setting.go b/http/api/setting.go index 7d43046..0e9909d 100644 --- a/http/api/setting.go +++ b/http/api/setting.go @@ -4,6 +4,7 @@ import ( "encoding/json" "gitee.ltd/lxh/logger/log" "github.com/gin-gonic/gin" + "wireguard-dashboard/config" "wireguard-dashboard/http/param" "wireguard-dashboard/model/entity" "wireguard-dashboard/queues" @@ -92,3 +93,13 @@ func (setting) GetPublicNetworkIP(c *gin.Context) { "IP": utils.Network().GetHostPublicIP(), }) } + +// GetServerRestartRule +// @description: 获取服务重启规则 +// @receiver setting +// @param c +func (setting) GetServerRestartRule(c *gin.Context) { + utils.GinResponse(c).OKWithData(map[string]string{ + "rule": config.Config.Wireguard.ListenConfig, + }) +} diff --git a/http/param/client.go b/http/param/client.go index 8df2078..8a58472 100644 --- a/http/param/client.go +++ b/http/param/client.go @@ -42,3 +42,9 @@ type SaveClient struct { type ControlServer struct { Status string `json:"status" form:"status" binding:"required,oneof=START STOP RESTART"` } + +// AssignIPAndAllowedIP +// @description: 分配IP和允许访问的IP段 +type AssignIPAndAllowedIP struct { + Rule string `json:"rule" form:"rule" binding:"required,oneof=RANDOM AUTO"` // 分配IP的规则 RANDOM - 固定 | AUTO - 自动生成 +} diff --git a/main.go b/main.go index 5aff427..7253fae 100644 --- a/main.go +++ b/main.go @@ -3,7 +3,9 @@ package main import ( "fmt" "gitee.ltd/lxh/logger/log" + "math/rand" "net/http" + "time" "wireguard-dashboard/config" "wireguard-dashboard/initialize" "wireguard-dashboard/queues" @@ -20,6 +22,7 @@ func init() { } func main() { + rand.New(rand.NewSource(time.Now().Local().UnixNano())) route.IncludeRouters( route.CaptchaApi, route.UserApi, diff --git a/queues/async_wg_config.go b/queues/async_wg_config.go index ebe0599..c2db28a 100644 --- a/queues/async_wg_config.go +++ b/queues/async_wg_config.go @@ -78,6 +78,10 @@ func asyncWireguardConfigFile() { // 客户端数据 var renderClients []template_data.Client for _, v := range serverEnt.Clients { + // 如果不是确认后创建或者未启用就不写入到wireguard配置文件当中 + if *v.EnableAfterCreation != 1 || *v.Enabled != 1 { + continue + } var clientKey template_data.Keys _ = json.Unmarshal([]byte(v.Keys), &clientKey) var createUserName string diff --git a/repository/client.go b/repository/client.go index 034ef25..d58608b 100644 --- a/repository/client.go +++ b/repository/client.go @@ -131,16 +131,40 @@ func (r clientRepo) Save(p param.SaveClient, adminId string) (client *entity.Cli return nil, errors.New("该客户端的IP已经存在,请检查后再添加!") } - // 为空,新增 - privateKey, err := wgtypes.GeneratePrivateKey() - if err != nil { - return + var privateKey, presharedKey wgtypes.Key + var publicKey string + + if p.Keys.PrivateKey == "" { + // 为空,新增 + privateKey, err = wgtypes.GeneratePrivateKey() + if err != nil { + log.Errorf("生成密钥对失败: %v", err.Error()) + return nil, errors.New("解析密钥失败") + } + } else { + privateKey, err = wgtypes.ParseKey(p.Keys.PrivateKey) + if err != nil { + log.Errorf("解析密钥对失败: %v", err.Error()) + return nil, errors.New("解析密钥失败") + } } - publicKey := privateKey.PublicKey().String() - presharedKey, err := wgtypes.GenerateKey() - if err != nil { - return + + publicKey = privateKey.PublicKey().String() + + if p.Keys.PresharedKey == "" { + presharedKey, err = wgtypes.GenerateKey() + if err != nil { + log.Errorf("生成共享密钥失败: %v", err.Error()) + return nil, errors.New("解析密钥失败") + } + } else { + presharedKey, err = wgtypes.ParseKey(p.Keys.PresharedKey) + if err != nil { + log.Errorf("解析共享密钥失败: %v", err.Error()) + return nil, errors.New("解析密钥失败") + } } + keys := template_data.Keys{ PrivateKey: privateKey.String(), PublicKey: publicKey, diff --git a/route/client.go b/route/client.go index f54a408..9254cb1 100644 --- a/route/client.go +++ b/route/client.go @@ -16,5 +16,7 @@ func ClientApi(r *gin.RouterGroup) { apiGroup.POST("generate-qrcode/:id", api.Client().GenerateQrCode) // 生成客户端二维码 apiGroup.GET("status", api.Client().Status) // 获取客户端链接状态监听列表 apiGroup.POST("offline/:id", api.Client().Offline) // 强制下线指定客户端 + apiGroup.POST("assignIP", api.Client().AssignIPAndAllowedIP) // 分配IP + apiGroup.POST("generate-keys", api.Client().GenerateKeys) // 生成密钥对 } } diff --git a/route/server.go b/route/server.go index 4d6f6fa..872adde 100644 --- a/route/server.go +++ b/route/server.go @@ -7,10 +7,10 @@ import ( ) func ServerApi(r *gin.RouterGroup) { - apiGroup := r.Group("server", middleware.Authorization(), middleware.Permission(), middleware.SystemLogRequest()) + apiGroup := r.Group("server", middleware.Authorization(), middleware.SystemLogRequest()) { - apiGroup.GET("", api.Server().GetServer) // 获取服务端信息 - apiGroup.POST("", middleware.Permission(), api.Server().SaveServer) // 新增/更新服务端信息 - apiGroup.POST("control-server", middleware.Permission(), api.Server().ControlServer) // 服务端操作控制 + apiGroup.GET("", api.Server().GetServer) // 获取服务端信息 + apiGroup.POST("", middleware.Permission(), middleware.Permission(), api.Server().SaveServer) // 新增/更新服务端信息 + apiGroup.POST("control-server", middleware.Permission(), middleware.Permission(), api.Server().ControlServer) // 服务端操作控制 } } diff --git a/route/setting.go b/route/setting.go index 74eb65a..0184d59 100644 --- a/route/setting.go +++ b/route/setting.go @@ -16,5 +16,6 @@ func SettingApi(r *gin.RouterGroup) { apiGroup.POST("server-global", middleware.Permission(), api.Setting().SetServerGlobal) // 设置服务端全局配置 apiGroup.GET("server", api.Setting().GetGlobalSetting) // 获取全局服务端配置 apiGroup.GET("public-ip", api.Setting().GetPublicNetworkIP) // 获取公网IP + apiGroup.GET("restart-rule", api.Setting().GetServerRestartRule) // 服务端重启规则 } } diff --git a/script/script.go b/script/script.go index 8768b5e..24664e0 100644 --- a/script/script.go +++ b/script/script.go @@ -107,7 +107,7 @@ func (s Script) InitServer() error { // 初始化服务端的全局配置 var data = map[string]any{ "endpointAddress": utils.Network().GetHostPublicIP(), - "dnsServer": []string{"10.10.10.1/24"}, + "dnsServer": []string{"10.25.8.1"}, "MTU": 1450, "persistentKeepalive": 15, "firewallMark": "0xca6c", @@ -135,13 +135,13 @@ func (s Script) InitServer() error { // 根据密钥生成公钥 publicKey := privateKey.PublicKey() serverEnt := &entity.Server{ - IpScope: "10.10.10.1/24", + IpScope: "10.25.8.1/24", ListenPort: 51820, PrivateKey: privateKey.String(), PublicKey: publicKey.String(), - PostUpScript: "", + PostUpScript: "iptables -A FORWARD -i wg0 -j ACCEPT; iptables -A FORWARD -o wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE", PreDownScript: "", - PostDownScript: "", + PostDownScript: "iptables -D FORWARD -i wg0 -j ACCEPT; iptables -D FORWARD -o wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE", } // 没有服务端,开始初始化 diff --git a/template/wg.client.conf b/template/wg.client.conf index 05950e8..a4970e0 100644 --- a/template/wg.client.conf +++ b/template/wg.client.conf @@ -1,8 +1,10 @@ [Interface] PrivateKey = {{ .PrivateKey|html }} Address = {{ .IpAllocation|html }} -{{ if .DNS }}DNS = {{ .DNS|html }} {{ end }} +{{ if .DNS }}DNS = {{ .DNS|html }} MTU = {{ .MTU }} +{{ else }}MTU = {{ .MTU }}{{ end }} + [Peer] PublicKey = {{ .PublicKey|html }} diff --git a/utils/wireguard.go b/utils/wireguard.go index c126575..885e26d 100644 --- a/utils/wireguard.go +++ b/utils/wireguard.go @@ -1,7 +1,12 @@ package utils import ( + "fmt" + "github.com/spf13/cast" "golang.zx2c4.com/wireguard/wgctrl/wgtypes" + "math/rand" + "slices" + "strings" "wireguard-dashboard/client" ) @@ -33,3 +38,78 @@ func (wireguard) GetSpecClient(pk string) (*wgtypes.Peer, error) { return nil, nil } + +// GenerateClientIP +// @description: 生成客户端IP +// @receiver wireguard +// @param serverIP +// @param rule +// @return string +func (w wireguard) GenerateClientIP(serverIP, rule string, assignedIPS ...string) string { + // 再次拆分,只取最后一段 + suffix := w.GetIPSuffix(serverIP) + prefix := w.GetIPPrefix(serverIP) + // 如果是随机模式,则需要结尾数字小于等于 255,并且生成的数字不能是已分配当中任何一个 + // 如果是自动模式,只需要是已经分配的最后一位自增 + switch rule { + case "RANDOM": + suffix = w.random(assignedIPS...) + case "AUTO": + switch len(assignedIPS) { + case 1: + suffix = w.GetIPSuffix(assignedIPS[0]) + case 2: + suffix = w.GetIPSuffix(assignedIPS[1]) + } + + suffix = cast.ToString(cast.ToInt64(suffix) + 1) + } + + return fmt.Sprintf("%s.%s", prefix, suffix) +} + +// random +// @description: 随机模式 +// @receiver w +// @param assignedIPS +// @return string +func (w wireguard) random(assignedIPS ...string) string { + randomNumber := rand.Int63n(256) + var assuffixIP []int64 + for _, v := range assignedIPS { + assuffixIP = append(assuffixIP, cast.ToInt64(strings.Split(v, ".")[3])) + } + + if slices.Contains(assuffixIP, randomNumber) { + return w.random(assignedIPS...) + } + + return cast.ToString(randomNumber) +} + +// GetIPSuffix +// @description: 获取IP后缀 [10.10.10.23] 这里只获取23 +// @receiver w +// @param ip +// @return string +func (w wireguard) GetIPSuffix(ip string) string { + if strings.Contains(ip, "/") { + ip = strings.Split(ip, "/")[0] + } + + // 再次拆分,只取最后一段 + return strings.Split(ip, ".")[3] +} + +// GetIPPrefix +// @description: 获取IP前缀[10.10.10.23] 这里只获取 10.10.10 +// @receiver w +// @param ip +// @return string +func (w wireguard) GetIPPrefix(ip string) string { + if strings.Contains(ip, "/") { + ip = strings.Split(ip, "/")[0] + } + + return strings.Join(strings.Split(ip, ".")[:3], ".") +} diff --git a/web-src/.env b/web-src/.env index 50a7579..f336828 100644 --- a/web-src/.env +++ b/web-src/.env @@ -4,4 +4,3 @@ VITE_PORT = 8848 # 是否隐藏首页 隐藏 true 不隐藏 false (勿删除,VITE_HIDE_HOME只需在.env文件配置) VITE_HIDE_HOME = false -VITE_PUBLIC_PATH = // diff --git a/web-src/.env.development b/web-src/.env.development index fc93654..90d1146 100644 --- a/web-src/.env.development +++ b/web-src/.env.development @@ -2,7 +2,7 @@ VITE_PORT = 8848 # 开发环境读取配置文件路径 -VITE_PUBLIC_PATH = // +VITE_PUBLIC_PATH = / # 开发环境路由历史模式(Hash模式传"hash"、HTML5模式传"h5"、Hash模式带base参数传"hash,base参数"、HTML5模式带base参数传"h5,base参数") VITE_ROUTER_HISTORY = "hash" diff --git a/web-src/public/platform-config.json b/web-src/public/platform-config.json index 9982ec6..0f670d8 100644 --- a/web-src/public/platform-config.json +++ b/web-src/public/platform-config.json @@ -1,6 +1,6 @@ { "Version": "5.5.0", - "Title": "Wireguard-Dashboard", + "Title": "WG-Dashboard", "FixedHeader": true, "HiddenSideBar": false, "MultiTagsCache": false, diff --git a/web-src/src/api/clients.ts b/web-src/src/api/clients.ts index b10a7dc..ebf771e 100644 --- a/web-src/src/api/clients.ts +++ b/web-src/src/api/clients.ts @@ -13,6 +13,16 @@ export const downloadClient = (id: string) => { }); }; +// 客户端IP生成 +export const generateClientIP = (data?: object) => { + return http.request("post", baseUri("/client/assignIP"), { data }); +}; + +// 生成客户端密钥对 +export const generateClientKeys = () => { + return http.request("post", baseUri("/client/generate-keys")); +}; + // 获取客户端配置二维码 export const clientQrCode = (id: string) => { return http.request("post", baseUri("/client/generate-qrcode/" + id)); @@ -32,3 +42,8 @@ export const deleteClient = (id: string) => { export const getClientConnects = () => { return http.request("get", baseUri("/client/status")); }; + +// 强制下线客户端 +export const offlineClient = (id: string) => { + return http.request("post", baseUri("/client/offline/" + id)); +}; diff --git a/web-src/src/api/server.ts b/web-src/src/api/server.ts index fe1fcbd..a18283b 100644 --- a/web-src/src/api/server.ts +++ b/web-src/src/api/server.ts @@ -25,3 +25,15 @@ export const updateGlobalSetting = (data?: object) => { export const getPublicIP = () => { return http.request("get", baseUri("/setting/public-ip")); }; + +// 获取服务端重启规则 +export const getServerRestartRule = () => { + return http.request("get", baseUri("/setting/restart-rule")); +}; + +// 重启服务端 +export const restartServer = (data?: object) => { + return http.request("post", baseUri("/server/control-server"), { + data + }); +}; diff --git a/web-src/src/layout/components/lay-navbar/index.vue b/web-src/src/layout/components/lay-navbar/index.vue index 3bf2a9b..53c3b11 100644 --- a/web-src/src/layout/components/lay-navbar/index.vue +++ b/web-src/src/layout/components/lay-navbar/index.vue @@ -24,6 +24,9 @@ import changePwdForms, { } from "./component/change-password.vue"; import { useRouter } from "vue-router"; import useGetGlobalProperties from "@/hooks/useGetGlobalProperties"; +import { Refresh } from "@element-plus/icons-vue"; +import { getServerRestartRule, restartServer } from "@/api/server"; +import { message } from "@/utils/message"; const { layout, @@ -121,6 +124,29 @@ const openChangePasswordDialog = () => { } }); }; +let rule = ref(false); +// 判断是否展示重载配置按钮 +const getRule = () => { + getServerRestartRule().then(res => { + if (res.code === 200) { + rule.value = res.data.rule === "hand"; + } + }); + return rule; +}; + +// 重启服务端 +const restartServerCommand = () => { + restartServer({ + status: "RESTART" + }).then(res => { + if (res.code === 200) { + message("应用配置成功", { type: "success" }); + } + }); +}; + +getRule(); + > + + + + + diff --git a/web-src/src/views/server/clients.vue b/web-src/src/views/server/clients.vue index 67a2d3b..5522ca3 100644 --- a/web-src/src/views/server/clients.vue +++ b/web-src/src/views/server/clients.vue @@ -1,7 +1,7 @@ @@ -132,6 +141,32 @@ defineExpose({ getDetailFormRef }); + + + + + + + + + + + + + + 生成密钥对 + diff --git a/web-src/src/views/server/server.vue b/web-src/src/views/server/server.vue index 4427803..85bcade 100644 --- a/web-src/src/views/server/server.vue +++ b/web-src/src/views/server/server.vue @@ -5,6 +5,7 @@ import { useServerStoreHook } from "@/store/modules/server"; import { serverFormRules } from "@/views/server/utils/rules"; import { useGlobalSettingStoreHook } from "@/store/modules/globalSetting"; import { getPublicIP } from "@/api/server"; +import { useUserStoreHook } from "@/store/modules/user"; defineOptions({ // name 作为一种规范最好必须写上并且和路由的name保持一致 @@ -113,6 +114,10 @@ const getPublicIPApi = () => { }); }; +const isEditServerKeys = () => { + return useUserStoreHook().isAdmin && useUserStoreHook().account === "admin"; +}; + getServerApi(); getGlobalSettingApi(); @@ -144,10 +149,18 @@ getGlobalSettingApi(); /> - + + - + + diff --git a/web-src/vite.config.ts b/web-src/vite.config.ts index aea37ee..f7d4133 100644 --- a/web-src/vite.config.ts +++ b/web-src/vite.config.ts @@ -47,7 +47,7 @@ export default ({ mode }: ConfigEnv): UserConfigExport => { sourcemap: false, // 消除打包大小超过500kb警告 chunkSizeWarningLimit: 4000, - outDir: '../web', + outDir: "../web", rollupOptions: { input: { index: pathResolve("./index.html", import.meta.url)