How do I set the Windows execution level to ask user for administrator privileges for a Rust program?

Viewed 2196

I'm writing a Windows CLI app and I need to run it as administrator. In C# I would add this line to app.manifest:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> 

How I do that in Rust?

2 Answers

Too late, but answering anyway. :-)

Please take a look at the winres library. It contains the following example:

The following manifest will brand the exe as requesting administrator privileges. Thus, everytime it is executed, a Windows UAC dialog will appear.

let mut res = winres::WindowsResource::new();
res.set_manifest(r#"
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
    <security>
        <requestedPrivileges>
            <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
        </requestedPrivileges>
    </security>
</trustInfo>
</assembly>
"#);

The full example is documented and available here.

I have been using this library in a project that contains an icon and requires admin privileges, its build.rs using winres is hosted here. See the generated executable: enter image description here

HTH

There is an open RFC #721 for manifest support in Rust.

Aside from discussing ways to add native support, the posts contain links to various workarounds using linker switches or other tools. There is currently no nice way to pass linker switches; you have to put a rustflags option into a Cargo config file and pass the arguments through to rustc like this: ["-C", "link-args=/exoticlinkerswitch"]. This is obviously not very portable.

For tools, you can use mt.exe from the Windows SDK to add a manifest to your program after it has been compiled.

Note that Cargo does not currently have a way to execute post-build steps automatically. However, there is a Cargo extension, cargo-make that supports such build processes. You can install it via cargo install cargo-make.

Related