secml-malware python library 源码分析及实践

Github地址:https://github.com/pralab/secml_malware

可以按照库的readme,通过pip安装

因为我需要对于库源码进行较大的改动,可以我通过以下方式安装

bash 复制代码
# 克隆源码
git clone https://github.com/pralab/secml_malware.git
cd secml_malware

# 创建虚拟环境
conda create -n secml_malware_local_env python=3.9
conda activate secml_malware_local_env

# 安装依赖
pip install -r requirements.txt
# 如果ember库安装失败,可以手动下载到本地安装(需要注释掉 requirements.txt中的git+https://github.com/zangobot/ember.git)
git clone https://github.com/zangobot/ember.git
cd ember
pip install .

# 关键:用"开发模式"安装secml-malware(Python import 的就是你当前目录源码)
pip install -e .

运行攻击代码示例代码:

python 复制代码
import numpy as np
from pathlib import Path

from secml.array import CArray
from secml_malware.models.malconv import MalConv
from secml_malware.models.c_classifier_end2end_malware import CClassifierEnd2EndMalware
from secml_malware.attack.blackbox.c_wrapper_phi import CEnd2EndWrapperPhi
from secml_malware.attack.blackbox.c_black_box_padding_evasion import CBlackBoxPaddingEvasionProblem
from secml_malware.attack.blackbox.ga.c_base_genetic_engine import CGeneticAlgorithm


# ===============================
# Load model
# ===============================
print("[*] Loading model...")
model = MalConv()
clf = CClassifierEnd2EndMalware(model)
clf.load_pretrained_model()
clf._model = clf._model.cpu()

net = CEnd2EndWrapperPhi(clf)


# ===============================
# Save adversarial sample
# ===============================
def save_adv(x_adv, path):
    arr = x_adv.tondarray().flatten()
    
    # 去 padding(256)
    arr = arr[arr != 256]
    
    # 限制范围
    arr = np.clip(arr, 0, 255)
    
    # 转 uint8
    arr = arr.astype(np.uint8)
    
    with open(path, "wb") as f:
        f.write(bytes(arr))


# ===============================
# Paths
# ===============================
samples_dir = Path("/data/xjw/workspace/dataset/sorel-20m/benign/")
out_dir = Path("results")
adv_dir = out_dir / "adv"
out_dir.mkdir(exist_ok=True)
adv_dir.mkdir(exist_ok=True)


# ===============================
# Attack loop
# ===============================
for i, sample_path in enumerate(samples_dir.iterdir()):
    if i >= 100:
        break
    if not sample_path.is_file():
        continue

    print(f"\n[*] {sample_path.name}")

    # 读取文件
    with open(sample_path, "rb") as f:
        code = f.read()

    x = CArray(np.frombuffer(code, dtype=np.uint8)).atleast_2d()

    # 原始预测
    _, conf = net.predict(x, True)
    orig_conf = conf[0, 1].item()
    print(f"    Original confidence: {orig_conf:.4f}")

    # 只攻击 benign
    if orig_conf >= 0.5:
        print("    Skip (already malware)")
        continue

    # 构建攻击
    problem = CBlackBoxPaddingEvasionProblem(
        net,
        how_many_padding_bytes=20000,
        population_size=50,
        iterations=100
    )

    ga = CGeneticAlgorithm(problem)

    # 运行攻击
    y_pred, adv_score, adv_ds, _ = ga.run(x, CArray([orig_conf]))

    final_conf = ga.confidences_[-1]
    print(f"    Final confidence: {final_conf:.4f}")

    # 保存结果
    adv_path = adv_dir / f"{sample_path.stem}_adv.exe"
    save_adv(adv_ds.X[0, :], adv_path)

    print(f"    Saved → {adv_path.name}")
相关推荐
“AI国潮设计-小江”8 小时前
《Python+SDXL实战:用ControlNet精准控制“英歌舞翻糖吐司”构图,附批量生成脚本》
开发语言·人工智能·python·prompt·aigc
程序喵大人8 小时前
【C++入门】编译链接模型 - 01 一个 C++ 程序是怎样变成可执行文件的
开发语言·c++·编译链接模型
wenwen_chao8 小时前
Python学习与开发资源合集:实用技巧与工具推荐
python
for_ever_love__9 小时前
函数——参数、lambda、*args与作用域
python·函数·大模型开发·编程基础
东莞市云毅网络有限公司9 小时前
企业资料时效性判定:Last-Modified、正文日期与版本字段三路交叉
python·sqlite·自动化运维·geo·数据监测
Query*9 小时前
深入浅出LangGraph【一】_基础篇
python·ai·langchain
sunshine22 girl9 小时前
Java学习七 Java 项目实战1-项目创建和主页面搭建
java·开发语言·学习
XiaoMaqqqq10 小时前
市面上正规的IP驱动产业新场景新工具哪家强
运维·python·网络协议·tcp/ip
菜鸟~noob23310 小时前
【电子战】第三季预告—波武器与电子系统强力毁伤
开发语言·数据库·matlab·电子战
ShyanZh10 小时前
【Python3基础】19-Socket 与 TCP、UDP 编程
python·网络协议·tcp/ip·udp