From c62a3424bc1b5eee56046cd28d15d3ab1caefa42 Mon Sep 17 00:00:00 2001 From: yisier <1340976576@qq.com> Date: Sun, 12 Jul 2026 21:31:06 -0600 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8DHTTP=E6=AD=A3=E5=90=91?= =?UTF-8?q?=E4=BB=A3=E7=90=86=E5=92=8CSOCKS5=E8=AE=A4=E8=AF=81=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/changelog/index.md | 2 + lib/common/const.go | 7 ++ server/proxy/base.go | 15 ++- server/proxy/socks5.go | 98 ++++++++++++------- server/proxy/tcp.go | 18 ++-- server/proxy/tcp_test.go | 205 +++++++++++++++++++++++++++++++++++++++ 6 files changed, 299 insertions(+), 46 deletions(-) diff --git a/docs/changelog/index.md b/docs/changelog/index.md index 0ca2f7b..6a1a9ef 100644 --- a/docs/changelog/index.md +++ b/docs/changelog/index.md @@ -9,6 +9,8 @@ - `nps -server` 安装成功后 `web_port` 未正常显示BUG [#317](https://github.com/yisier/nps/issues/317) - Bridge 握手增加 10s 读超时,校验失败/读失败立即关闭连接,减轻端口扫描导致的连接与 goroutine 堆积 [#281](https://github.com/yisier/nps/issues/281) - 解决私密代理和P2P连接的TLS启用问题 [#143](https://github.com/yisier/nps/issues/143) + - HTTP 正向代理 Basic 认证 BUG[#133](https://github.com/yisier/nps/issues/133) + - SOCKS5 用户名密码认证 BUG [#133](https://github.com/yisier/nps/issues/133) - 2026-07-04 v0.26.35 - 新增: diff --git a/lib/common/const.go b/lib/common/const.go index f545d34..c532e77 100644 --- a/lib/common/const.go +++ b/lib/common/const.go @@ -35,6 +35,13 @@ Content-Type: text/plain; charset=utf-8 WWW-Authenticate: Basic realm="easyProxy" 401 Unauthorized` + // ProxyAuthRequiredBytes is the challenge for HTTP forward proxy Basic auth (RFC 7235). + // Clients expect 407 + Proxy-Authenticate, not 401 + WWW-Authenticate. + ProxyAuthRequiredBytes = "HTTP/1.1 407 Proxy Authentication Required\r\n" + + "Content-Type: text/plain; charset=utf-8\r\n" + + "Proxy-Authenticate: Basic realm=\"nps\"\r\n" + + "\r\n" + + "407 Proxy Authentication Required" ConnectionFailBytes = `HTTP/1.1 404 Not Found ` diff --git a/server/proxy/base.go b/server/proxy/base.go index 323e584..c328dba 100644 --- a/server/proxy/base.go +++ b/server/proxy/base.go @@ -64,12 +64,21 @@ func (s *BaseServer) writeConnFail(c net.Conn) { c.Write(s.errorContent) } -// auth check +// auth check for reverse-proxy hosts (401 + WWW-Authenticate). func (s *BaseServer) auth(r *http.Request, c *conn.Conn, u, p string) error { + return s.doAuth(r, c, u, p, common.UnauthorizedBytes, "401 Unauthorized") +} + +// proxyAuth check for HTTP forward proxy (407 + Proxy-Authenticate). +func (s *BaseServer) proxyAuth(r *http.Request, c *conn.Conn, u, p string) error { + return s.doAuth(r, c, u, p, common.ProxyAuthRequiredBytes, "407 Proxy Authentication Required") +} + +func (s *BaseServer) doAuth(r *http.Request, c *conn.Conn, u, p, failBytes, errMsg string) error { if u != "" && p != "" && !common.CheckAuth(r, u, p) { - c.Write([]byte(common.UnauthorizedBytes)) + c.Write([]byte(failBytes)) c.Close() - return errors.New("401 Unauthorized") + return errors.New(errMsg) } return nil } diff --git a/server/proxy/socks5.go b/server/proxy/socks5.go index 4dfb16d..d59986e 100755 --- a/server/proxy/socks5.go +++ b/server/proxy/socks5.go @@ -348,33 +348,62 @@ func (s *Sock5ModeServer) handleConn(c net.Conn) { c.Close() return } - nMethods := buf[1] + nMethods := int(buf[1]) + if nMethods == 0 { + logs.Warn("socks5 client offered no auth methods, remote %s", c.RemoteAddr()) + c.Close() + return + } methods := make([]byte, nMethods) - if len, err := c.Read(methods); len != int(nMethods) || err != nil { + if _, err := io.ReadFull(c, methods); err != nil { logs.Warn("wrong method") c.Close() return } - if (s.task.Client.Cnf.U != "" && s.task.Client.Cnf.P != "") || (s.task.MultiAccount != nil && len(s.task.MultiAccount.AccountMap) > 0) { - buf[1] = UserPassAuth - c.Write(buf) + + needAuth := (s.task.Client.Cnf.U != "" && s.task.Client.Cnf.P != "") || + (s.task.MultiAccount != nil && len(s.task.MultiAccount.AccountMap) > 0) + + if needAuth { + if !methodOffered(methods, UserPassAuth) { + // Client cannot authenticate; reply no acceptable methods (RFC 1928). + _, _ = c.Write([]byte{5, 0xFF}) + c.Close() + logs.Warn("socks5 client %s does not support username/password auth", c.RemoteAddr()) + return + } + if _, err := c.Write([]byte{5, UserPassAuth}); err != nil { + c.Close() + return + } if err := s.Auth(c); err != nil { c.Close() - logs.Warn("Validation failed:", err) + logs.Warn("Validation failed: %v, remote %s", err, c.RemoteAddr()) return } } else { - buf[1] = 0 - c.Write(buf) + if _, err := c.Write([]byte{5, 0}); err != nil { + c.Close() + return + } } s.handleRequest(c) } -// socks5 auth +func methodOffered(methods []byte, method byte) bool { + for _, m := range methods { + if m == method { + return true + } + } + return false +} + +// socks5 auth (RFC 1929 username/password) func (s *Sock5ModeServer) Auth(c net.Conn) error { - header := []byte{0, 0} - if _, err := io.ReadAtLeast(c, header, 2); err != nil { + header := make([]byte, 2) + if _, err := io.ReadFull(c, header); err != nil { return err } if header[0] != userAuthVersion { @@ -382,46 +411,43 @@ func (s *Sock5ModeServer) Auth(c net.Conn) error { } userLen := int(header[1]) user := make([]byte, userLen) - if _, err := io.ReadAtLeast(c, user, userLen); err != nil { - return err + if userLen > 0 { + if _, err := io.ReadFull(c, user); err != nil { + return err + } } - if _, err := c.Read(header[:1]); err != nil { + plen := make([]byte, 1) + if _, err := io.ReadFull(c, plen); err != nil { return errors.New("密码长度获取错误") } - passLen := int(header[0]) + passLen := int(plen[0]) pass := make([]byte, passLen) - if _, err := io.ReadAtLeast(c, pass, passLen); err != nil { - return err + if passLen > 0 { + if _, err := io.ReadFull(c, pass); err != nil { + return err + } } - var U, P string - if s.task.MultiAccount != nil { - // enable multi user auth - U = string(user) - if len(U) == 0 { - return errors.New("验证不通过") - } - var ok bool - P, ok = s.task.MultiAccount.AccountMap[U] - if !ok { - return errors.New("验证不通过") + ok := false + if s.task.MultiAccount != nil && len(s.task.MultiAccount.AccountMap) > 0 { + // multi-user auth + if expected, found := s.task.MultiAccount.AccountMap[string(user)]; found && string(pass) == expected { + ok = true } } else { - U = s.task.Client.Cnf.U - P = s.task.Client.Cnf.P + ok = string(user) == s.task.Client.Cnf.U && string(pass) == s.task.Client.Cnf.P } - if string(user) == U && string(pass) == P { + if ok { if _, err := c.Write([]byte{userAuthVersion, authSuccess}); err != nil { return err } return nil - } else { - if _, err := c.Write([]byte{userAuthVersion, authFailure}); err != nil { - return err - } - return errors.New("验证不通过") } + if _, err := c.Write([]byte{userAuthVersion, authFailure}); err != nil { + return err + } + return errors.New("验证不通过") } // start diff --git a/server/proxy/tcp.go b/server/proxy/tcp.go index d947479..5a6c39a 100755 --- a/server/proxy/tcp.go +++ b/server/proxy/tcp.go @@ -111,20 +111,24 @@ func ProcessTunnel(c *conn.Conn, s *TunnelModeServer) error { // http proxy func ProcessHttp(c *conn.Conn, s *TunnelModeServer) error { - _, addr, rb, err, r := c.GetHost() if err != nil { c.Close() logs.Info(err) return err } - if r.Method == "CONNECT" { - c.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n")) - rb = nil - } - if err := s.auth(r, c, s.task.Client.Cnf.U, s.task.Client.Cnf.P); err != nil { + // Authenticate before establishing CONNECT tunnel (fixes auth-after-200 bug). + if err := s.proxyAuth(r, c, s.task.Client.Cnf.U, s.task.Client.Cnf.P); err != nil { + logs.Warn("http proxy auth failed, client %d, remote %s: %v", s.task.Client.Id, c.Conn.RemoteAddr(), err) return err } + if r.Method == "CONNECT" { + if _, err := c.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n")); err != nil { + c.Close() + return err + } + rb = nil + } + logs.Info("http proxy request, method %s, host %s, client %d, remote %s", r.Method, addr, s.task.Client.Id, c.Conn.RemoteAddr()) return s.DealClient(c, s.task.Client, addr, rb, common.CONN_TCP, nil, s.task.Client.Flow, s.task.Target.LocalProxy, nil, nil) - } diff --git a/server/proxy/tcp_test.go b/server/proxy/tcp_test.go index bc7f44c..6a5c185 100644 --- a/server/proxy/tcp_test.go +++ b/server/proxy/tcp_test.go @@ -1,11 +1,15 @@ package proxy import ( + "bufio" "bytes" + "encoding/base64" "io" "net" + "net/http" "os" "path/filepath" + "strings" "testing" "time" @@ -92,3 +96,204 @@ func TestProcessTunnelForwardsBufferedBytesWhenAuthProbeFails(t *testing.T) { t.Fatal("ProcessTunnel did not exit after connections closed") } } + +func setupProxyTestConf(t *testing.T) { + t.Helper() + confPath := t.TempDir() + confDir := filepath.Join(confPath, "conf") + if err := os.MkdirAll(confDir, 0755); err != nil { + t.Fatal(err) + } + for _, name := range []string{"clients.json", "tasks.json", "hosts.json"} { + if err := os.WriteFile(filepath.Join(confDir, name), nil, 0644); err != nil { + t.Fatal(err) + } + } + oldConfPath := common.ConfPath + common.ConfPath = confPath + t.Cleanup(func() { + common.ConfPath = oldConfPath + }) +} + +func newHTTPProxyServer(t *testing.T, u, p string, target net.Conn) *TunnelModeServer { + t.Helper() + client := file.NewClient("test", true, true) + client.Id = 1 + client.Cnf.U = u + client.Cnf.P = p + task := &file.Tunnel{ + Id: 1, + Client: client, + Mode: "httpProxy", + Target: &file.Target{TargetStr: "127.0.0.1:80"}, + } + return NewTunnelModeServer(ProcessHttp, &tunnelTestBridge{target: target}, task) +} + +func TestProcessHttpConnectAuthBeforeTunnel(t *testing.T) { + setupProxyTestConf(t) + + clientConn, serverConn := net.Pipe() + defer clientConn.Close() + defer serverConn.Close() + + // target unused: auth must fail before DealClient + targetClient, targetServer := net.Pipe() + defer targetClient.Close() + defer targetServer.Close() + + server := newHTTPProxyServer(t, "user", "pass", targetServer) + + done := make(chan error, 1) + go func() { + done <- ProcessHttp(conn.NewConn(serverConn), server) + }() + + // CONNECT without credentials + req := "CONNECT example.com:443 HTTP/1.1\r\nHost: example.com:443\r\n\r\n" + if _, err := clientConn.Write([]byte(req)); err != nil { + t.Fatal(err) + } + + _ = clientConn.SetReadDeadline(time.Now().Add(time.Second)) + br := bufio.NewReader(clientConn) + resp, err := http.ReadResponse(br, nil) + if err != nil { + t.Fatalf("read response: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusProxyAuthRequired { + t.Fatalf("expected 407 before CONNECT tunnel, got %d", resp.StatusCode) + } + if got := resp.Header.Get("Proxy-Authenticate"); !strings.Contains(got, "Basic") { + t.Fatalf("expected Proxy-Authenticate Basic challenge, got %q", got) + } + + select { + case err := <-done: + if err == nil { + t.Fatal("expected auth error") + } + case <-time.After(time.Second): + t.Fatal("ProcessHttp did not exit after auth failure") + } +} + +func TestProcessHttpConnectWithProxyAuth(t *testing.T) { + setupProxyTestConf(t) + + clientConn, serverConn := net.Pipe() + defer clientConn.Close() + defer serverConn.Close() + + targetClient, targetServer := net.Pipe() + defer targetClient.Close() + defer targetServer.Close() + + server := newHTTPProxyServer(t, "user", "pass", targetServer) + + done := make(chan error, 1) + go func() { + done <- ProcessHttp(conn.NewConn(serverConn), server) + }() + + token := base64.StdEncoding.EncodeToString([]byte("user:pass")) + req := "CONNECT example.com:443 HTTP/1.1\r\n" + + "Host: example.com:443\r\n" + + "Proxy-Authorization: Basic " + token + "\r\n\r\n" + if _, err := clientConn.Write([]byte(req)); err != nil { + t.Fatal(err) + } + + _ = clientConn.SetReadDeadline(time.Now().Add(time.Second)) + br := bufio.NewReader(clientConn) + // First line of CONNECT success is not always a full http.Response parse-friendly body; + // read status line. + statusLine, err := br.ReadString('\n') + if err != nil { + t.Fatalf("read status: %v", err) + } + if !strings.Contains(statusLine, "200") { + t.Fatalf("expected 200 Connection established after auth, got %q", statusLine) + } + // consume remaining headers + for { + line, err := br.ReadString('\n') + if err != nil { + t.Fatal(err) + } + if line == "\r\n" || line == "\n" { + break + } + } + + // After tunnel is up, write application data and ensure it reaches target. + payload := []byte("hello-tls") + if _, err := clientConn.Write(payload); err != nil { + t.Fatal(err) + } + _ = targetClient.SetReadDeadline(time.Now().Add(time.Second)) + got := make([]byte, len(payload)) + if _, err := io.ReadFull(targetClient, got); err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, payload) { + t.Fatalf("expected %q, got %q", payload, got) + } + + clientConn.Close() + targetClient.Close() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("ProcessHttp did not exit") + } +} + +func TestProcessHttpPlainGetWithProxyAuth(t *testing.T) { + setupProxyTestConf(t) + + clientConn, serverConn := net.Pipe() + defer clientConn.Close() + defer serverConn.Close() + + targetClient, targetServer := net.Pipe() + defer targetClient.Close() + defer targetServer.Close() + + server := newHTTPProxyServer(t, "user", "pass", targetServer) + + done := make(chan error, 1) + go func() { + done <- ProcessHttp(conn.NewConn(serverConn), server) + }() + + token := base64.StdEncoding.EncodeToString([]byte("user:pass")) + req := "GET http://example.com/ HTTP/1.1\r\n" + + "Host: example.com\r\n" + + "Proxy-Authorization: Basic " + token + "\r\n\r\n" + if _, err := clientConn.Write([]byte(req)); err != nil { + t.Fatal(err) + } + + // Absolute-form request is forwarded (buffered) to the tunnel target. + _ = targetClient.SetReadDeadline(time.Now().Add(time.Second)) + buf := make([]byte, 512) + n, err := targetClient.Read(buf) + if err != nil { + t.Fatal(err) + } + if !bytes.Contains(buf[:n], []byte("GET ")) { + t.Fatalf("expected forwarded GET, got %q", buf[:n]) + } + + clientConn.Close() + targetClient.Close() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("ProcessHttp did not exit") + } +}