Build.rs with elevated privileges?

Is there a proper way to use elevated privileges in a build.rs script?

I am trying to use setcap to allow a binary to use libpcap without running as sudo, by way of pcap 0.7.0 - Docs.rs.

Here is my current build.rs -- it asks for my sudo password and exit status of cargo build is 0, but it doesn't look like it works (getcap doesn't show any extra capabilities on the resulting binary).

use std::process::Command;

fn main() {
    Command::new("sudo")
        .args(&[
                "setcap",
                "cap_net_raw,cap_net_admin=eip",
                "/path/to/binary"
        ])
        .status()
        .unwrap();
}

Maybe it has to do with the order that the build script runs (e.g. before the binary is finalized)?

Should I just be using a Makefile for this kind of thing?

build.rs runs first, before anything else is built. The binary won't exist at that point (at best, it'll be an older out of date copy).

Cargo doesn't have support for any actions after the build, so you'll have to wrap cargo in another script or build system for this.

2 Likes

That's what I figured, thanks. Makefile it is!

1 Like