Files
fscan/plugins/services/netbios.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

460 lines
13 KiB
Go

//go:build plugin_netbios || !plugin_selective
package services
import (
"bytes"
"context"
"fmt"
"net"
"strings"
"time"
"github.com/shadow1ng/fscan/common"
"github.com/shadow1ng/fscan/plugins"
)
// NetBIOSPlugin NetBIOS名称服务扫描插件 - 收集Windows主机名和域信息
type NetBIOSPlugin struct {
plugins.BasePlugin
}
// NewNetBIOSPlugin 创建NetBIOS插件
func NewNetBIOSPlugin() *NetBIOSPlugin {
return &NetBIOSPlugin{
BasePlugin: plugins.NewBasePlugin("netbios"),
}
}
// GetPorts 实现Plugin接口
// Scan 执行NetBIOS扫描 - 收集Windows主机和域信息
func (p *NetBIOSPlugin) Scan(ctx context.Context, info *common.HostInfo, session *common.ScanSession) *ScanResult {
config := session.Config
state := session.State
target := info.Target()
// 检查端口类型
if info.Port != 137 && info.Port != 139 {
return &ScanResult{
Success: false,
Service: "netbios",
Error: fmt.Errorf("NetBIOS插件仅支持137和139端口"),
}
}
var netbiosInfo *NetBIOSInfo
var err error
if info.Port == 137 {
// UDP端口137 - NetBIOS名称服务
netbiosInfo, err = p.queryNetBIOSNames(info.Host, config, state)
} else {
// TCP端口139 - NetBIOS会话服务
netbiosInfo, err = p.queryNetBIOSSession(ctx, info.Host, session)
}
if err != nil {
return &ScanResult{
Success: false,
Service: "netbios",
Error: err,
}
}
if !netbiosInfo.Valid {
return &ScanResult{
Success: false,
Service: "netbios",
Error: fmt.Errorf("未发现有效的NetBIOS信息"),
}
}
// 记录NetBIOS发现信息
msg := fmt.Sprintf("NetBios %s", target)
if netbiosInfo.Summary() != "" {
msg += fmt.Sprintf(" %s", netbiosInfo.Summary())
}
common.LogSuccess(msg)
return &ScanResult{
Success: true,
Type: plugins.ResultTypeService,
Service: "netbios",
Banner: netbiosInfo.Summary(),
}
}
// NetBIOSInfo NetBIOS信息结构
type NetBIOSInfo struct {
Valid bool
ComputerName string
DomainName string
WorkstationService string
ServerService string
DomainControllers string
OSVersion string
NetBIOSComputerName string
NetBIOSDomainName string
}
// Summary 返回NetBIOS信息摘要
func (ni *NetBIOSInfo) Summary() string {
if !ni.Valid {
return ""
}
var parts []string
// 优先使用完整的计算机名
if ni.ComputerName != "" {
if ni.DomainName != "" && !strings.Contains(ni.ComputerName, ".") {
parts = append(parts, fmt.Sprintf("%s\\%s", ni.DomainName, ni.ComputerName))
} else {
parts = append(parts, ni.ComputerName)
}
} else {
// 使用服务名称
var name string
if ni.ServerService != "" {
name = ni.ServerService
} else if ni.WorkstationService != "" {
name = ni.WorkstationService
} else if ni.NetBIOSComputerName != "" {
name = ni.NetBIOSComputerName
}
if name != "" {
if ni.DomainName != "" {
parts = append(parts, fmt.Sprintf("%s\\%s", ni.DomainName, name))
} else if ni.NetBIOSDomainName != "" {
parts = append(parts, fmt.Sprintf("%s\\%s", ni.NetBIOSDomainName, name))
} else {
parts = append(parts, name)
}
}
}
// 添加域控制器标识
if ni.DomainControllers != "" {
if len(parts) > 0 {
parts[0] = fmt.Sprintf("DC:%s", parts[0])
}
}
// 添加操作系统信息
if ni.OSVersion != "" {
parts = append(parts, ni.OSVersion)
}
return strings.Join(parts, " ")
}
// queryNetBIOSNames 查询NetBIOS名称服务(UDP 137)
func (p *NetBIOSPlugin) queryNetBIOSNames(host string, config *common.Config, state *common.State) (*NetBIOSInfo, error) {
// NetBIOS名称查询数据包
queryPacket := []byte{
0x66, 0x66, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x20, 0x43, 0x4B, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x00, 0x00, 0x21, 0x00, 0x01,
}
target := fmt.Sprintf("%s:137", host)
conn, err := net.DialTimeout("udp", target, config.Timeout)
if err != nil {
return nil, fmt.Errorf("连接NetBIOS名称服务失败: %w", err)
}
state.IncrementUDPPacketCount()
defer func() { _ = conn.Close() }()
_ = conn.SetDeadline(time.Now().Add(config.Timeout))
_, err = conn.Write(queryPacket)
if err != nil {
return nil, fmt.Errorf("发送NetBIOS查询失败: %w", err)
}
response := make([]byte, 1024)
n, err := conn.Read(response)
if err != nil {
return nil, fmt.Errorf("读取NetBIOS响应失败: %w", err)
}
return p.parseNetBIOSNames(response[:n])
}
// queryNetBIOSSession 查询NetBIOS会话服务(TCP 139)
func (p *NetBIOSPlugin) queryNetBIOSSession(ctx context.Context, host string, session *common.ScanSession) (*NetBIOSInfo, error) {
target := fmt.Sprintf("%s:139", host)
conn, err := session.DialTCP(ctx, "tcp", target, session.Config.Timeout)
if err != nil {
return nil, fmt.Errorf("连接NetBIOS会话服务失败: %w", err)
}
defer func() { _ = conn.Close() }()
_ = conn.SetDeadline(time.Now().Add(session.Config.Timeout))
// 发送SMB协商数据包
smbNegotiate1 := []byte{
0x00, 0x00, 0x00, 0x85, 0xFF, 0x53, 0x4D, 0x42, 0x72, 0x00, 0x00, 0x00, 0x00, 0x18, 0x53, 0xC8,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFE,
0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x00, 0x02, 0x50, 0x43, 0x20, 0x4E, 0x45, 0x54, 0x57, 0x4F,
0x52, 0x4B, 0x20, 0x50, 0x52, 0x4F, 0x47, 0x52, 0x41, 0x4D, 0x20, 0x31, 0x2E, 0x30, 0x00, 0x02,
0x4C, 0x41, 0x4E, 0x4D, 0x41, 0x4E, 0x31, 0x2E, 0x30, 0x00, 0x02, 0x57, 0x69, 0x6E, 0x64, 0x6F,
0x77, 0x73, 0x20, 0x66, 0x6F, 0x72, 0x20, 0x57, 0x6F, 0x72, 0x6B, 0x67, 0x72, 0x6F, 0x75, 0x70,
0x73, 0x20, 0x33, 0x2E, 0x31, 0x61, 0x00, 0x02, 0x4C, 0x4D, 0x31, 0x2E, 0x32, 0x58, 0x30, 0x30,
0x32, 0x00, 0x02, 0x4C, 0x41, 0x4E, 0x4D, 0x41, 0x4E, 0x32, 0x2E, 0x31, 0x00, 0x02, 0x4E, 0x54,
0x20, 0x4C, 0x4D, 0x20, 0x30, 0x2E, 0x31, 0x32, 0x00,
}
_, err = conn.Write(smbNegotiate1)
if err != nil {
return nil, fmt.Errorf("发送SMB协商1失败: %w", err)
}
response1 := make([]byte, 1024)
_, err = conn.Read(response1)
if err != nil {
return nil, fmt.Errorf("读取SMB协商1响应失败: %w", err)
}
// 发送Session Setup请求
smbSessionSetup := []byte{
0x00, 0x00, 0x01, 0x0A, 0xFF, 0x53, 0x4D, 0x42, 0x73, 0x00, 0x00, 0x00, 0x00, 0x18, 0x07, 0xC8,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFE,
0x00, 0x00, 0x40, 0x00, 0x0C, 0xFF, 0x00, 0x0A, 0x01, 0x04, 0x41, 0x32, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x4A, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD4, 0x00, 0x00, 0xA0, 0xCF, 0x00, 0x60,
0x48, 0x06, 0x06, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x02, 0xA0, 0x3E, 0x30, 0x3C, 0xA0, 0x0E, 0x30,
0x0C, 0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x02, 0x02, 0x0A, 0xA2, 0x2A, 0x04,
0x28, 0x4E, 0x54, 0x4C, 0x4D, 0x53, 0x53, 0x50, 0x00, 0x01, 0x00, 0x00, 0x00, 0x07, 0x82, 0x08,
0xA2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x05, 0x02, 0xCE, 0x0E, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x57, 0x00, 0x69, 0x00, 0x6E, 0x00,
0x64, 0x00, 0x6F, 0x00, 0x77, 0x00, 0x73, 0x00, 0x20, 0x00, 0x53, 0x00, 0x65, 0x00, 0x72, 0x00,
0x76, 0x00, 0x65, 0x00, 0x72, 0x00, 0x20, 0x00, 0x32, 0x00, 0x30, 0x00, 0x30, 0x00, 0x33, 0x00,
0x20, 0x00, 0x33, 0x00, 0x37, 0x00, 0x39, 0x00, 0x30, 0x00, 0x20, 0x00, 0x53, 0x00, 0x65, 0x00,
0x72, 0x00, 0x76, 0x00, 0x69, 0x00, 0x63, 0x00, 0x65, 0x00, 0x20, 0x00, 0x50, 0x00, 0x61, 0x00,
0x63, 0x00, 0x6B, 0x00, 0x20, 0x00, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x57, 0x00, 0x69, 0x00,
0x6E, 0x00, 0x64, 0x00, 0x6F, 0x00, 0x77, 0x00, 0x73, 0x00, 0x20, 0x00, 0x53, 0x00, 0x65, 0x00,
0x72, 0x00, 0x76, 0x00, 0x65, 0x00, 0x72, 0x00, 0x20, 0x00, 0x32, 0x00, 0x30, 0x00, 0x30, 0x00,
0x33, 0x00, 0x20, 0x00, 0x35, 0x00, 0x2E, 0x00, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00,
}
_, err = conn.Write(smbSessionSetup)
if err != nil {
return nil, fmt.Errorf("发送SMB Session Setup失败: %w", err)
}
response2 := make([]byte, 2048)
n, err := conn.Read(response2)
if err != nil {
return nil, fmt.Errorf("读取SMB Session Setup响应失败: %w", err)
}
return p.parseNetBIOSSession(response2[:n])
}
// parseNetBIOSNames 解析NetBIOS名称查询响应
func (p *NetBIOSPlugin) parseNetBIOSNames(data []byte) (*NetBIOSInfo, error) {
info := &NetBIOSInfo{Valid: false}
if len(data) < 57 {
return info, fmt.Errorf("NetBIOS响应数据过短")
}
// 获取名称记录数量
numNames := int(data[56])
if numNames == 0 {
return info, fmt.Errorf("没有NetBIOS名称记录")
}
nameData := data[57:]
// 服务类型映射
uniqueNames := map[byte]string{
0x00: "WorkstationService",
0x03: "Messenger Service",
0x06: "RAS Server Service",
0x1F: "NetDDE Service",
0x20: "ServerService",
0x21: "RAS Client Service",
0x1D: "Master Browser",
0x1B: "Domain Master Browser",
}
groupNames := map[byte]string{
0x00: "DomainName",
0x1C: "DomainControllers",
0x1E: "Browser Service Elections",
}
info.Valid = true
// 解析每个名称记录
for i := 0; i < numNames && len(nameData) >= 18*(i+1); i++ {
offset := 18 * i
name := strings.TrimSpace(string(nameData[offset : offset+15]))
flagByte := nameData[offset+15]
if len(nameData) >= 18*(i+1) {
nameFlags := nameData[offset+16]
if nameFlags >= 128 {
// 组名称
if service, exists := groupNames[flagByte]; exists {
switch service {
case "DomainName":
info.DomainName = name
case "DomainControllers":
info.DomainControllers = name
}
}
} else {
// 唯一名称
if service, exists := uniqueNames[flagByte]; exists {
switch service {
case "WorkstationService":
info.WorkstationService = name
case "ServerService":
info.ServerService = name
}
}
}
}
}
return info, nil
}
// parseNetBIOSSession 解析NetBIOS会话响应
func (p *NetBIOSPlugin) parseNetBIOSSession(data []byte) (*NetBIOSInfo, error) {
info := &NetBIOSInfo{Valid: false}
if len(data) < 47 {
return info, fmt.Errorf("SMB响应数据过短")
}
info.Valid = true
// 解析OS版本信息
blobLength := int(data[43]) + int(data[44])*256
if len(data) >= 48+blobLength {
osVersion := data[47+blobLength:]
osText := p.cleanOSString(osVersion)
if osText != "" {
info.OSVersion = osText
}
}
// 查找NTLM数据
ntlmStart := bytes.Index(data, []byte("NTLMSSP"))
if ntlmStart != -1 && len(data) > ntlmStart+45 {
p.parseNTLMInfo(data[ntlmStart:], info)
}
return info, nil
}
// parseNTLMInfo 解析NTLM信息
func (p *NetBIOSPlugin) parseNTLMInfo(data []byte, info *NetBIOSInfo) {
if len(data) < 45 {
return
}
// 获取Target Info偏移和长度
targetInfoLength := int(data[40]) + int(data[41])*256
targetInfoOffset := int(data[44])
if targetInfoOffset+targetInfoLength > len(data) {
return
}
// 解析AV_PAIR结构
targetInfo := data[targetInfoOffset : targetInfoOffset+targetInfoLength]
offset := 0
for offset+4 <= len(targetInfo) {
avId := int(targetInfo[offset]) + int(targetInfo[offset+1])*256
avLen := int(targetInfo[offset+2]) + int(targetInfo[offset+3])*256
if avId == 0x0000 || offset+4+avLen > len(targetInfo) {
break
}
value := p.parseUnicodeString(targetInfo[offset+4 : offset+4+avLen])
switch avId {
case 0x0001: // NetBIOS computer name
info.NetBIOSComputerName = value
case 0x0002: // NetBIOS domain name
info.NetBIOSDomainName = value
case 0x0003: // DNS computer name
if info.ComputerName == "" {
info.ComputerName = value
}
case 0x0004: // DNS domain name
if info.DomainName == "" {
info.DomainName = value
}
}
offset += 4 + avLen
}
}
// cleanOSString 清理操作系统字符串
func (p *NetBIOSPlugin) cleanOSString(data []byte) string {
// 移除NULL字节并分割
cleaned := bytes.ReplaceAll(data, []byte{0x00, 0x00}, []byte{124})
cleaned = bytes.ReplaceAll(cleaned, []byte{0x00}, []byte{})
if len(cleaned) == 0 {
return ""
}
// 移除最后的分隔符
if cleaned[len(cleaned)-1] == 124 {
cleaned = cleaned[:len(cleaned)-1]
}
osText := string(cleaned)
parts := strings.Split(osText, "|")
if len(parts) > 0 {
return parts[0]
}
return ""
}
// parseUnicodeString 解析Unicode字符串
func (p *NetBIOSPlugin) parseUnicodeString(data []byte) string {
if len(data)%2 != 0 {
return ""
}
var result []rune
for i := 0; i < len(data); i += 2 {
if i+1 >= len(data) {
break
}
// UTF-16LE编码
char := uint16(data[i]) | uint16(data[i+1])<<8
if char == 0 {
break
}
result = append(result, rune(char))
}
return string(result)
}
// init 自动注册插件
func init() {
// 使用高效注册方式:直接传递端口信息,避免实例创建
RegisterPluginWithPorts("netbios", func() Plugin {
return NewNetBIOSPlugin()
}, []int{137, 139})
}