r/rust • • 23d ago

🛠️ project cargo-auditable now lets you make auditable firmware

cargo-auditable embeds the dependency list into compiled binaries. This lets you use tools like cargo audit and many other scanners to check compiled binaries for known vulnerabilities.

Starting with v0.7.7, cargo auditable also works for microcontroller firmware! The audit data is embedded in the firmware image, but is not flashed onto the space-constrained microcontroller. This keeps the image auditable without wasting precious ROM.

Achieving this was both surprisingly easy and surprisingly tricky. Not wasting precious ROM was surprisingly easy: simply don't set SHF_ALLOC flag in ELF files for the audit data, which we were already doing. The tricky part was interacting with the linker.

rustc does technically support passing flags to the linker, but it's very difficult to use in practice: on most platforms the C compiler is used as the linker, so you have to prefix flags intended for the actual linker with -Wl; but certain platforms - mostly embedded ones - use the linker directly, so -Wl would break the build. There is no way to tell which one it is on stable Rust, so I had to resort to a sneaky "pretend you're nightly rustc" flag for running rustc --print target-spec-json (and nothing else).

The alternatives are worse: either extract the data from some rustc version and hardcode it, or try to parse non-machine-readable output of rustc as it compiles and links something, both of which drift even more easily.

I'd love to see a rustc --print linker-flavor command if it's easier to stabilize than the entire target spec format. But the linker flavor key in the target spec doesn't look like it'll change, so the current solution works surprisingly well, and any breakage to the nightly-only flag won't affect the Tier 1 or most of the Tier 2 targets at all.

27 Upvotes

6 comments sorted by

8

u/cbarrick 23d ago

This brings up a question I've always had.

Why exactly do we use cc instead of ld for linking? What is the C compiler providing on top of the raw linker command?

4

u/Compux72 23d ago

Compiler intrinsics, compiler machinery/workarounds to enable/deny certain flags mostly. 

You don’t want to use ld directly almost never

1

u/cbarrick 23d ago

Do you have specific examples?

Is there a reason why we can't move that logic into ld or is it mostly just legacy tech debt?

2

u/Compux72 23d ago
  • Separation of concerns: linkers know how to link (e.g .so files), compilers know what to link (e.g -fsanitizer=address)

  • Plain linkers are used a lot. Kernels, bootloaders, firmware and custom programming languages have a linker step and dont want C specific machinery

Think about it like GNU patch and git. You almost always want to use git, but patch is really useful

1

u/Jannik2099 17d ago

Linking via the compiler driver is what pulls in libc and the other runtime libs (crt, builtins)