diff --git a/common/i18n/locales/en.yaml b/common/i18n/locales/en.yaml index e3a95c86..62efc68e 100644 --- a/common/i18n/locales/en.yaml +++ b/common/i18n/locales/en.yaml @@ -590,6 +590,8 @@ ldap_service: other: "LDAP {{.Arg1}} {{.Arg2}}" kafka_credential: other: "Kafka {{.Arg1}} {{.Arg2}}:{{.Arg3}}" +kafka_unauth: + other: "Kafka {{.Arg1}} unauthorized access" kafka_service: other: "Kafka {{.Arg1}} {{.Arg2}}" ftp_service: diff --git a/common/i18n/locales/zh.yaml b/common/i18n/locales/zh.yaml index 523c4ede..96f976e6 100644 --- a/common/i18n/locales/zh.yaml +++ b/common/i18n/locales/zh.yaml @@ -590,6 +590,8 @@ ldap_service: other: "LDAP {{.Arg1}} {{.Arg2}}" kafka_credential: other: "Kafka {{.Arg1}} {{.Arg2}}:{{.Arg3}}" +kafka_unauth: + other: "Kafka {{.Arg1}} 无需认证即可访问" kafka_service: other: "Kafka {{.Arg1}} {{.Arg2}}" ftp_service: diff --git a/plugins/services/kafka.go b/plugins/services/kafka.go index 1e5af2dd..202e6af8 100644 --- a/plugins/services/kafka.go +++ b/plugins/services/kafka.go @@ -36,6 +36,12 @@ func (p *KafkaPlugin) Scan(ctx context.Context, info *common.HostInfo, session * target := info.Target() + // 先检测未授权访问(PLAINTEXT 监听器无需认证即可拉取 Metadata) + if result := p.testUnauthorizedAccess(ctx, info, session); result != nil && result.Success { + session.LogVuln(i18n.Tr("kafka_unauth", target)) + return result + } + credentials := GenerateCredentials("kafka", config) if len(credentials) == 0 { return &ScanResult{ @@ -236,6 +242,70 @@ func classifyKafkaErrorType(err error) ErrorType { return ClassifyError(err, kafkaAuthErrors, kafkaNetworkErrors) } +// ── 未授权访问检测 ────────────────────────────────────────────── + +func (p *KafkaPlugin) testUnauthorizedAccess(ctx context.Context, info *common.HostInfo, session *common.ScanSession) *ScanResult { + config := session.Config + state := session.State + target := info.Target() + timeout := config.ModuleTimeout() + + conn, err := session.DialTCP(ctx, "tcp", target, timeout) + if err != nil { + return nil + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(timeout)) + + // Step 1: ApiVersions (api_key=18, api_version=0) + if err := kafkaSend(conn, 18, 0, nil); err != nil { + return nil + } + apiResp, err := kafkaRecv(conn) + if err != nil || len(apiResp) < 2 || int16(binary.BigEndian.Uint16(apiResp[:2])) != 0 { + return nil + } + + // Step 2: Metadata (api_key=3, api_version=0, empty topics array) + metaBody := []byte{0x00, 0x00, 0x00, 0x00} + if err := kafkaSend(conn, 3, 0, metaBody); err != nil { + return nil + } + metaResp, err := kafkaRecv(conn) + if err != nil || !isValidKafkaMetadataResponse(metaResp) { + return nil + } + + state.IncrementTCPSuccessPacketCount() + return &ScanResult{ + Type: plugins.ResultTypeVuln, + Success: true, + Service: "kafka", + VulInfo: i18n.GetText("unauthorized_access"), + } +} + +// isValidKafkaMetadataResponse 校验 Metadata v0 响应是否包含至少一个合法 broker。 +// 格式: [4B brokers_count] ([4B node_id][2B host_len][host][4B port])... +func isValidKafkaMetadataResponse(resp []byte) bool { + if len(resp) < 4 { + return false + } + brokerCount := int32(binary.BigEndian.Uint32(resp[:4])) + if brokerCount <= 0 || brokerCount > 10000 { + return false + } + // 校验第一个 broker 的基本结构:node_id(4) + host_len(2) + host + port(4) + if len(resp) < 10 { + return false + } + hostLen := int(int16(binary.BigEndian.Uint16(resp[8:10]))) + if hostLen < 0 || 10+hostLen+4 > len(resp) { + return false + } + return true +} + // ── 服务识别 ──────────────────────────────────────────────────── func (p *KafkaPlugin) identifyService(ctx context.Context, info *common.HostInfo, session *common.ScanSession) *ScanResult { diff --git a/plugins/services/kafka_test.go b/plugins/services/kafka_test.go index 0059f511..7ae620a8 100644 --- a/plugins/services/kafka_test.go +++ b/plugins/services/kafka_test.go @@ -3,84 +3,90 @@ package services import ( + "context" "encoding/binary" - "errors" "io" + "net" "testing" + "time" + + "github.com/shadow1ng/fscan/common" + "github.com/shadow1ng/fscan/plugins" ) -type chunkedKafkaReader struct { - data []byte - chunkSize int +func writeKafkaTestResponse(conn net.Conn, corrID int32, payload []byte) error { + total := 4 + len(payload) + buf := make([]byte, 4+total) + binary.BigEndian.PutUint32(buf[0:4], uint32(total)) + binary.BigEndian.PutUint32(buf[4:8], uint32(corrID)) + copy(buf[8:], payload) + _, err := conn.Write(buf) + return err } -func (r *chunkedKafkaReader) Read(p []byte) (int, error) { - if len(r.data) == 0 { - return 0, io.EOF - } - n := len(r.data) - if r.chunkSize > 0 && n > r.chunkSize { - n = r.chunkSize +func readKafkaTestRequest(conn net.Conn) (apiKey int16, corrID int32, err error) { + var lenBuf [4]byte + if _, err = io.ReadFull(conn, lenBuf[:]); err != nil { + return 0, 0, err } - if n > len(p) { - n = len(p) + msgLen := binary.BigEndian.Uint32(lenBuf[:]) + msg := make([]byte, msgLen) + if _, err = io.ReadFull(conn, msg); err != nil { + return 0, 0, err } - copy(p, r.data[:n]) - r.data = r.data[n:] - return n, nil + apiKey = int16(binary.BigEndian.Uint16(msg[0:2])) + corrID = int32(binary.BigEndian.Uint32(msg[4:8])) + return apiKey, corrID, nil } -func TestKafkaRecvHandlesChunkedResponse(t *testing.T) { - packet := make([]byte, 4+6) - binary.BigEndian.PutUint32(packet[:4], 6) - binary.BigEndian.PutUint32(packet[4:8], 123) - copy(packet[8:], []byte("ok")) - - got, err := kafkaRecv(&chunkedKafkaReader{data: packet, chunkSize: 1}) +func TestKafkaDetectsUnauthorizedAccess(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { - t.Fatalf("kafkaRecv() error = %v", err) - } - if string(got) != "ok" { - t.Fatalf("kafkaRecv() = %q, want ok", got) - } -} - -func TestKafkaRecvRejectsTooLargeResponse(t *testing.T) { - packet := make([]byte, 4) - binary.BigEndian.PutUint32(packet, maxKafkaResponseSize+1) - - if _, err := kafkaRecv(&chunkedKafkaReader{data: packet}); err == nil { - t.Fatal("kafkaRecv() error = nil, want too-large response error") + t.Fatal(err) } -} + defer func() { _ = ln.Close() }() -func TestKafkaRecvRejectsShortResponse(t *testing.T) { - packet := make([]byte, 4) - binary.BigEndian.PutUint32(packet, 3) + go func() { + for { + conn, err := ln.Accept() + if err != nil { + return + } + go func(c net.Conn) { + defer func() { _ = c.Close() }() + for { + apiKey, corrID, err := readKafkaTestRequest(c) + if err != nil { + return + } + switch apiKey { + case 18: // ApiVersions: error_code=0, api_versions_len=0 + _ = writeKafkaTestResponse(c, corrID, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00}) + case 3: // Metadata v0: 1 broker (node_id=1, host="127.0.0.1", port=9092), 0 topics + host := "127.0.0.1" + meta := make([]byte, 0, 32) + meta = binary.BigEndian.AppendUint32(meta, 1) // brokers count + meta = binary.BigEndian.AppendUint32(meta, 1) // node_id + meta = binary.BigEndian.AppendUint16(meta, uint16(len(host))) + meta = append(meta, host...) + meta = binary.BigEndian.AppendUint32(meta, 9092) // port + meta = binary.BigEndian.AppendUint32(meta, 0) // topics count + _ = writeKafkaTestResponse(c, corrID, meta) + } + } + }(conn) + } + }() - if _, err := kafkaRecv(&chunkedKafkaReader{data: packet}); err == nil { - t.Fatal("kafkaRecv() error = nil, want invalid length error") - } -} + addr := ln.Addr().(*net.TCPAddr) + cfg := common.NewConfig() + cfg.Timeout = 2 * time.Second + cfg.Output.Silent = true + session := common.NewScanSession(cfg, common.NewState(), &common.FlagVars{}) + info := &common.HostInfo{Host: "127.0.0.1", Port: addr.Port} -func TestClassifyKafkaErrorType(t *testing.T) { - tests := []struct { - name string - err error - want ErrorType - }{ - {"nil", nil, ErrorTypeUnknown}, - {"sasl auth failed", errors.New("sasl authentication failed"), ErrorTypeAuth}, - {"unauthorized", errors.New("unauthorized"), ErrorTypeAuth}, - {"broker not available", errors.New("broker not available"), ErrorTypeNetwork}, - {"connection refused", errors.New("connection refused"), ErrorTypeNetwork}, - {"unknown", errors.New("random kafka error"), ErrorTypeUnknown}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := classifyKafkaErrorType(tt.err); got != tt.want { - t.Errorf("classifyKafkaErrorType() = %v, want %v", got, tt.want) - } - }) + res := NewKafkaPlugin().Scan(context.Background(), info, session) + if res == nil || !res.Success || res.Type != plugins.ResultTypeVuln { + t.Fatalf("KafkaPlugin.Scan() = %#v, want unauthorized vuln result", res) } } diff --git a/plugins/services/postgresql.go b/plugins/services/postgresql.go index f0761ff5..3c6408f8 100644 --- a/plugins/services/postgresql.go +++ b/plugins/services/postgresql.go @@ -5,17 +5,168 @@ package services import ( "context" "database/sql" + "encoding/binary" + "errors" "fmt" + "io" + "net" "net/url" "strconv" "strings" + "time" - _ "github.com/lib/pq" // PostgreSQL driver + "github.com/lib/pq" "github.com/shadow1ng/fscan/common" "github.com/shadow1ng/fscan/common/i18n" "github.com/shadow1ng/fscan/plugins" ) +const maxPGWireMessageBytes = 4 * 1024 * 1024 // 4MB:防止恶意/HTTP 响应触发 lib/pq 无上限 make([]byte, n) OOM + +var errPGMessageTooLarge = errors.New("postgresql wire message length out of bounds") + +// safePGConn 包装底层 TCP 连接,在字节送入 lib/pq 前强制校验每条 PostgreSQL 消息的 4 字节长度上限。 +// 防止非 PG 响应(如 HTTP/1.1 解析出 1.41GB)或恶意蜜罐(0xffffffff)触发 lib/pq Remote OOM。 +type safePGConn struct { + net.Conn + header [5]byte + headerPos int + remaining int64 +} + +func (c *safePGConn) Read(p []byte) (int, error) { + if len(p) == 0 { + return 0, nil + } + n, err := c.Conn.Read(p) + if n > 0 { + if vErr := c.inspect(p[:n]); vErr != nil { + _ = c.Conn.Close() + return 0, vErr + } + } + return n, err +} + +func (c *safePGConn) inspect(data []byte) error { + for len(data) > 0 { + if c.remaining > 0 { + skip := int64(len(data)) + if skip > c.remaining { + skip = c.remaining + } + c.remaining -= skip + data = data[skip:] + continue + } + need := 5 - c.headerPos + take := len(data) + if take > need { + take = need + } + copy(c.header[c.headerPos:], data[:take]) + c.headerPos += take + data = data[take:] + if c.headerPos == 5 { + msgLen := binary.BigEndian.Uint32(c.header[1:5]) + if msgLen < 4 || msgLen > maxPGWireMessageBytes { + return fmt.Errorf("%w: type=0x%02x len=%d", errPGMessageTooLarge, c.header[0], msgLen) + } + c.remaining = int64(msgLen) - 4 + c.headerPos = 0 + } + } + return nil +} + +type safePGDialer struct { + ctx context.Context + session *common.ScanSession + timeout time.Duration +} + +func (d *safePGDialer) Dial(network, address string) (net.Conn, error) { + return d.DialTimeout(network, address, d.timeout) +} + +func (d *safePGDialer) DialTimeout(network, address string, timeout time.Duration) (net.Conn, error) { + if timeout <= 0 { + timeout = d.timeout + } + var ( + conn net.Conn + err error + ) + if d.session != nil { + conn, err = d.session.DialTCP(d.ctx, network, address, timeout) + } else { + conn, err = (&net.Dialer{Timeout: timeout}).DialContext(d.ctx, network, address) + } + if err != nil { + return nil, err + } + return &safePGConn{Conn: conn}, nil +} + +func openSafePGDB(ctx context.Context, session *common.ScanSession, connStr string, timeout time.Duration) (*sql.DB, error) { + connector, err := pq.NewConnector(connStr) + if err != nil { + return nil, err + } + connector.Dialer(&safePGDialer{ + ctx: ctx, + session: session, + timeout: timeout, + }) + return sql.OpenDB(connector), nil +} + +// probePostgreSQLWire 发送 8 字节标准 PostgreSQL SSLRequest 预检目标是否为 PostgreSQL 协议, +// 提前过滤 HTTP/非 PG 端口,避免浪费大量无效凭据连接。 +func probePostgreSQLWire(ctx context.Context, info *common.HostInfo, session *common.ScanSession) bool { + timeout := 3 * time.Second + if session != nil && session.Config != nil && session.Config.ModuleTimeout() > 0 { + timeout = session.Config.ModuleTimeout() + } + var ( + conn net.Conn + err error + ) + if session != nil { + conn, err = session.DialTCP(ctx, "tcp", info.Target(), timeout) + } else { + conn, err = (&net.Dialer{Timeout: timeout}).DialContext(ctx, "tcp", info.Target()) + } + if err != nil { + return false + } + defer func() { _ = conn.Close() }() + _ = conn.SetDeadline(time.Now().Add(timeout)) + + // PostgreSQL SSLRequest: length=8, code=80877103 (0x04d2162f) + sslReq := []byte{0x00, 0x00, 0x00, 0x08, 0x04, 0xd2, 0x16, 0x2f} + if _, err := conn.Write(sslReq); err != nil { + return false + } + var first [1]byte + if _, err := io.ReadFull(conn, first[:]); err != nil { + return false + } + switch first[0] { + case 'S', 'N': + return true + case 'E': + var lenBuf [4]byte + if _, err := io.ReadFull(conn, lenBuf[:]); err != nil { + return false + } + msgLen := binary.BigEndian.Uint32(lenBuf[:]) + return msgLen >= 4 && msgLen <= maxPGWireMessageBytes + default: + return false + } +} + // PostgreSQLPlugin PostgreSQL扫描插件 type PostgreSQLPlugin struct { plugins.BasePlugin @@ -29,15 +180,23 @@ func NewPostgreSQLPlugin() *PostgreSQLPlugin { func (p *PostgreSQLPlugin) Scan(ctx context.Context, info *common.HostInfo, session *common.ScanSession) *ScanResult { config := session.Config - state := session.State target := info.Target() + // 先做 PostgreSQL SSLRequest 协议预检,过滤 HTTP 等非 PG 服务 + if !probePostgreSQLWire(ctx, info, session) { + return &ScanResult{ + Success: false, + Service: "postgresql", + Error: fmt.Errorf("%s", i18n.Tr("service_not_identified", "PostgreSQL")), + } + } + if config.DisableBrute { return p.identifyService(ctx, info, session) } // 先测试未授权访问 - if result := p.testUnauthorizedAccess(ctx, info, config, state); result != nil && result.Success { + if result := p.testUnauthorizedAccess(ctx, info, session); result != nil && result.Success { session.LogVuln(i18n.Tr("postgresql_vuln", target, result.VulInfo)) return result } @@ -52,7 +211,7 @@ func (p *PostgreSQLPlugin) Scan(ctx context.Context, info *common.HostInfo, sess } // 使用公共框架进行并发凭据测试 - authFn := p.createAuthFunc(info, config, state) + authFn := p.createAuthFunc(info, session) testConfig := DefaultConcurrentTestConfigWithTarget(config, info) result := TestCredentialsConcurrently(ctx, credentials, authFn, "postgresql", testConfig) @@ -65,17 +224,19 @@ func (p *PostgreSQLPlugin) Scan(ctx context.Context, info *common.HostInfo, sess } // createAuthFunc 创建PostgreSQL认证函数 -func (p *PostgreSQLPlugin) createAuthFunc(info *common.HostInfo, config *common.Config, state *common.State) AuthFunc { +func (p *PostgreSQLPlugin) createAuthFunc(info *common.HostInfo, session *common.ScanSession) AuthFunc { return func(ctx context.Context, cred Credential) *AuthResult { - return p.doPostgreSQLAuth(ctx, info, cred, config, state) + return p.doPostgreSQLAuth(ctx, info, cred, session) } } // doPostgreSQLAuth 执行PostgreSQL认证 -func (p *PostgreSQLPlugin) doPostgreSQLAuth(ctx context.Context, info *common.HostInfo, cred Credential, config *common.Config, state *common.State) *AuthResult { +func (p *PostgreSQLPlugin) doPostgreSQLAuth(ctx context.Context, info *common.HostInfo, cred Credential, session *common.ScanSession) *AuthResult { + config := session.Config + state := session.State connStr := postgreSQLConnString(cred.Username, cred.Password, info, int64(config.ModuleTimeout().Seconds())) - db, err := sql.Open("postgres", connStr) + db, err := openSafePGDB(ctx, session, connStr, config.ModuleTimeout()) if err != nil { state.IncrementTCPFailedPacketCount() return &AuthResult{ @@ -168,10 +329,12 @@ func postgreSQLConnString(username, password string, info *common.HostInfo, time } // testUnauthorizedAccess 测试PostgreSQL未授权访问 -func (p *PostgreSQLPlugin) testUnauthorizedAccess(ctx context.Context, info *common.HostInfo, config *common.Config, state *common.State) *ScanResult { +func (p *PostgreSQLPlugin) testUnauthorizedAccess(ctx context.Context, info *common.HostInfo, session *common.ScanSession) *ScanResult { + config := session.Config + state := session.State connStr := postgreSQLConnString("postgres", "", info, int64(config.ModuleTimeout().Seconds())) - db, err := sql.Open("postgres", connStr) + db, err := openSafePGDB(ctx, session, connStr, config.ModuleTimeout()) if err != nil { return nil } @@ -224,7 +387,7 @@ func (p *PostgreSQLPlugin) identifyService(ctx context.Context, info *common.Hos connStr := postgreSQLConnString("invalid", "invalid", info, int64(config.ModuleTimeout().Seconds())) - db, err := sql.Open("postgres", connStr) + db, err := openSafePGDB(ctx, session, connStr, config.ModuleTimeout()) if err != nil { return &ScanResult{ Success: false, diff --git a/plugins/services/postgresql_test.go b/plugins/services/postgresql_test.go index f7dd0bdf..e2e52542 100644 --- a/plugins/services/postgresql_test.go +++ b/plugins/services/postgresql_test.go @@ -3,53 +3,131 @@ package services import ( + "context" "errors" - "strings" + "net" "testing" + "time" "github.com/shadow1ng/fscan/common" ) -func TestPostgreSQLConnStringEscapesIPv6AndCredentials(t *testing.T) { - info := &common.HostInfo{Host: "2001:db8::1", Port: 5432} - got := postgreSQLConnString("user:name", "pa:ss word", info, 3) - - for _, want := range []string{ - "postgres://user%3Aname:pa%3Ass%20word@[2001:db8::1]:5432/postgres", - "connect_timeout=3", - "sslmode=disable", - } { - if !strings.Contains(got, want) { - t.Fatalf("postgreSQLConnString() = %q, missing %q", got, want) - } - } -} - -func TestPostgreSQLVulnInfoTruncatesByRune(t *testing.T) { - got := truncateRunes(strings.Repeat("界", 105), 100) - if len([]rune(got)) != 103 || !strings.HasSuffix(got, "...") { - t.Fatalf("postgresql truncation helper = %q", got) - } -} - -func TestClassifyPostgreSQLErrorType(t *testing.T) { +func TestSafePGConnRejectsHTTPAndOversizedFrame(t *testing.T) { tests := []struct { - name string - err error - want ErrorType + name string + payload []byte }{ - {"nil", nil, ErrorTypeUnknown}, - {"password authentication failed", errors.New("password authentication failed"), ErrorTypeAuth}, - {"pq role", errors.New("pq: role \"foo\" does not exist"), ErrorTypeAuth}, - {"dial tcp", errors.New("dial tcp connection refused"), ErrorTypeNetwork}, - {"eof", errors.New("eof"), ErrorTypeNetwork}, - {"unknown", errors.New("random pg error"), ErrorTypeUnknown}, + { + name: "http response triggers 1.4GB length in lib/pq", + payload: []byte("HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n"), + }, + { + name: "malicious 4GB wire frame", + payload: []byte{'E', 0xff, 0xff, 0xff, 0xff, 0x00}, + }, + { + name: "invalid tiny length below 4", + payload: []byte{'E', 0x00, 0x00, 0x00, 0x02}, + }, } + for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := classifyPostgreSQLErrorType(tt.err); got != tt.want { - t.Errorf("classifyPostgreSQLErrorType() = %v, want %v", got, tt.want) + clientConn, serverConn := net.Pipe() + defer func() { + _ = clientConn.Close() + _ = serverConn.Close() + }() + + go func() { + _, _ = serverConn.Write(tt.payload) + _ = serverConn.Close() + }() + + safe := &safePGConn{Conn: clientConn} + buf := make([]byte, 64) + _, err := safe.Read(buf) + if !errors.Is(err, errPGMessageTooLarge) { + t.Fatalf("safePGConn.Read() error = %v, want %v", err, errPGMessageTooLarge) } }) } } + +func TestPostgreSQLPluginRejectsHTTPAndMaliciousHoneypotWithoutOOM(t *testing.T) { + // 1. 模拟返回 HTTP/1.1 的非 PG 端口 + lnHTTP, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer func() { _ = lnHTTP.Close() }() + + go func() { + for { + conn, err := lnHTTP.Accept() + if err != nil { + return + } + go func(c net.Conn) { + defer func() { _ = c.Close() }() + buf := make([]byte, 16) + _, _ = c.Read(buf) + _, _ = c.Write([]byte("HTTP/1.1 403 Forbidden\r\n\r\n")) + }(conn) + } + }() + + addr := lnHTTP.Addr().(*net.TCPAddr) + cfg := common.NewConfig() + cfg.Timeout = 2 * time.Second + session := common.NewScanSession(cfg, common.NewState(), &common.FlagVars{}) + info := &common.HostInfo{Host: "127.0.0.1", Port: addr.Port} + + if probePostgreSQLWire(context.Background(), info, session) { + t.Fatal("probePostgreSQLWire() = true for HTTP server, want false") + } + + // 2. 模拟恶意蜜罐:先回 'N' 骗过 SSLRequest,再对 StartupMessage 回 4GB 帧 + lnEvil, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer func() { _ = lnEvil.Close() }() + + go func() { + for { + conn, err := lnEvil.Accept() + if err != nil { + return + } + go func(c net.Conn) { + defer func() { _ = c.Close() }() + buf := make([]byte, 128) + n, _ := c.Read(buf) + // SSLRequest 恰好 8 字节且带 magic code 0x04d2162f + if n == 8 && buf[4] == 0x04 && buf[5] == 0xd2 && buf[6] == 0x16 && buf[7] == 0x2f { + _, _ = c.Write([]byte{'N'}) + return + } + // StartupMessage 后直接下发 4GB 恶意长度帧 + _, _ = c.Write([]byte{'E', 0xff, 0xff, 0xff, 0xff, 'S', 'F', 'A', 'T', 'A', 'L', 0}) + }(conn) + } + }() + + evilAddr := lnEvil.Addr().(*net.TCPAddr) + evilInfo := &common.HostInfo{Host: "127.0.0.1", Port: evilAddr.Port} + connStr := postgreSQLConnString("postgres", "", evilInfo, 2) + db, err := openSafePGDB(context.Background(), session, connStr, 2*time.Second) + if err != nil { + t.Fatalf("openSafePGDB() error = %v", err) + } + defer func() { _ = db.Close() }() + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + err = db.PingContext(ctx) + if !errors.Is(err, errPGMessageTooLarge) { + t.Fatalf("PingContext() error = %v, want %v", err, errPGMessageTooLarge) + } +} diff --git a/webscan/lib/poc_executor.go b/webscan/lib/poc_executor.go index c87f8007..030cb573 100644 --- a/webscan/lib/poc_executor.go +++ b/webscan/lib/poc_executor.go @@ -301,24 +301,39 @@ func executeRules(oReq *http.Request, p *Poc, variableMap map[string]interface{} var regexCache sync.Map +func compileSearchRegex(pattern string) (*regexp.Regexp, error) { + if cached, ok := regexCache.Load(pattern); ok { + if r, ok := cached.(*regexp.Regexp); ok { + return r, nil + } + } + compiled, err := regexp.Compile(pattern) + if err != nil { + return nil, err + } + actual, _ := regexCache.LoadOrStore(pattern, compiled) + r, _ := actual.(*regexp.Regexp) + return r, nil +} + // doSearch 在响应体中执行正则匹配并提取命名捕获组 func doSearch(re string, body string) map[string]string { - // 编译正则表达式(带缓存) - var r *regexp.Regexp - if cached, ok := regexCache.Load(re); ok { - r, _ = cached.(*regexp.Regexp) - } else { - compiled, err := regexp.Compile(re) - if err != nil { - common.LogError(i18n.Tr("webscan_regex_compile_error", err)) - return nil - } - actual, _ := regexCache.LoadOrStore(re, compiled) - r, _ = actual.(*regexp.Regexp) + r, err := compileSearchRegex(re) + if err != nil { + common.LogError(i18n.Tr("webscan_regex_compile_error", err)) + return nil } - // 执行正则匹配 + // 执行正则匹配;由于 ParseResponse 将 Header 键规范化为小写, + // 对 Set-Cookie: 搜索在精确匹配未命中时自动回退大小写不敏感匹配。 result := r.FindStringSubmatch(body) + isSetCookie := strings.HasPrefix(strings.ToLower(strings.TrimPrefix(re, "(?i)")), "set-cookie:") + if len(result) <= 1 && isSetCookie && !strings.HasPrefix(re, "(?i)") { + if ci, ciErr := compileSearchRegex("(?i)" + re); ciErr == nil { + r = ci + result = r.FindStringSubmatch(body) + } + } names := r.SubexpNames() // 处理匹配结果 @@ -327,7 +342,7 @@ func doSearch(re string, body string) map[string]string { for i, name := range names { if i > 0 && i < len(result) && name != "" { // 特殊处理Set-Cookie头:剥离Path/Expires等属性,仅保留key=value - if strings.HasPrefix(re, "Set-Cookie:") { + if isSetCookie { paramsMap[name] = optimizeCookies(result[i]) } else { paramsMap[name] = result[i] diff --git a/webscan/lib/poc_executor_test.go b/webscan/lib/poc_executor_test.go index 3bb1fe84..d87cfa8d 100644 --- a/webscan/lib/poc_executor_test.go +++ b/webscan/lib/poc_executor_test.go @@ -895,3 +895,13 @@ func TestEvalSetStillEvaluatesExpressions(t *testing.T) { t.Fatalf("randomLowercase result length = %d, want 6", len(got)) } } + +func TestDoSearchMatchesCaseInsensitiveSetCookieHeader(t *testing.T) { + headers := GetHeader(map[string]string{ + "set-cookie": "PHPSESSID=test123; path=/; HttpOnly", + }) + got := doSearch("Set-Cookie:(?P.*?)\n", headers) + if got["cookie"] != "PHPSESSID=test123" { + t.Fatalf("doSearch Set-Cookie = %q, want %q", got["cookie"], "PHPSESSID=test123") + } +}