mirror of
https://github.com/shadow1ng/fscan.git
synced 2026-09-22 03:10:42 +08:00
* 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]>
830 lines
24 KiB
Go
830 lines
24 KiB
Go
//go:build (plugin_dcinfo || !plugin_selective) && windows && !no_local
|
|
|
|
package local
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net"
|
|
"os/exec"
|
|
"strings"
|
|
|
|
"github.com/go-ldap/ldap/v3"
|
|
"github.com/go-ldap/ldap/v3/gssapi"
|
|
"github.com/shadow1ng/fscan/common"
|
|
"github.com/shadow1ng/fscan/common/i18n"
|
|
"github.com/shadow1ng/fscan/plugins"
|
|
)
|
|
|
|
// DCInfoPlugin 域控信息收集插件
|
|
// 设计哲学:直接实现,删除过度设计
|
|
// - 删除复杂的继承体系
|
|
// - 直接实现域信息收集功能
|
|
// - 保持原有功能逻辑
|
|
type DCInfoPlugin struct {
|
|
plugins.BasePlugin
|
|
}
|
|
|
|
// DomainInfo 域信息结构
|
|
type DomainInfo struct {
|
|
Domain string
|
|
BaseDN string
|
|
LDAPConn *ldap.Conn
|
|
}
|
|
|
|
// NewDCInfoPlugin 创建域控信息收集插件
|
|
func NewDCInfoPlugin() *DCInfoPlugin {
|
|
return &DCInfoPlugin{
|
|
BasePlugin: plugins.NewBasePlugin("dcinfo"),
|
|
}
|
|
}
|
|
|
|
// Scan 执行域控信息收集 - 直接实现
|
|
func (p *DCInfoPlugin) Scan(ctx context.Context, info *common.HostInfo, session *common.ScanSession) *plugins.Result {
|
|
config := session.Config
|
|
state := session.State
|
|
var output strings.Builder
|
|
|
|
output.WriteString("=== 域控制器信息收集 ===\n")
|
|
|
|
// 建立域控连接
|
|
domainConn, err := p.connectToDomain()
|
|
if err != nil {
|
|
if common.ContainsAny(err.Error(), "未加入域", "WORKGROUP") {
|
|
msg := i18n.GetText("dcinfo_not_joined")
|
|
output.WriteString(msg + ",无法执行域信息收集\n")
|
|
common.LogError(msg)
|
|
return &plugins.Result{
|
|
Success: false,
|
|
Output: output.String(),
|
|
Error: errors.New(msg),
|
|
}
|
|
}
|
|
output.WriteString(fmt.Sprintf("域控连接失败: %v\n", err))
|
|
return &plugins.Result{
|
|
Success: false,
|
|
Output: output.String(),
|
|
Error: fmt.Errorf("域控连接失败: %w", err),
|
|
}
|
|
}
|
|
defer func() {
|
|
if domainConn.LDAPConn != nil {
|
|
_ = domainConn.LDAPConn.Close()
|
|
}
|
|
}()
|
|
|
|
output.WriteString(fmt.Sprintf("成功连接到域: %s\n", domainConn.Domain))
|
|
output.WriteString(fmt.Sprintf("Base DN: %s\n\n", domainConn.BaseDN))
|
|
|
|
var successCount int
|
|
|
|
// 收集域基本信息
|
|
if domainInfo, err := p.getDomainInfo(domainConn); err == nil {
|
|
output.WriteString("✓ 域基本信息:\n")
|
|
p.logDomainInfoToOutput(&output, domainInfo)
|
|
successCount++
|
|
} else {
|
|
output.WriteString(fmt.Sprintf("✗ 获取域基本信息失败: %v\n", err))
|
|
}
|
|
|
|
// 获取域控制器信息
|
|
if domainControllers, err := p.getDomainControllers(domainConn); err == nil {
|
|
output.WriteString("✓ 域控制器信息:\n")
|
|
p.logDomainControllersToOutput(&output, domainControllers)
|
|
successCount++
|
|
} else {
|
|
output.WriteString(fmt.Sprintf("✗ 获取域控制器信息失败: %v\n", err))
|
|
}
|
|
|
|
// 获取域用户信息
|
|
if users, err := p.getDomainUsersDetailed(domainConn); err == nil {
|
|
output.WriteString("✓ 域用户信息:\n")
|
|
p.logDomainUsersToOutput(&output, users)
|
|
successCount++
|
|
} else {
|
|
output.WriteString(fmt.Sprintf("✗ 获取域用户失败: %v\n", err))
|
|
}
|
|
|
|
// 获取域管理员信息
|
|
if admins, err := p.getDomainAdminsDetailed(domainConn); err == nil {
|
|
output.WriteString("✓ 域管理员信息:\n")
|
|
p.logDomainAdminsToOutput(&output, admins)
|
|
successCount++
|
|
} else {
|
|
output.WriteString(fmt.Sprintf("✗ 获取域管理员失败: %v\n", err))
|
|
}
|
|
|
|
// 获取域计算机信息
|
|
if computers, err := p.getComputersDetailed(domainConn); err == nil {
|
|
output.WriteString("✓ 域计算机信息:\n")
|
|
p.logComputersToOutput(&output, computers)
|
|
successCount++
|
|
} else {
|
|
output.WriteString(fmt.Sprintf("✗ 获取域计算机失败: %v\n", err))
|
|
}
|
|
|
|
// 获取组策略信息
|
|
if gpos, err := p.getGroupPolicies(domainConn); err == nil {
|
|
output.WriteString("✓ 组策略信息:\n")
|
|
p.logGroupPoliciesToOutput(&output, gpos)
|
|
successCount++
|
|
} else {
|
|
output.WriteString(fmt.Sprintf("✗ 获取组策略失败: %v\n", err))
|
|
}
|
|
|
|
// 获取组织单位信息
|
|
if ous, err := p.getOrganizationalUnits(domainConn); err == nil {
|
|
output.WriteString("✓ 组织单位信息:\n")
|
|
p.logOrganizationalUnitsToOutput(&output, ous)
|
|
successCount++
|
|
} else {
|
|
output.WriteString(fmt.Sprintf("✗ 获取组织单位失败: %v\n", err))
|
|
}
|
|
|
|
// 输出统计
|
|
output.WriteString(fmt.Sprintf("\n域信息收集完成: 成功(%d) 总计(%d)\n", successCount, 7))
|
|
|
|
if successCount > 0 {
|
|
common.LogSuccess(i18n.Tr("dcinfo_success", successCount))
|
|
}
|
|
|
|
return &plugins.Result{
|
|
Success: successCount > 0,
|
|
Output: output.String(),
|
|
Error: nil,
|
|
}
|
|
}
|
|
|
|
// connectToDomain 连接到域控制器
|
|
func (p *DCInfoPlugin) connectToDomain() (*DomainInfo, error) {
|
|
// 获取域控制器地址
|
|
dcHost, domain, err := p.getDomainController()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("获取域控制器失败: %w", err)
|
|
}
|
|
|
|
// 建立LDAP连接
|
|
ldapConn, baseDN, err := p.connectToLDAP(dcHost, domain)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("LDAP连接失败: %w", err)
|
|
}
|
|
|
|
return &DomainInfo{
|
|
Domain: domain,
|
|
BaseDN: baseDN,
|
|
LDAPConn: ldapConn,
|
|
}, nil
|
|
}
|
|
|
|
// getDomainController 获取域控制器地址
|
|
func (p *DCInfoPlugin) getDomainController() (string, string, error) {
|
|
// 尝试使用PowerShell获取域名
|
|
domain, err := p.getDomainNamePowerShell()
|
|
if err != nil {
|
|
// 尝试使用wmic
|
|
domain, err = p.getDomainNameWmic()
|
|
if err != nil {
|
|
// 尝试使用环境变量
|
|
domain, err = p.getDomainNameFromEnv()
|
|
if err != nil {
|
|
return "", "", fmt.Errorf("获取域名失败: %w", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
if domain == "" || domain == "WORKGROUP" {
|
|
return "", "", fmt.Errorf("当前机器未加入域")
|
|
}
|
|
|
|
// 查询域控制器
|
|
dcHost, err := p.findDomainController(domain)
|
|
if err != nil {
|
|
// 备选方案:使用域名直接构造
|
|
dcHost = fmt.Sprintf("dc.%s", domain)
|
|
}
|
|
|
|
return dcHost, domain, nil
|
|
}
|
|
|
|
// getDomainNamePowerShell 使用PowerShell获取域名
|
|
func (p *DCInfoPlugin) getDomainNamePowerShell() (string, error) {
|
|
cmd := exec.Command("powershell", "-Command", "(Get-WmiObject Win32_ComputerSystem).Domain")
|
|
output, err := cmd.Output()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
domain := strings.TrimSpace(string(output))
|
|
if domain == "" || domain == "WORKGROUP" {
|
|
return "", fmt.Errorf("未加入域")
|
|
}
|
|
|
|
return domain, nil
|
|
}
|
|
|
|
// getDomainNameWmic 使用wmic获取域名
|
|
func (p *DCInfoPlugin) getDomainNameWmic() (string, error) {
|
|
cmd := exec.Command("wmic", "computersystem", "get", "domain", "/value")
|
|
output, err := cmd.Output()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
lines := strings.Split(string(output), "\n")
|
|
for _, line := range lines {
|
|
if strings.HasPrefix(line, "Domain=") {
|
|
domain := strings.TrimSpace(strings.TrimPrefix(line, "Domain="))
|
|
if domain != "" && domain != "WORKGROUP" {
|
|
return domain, nil
|
|
}
|
|
}
|
|
}
|
|
|
|
return "", fmt.Errorf("未找到域名")
|
|
}
|
|
|
|
// getDomainNameFromEnv 从环境变量获取域名
|
|
func (p *DCInfoPlugin) getDomainNameFromEnv() (string, error) {
|
|
cmd := exec.Command("cmd", "/c", "echo %USERDOMAIN%")
|
|
output, err := cmd.Output()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
userDomain := strings.ToLower(strings.TrimSpace(string(output)))
|
|
if userDomain != "" && userDomain != "workgroup" && userDomain != "%userdomain%" {
|
|
return userDomain, nil
|
|
}
|
|
|
|
return "", fmt.Errorf("从环境变量获取域名失败")
|
|
}
|
|
|
|
// findDomainController 查找域控制器
|
|
func (p *DCInfoPlugin) findDomainController(domain string) (string, error) {
|
|
// 使用nslookup查询SRV记录
|
|
cmd := exec.Command("nslookup", "-type=SRV", fmt.Sprintf("_ldap._tcp.dc._msdcs.%s", domain))
|
|
output, err := cmd.Output()
|
|
if err == nil {
|
|
lines := strings.Split(string(output), "\n")
|
|
for _, line := range lines {
|
|
if common.ContainsAny(line, "svr hostname", "service") {
|
|
parts := strings.Split(line, "=")
|
|
if len(parts) > 1 {
|
|
dcHost := strings.TrimSpace(parts[len(parts)-1])
|
|
dcHost = strings.TrimSuffix(dcHost, ".")
|
|
if dcHost != "" {
|
|
return dcHost, nil
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// 尝试直接ping域名
|
|
cmd = exec.Command("ping", "-n", "1", domain)
|
|
if err := cmd.Run(); err == nil {
|
|
return domain, nil
|
|
}
|
|
|
|
return "", fmt.Errorf("无法找到域控制器")
|
|
}
|
|
|
|
// connectToLDAP 连接到LDAP服务器
|
|
func (p *DCInfoPlugin) connectToLDAP(dcHost, domain string) (*ldap.Conn, string, error) {
|
|
// 创建SSPI客户端
|
|
ldapClient, err := gssapi.NewSSPIClient()
|
|
if err != nil {
|
|
return nil, "", fmt.Errorf("创建SSPI客户端失败: %w", err)
|
|
}
|
|
defer func() { _ = ldapClient.Close() }()
|
|
|
|
// 尝试连接
|
|
var conn *ldap.Conn
|
|
var lastError error
|
|
|
|
// 直接连接
|
|
conn, err = ldap.DialURL(fmt.Sprintf("ldap://%s:389", dcHost))
|
|
if err != nil {
|
|
lastError = err
|
|
// 尝试使用IPv4地址
|
|
ipv4, resolveErr := p.resolveIPv4(dcHost)
|
|
if resolveErr == nil {
|
|
conn, err = ldap.DialURL(fmt.Sprintf("ldap://%s:389", ipv4))
|
|
if err != nil {
|
|
lastError = err
|
|
}
|
|
} else {
|
|
lastError = resolveErr
|
|
}
|
|
}
|
|
|
|
if conn == nil {
|
|
return nil, "", fmt.Errorf("LDAP连接失败: %w", lastError)
|
|
}
|
|
|
|
// 使用GSSAPI进行绑定
|
|
err = conn.GSSAPIBind(ldapClient, fmt.Sprintf("ldap/%s", dcHost), "")
|
|
if err != nil {
|
|
_ = conn.Close()
|
|
return nil, "", fmt.Errorf("GSSAPI绑定失败: %w", err)
|
|
}
|
|
|
|
// 获取BaseDN
|
|
baseDN, err := p.getBaseDN(conn, domain)
|
|
if err != nil {
|
|
_ = conn.Close()
|
|
return nil, "", err
|
|
}
|
|
|
|
return conn, baseDN, nil
|
|
}
|
|
|
|
// getBaseDN 获取BaseDN
|
|
func (p *DCInfoPlugin) getBaseDN(conn *ldap.Conn, domain string) (string, error) {
|
|
searchRequest := ldap.NewSearchRequest(
|
|
"",
|
|
ldap.ScopeBaseObject,
|
|
ldap.NeverDerefAliases,
|
|
0, 0, false,
|
|
"(objectClass=*)",
|
|
[]string{"defaultNamingContext"},
|
|
nil,
|
|
)
|
|
|
|
result, err := conn.Search(searchRequest)
|
|
if err != nil {
|
|
return "", fmt.Errorf("获取defaultNamingContext失败: %w", err)
|
|
}
|
|
|
|
if len(result.Entries) == 0 {
|
|
// 备选方案:从域名构造BaseDN
|
|
parts := strings.Split(domain, ".")
|
|
var dn []string
|
|
for _, part := range parts {
|
|
dn = append(dn, fmt.Sprintf("DC=%s", part))
|
|
}
|
|
return strings.Join(dn, ","), nil
|
|
}
|
|
|
|
baseDN := result.Entries[0].GetAttributeValue("defaultNamingContext")
|
|
if baseDN == "" {
|
|
return "", fmt.Errorf("获取BaseDN失败")
|
|
}
|
|
|
|
return baseDN, nil
|
|
}
|
|
|
|
// resolveIPv4 解析主机名为IPv4地址
|
|
func (p *DCInfoPlugin) resolveIPv4(hostname string) (string, error) {
|
|
ips, err := net.LookupIP(hostname)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
for _, ip := range ips {
|
|
if ip.To4() != nil {
|
|
return ip.String(), nil
|
|
}
|
|
}
|
|
|
|
return "", fmt.Errorf("未找到IPv4地址")
|
|
}
|
|
|
|
// getDomainInfo 获取域基本信息
|
|
func (p *DCInfoPlugin) getDomainInfo(conn *DomainInfo) (map[string]interface{}, error) {
|
|
searchRequest := ldap.NewSearchRequest(
|
|
conn.BaseDN,
|
|
ldap.ScopeBaseObject,
|
|
ldap.NeverDerefAliases,
|
|
0, 0, false,
|
|
"(objectClass=*)",
|
|
[]string{"whenCreated", "whenChanged", "objectSid", "msDS-Behavior-Version", "dnsRoot"},
|
|
nil,
|
|
)
|
|
|
|
sr, err := conn.LDAPConn.Search(searchRequest)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
domainInfo := make(map[string]interface{})
|
|
domainInfo["domain"] = conn.Domain
|
|
domainInfo["base_dn"] = conn.BaseDN
|
|
|
|
if len(sr.Entries) > 0 {
|
|
entry := sr.Entries[0]
|
|
domainInfo["created"] = entry.GetAttributeValue("whenCreated")
|
|
domainInfo["modified"] = entry.GetAttributeValue("whenChanged")
|
|
domainInfo["object_sid"] = entry.GetAttributeValue("objectSid")
|
|
domainInfo["functional_level"] = entry.GetAttributeValue("msDS-Behavior-Version")
|
|
domainInfo["dns_root"] = entry.GetAttributeValue("dnsRoot")
|
|
}
|
|
|
|
return domainInfo, nil
|
|
}
|
|
|
|
// getDomainControllers 获取域控制器信息
|
|
func (p *DCInfoPlugin) getDomainControllers(conn *DomainInfo) ([]map[string]interface{}, error) {
|
|
dcQuery := ldap.NewSearchRequest(
|
|
conn.BaseDN,
|
|
ldap.ScopeWholeSubtree,
|
|
ldap.NeverDerefAliases,
|
|
0, 0, false,
|
|
"(&(objectClass=computer)(userAccountControl:1.2.840.113556.1.4.803:=8192))",
|
|
[]string{"cn", "dNSHostName", "operatingSystem", "operatingSystemVersion", "operatingSystemServicePack", "whenCreated", "lastLogonTimestamp"},
|
|
nil,
|
|
)
|
|
|
|
sr, err := conn.LDAPConn.SearchWithPaging(dcQuery, 10000)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var dcs []map[string]interface{}
|
|
for _, entry := range sr.Entries {
|
|
dc := make(map[string]interface{})
|
|
dc["name"] = entry.GetAttributeValue("cn")
|
|
dc["dns_name"] = entry.GetAttributeValue("dNSHostName")
|
|
dc["os"] = entry.GetAttributeValue("operatingSystem")
|
|
dc["os_version"] = entry.GetAttributeValue("operatingSystemVersion")
|
|
dc["os_service_pack"] = entry.GetAttributeValue("operatingSystemServicePack")
|
|
dc["created"] = entry.GetAttributeValue("whenCreated")
|
|
dc["last_logon"] = entry.GetAttributeValue("lastLogonTimestamp")
|
|
dcs = append(dcs, dc)
|
|
}
|
|
|
|
return dcs, nil
|
|
}
|
|
|
|
// getDomainUsersDetailed 获取域用户信息
|
|
func (p *DCInfoPlugin) getDomainUsersDetailed(conn *DomainInfo) ([]map[string]interface{}, error) {
|
|
searchRequest := ldap.NewSearchRequest(
|
|
conn.BaseDN,
|
|
ldap.ScopeWholeSubtree,
|
|
ldap.NeverDerefAliases,
|
|
0, 0, false,
|
|
"(&(objectCategory=person)(objectClass=user))",
|
|
[]string{"sAMAccountName", "displayName", "mail", "userAccountControl", "whenCreated", "lastLogonTimestamp", "badPwdCount", "pwdLastSet"},
|
|
nil,
|
|
)
|
|
|
|
sr, err := conn.LDAPConn.SearchWithPaging(searchRequest, 0)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var users []map[string]interface{}
|
|
for _, entry := range sr.Entries {
|
|
user := make(map[string]interface{})
|
|
user["username"] = entry.GetAttributeValue("sAMAccountName")
|
|
user["display_name"] = entry.GetAttributeValue("displayName")
|
|
user["email"] = entry.GetAttributeValue("mail")
|
|
user["account_control"] = entry.GetAttributeValue("userAccountControl")
|
|
user["created"] = entry.GetAttributeValue("whenCreated")
|
|
user["last_logon"] = entry.GetAttributeValue("lastLogonTimestamp")
|
|
user["bad_pwd_count"] = entry.GetAttributeValue("badPwdCount")
|
|
user["pwd_last_set"] = entry.GetAttributeValue("pwdLastSet")
|
|
users = append(users, user)
|
|
}
|
|
|
|
return users, nil
|
|
}
|
|
|
|
// getDomainAdminsDetailed 获取域管理员信息
|
|
func (p *DCInfoPlugin) getDomainAdminsDetailed(conn *DomainInfo) ([]map[string]interface{}, error) {
|
|
// 获取Domain Admins组
|
|
searchRequest := ldap.NewSearchRequest(
|
|
conn.BaseDN,
|
|
ldap.ScopeWholeSubtree,
|
|
ldap.NeverDerefAliases,
|
|
0, 0, false,
|
|
"(&(objectCategory=group)(cn=Domain Admins))",
|
|
[]string{"member"},
|
|
nil,
|
|
)
|
|
|
|
sr, err := conn.LDAPConn.SearchWithPaging(searchRequest, 10000)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var admins []map[string]interface{}
|
|
if len(sr.Entries) > 0 {
|
|
members := sr.Entries[0].GetAttributeValues("member")
|
|
for _, memberDN := range members {
|
|
adminInfo, err := p.getUserInfoByDN(conn, memberDN)
|
|
if err == nil {
|
|
admins = append(admins, adminInfo)
|
|
}
|
|
}
|
|
}
|
|
|
|
return admins, nil
|
|
}
|
|
|
|
// getComputersDetailed 获取域计算机信息
|
|
func (p *DCInfoPlugin) getComputersDetailed(conn *DomainInfo) ([]map[string]interface{}, error) {
|
|
searchRequest := ldap.NewSearchRequest(
|
|
conn.BaseDN,
|
|
ldap.ScopeWholeSubtree,
|
|
ldap.NeverDerefAliases,
|
|
0, 0, false,
|
|
"(&(objectClass=computer)(!userAccountControl:1.2.840.113556.1.4.803:=8192))",
|
|
[]string{"cn", "operatingSystem", "operatingSystemVersion", "dNSHostName", "whenCreated", "lastLogonTimestamp", "userAccountControl"},
|
|
nil,
|
|
)
|
|
|
|
sr, err := conn.LDAPConn.SearchWithPaging(searchRequest, 0)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var computers []map[string]interface{}
|
|
for _, entry := range sr.Entries {
|
|
computer := make(map[string]interface{})
|
|
computer["name"] = entry.GetAttributeValue("cn")
|
|
computer["os"] = entry.GetAttributeValue("operatingSystem")
|
|
computer["os_version"] = entry.GetAttributeValue("operatingSystemVersion")
|
|
computer["dns_name"] = entry.GetAttributeValue("dNSHostName")
|
|
computer["created"] = entry.GetAttributeValue("whenCreated")
|
|
computer["last_logon"] = entry.GetAttributeValue("lastLogonTimestamp")
|
|
computer["account_control"] = entry.GetAttributeValue("userAccountControl")
|
|
computers = append(computers, computer)
|
|
}
|
|
|
|
return computers, nil
|
|
}
|
|
|
|
// getUserInfoByDN 根据DN获取用户信息
|
|
func (p *DCInfoPlugin) getUserInfoByDN(conn *DomainInfo, userDN string) (map[string]interface{}, error) {
|
|
searchRequest := ldap.NewSearchRequest(
|
|
userDN,
|
|
ldap.ScopeBaseObject,
|
|
ldap.NeverDerefAliases,
|
|
0, 0, false,
|
|
"(objectClass=*)",
|
|
[]string{"sAMAccountName", "displayName", "mail", "whenCreated", "lastLogonTimestamp", "userAccountControl"},
|
|
nil,
|
|
)
|
|
|
|
sr, err := conn.LDAPConn.Search(searchRequest)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if len(sr.Entries) == 0 {
|
|
return nil, fmt.Errorf("用户不存在")
|
|
}
|
|
|
|
entry := sr.Entries[0]
|
|
userInfo := make(map[string]interface{})
|
|
userInfo["dn"] = userDN
|
|
userInfo["username"] = entry.GetAttributeValue("sAMAccountName")
|
|
userInfo["display_name"] = entry.GetAttributeValue("displayName")
|
|
userInfo["email"] = entry.GetAttributeValue("mail")
|
|
userInfo["created"] = entry.GetAttributeValue("whenCreated")
|
|
userInfo["last_logon"] = entry.GetAttributeValue("lastLogonTimestamp")
|
|
userInfo["group_type"] = "Domain Admins"
|
|
|
|
return userInfo, nil
|
|
}
|
|
|
|
// getGroupPolicies 获取组策略信息
|
|
func (p *DCInfoPlugin) getGroupPolicies(conn *DomainInfo) ([]map[string]interface{}, error) {
|
|
searchRequest := ldap.NewSearchRequest(
|
|
conn.BaseDN,
|
|
ldap.ScopeWholeSubtree,
|
|
ldap.NeverDerefAliases,
|
|
0, 0, false,
|
|
"(objectClass=groupPolicyContainer)",
|
|
[]string{"cn", "displayName", "objectClass", "distinguishedName", "whenCreated", "whenChanged", "gPCFileSysPath"},
|
|
nil,
|
|
)
|
|
|
|
sr, err := conn.LDAPConn.Search(searchRequest)
|
|
if err != nil {
|
|
sr, err = conn.LDAPConn.SearchWithPaging(searchRequest, 1000)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
var gpos []map[string]interface{}
|
|
for _, entry := range sr.Entries {
|
|
gpo := make(map[string]interface{})
|
|
gpo["guid"] = entry.GetAttributeValue("cn")
|
|
gpo["display_name"] = entry.GetAttributeValue("displayName")
|
|
gpo["created"] = entry.GetAttributeValue("whenCreated")
|
|
gpo["modified"] = entry.GetAttributeValue("whenChanged")
|
|
gpo["file_sys_path"] = entry.GetAttributeValue("gPCFileSysPath")
|
|
gpo["dn"] = entry.GetAttributeValue("distinguishedName")
|
|
gpos = append(gpos, gpo)
|
|
}
|
|
|
|
return gpos, nil
|
|
}
|
|
|
|
// getOrganizationalUnits 获取组织单位信息
|
|
func (p *DCInfoPlugin) getOrganizationalUnits(conn *DomainInfo) ([]map[string]interface{}, error) {
|
|
searchRequest := ldap.NewSearchRequest(
|
|
conn.BaseDN,
|
|
ldap.ScopeWholeSubtree,
|
|
ldap.NeverDerefAliases,
|
|
0, 0, false,
|
|
"(objectClass=*)",
|
|
[]string{"ou", "cn", "name", "description", "objectClass", "distinguishedName", "whenCreated", "gPLink"},
|
|
nil,
|
|
)
|
|
|
|
sr, err := conn.LDAPConn.SearchWithPaging(searchRequest, 100)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var ous []map[string]interface{}
|
|
for _, entry := range sr.Entries {
|
|
objectClasses := entry.GetAttributeValues("objectClass")
|
|
dn := entry.GetAttributeValue("distinguishedName")
|
|
|
|
isOU := false
|
|
isContainer := false
|
|
for _, class := range objectClasses {
|
|
switch class {
|
|
case "organizationalUnit":
|
|
isOU = true
|
|
case "container":
|
|
isContainer = true
|
|
}
|
|
}
|
|
|
|
if !isOU && !isContainer {
|
|
continue
|
|
}
|
|
|
|
// 获取名称
|
|
name := entry.GetAttributeValue("ou")
|
|
if name == "" {
|
|
name = entry.GetAttributeValue("cn")
|
|
}
|
|
if name == "" {
|
|
name = entry.GetAttributeValue("name")
|
|
}
|
|
|
|
// 跳过系统容器
|
|
if strings.Contains(dn, "CN=LostAndFound") ||
|
|
strings.Contains(dn, "CN=Configuration") ||
|
|
strings.Contains(dn, "CN=Schema") ||
|
|
strings.Contains(dn, "CN=System") ||
|
|
strings.Contains(dn, "CN=Program Data") ||
|
|
strings.Contains(dn, "CN=Microsoft") ||
|
|
(strings.HasPrefix(dn, "CN=") && len(name) == 36 && strings.Count(name, "-") == 4) {
|
|
continue
|
|
}
|
|
|
|
if name != "" {
|
|
ou := make(map[string]interface{})
|
|
ou["name"] = name
|
|
ou["description"] = entry.GetAttributeValue("description")
|
|
ou["created"] = entry.GetAttributeValue("whenCreated")
|
|
ou["gp_link"] = entry.GetAttributeValue("gPLink")
|
|
ou["dn"] = dn
|
|
ou["is_ou"] = isOU
|
|
ous = append(ous, ou)
|
|
}
|
|
}
|
|
|
|
return ous, nil
|
|
}
|
|
|
|
// 输出日志函数
|
|
func (p *DCInfoPlugin) logDomainInfoToOutput(output *strings.Builder, domainInfo map[string]interface{}) {
|
|
if domain, ok := domainInfo["domain"]; ok {
|
|
_, _ = fmt.Fprintf(output, " 域名: %v\n", domain)
|
|
}
|
|
if created, ok := domainInfo["created"]; ok && created != "" {
|
|
_, _ = fmt.Fprintf(output, " 创建时间: %v\n", created)
|
|
}
|
|
output.WriteString("\n")
|
|
}
|
|
|
|
func (p *DCInfoPlugin) logDomainControllersToOutput(output *strings.Builder, dcs []map[string]interface{}) {
|
|
_, _ = fmt.Fprintf(output, " 发现 %d 个域控制器\n", len(dcs))
|
|
for _, dc := range dcs {
|
|
if name, ok := dc["name"]; ok {
|
|
_, _ = fmt.Fprintf(output, " - %v (%v)\n", name, dc["dns_name"])
|
|
if os, ok := dc["os"]; ok && os != "" {
|
|
_, _ = fmt.Fprintf(output, " 操作系统: %v\n", os)
|
|
}
|
|
}
|
|
}
|
|
output.WriteString("\n")
|
|
}
|
|
|
|
func (p *DCInfoPlugin) logDomainUsersToOutput(output *strings.Builder, users []map[string]interface{}) {
|
|
_, _ = fmt.Fprintf(output, " 发现 %d 个域用户\n", len(users))
|
|
count := 0
|
|
for _, user := range users {
|
|
if count >= 10 { // 限制显示数量
|
|
output.WriteString(" ...(更多用户已省略)\n")
|
|
break
|
|
}
|
|
if username, ok := user["username"]; ok && username != "" {
|
|
displayInfo := fmt.Sprintf(" - %v", username)
|
|
if displayName, ok := user["display_name"]; ok && displayName != "" {
|
|
displayInfo += fmt.Sprintf(" (%v)", displayName)
|
|
}
|
|
if email, ok := user["email"]; ok && email != "" {
|
|
displayInfo += fmt.Sprintf(" [%v]", email)
|
|
}
|
|
output.WriteString(displayInfo + "\n")
|
|
count++
|
|
}
|
|
}
|
|
output.WriteString("\n")
|
|
}
|
|
|
|
func (p *DCInfoPlugin) logDomainAdminsToOutput(output *strings.Builder, admins []map[string]interface{}) {
|
|
_, _ = fmt.Fprintf(output, " 发现 %d 个域管理员\n", len(admins))
|
|
for _, admin := range admins {
|
|
if username, ok := admin["username"]; ok && username != "" {
|
|
adminInfo := fmt.Sprintf(" - %v", username)
|
|
if displayName, ok := admin["display_name"]; ok && displayName != "" {
|
|
adminInfo += fmt.Sprintf(" (%v)", displayName)
|
|
}
|
|
if email, ok := admin["email"]; ok && email != "" {
|
|
adminInfo += fmt.Sprintf(" [%v]", email)
|
|
}
|
|
output.WriteString(adminInfo + "\n")
|
|
}
|
|
}
|
|
output.WriteString("\n")
|
|
}
|
|
|
|
func (p *DCInfoPlugin) logComputersToOutput(output *strings.Builder, computers []map[string]interface{}) {
|
|
_, _ = fmt.Fprintf(output, " 发现 %d 台域计算机\n", len(computers))
|
|
count := 0
|
|
for _, computer := range computers {
|
|
if count >= 10 { // 限制显示数量
|
|
output.WriteString(" ...(更多计算机已省略)\n")
|
|
break
|
|
}
|
|
if name, ok := computer["name"]; ok && name != "" {
|
|
computerInfo := fmt.Sprintf(" - %v", name)
|
|
if os, ok := computer["os"]; ok && os != "" {
|
|
computerInfo += fmt.Sprintf(" (%v)", os)
|
|
}
|
|
if dnsName, ok := computer["dns_name"]; ok && dnsName != "" {
|
|
computerInfo += fmt.Sprintf(" [%v]", dnsName)
|
|
}
|
|
output.WriteString(computerInfo + "\n")
|
|
count++
|
|
}
|
|
}
|
|
output.WriteString("\n")
|
|
}
|
|
|
|
func (p *DCInfoPlugin) logGroupPoliciesToOutput(output *strings.Builder, gpos []map[string]interface{}) {
|
|
_, _ = fmt.Fprintf(output, " 发现 %d 个组策略对象\n", len(gpos))
|
|
for _, gpo := range gpos {
|
|
if displayName, ok := gpo["display_name"]; ok && displayName != "" {
|
|
gpoInfo := fmt.Sprintf(" - %v", displayName)
|
|
if guid, ok := gpo["guid"]; ok {
|
|
gpoInfo += fmt.Sprintf(" [%v]", guid)
|
|
}
|
|
output.WriteString(gpoInfo + "\n")
|
|
}
|
|
}
|
|
output.WriteString("\n")
|
|
}
|
|
|
|
func (p *DCInfoPlugin) logOrganizationalUnitsToOutput(output *strings.Builder, ous []map[string]interface{}) {
|
|
_, _ = fmt.Fprintf(output, " 发现 %d 个组织单位和容器\n", len(ous))
|
|
for _, ou := range ous {
|
|
if name, ok := ou["name"]; ok && name != "" {
|
|
ouInfo := fmt.Sprintf(" - %v", name)
|
|
if isOU, ok := ou["is_ou"]; ok {
|
|
if isOUBool, ok := isOU.(bool); ok && isOUBool {
|
|
ouInfo += " [OU]"
|
|
} else {
|
|
ouInfo += " [Container]"
|
|
}
|
|
} else {
|
|
ouInfo += " [Container]"
|
|
}
|
|
if desc, ok := ou["description"]; ok && desc != "" {
|
|
ouInfo += fmt.Sprintf(" 描述: %v", desc)
|
|
}
|
|
output.WriteString(ouInfo + "\n")
|
|
}
|
|
}
|
|
output.WriteString("\n")
|
|
}
|
|
|
|
// 注册插件
|
|
func init() {
|
|
RegisterLocalPlugin("dcinfo", func() Plugin {
|
|
return NewDCInfoPlugin()
|
|
})
|
|
}
|