Communitygithub.com

bg-szy/TOP-SKILLS

使用模块化的 Rust 模糊测试库 LibAFL 构建自定义模糊测试器。涵盖将观察器、反馈、变异器、调度器和执行器组合成适用于标准工具无法适配的目标的模糊测试器。当需要编写定制模糊测试器或变异器、模糊非标准目标或架构、实现模糊测试研究思路,或 libFuzzer 和 AFL++ 无法提供所需控制时使用。

TOP-SKILLS 是什么?

该技能专注于使用 LibAFL 构建自定义模糊测试器,LibAFL 是一个模块化的 Rust 模糊测试库,从 AFL 类模糊测试器(如 AFL++)中提取功能并以高度可组合的方式实现。与适用于快速设置的传统模糊测试器(如 libFuzzer 或 AFL++)不同,LibAFL 提供对观察器、反馈、变异器、调度器和执行器等组件的细粒度控制。该技能通过在 SKILL.md 中提供明确定义的使用场景(例如自定义变异策略、非标准架构或新颖技术),帮助用户确定何时选择 LibAFL。它支持两种主要模式:libFuzzer 的即插即用替代模式(用于最小化设置)和全面的 Rust 库模式(用于完全定制)。文档包括详细的快速入门指南、安装说明(涵盖针对 Linux/macOS 的 Clang/LLVM 和 Rust 依赖项)、完整模糊测试器的逐步示例(演示每个组件的集成)以及诸如崩溃去重、字典模糊测试和性能调优等高级主题。此外,还提供了现实世界的示例(例如对 libpng 进行模糊测试以及集成到基于 CMake 的项目中),使该技能对于希望突破标准模糊测试工具限制的开发人员和研究人员来说至关重要。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/bg-szy/TOP-SKILLS/tree/HEAD/skills/skills/libafl

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

LibAFL

LibAFL 是一个模块化的模糊测试库,实现了基于 AFL 的模糊测试器(如 AFL++)的功能。与传统的模糊测试器不同,LibAFL 以 Rust 库的形式提供所有功能,使其模块化且高度可定制。它可以作为 libFuzzer 的即插即用替代品,也可以作为从头构建自定义模糊测试器的库。

何时使用

模糊测试器最适合复杂度
libFuzzer快速设置,单线程低
AFL++多核,通用中
LibAFL自定义模糊测试器,高级功能,研究高

选择 LibAFL 当:

  • 你需要自定义的变异策略或反馈机制
  • 标准模糊测试器不支持你的目标架构
  • 你想要实现新颖的模糊测试技术
  • 你需要对模糊测试组件进行细粒度控制
  • 你正在进行模糊测试研究

快速开始

LibAFL 可以作为 libFuzzer 的即插即用替代品,只需最少的设置:

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
    // 使用模糊测试器提供的数据调用你的代码
    my_function(data, size);
    return 0;
}

构建 LibAFL 的 libFuzzer 兼容层:

git clone https://github.com/AFLplusplus/LibAFL
cd LibAFL/libafl_libfuzzer_runtime
./build.sh

编译并运行:

clang++ -DNO_MAIN -g -O2 -fsanitize=fuzzer-no-link libFuzzer.a harness.cc main.cc -o fuzz
./fuzz corpus/

安装

先决条件

  • Clang/LLVM 15-18
  • Rust (通过 rustup)
  • 额外的系统依赖项

Linux/macOS

安装 Clang:

apt install clang

或通过 apt.llvm.org 安装特定版本:

wget https://apt.llvm.org/llvm.sh
chmod +x llvm.sh
sudo ./llvm.sh 15

为 Rust 配置环境:

export RUSTFLAGS="-C linker=/usr/bin/clang-15"
export CC="clang-15"
export CXX="clang++-15"

安装 Rust:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

安装额外的依赖项:

apt install libssl-dev pkg-config

对于 libFuzzer 兼容模式,安装 Rust nightly 版本:

rustup toolchain install nightly --component llvm-tools

验证

构建 LibAFL 以验证安装:

cd LibAFL/libafl_libfuzzer_runtime
./build.sh
# 应该生成 libFuzzer.a

编写测试用例

当使用即插即用替代模式时,LibAFL 的测试用例遵循与 libFuzzer 相同的模式:

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
    // 你的模糊测试目标代码放在这里
    return 0;
}

当使用 LibAFL 作为 Rust 库构建自定义模糊测试器时,测试用例逻辑直接集成到模糊测试器中。有关完整模式,请参阅下面的“编写自定义模糊测试器”部分。

另请参阅: 有关详细的测试用例编写技术,请参阅 harness-writing 技术技能。

使用模式

LibAFL 支持两种主要使用模式:

1. libFuzzer 即插即用替代

使用 LibAFL 替换 libFuzzer 与现有测试用例。

编译:

clang++ -DNO_MAIN -g -O2 -fsanitize=fuzzer-no-link libFuzzer.a harness.cc main.cc -o fuzz

运行:

./fuzz corpus/

建议用于长时间运行的测试活动:

./fuzz -fork=1 -ignore_crashes=1 corpus/

2. 作为 Rust 库的自定义模糊测试器

使用 LibAFL 组件构建完全自定义的模糊测试器。

创建项目:

cargo init --lib my_fuzzer
cd my_fuzzer
cargo add [email protected] [email protected] [email protected] [email protected] \
  --features "[email protected]/libfuzzer,[email protected]/sancov_pcguard_hitcounts"

配置 Cargo.toml:

[lib]
crate-type = ["staticlib"]

编写自定义模糊测试器

另请参阅: 有关详细的测试用例编写技术、处理复杂输入的模式以及高级策略,请参阅 fuzz-harness-writing 技术技能。

模糊测试器组件

一个 LibAFL 模糊测试器由模块化组件组成:

  1. 观察器 - 收集执行反馈(覆盖率、时间)
  2. 反馈 - 确定输入是否有趣
  3. 目标 - 定义模糊测试目标(崩溃、超时)
  4. 状态 - 维护语料库和元数据
  5. 变异器 - 生成新输入
  6. 调度器 - 选择要变异的输入
  7. 执行器 - 使用输入运行目标

基本模糊测试器结构

use libafl::prelude::*;
use libafl_bolts::prelude::*;
use libafl_targets::{libfuzzer_test_one_input, std_edges_map_observer};

#[no_mangle]
pub extern "C" fn libafl_main() {
    let mut run_client = |state: Option<_>, mut restarting_mgr, _core_id| {
        // 1. 设置观察器
        let edges_observer = HitcountsMapObserver::new(
            unsafe { std_edges_map_observer("edges") }
        ).track_indices();
        let time_observer = TimeObserver::new("time");

        // 2. 定义反馈
        let mut feedback = feedback_or!(
            MaxMapFeedback::new(&edges_observer),
            TimeFeedback::new(&time_observer)
        );

        // 3. 定义目标
        let mut objective = feedback_or_fast!(
            CrashFeedback::new(),
            TimeoutFeedback::new()
        );

        // 4. 创建或恢复状态
        let mut state = state.unwrap_or_else(|| {
            StdState::new(
                StdRand::new(),
                InMemoryCorpus::new(),
                OnDiskCorpus::new(&output_dir).unwrap(),
                &mut feedback,
                &mut objective,
            ).unwrap()
        });

        // 5. 设置变异器
        let mutator = StdScheduledMutator::new(havoc_mutations());
        let mut stages = tuple_list!(StdMutationalStage::new(mutator));

        // 6. 设置调度器
        let scheduler = IndexesLenTimeMinimizerScheduler::new(
            &edges_observer,
            QueueScheduler::new()
        );

        // 7. 创建模糊测试器
        let mut fuzzer = StdFuzzer::new(scheduler, feedback, objective);

        // 8. 定义测试用例
        let mut harness = |input: &BytesInput| {
            let buf = input.target_bytes().as_slice();
            libfuzzer_test_one_input(buf);
            ExitKind::Ok
        };

        // 9. 设置执行器
        let mut executor = InProcessExecutor::with_timeout(
            &mut harness,
            tuple_list!(edges_observer, time_observer),
            &mut fuzzer,
            &mut state,
            &mut restarting_mgr,
            timeout,
        )?;

        // 10. 加载初始输入
        if state.must_load_initial_inputs() {
            state.load_initial_inputs(
                &mut fuzzer,
                &mut executor,
                &mut restarting_mgr,
                &input_dir
            )?;
        }

        // 11. 开始模糊测试
        fuzzer.fuzz_loop(&mut stages, &mut executor, &mut state, &mut restarting_mgr)?;
        Ok(())
    };

    // 启动模糊测试器
    Launcher::builder()
        .run_client(&mut run_client)
        .cores(&cores)
        .build()
        .launch()
        .unwrap();
}

编译

详细模式

手动指定所有插桩标志:

clang++-15 -DNO_MAIN -g -O2 \
  -fsanitize-coverage=trace-pc-guard \
  -fsanitize=address \
  -Wl,--whole-archive target/release/libmy_fuzzer.a -Wl,--no-whole-archive \
  main.cc harness.cc -o fuzz

编译器包装器(推荐)

创建一个 LibAFL 编译器包装器以自动处理插桩。

创建 src/bin/libafl_cc.rs:

use libafl_cc::{ClangWrapper, CompilerWrapper, Configuration, ToolWrapper};

pub fn main() {
    let args: Vec<String> = env::args().collect();
    let mut cc = ClangWrapper::new();
    cc.cpp(is_cpp)
      .parse_args(&args)
      .link_staticlib(&dir, "my_fuzzer")
      .add_args(&Configuration::GenerateCoverageMap.to_flags().unwrap())
      .add_args(&Configuration::AddressSanitizer.to_flags().unwrap())
      .run()
      .unwrap();
}

编译并使用:

cargo build --release
target/release/libafl_cxx -DNO_MAIN -g -O2 main.cc harness.cc -o fuzz

另请参阅: 有关详细的 sanitizer 配置、常见问题和高级标志,请参阅 address-sanitizer 和 undefined-behavior-sanitizer 技术技能。

运行测试活动

基本运行

./fuzz --cores 0 --input corpus/

多核模糊测试

./fuzz --cores 0,8-15 --input corpus/

这将运行 9 个客户端:一个在核心 0 上,8 个在核心 8-15 上。

带选项运行

./fuzz --cores 0-7 --input corpus/ --output crashes/ --timeout 1000

文本用户界面 (TUI)

启用图形化统计视图:

./fuzz -tui=1 corpus/

解释输出

输出含义
corpus: N找到的有趣测试用例数量
objectives: N找到的崩溃/超时数量
executions: N目标的总调用次数
exec/sec: N当前执行吞吐量
edges: X%代码覆盖率百分比
clients: N并行模糊测试进程数量

模糊测试器发出两种主要事件类型:

  • UserStats - 包含当前统计信息的常规心跳
  • Testcase - 发现新的有趣输入

高级用法

提示和技巧

提示为何有帮助
使用 -fork=1 -ignore_crashes=1在首次崩溃后继续模糊测试
使用 InMemoryOnDiskCorpus跨重启持久化语料库
使用 -tui=1 启用 TUI更好地可视化进度
使用特定的 LLVM 版本避免兼容性问题
正确设置 RUSTFLAGS防止链接错误

崩溃去重

避免存储来自同一错误的重复崩溃:

添加回溯观察器:

let backtrace_observer = BacktraceObserver::owned(
    "BacktraceObserver",
    libafl::observers::HarnessType::InProcess
);

更新执行器:

let mut executor = InProcessExecutor::with_timeout(
    &mut harness,
    tuple_list!(edges_observer, time_observer, backtrace_observer),
    &mut fuzzer,
    &mut state,
    &mut restarting_mgr,
    timeout,
)?;

使用哈希反馈更新目标:

let mut objective = feedback_and!(
    feedback_or_fast!(CrashFeedback::new(), TimeoutFeedback::new()),
    NewHashFeedback::new(&backtrace_observer)
);

这确保了只保存具有唯一回溯的崩溃。

字典模糊测试

使用字典引导模糊测试朝向特定标记:

从文件添加标记:

let mut tokens = Tokens::new();
if let Some(tokenfile) = &tokenfile {
    tokens.add_from_file(tokenfile)?;
}
state.add_metadata(tokens);

更新变异器:

let mutator = StdScheduledMutator::new(
    havoc_mutations().merge(tokens_mutations())
);

硬编码标记示例 (PNG):

state.add_metadata(Tokens::from([
    vec![137, 80, 78, 71, 13, 10, 26, 10], // PNG 头部
    "IHDR".as_bytes().to_vec(),
    "IDAT".as_bytes().to_vec(),
    "PLTE".as_bytes().to_vec(),
    "IEND".as_bytes().to_vec(),
]));

另请参阅: 有关详细的字典创建策略和特定格式的字典,请参阅 fuzzing-dictionaries 技术技能。

自动标记

自动从程序中提取魔数和校验和:

在编译器包装器中启用:

cc.add_pass(LLVMPasses::AutoTokens)

在模糊测试器中加载自动标记:

tokens += libafl_targets::autotokens()?;

验证标记部分:

echo "p (uint8_t *)__token_start" | gdb fuzz

性能调优

设置影响
多核模糊测试核心数线性加速
InMemoryCorpus更快但非持久化
InMemoryOnDiskCorpus平衡速度和持久性
Sanitizer2-5 倍减速,对发现错误至关重要
优化级别 -O2平衡速度和覆盖率

调试模糊测试器

在单进程模式下运行模糊测试器以便于调试:

// 替换启动器为直接调用
run_client(None, SimpleEventManager::new(monitor), 0).unwrap();

// 注释掉:
// Launcher::builder()
//     .run_client(&mut run_client)
//     ...
//     .launch()

然后使用 GDB 调试:

gdb --args ./fuzz --cores 0 --input corpus/

现实世界示例

示例:libpng

使用 LibAFL 模糊测试 libpng:

1. 获取源代码:

curl -L -O https://downloads.sourceforge.net/project/libpng/libpng16/1.6.37/libpng-1.6.37.tar.xz
tar xf libpng-1.6.37.tar.xz
cd libpng-1.6.37/
apt install zlib1g-dev

2. 设置编译器包装器:

export FUZZER_CARGO_DIR="/path/to/libafl/project"
export CC=$FUZZER_CARGO_DIR/target/release/libafl_cc
export CXX=$FUZZER_CARGO_DIR/target/release/libafl_cxx

3. 构建静态库:

./configure --enable-shared=no
make

4. 获取测试用例:

curl -O https://raw.githubusercontent.com/glennrp/libpng/f8e5fa92b0e37ab597616f554bee254157998227/contrib/oss-fuzz/libpng_read_fuzzer.cc

5. 链接模糊测试器:

$CXX libpng_read_fuzzer.cc .libs/libpng16.a -lz -o fuzz

6. 准备种子:

mkdir seeds/
curl -o seeds/input.png https://raw.githubusercontent.com/glennrp/libpng/acfd50ae0ba3198ad734e5d4dec2b05341e50924/contrib/pngsuite/iftp1n3p08.png

7. 获取字典(可选):

curl -O https://raw.githubusercontent.com/glennrp/libpng/2fff013a6935967960a5ae626fc21432807933dd/contrib/oss-fuzz/png.dict

8. 开始模糊测试:

./fuzz --input seeds/ --cores 0 -x png.dict

示例:CMake 项目

将 LibAFL 集成到 CMake 构建系统中:

CMakeLists.txt:

project(BuggyProgram)
cmake_minimum_required(VERSION 3.0)

add_executable(buggy_program main.cc)

add_executable(fuzz main.cc harness.cc)
target_compile_definitions(fuzz PRIVATE NO_MAIN=1)
target_compile_options(fuzz PRIVATE -g -O2)

构建未插桩的二进制文件:

cmake -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ .
cmake --build . --target buggy_program

构建模糊测试器:

export FUZZER_CARGO_DIR="/

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

bg-szy/TOP-SKILLS

Brand-first landing page designer — runs a brand-identity interview (colors, typography, shape language), then generates and iterates on a polished landing page via Stitch with deployment-ready HTML. Use when the user asks to create, design, or build a landing page, homepage, or marketing page and has no established visual direction. Skip when they have a design mockup, need a dashboard or app UI, are working at component level, building a multi-page app, or restyling with known design tokens — use frontend-design instead.

bg-szy/TOP-SKILLS

Fill out Microsoft Azure Landing Zone (ALZ) Accelerator checklists by interviewing the user, mapping their Azure subscriptions, integrating IP addressing documentation, and applying Microsoft Cloud Adoption Framework best practices. Produces a completed Excel checklist (.xlsx) ready for ALZ deployment. Use this skill whenever the user mentions Azure Landing Zone, ALZ checklist, landing zone accelerator, platform landing zone configuration, ALZ bootstrap, hub-and-spoke setup, Azure network topology planning, or wants to fill out any ALZ-related checklist or configuration file. Also trigger when the user uploads an Excel file that contains tabs like "Accelerator - Bootstrap", "Accelerator - Bicep", or "Accelerator - Terraform".

bg-szy/TOP-SKILLS

Compose a premium, animated landing page section by section in Next.js + Tailwind + Motion (Framer Motion) — built on a real design system, with editorial copy and motion that feels human-crafted, not template-generated. Use when building or rebuilding a landing page, marketing site, or hero/feature/pricing/CTA sections that need to look production-ready and bespoke from day one.

bg-szy/TOP-SKILLS

Write high-converting landing page copy using proven frameworks like PAS (Problem-Agitate-Solution), AIDA, and StoryBrand. Creates headlines, value propositions, CTAs, and full page sections optimized for conversion. Use when users need landing page copy, sales page content, or marketing website text.

bg-szy/TOP-SKILLS

Optimize landing pages for conversions, performance, and SEO. Use when improving landing pages, increasing conversions, or optimizing page performance.

bg-szy/TOP-SKILLS

Review investment portfolios for risk, diversification, fees. Asset allocation recommendations, tax-loss harvesting, rebalancing.

bg-szy/TOP-SKILLS

Beads Viewer - Graph-aware triage engine for Beads projects. Computes PageRank, betweenness, critical path, and cycles. Use --robot-* flags for AI agents.

bg-szy/TOP-SKILLS

CI red? Call us. Pipeline fire brigade deploys. Use when user mentions CI failures, build errors, test failures, or pipeline issues. Do NOT load for: local builds, standard implementation work, reviews, or setup.

bg-szy/TOP-SKILLS

CASS Memory System - procedural memory for AI coding agents. Three-layer cognitive architecture with confidence decay, anti-pattern learning, cross-agent knowledge transfer, trauma guard safety system. Bun/TypeScript CLI.

bg-szy/TOP-SKILLS

Mandatory entry point: read this first for any request to make, create, edit, animate, or render a video, animation, or motion graphic, including a promo, explainer, captioned clip, title card, overlay, slideshow or interactive deck, Remotion port, or any HyperFrames HTML composition. Also use it to inspect, diagnose, validate, preview, publish, or batch-render an existing HyperFrames project. Inputs may be a website URL, GitHub PR, Figma design or URL, text or brief, existing footage, or music. It resumes project state, captures intent when applicable, selects and installs the owning workflow, and routes domain capabilities. HyperFrames is the default output framework unless the user explicitly chooses another framework for the deliverable or asks only to record a browser session.

bg-szy/TOP-SKILLS

Expert in building portfolios that actually land jobs and clients - not just showing work, but creating memorable experiences. Covers developer portfolios, designer portfolios, creative portfolios, and portfolios that convert visitors into opportunities.

bg-szy/TOP-SKILLS

Use when the user asks to "pre-launch check the landing page", "run a Quality-Score preflight", or "verify ad-to-page message match before launch"; produces an ad↔page continuity report — message-match gaps, above-the-fold check, page-speed read, form-friction count, mobile-render flags — as a pass/fix punch list. Not for redesigning or rewriting the page — use landing-optimizer; not for scoring the account or the RQS — use ad-account-auditor. 落地页体验预检/广告落地页一致性检查

bg-szy/TOP-SKILLS

Use when the user asks to "optimize our landing page for influencer traffic", "fix our promo-code landing page", or "improve conversion from a creator campaign"; produces a message-match audit, page-structure and social-proof recommendations, a promo-code/CTA conversion plan, and an A/B test roadmap. Not for measuring campaign results after launch — use performance-analyzer.

bg-szy/TOP-SKILLS

Audit a landing page, sales page or checkout page for conversion leaks and return a fix list ordered by expected revenue impact. Use when asked to review, critique or improve a landing page, sales page, opt-in page, product page or checkout flow, when conversion rate is low, when paid traffic is not converting, or when someone asks "why isn't this page converting" or wants a CRO / landing page review.

bg-szy/TOP-SKILLS

Landing page conversion optimization with layout rules, hero section design, and CTA psychology. Covers above-the-fold formula, social proof placement, mobile design, and F-pattern reading. Use for: startup landing pages, product pages, SaaS marketing, conversion optimization. Triggers: landing page, hero section, above the fold, conversion optimization, landing page design, cta button, hero image, landing page layout, saas landing page, product page design, conversion rate, landing page best practices

bg-szy/TOP-SKILLS

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

bg-szy/TOP-SKILLS

Landing page conversion optimization with layout rules, hero section design, and CTA psychology. Covers above-the-fold formula, social proof placement, mobile design, and F-pattern reading. Use for: startup landing pages, product pages, SaaS marketing, conversion optimization. Triggers: landing page, hero section, above the fold, conversion optimization, landing page design, cta button, hero image, landing page layout, saas landing page, product page design, conversion rate, landing page best practices

bg-szy/TOP-SKILLS

Account assets, equity and fund positions, P&L, cash flow records, account statements, margin ratios, buy-power estimates, order management, and DCA recurring investments via Longbridge (most require Trade permission). Frameworks: portfolio diagnosis, rebalancing, asset allocation, risk analysis (VaR/CVaR), performance attribution, and tax-loss harvesting. Triggers: "持仓", "账户", "盈亏", "资产", "对账单", "下单", "买入", "卖出", "撤单", "定投", "组合诊断", "再平衡", "资产配置", "风险分析", "绩效归因", "税损收割", "持倉", "賬戶", "盈虧", "對賬單", "下單", "買入", "賣出", "組合診斷", "再平衡", "稅損收割", "positions", "portfolio", "P&L", "order", "buy", "sell", "DCA", "statement", "risk analysis", "rebalancing", "tax harvesting", "我的风险", "持仓风险", "风险敞口", "資產", "資產配置", "風險分析", "績效歸因", "撤單

bg-szy/TOP-SKILLS

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

bg-szy/TOP-SKILLS

Process video files with audio extraction, format conversion (mp4, webm), and Whisper transcription. Use when user mentions video conversion, audio extraction, transcription, mp4, webm, ffmpeg, or whisper transcription.

相关技能