From b4362a68fc52f9a009f163871851b7b1b96fd10f Mon Sep 17 00:00:00 2001 From: yisier <1340976576@qq.com> Date: Sat, 6 Dec 2025 00:31:32 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=BC=BA=E5=AE=A2=E6=88=B7=E7=AB=AFIP?= =?UTF-8?q?=E7=99=BD=E5=90=8D=E5=8D=95=E8=AE=A4=E8=AF=81=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/nps/nps.go | 2 +- lib/file/db.go | 3 ++- lib/file/obj.go | 1 + lib/goroutine/pool.go | 50 +++++++++++++++++++++++++++-------- lib/rate/rate.go | 15 +---------- server/proxy/http.go | 32 +++++++++++++++++++--- server/proxy/https.go | 4 +-- web/controllers/auth.go | 17 ++++++++++-- web/controllers/base.go | 39 +++++++++++++++++---------- web/controllers/global.go | 11 ++++---- web/static/js/language.js | 2 +- web/static/page/auth.html | 17 ++++-------- web/static/page/languages.xml | 10 +++++++ web/views/global/index.html | 8 ++++++ web/views/login/index.html | 2 +- web/views/login/register.html | 2 +- web/views/public/layout.html | 2 +- 17 files changed, 147 insertions(+), 70 deletions(-) diff --git a/cmd/nps/nps.go b/cmd/nps/nps.go index e3325b9..e6eda79 100644 --- a/cmd/nps/nps.go +++ b/cmd/nps/nps.go @@ -430,7 +430,7 @@ func run() { os.Exit(0) } - logs.Info("日志路径111:" + *npsLogPath) + logs.Info("日志路径:" + *npsLogPath) logs.Info("the config path is:" + common.GetRunPath()) logs.Info("the version of server is %s ,allow client core version to be %s,tls enable is %t", version.VERSION, version.GetVersion(), bridge.ServerTlsEnable) connection.InitConnectionService() diff --git a/lib/file/db.go b/lib/file/db.go index 6509156..a68fefc 100644 --- a/lib/file/db.go +++ b/lib/file/db.go @@ -1,6 +1,7 @@ package file import ( + "crypto/md5" "errors" "fmt" "net/http" @@ -321,7 +322,7 @@ func (s *DbUtils) GetClientByVkey(vkey string) (c *Client, err error) { var exist bool s.JsonDb.Clients.Range(func(key, value interface{}) bool { v := value.(*Client) - if v.VerifyKey == vkey { + if fmt.Sprintf("%x", md5.Sum([]byte(v.VerifyKey))) == vkey { exist = true c = v return false diff --git a/lib/file/obj.go b/lib/file/obj.go index f8016b2..99e5888 100644 --- a/lib/file/obj.go +++ b/lib/file/obj.go @@ -227,5 +227,6 @@ func (s *Target) GetRandomTarget() (string, error) { type Glob struct { BlackIpList []string + ServerUrl string sync.RWMutex } diff --git a/lib/goroutine/pool.go b/lib/goroutine/pool.go index 04c7d27..e4648bc 100644 --- a/lib/goroutine/pool.go +++ b/lib/goroutine/pool.go @@ -1,17 +1,18 @@ package goroutine import ( - "ehang.io/nps/lib/common" - "ehang.io/nps/lib/file" + "encoding/json" "fmt" - "github.com/astaxie/beego" - "github.com/astaxie/beego/logs" - "github.com/panjf2000/ants/v2" "io" "net" "path/filepath" "strings" "sync" + + "ehang.io/nps/lib/common" + "ehang.io/nps/lib/file" + "github.com/astaxie/beego/logs" + "github.com/panjf2000/ants/v2" ) type connGroup struct { @@ -56,16 +57,43 @@ func CopyBuffer(dst io.Writer, src io.Reader, flow *file.Flow, task *file.Tunnel if task != nil { if task.Client.IpWhite && task.Client.IpWhitePass != "" { + if common.IsAuthIp(remote, task.Client.VerifyKey, task.Client.IpWhiteList) { + ip := common.GetIpByAddr(remote) + var jsonBytes []byte + errorContent, _ := common.ReadAllFromFile(filepath.Join(common.GetRunPath(), "web", "static", "page", "auth.html")) authHtml := string(errorContent) - authHtml = strings.ReplaceAll(authHtml, "${ip}", common.GetIpByAddr(remote)) - authHtml = strings.ReplaceAll(authHtml, "${vkey}", task.Client.VerifyKey) - authHtml = strings.ReplaceAll(authHtml, "${port}", beego.AppConfig.String("web_port")) + authHtml = strings.ReplaceAll(authHtml, "${ip}", ip) + + fullRequest := string(buf[0:nr]) + // 获取HTTP请求的第一行 + lines := strings.Split(fullRequest, "\r\n") + if len(lines) == 0 { + lines = strings.Split(fullRequest, "\n") + } + firstLine := lines[0] + + if strings.HasPrefix(firstLine, "POST /authIp?pass=") { + pass := strings.Split(firstLine, " ")[1] + pass = strings.ReplaceAll(pass, "/authIp?pass=", "") + if pass == task.Client.IpWhitePass { + task.Client.IpWhiteList = append(task.Client.IpWhiteList, ip) + file.GetDb().UpdateClient(task.Client) + logs.Info("客户端IP白名单认证授权成功:vkey [%s] ip [%s] password [%s]", task.Client.VerifyKey, ip, pass) + jsonBytes, err = json.Marshal(map[string]interface{}{"success": true, "message": "授权成功"}) + } else { + logs.Error("客户端IP白名单认证授权密码错误:vkey [%s] ip [%s] password [%s]", task.Client.VerifyKey, ip, pass) + jsonBytes, err = json.Marshal(map[string]interface{}{"success": false, "message": "密码错误"}) + } + response := fmt.Sprintf("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: %d\r\nConnection: close\r\n\r\n%s", len(jsonBytes), jsonBytes) + dst.Write([]byte(response)) + return + } response := fmt.Sprintf("HTTP/1.1 401 Unauthorized\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: %d\r\nConnection: close\r\n\r\n%s", len(authHtml), authHtml) dst.Write([]byte(response)) - break + return } } } @@ -78,7 +106,7 @@ func CopyBuffer(dst io.Writer, src io.Reader, flow *file.Flow, task *file.Tunnel flow.Add(int64(nw), int64(nw)) // <<20 = 1024 * 1024 if flow.FlowLimit > 0 && (flow.FlowLimit<<20) < (flow.ExportFlow+flow.InletFlow) { - logs.Info("流量已经超出.........") + logs.Error("隧道[%s]流量已经超出", task.Client.VerifyKey) break } } @@ -98,7 +126,6 @@ func CopyBuffer(dst io.Writer, src io.Reader, flow *file.Flow, task *file.Tunnel break } } - //return written, err return err } @@ -108,6 +135,7 @@ func copyConnGroup(group interface{}) { if !ok { return } + var err error err = CopyBuffer(cg.dst, cg.src, cg.flow, cg.task, cg.remote) if err != nil { diff --git a/lib/rate/rate.go b/lib/rate/rate.go index 30e7758..6b22a18 100644 --- a/lib/rate/rate.go +++ b/lib/rate/rate.go @@ -2,20 +2,16 @@ package rate import ( "context" - "fmt" "time" xrate "golang.org/x/time/rate" ) -// Rate 使用 golang.org/x/time/rate 实现的字节令牌桶限速器 -// 保持原有对外接口:NewRate、Start、Get、ReturnBucket、Stop、NowRate type Rate struct { limiter *xrate.Limiter addSize int64 stopChan chan struct{} - // 暂时表示配置的每秒速率(字节/秒),用于展示 - NowRate int64 + NowRate int64 } func NewRate(addSize int64) *Rate { @@ -28,16 +24,13 @@ func NewRate(addSize int64) *Rate { } func (s *Rate) Start() { - // 保留一个 goroutine 以兼容原有 Stop 调用,用于未来扩展(例如监控) go func() { ticker := time.NewTicker(time.Second) defer ticker.Stop() for { select { case <-ticker.C: - // 目前将 NowRate 保持为配置速率;可以在此处扩展动态统计 s.NowRate = s.addSize - (int64(s.limiter.Tokens())) - //fmt.Printf("token left 2: %f\n", s.limiter.Tokens()) case <-s.stopChan: return } @@ -45,17 +38,14 @@ func (s *Rate) Start() { }() } -// 停止内部 goroutine func (s *Rate) Stop() { select { case <-s.stopChan: - // already closed default: close(s.stopChan) } } -// Get 阻塞直到获得 size 字节的令牌 func (s *Rate) Get(size int64) { if s.addSize <= 0 { return @@ -63,10 +53,7 @@ func (s *Rate) Get(size int64) { if size <= 0 { return } - // 使用背景上下文直接等待,必要时可替换为带超时的 Context ctx := context.Background() - // x/time/rate 的 WaitN 接受 int _ = s.limiter.WaitN(ctx, int(size)) s.NowRate = s.addSize - (int64(s.limiter.Tokens())) - fmt.Printf("get size: %d\n, token left: %f\n", size, s.limiter.Tokens()) } diff --git a/server/proxy/http.go b/server/proxy/http.go index 2ea8582..7c08a49 100644 --- a/server/proxy/http.go +++ b/server/proxy/http.go @@ -10,7 +10,7 @@ import ( "ehang.io/nps/lib/file" "ehang.io/nps/lib/goroutine" "ehang.io/nps/server/connection" - "github.com/astaxie/beego" + "encoding/json" "github.com/astaxie/beego/logs" "io" "net" @@ -199,11 +199,37 @@ reset: if host.Client.IpWhite && host.Client.IpWhitePass != "" { if common.IsAuthIp(c.RemoteAddr().String(), host.Client.VerifyKey, host.Client.IpWhiteList) { + + if r.URL.Path == "/authIp" { + rawQuery := r.URL.RawQuery + + var jsonBytes []byte + ip := common.GetIpByAddr(c.RemoteAddr().String()) + + if strings.Contains(rawQuery, "pass=") { + // 截取 = 后面的值 + pass := strings.Split(rawQuery, "pass=")[1] + if pass == host.Client.IpWhitePass { + host.Client.IpWhiteList = append(host.Client.IpWhiteList, ip) + file.GetDb().UpdateClient(host.Client) + logs.Info("客户端IP白名单认证授权成功:vkey [%s] ip [%s] password [%s]", host.Client.VerifyKey, ip, pass) + jsonBytes, err = json.Marshal(map[string]interface{}{"success": true, "message": "授权成功"}) + } else { + logs.Error("客户端IP白名单认证授权密码错误:vkey [%s] ip [%s] password [%s]", host.Client.VerifyKey, ip, pass) + jsonBytes, err = json.Marshal(map[string]interface{}{"success": false, "message": "密码错误"}) + } + } else { + logs.Error("客户端IP白名单认证授权密码错误:vkey [%s] ip [%s]", host.Client.VerifyKey, ip) + jsonBytes, err = json.Marshal(map[string]interface{}{"success": false, "message": "参数错误"}) + } + s.errorContent, err = jsonBytes, err + s.errorCode = 200 + return + } + errorContent, _ := common.ReadAllFromFile(filepath.Join(common.GetRunPath(), "web", "static", "page", "auth.html")) authHtml := string(errorContent) authHtml = strings.ReplaceAll(authHtml, "${ip}", common.GetIpByAddr(c.RemoteAddr().String())) - authHtml = strings.ReplaceAll(authHtml, "${vkey}", host.Client.VerifyKey) - authHtml = strings.ReplaceAll(authHtml, "${port}", beego.AppConfig.String("web_port")) s.errorContent, err = []byte(authHtml), err s.errorCode = 401 return diff --git a/server/proxy/https.go b/server/proxy/https.go index 79af848..054e89a 100644 --- a/server/proxy/https.go +++ b/server/proxy/https.go @@ -159,14 +159,14 @@ func (https *HttpsServer) cert(host *file.Host, c net.Conn, rb []byte, certFileU } https.httpsListenerMap.Delete(value) https.hostIdCertMap.Delete(key) - logs.Info("Listener 已释放") + logs.Debug("Listener 已释放") } } } return true }) - logs.Info("当前 Listener 连接数量", i) + logs.Debug("当前 Listener 连接数量", i) if cert, ok := https.hostIdCertMap.Load(host.Id); ok { if cert == certFileUrl { diff --git a/web/controllers/auth.go b/web/controllers/auth.go index 21282fc..d24ed08 100644 --- a/web/controllers/auth.go +++ b/web/controllers/auth.go @@ -1,11 +1,13 @@ package controllers import ( - "ehang.io/nps/lib/file" "encoding/hex" + "github.com/astaxie/beego/logs" "html" "time" + "ehang.io/nps/lib/file" + "ehang.io/nps/lib/crypt" "github.com/astaxie/beego" ) @@ -52,22 +54,30 @@ func (s *AuthController) IpWhiteAuth() { ip := s.getEscapeString("ip") password := s.getEscapeString("pass") - if vkey == "" || ip == "" || password == "" { + if vkey == "" || password == "" { s.Data["json"] = map[string]interface{}{"success": false, "message": "参数错误"} s.ServeJSON() return } + // 如果未提供 ip,则使用请求中的客户端 IP(支持代理头) + if ip == "" { + ip = s.Ctx.Input.IP() + ip = html.EscapeString(ip) + } + c, err := file.GetDb().GetClientByVkey(vkey) if err != nil { s.Data["json"] = map[string]interface{}{"success": false, "message": "客户端密钥错误"} s.ServeJSON() + logs.Error("客户端IP白名单认证失败,客户端密钥错误:vkey [%s] ip [%s] password [%s]", vkey, ip, password) return } if c.IpWhitePass != password { s.Data["json"] = map[string]interface{}{"success": false, "message": "授权密码错误"} s.ServeJSON() + logs.Error("客户端IP白名单认证失败,授权密码错误:vkey [%s] ip [%s] password [%s]", vkey, ip, password) return } @@ -86,6 +96,9 @@ func (s *AuthController) IpWhiteAuth() { s.Data["json"] = map[string]interface{}{"success": true, "message": "授权成功"} s.ServeJSON() + + logs.Info("客户端IP白名单认证授权成功:vkey [%s] ip [%s] password [%s]", vkey, ip, password) + } func (s *AuthController) getEscapeString(key string) string { diff --git a/web/controllers/base.go b/web/controllers/base.go index 244838a..b2eef43 100755 --- a/web/controllers/base.go +++ b/web/controllers/base.go @@ -1,13 +1,14 @@ package controllers import ( - "ehang.io/nps/bridge" "html" "math" "strconv" "strings" "time" + "ehang.io/nps/bridge" + "ehang.io/nps/lib/common" "ehang.io/nps/lib/crypt" "ehang.io/nps/lib/file" @@ -21,7 +22,7 @@ type BaseController struct { actionName string } -//初始化参数 +// 初始化参数 func (s *BaseController) Prepare() { s.Data["web_base_url"] = beego.AppConfig.String("web_base_url") controllerName, actionName := s.GetControllerAndAction() @@ -66,7 +67,7 @@ func (s *BaseController) Prepare() { s.Data["allow_user_change_username"], _ = beego.AppConfig.Bool("allow_user_change_username") } -//加载模板 +// 加载模板 func (s *BaseController) display(tpl ...string) { s.Data["web_base_url"] = beego.AppConfig.String("web_base_url") var tplname string @@ -80,6 +81,16 @@ func (s *BaseController) display(tpl ...string) { } ip := s.Ctx.Request.Host s.Data["ip"] = common.GetIpByAddr(ip) + + global := file.GetDb().GetGlobal() + if global.ServerUrl != "" && global.ServerUrl != ip { + // 替换掉 http:// 或者 https:// + ip = global.ServerUrl + ip = strings.ReplaceAll(ip, "http://", "") + ip = strings.ReplaceAll(ip, "https://", "") + s.Data["ip"] = ip + } + s.Data["bridgeType"] = beego.AppConfig.String("bridge_type") if common.IsWindows() { s.Data["win"] = ".exe" @@ -100,19 +111,19 @@ func (s *BaseController) display(tpl ...string) { s.TplName = tplname } -//错误 +// 错误 func (s *BaseController) error() { s.Data["web_base_url"] = beego.AppConfig.String("web_base_url") s.Layout = "public/layout.html" s.TplName = "public/error.html" } -//getEscapeString +// getEscapeString func (s *BaseController) getEscapeString(key string) string { return html.EscapeString(s.GetString(key)) } -//去掉没有err返回值的int +// 去掉没有err返回值的int func (s *BaseController) GetIntNoErr(key string, def ...int) int { strv := s.Ctx.Input.Query(key) if len(strv) == 0 && len(def) > 0 { @@ -122,7 +133,7 @@ func (s *BaseController) GetIntNoErr(key string, def ...int) int { return val } -//获取去掉错误的bool值 +// 获取去掉错误的bool值 func (s *BaseController) GetBoolNoErr(key string, def ...bool) bool { strv := s.Ctx.Input.Query(key) if len(strv) == 0 && len(def) > 0 { @@ -132,28 +143,28 @@ func (s *BaseController) GetBoolNoErr(key string, def ...bool) bool { return val } -//ajax正确返回 +// ajax正确返回 func (s *BaseController) AjaxOk(str string) { s.Data["json"] = ajax(str, 1) s.ServeJSON() s.StopRun() } -//ajax正确返回 +// ajax正确返回 func (s *BaseController) AjaxOkWithId(str string, id int) { s.Data["json"] = ajaxWithId(str, 1, id) s.ServeJSON() s.StopRun() } -//ajax错误返回 +// ajax错误返回 func (s *BaseController) AjaxErr(str string) { s.Data["json"] = ajax(str, 0) s.ServeJSON() s.StopRun() } -//组装ajax +// 组装ajax func ajax(str string, status int) map[string]interface{} { json := make(map[string]interface{}) json["status"] = status @@ -161,7 +172,7 @@ func ajax(str string, status int) map[string]interface{} { return json } -//组装ajax +// 组装ajax func ajaxWithId(str string, status int, id int) map[string]interface{} { json := make(map[string]interface{}) json["status"] = status @@ -170,7 +181,7 @@ func ajaxWithId(str string, status int, id int) map[string]interface{} { return json } -//ajax table返回 +// ajax table返回 func (s *BaseController) AjaxTable(list interface{}, cnt int, recordsTotal int, kwargs map[string]interface{}) { json := make(map[string]interface{}) json["rows"] = list @@ -187,7 +198,7 @@ func (s *BaseController) AjaxTable(list interface{}, cnt int, recordsTotal int, s.StopRun() } -//ajax table参数 +// ajax table参数 func (s *BaseController) GetAjaxParams() (start, limit int) { return s.GetIntNoErr("offset"), s.GetIntNoErr("limit") } diff --git a/web/controllers/global.go b/web/controllers/global.go index 760ad81..dc431cf 100644 --- a/web/controllers/global.go +++ b/web/controllers/global.go @@ -23,21 +23,20 @@ func (s *GlobalController) Index() { return } s.Data["globalBlackIpList"] = strings.Join(global.BlackIpList, "\r\n") + s.Data["serverUrl"] = global.ServerUrl } -//添加全局黑名单IP +// 添加全局参数 func (s *GlobalController) Save() { - //global, err := file.GetDb().GetGlobal() - //if err != nil { - // return - //} if s.Ctx.Request.Method == "GET" { s.Data["menu"] = "global" s.SetInfo("save global") s.display() } else { - t := &file.Glob{BlackIpList: RemoveRepeatedElement(strings.Split(s.getEscapeString("globalBlackIpList"), "\r\n"))} + t := &file.Glob{ + BlackIpList: RemoveRepeatedElement(strings.Split(s.getEscapeString("globalBlackIpList"), "\r\n")), + ServerUrl: s.getEscapeString("serverUrl")} if err := file.GetDb().SaveGlobal(t); err != nil { s.AjaxErr(err.Error()) diff --git a/web/static/js/language.js b/web/static/js/language.js index 595bc73..cf432ee 100644 --- a/web/static/js/language.js +++ b/web/static/js/language.js @@ -59,7 +59,7 @@ $.fn.cloudLang = function () { $.ajax({ type: 'GET', - url: window.nps.web_base_url + '/static/page/languages.xml?v=20250107', + url: window.nps.web_base_url + '/static/page/languages.xml?v=202512051', dataType: 'xml', success: function (xml) { languages['content'] = xml2json($(xml).children())['content']; diff --git a/web/static/page/auth.html b/web/static/page/auth.html index 1964293..2a2b850 100644 --- a/web/static/page/auth.html +++ b/web/static/page/auth.html @@ -176,20 +176,19 @@ text-align: center; color: red; } - - +

访问验证

当前 IP (${ip}) 未经授权, 已禁止访问
- +
@@ -199,15 +198,11 @@ diff --git a/web/static/page/languages.xml b/web/static/page/languages.xml index 3bd47bb..1f5444f 100644 --- a/web/static/page/languages.xml +++ b/web/static/page/languages.xml @@ -756,6 +756,16 @@ Global IP Black List + + 服务地址 + Server + + + + 客户端命令地址显示、隧道访问显示、白名单IP认证地址 + Server URL, Tunnel Access, White IP Authentication URL + + 例如 10.1.50.203 10.1.50.202 such as 10.1.50.203 10.1.50.202 diff --git a/web/views/global/index.html b/web/views/global/index.html index 7489e8f..c44f890 100644 --- a/web/views/global/index.html +++ b/web/views/global/index.html @@ -18,6 +18,14 @@
+
+ +
+ +
+
+