Linux 默认不提供 Yara 预编译包,需自行构建。本文介绍使用 Ubuntu 22 作为构建机器,通过 musl 工具链静态编译二进制文件,使其可在 CentOS 7 等低版本 glibc 系统上运行。
通过 Cargo 编译 Yara-x 项目,可生成不依赖系统动态库的二进制文件。
Yara-x 默认使用动态链接 glibc,在 Ubuntu 22.04(glibc 2.35)编译的二进制无法在 CentOS 7(glibc 2.17)上运行,会报版本不兼容错误。
解决方案是使用 musl libc 进行静态链接编译。
首先安装 Rust 工具链并配置国内镜像源:
export RUSTUP_DIST_SERVER="https://rsproxy.cn"
export RUSTUP_UPDATE_ROOT="https://rsproxy.cn/rustup"
curl --proto '=https' --tlsv1.2 -sSf https://rsproxy.cn/rustup-init.sh | sh
source ~/.cargo/env
配置 Cargo 使用字节跳动镜像源:
cat <<EOF > ~/.cargo/config.toml
[source.crates-io]
replace-with = 'rsproxy-sparse'
[source.rsproxy]
registry = "https://rsproxy.cn/crates.io-index"
[source.rsproxy-sparse]
registry = "sparse+https://rsproxy.cn/index/"
[registries.rsproxy]
index = "https://rsproxy.cn/crates.io-index"
[net]
git-fetch-with-cli = true
EOF
安装 musl 工具链并配置链接器:
sudo apt install musl-tools gcc
rustup target add x86_64-unknown-linux-musl
cat >> ~/.cargo/config.toml << EOF
[target.x86_64-unknown-linux-musl]
linker = "musl-gcc"
EOF
拉取 Yara-x 源码并执行静态编译:
git clone https://github.com/VirusTotal/yara-x.git
cd yara-x
cargo build --release \
--target x86_64-unknown-linux-musl \
-p yara-x-cli
验证编译产物为静态链接:
ldd target/x86_64-unknown-linux-musl/release/yr
# 期望输出:not a dynamic executable
file target/x86_64-unknown-linux-musl/release/yr
# 期望输出:statically linked
构建完成后,二进制文件可在任意 Linux 发行版上运行,无需考虑 glibc 版本差异。
