osslsigncode 0.1.1

In-process Rust bindings for the vendored osslsigncode Authenticode implementation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
use std::fs::File;
use std::io;
use std::marker::PhantomData;
use std::mem;
use std::path::{Path, PathBuf};

use crate::credential::Credential;
use crate::digest::{Digest, JpLevel, LeafHash};
use crate::error::{Error, Result};
use crate::native::{NativeJob, require_readable};
use crate::policy::{Network, Timestamp, TrustAnchors};
use crate::sys::cmd_type_t;
use crate::{Signed, Unsigned};

/// Output path has not been chosen yet.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct NeedsOutput;

/// Input, output, and credentials required by the command are present.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct Ready;

/// Retarget a type-state job: only `PhantomData` differs, so layouts match.
macro_rules! retarget {
    ($value:expr) => {{
        // SAFETY: marker types are ZSTs; fields are identical across states.
        unsafe { mem::transmute($value) }
    }};
}

macro_rules! with_output {
    ($($Ty:ident),+ $(,)?) => {
        $(
            impl $Ty<NeedsOutput> {
                pub fn output(self, output: impl AsRef<Path>) -> $Ty<Ready> {
                    let mut next: $Ty<Ready> = retarget!(self);
                    next.job.output = Some(output.as_ref().to_path_buf());
                    next
                }
            }
        )+
    };
}

/// Assign an already-typed value straight to a (possibly nested) field.
macro_rules! setter {
    ($(#[$meta:meta])* $name:ident($arg:ident: $Ty:ty) => $($path:ident).+) => {
        $(#[$meta])*
        pub fn $name(mut self, $arg: $Ty) -> Self {
            self.$($path).+ = $arg;
            self
        }
    };
}

/// Wrap an already-typed value in `Some` and assign.
macro_rules! setter_some {
    ($(#[$meta:meta])* $name:ident($arg:ident: $Ty:ty) => $($path:ident).+) => {
        $(#[$meta])*
        pub fn $name(mut self, $arg: $Ty) -> Self {
            self.$($path).+ = Some($arg);
            self
        }
    };
}

/// Convert `impl AsRef<Path>` to an owned path, wrap in `Some`, and assign.
macro_rules! setter_path {
    ($(#[$meta:meta])* $name:ident($arg:ident) => $($path:ident).+) => {
        $(#[$meta])*
        pub fn $name(mut self, $arg: impl AsRef<Path>) -> Self {
            self.$($path).+ = Some($arg.as_ref().to_path_buf());
            self
        }
    };
}

/// Convert `impl Into<String>`, wrap in `Some`, and assign.
macro_rules! setter_string {
    ($(#[$meta:meta])* $name:ident($arg:ident) => $($path:ident).+) => {
        $(#[$meta])*
        pub fn $name(mut self, $arg: impl Into<String>) -> Self {
            self.$($path).+ = Some($arg.into());
            self
        }
    };
}

/// Set a boolean flag field to `true`.
macro_rules! flag {
    ($(#[$meta:meta])* $name:ident => $($path:ident).+) => {
        $(#[$meta])*
        pub fn $name(mut self) -> Self {
            self.$($path).+ = true;
            self
        }
    };
}

/// Push a value onto a `Vec` field.
macro_rules! push {
    ($(#[$meta:meta])* $name:ident($arg:ident: $Ty:ty) => $($path:ident).+) => {
        $(#[$meta])*
        pub fn $name(mut self, $arg: $Ty) -> Self {
            self.$($path).+.push($arg);
            self
        }
    };
}

#[derive(Clone, Debug)]
#[must_use = "jobs do nothing until you call the command verb"]
pub struct Sign<State> {
    job: NativeJob,
    _state: PhantomData<State>,
}

with_output!(Sign);

impl Sign<Ready> {
    /// Fully specified sign job. Prefer [`Unsigned::sign`] so the input is typed.
    pub fn new(input: impl AsRef<Path>, output: impl AsRef<Path>, credential: Credential) -> Self {
        sign_from_unsigned(input.as_ref().to_path_buf(), credential).output(output)
    }

    /// Sign and return a typed [`Signed`] handle for the output.
    pub fn sign(self) -> Result<Signed> {
        let output = self.job.output.clone().expect("Ready always has output");
        self.job.run("sign")?;
        Ok(Signed::from_path_unchecked(output))
    }
}

impl<State> Sign<State> {
    setter!(digest(digest: Digest) => job.digest);
    push!(timestamp(timestamp: Timestamp) => job.timestamps);
    setter!(network(network: Network) => job.network);
    setter!(options(options: crate::format::AuthenticodeOptions) => job.options);
    setter_path!(
        /// Extra certificates to embed in the chain (`-ac`), with any credential.
        additional_certs(path) => job.additional_certs
    );
    setter_some!(
        /// Microsoft IE 4.x CAB permission level (`-jp`). Upstream supports `Low`.
        jp(level: JpLevel) => job.options.jp
    );
    setter_string!(description(description) => job.options.description);
    setter_string!(url(url) => job.options.url);
    flag!(nest => job.options.nest);
    flag!(page_hashes => job.options.page_hashes);
    flag!(commercial => job.options.commercial);
    flag!(pem => job.options.pem);
    flag!(verbose => job.verbose);
    flag!(no_legacy => job.no_legacy);
    setter_some!(time(unix_time: i64) => job.time);
}

pub(crate) fn sign_from_unsigned(input: PathBuf, credential: Credential) -> Sign<NeedsOutput> {
    let mut job = NativeJob::new(cmd_type_t::CMD_SIGN, input);
    job.credential = Some(credential);
    Sign {
        job,
        _state: PhantomData,
    }
}

#[derive(Clone, Debug)]
#[must_use = "jobs do nothing until you call check()"]
pub struct Verify {
    job: NativeJob,
}

impl Verify {
    pub fn new(input: impl AsRef<Path>) -> Self {
        Self {
            job: NativeJob::new(cmd_type_t::CMD_VERIFY, input.as_ref().to_path_buf()),
        }
    }

    setter_path!(catalog(path) => job.catalog);
    setter!(network(network: Network) => job.network);
    flag!(ignore_timestamp => job.ignore_timestamp);
    flag!(ignore_cdp => job.ignore_cdp);
    flag!(ignore_crl => job.ignore_crl);
    setter_some!(time(unix_time: i64) => job.time);
    flag!(verbose => job.verbose);

    /// Trust anchors spread across the four native CA/CRL fields.
    pub fn trust(mut self, trust: TrustAnchors) -> Self {
        self.job.ca_file = trust.ca_file;
        self.job.crl_file = trust.crl_file;
        self.job.tsa_ca = trust.tsa_ca;
        self.job.tsa_crl = trust.tsa_crl;
        self
    }

    /// A `u32` index into a wider CAB/MSI signature, cast for the native side.
    pub fn index(mut self, index: u32) -> Self {
        self.job.index = Some(index as i32);
        self
    }

    pub fn require_leaf_hash(mut self, hash: LeafHash<'_>) -> Self {
        self.job.leafhash = Some(hash.to_string());
        self
    }

    /// Verify the signature. Returns `Ok(())` when the native check succeeds.
    pub fn check(self) -> Result<()> {
        require_readable(&self.job.input, "input")?;
        self.job.run("verify")
    }
}

#[derive(Clone, Debug)]
#[must_use = "jobs do nothing until you call add()"]
pub struct Add<State> {
    job: NativeJob,
    _state: PhantomData<State>,
}

with_output!(Add);

impl Add<Ready> {
    pub fn new(input: impl AsRef<Path>, output: impl AsRef<Path>) -> Self {
        add_from_signed(input.as_ref().to_path_buf()).output(output)
    }

    /// Add the timestamp/blob and return a typed [`Signed`] handle for the output.
    pub fn add(self) -> Result<Signed> {
        let output = self.job.output.clone().expect("Ready always has output");
        self.job.run("add")?;
        Ok(Signed::from_path_unchecked(output))
    }
}

impl<State> Add<State> {
    push!(timestamp(timestamp: Timestamp) => job.timestamps);
    setter!(network(network: Network) => job.network);
    setter!(digest(digest: Digest) => job.digest);
    setter_path!(unauthenticated_blob(path) => job.options.blob);
    flag!(msi_dse => job.options.msi_dse);
    flag!(verbose => job.verbose);

    /// A `u32` index into a wider CAB/MSI signature, cast for the native side.
    pub fn index(mut self, index: u32) -> Self {
        self.job.index = Some(index as i32);
        self
    }
}

pub(crate) fn add_from_signed(input: PathBuf) -> Add<NeedsOutput> {
    Add {
        job: NativeJob::new(cmd_type_t::CMD_ADD, input),
        _state: PhantomData,
    }
}

#[derive(Clone, Debug)]
#[must_use = "call reader() to extract"]
pub struct ExtractData {
    job: NativeJob,
}

impl ExtractData {
    setter!(digest(digest: Digest) => job.digest);
    flag!(pem => job.options.pem);
    flag!(page_hashes => job.options.page_hashes);

    /// Extract, returning a [`Read`](io::Read) over the content.
    pub fn reader(mut self) -> Result<Extracted> {
        Extracted::run("osslsigncode-data", move |output| {
            self.job.output = Some(output);
            self.job.run("extract-data")
        })
    }
}

pub(crate) fn extract_data_from(input: PathBuf) -> ExtractData {
    ExtractData {
        job: NativeJob::new(cmd_type_t::CMD_EXTRACT_DATA, input),
    }
}

#[derive(Clone, Debug)]
#[must_use = "call reader() to extract"]
pub struct ExtractSignature {
    job: NativeJob,
}

impl ExtractSignature {
    flag!(pem => job.options.pem);

    /// Extract, returning a [`Read`](io::Read) over the content.
    pub fn reader(mut self) -> Result<Extracted> {
        Extracted::run("osslsigncode-sig", move |output| {
            self.job.output = Some(output);
            self.job.run("extract-signature")
        })
    }
}

pub(crate) fn extract_signature_from(input: PathBuf) -> ExtractSignature {
    ExtractSignature {
        job: NativeJob::new(cmd_type_t::CMD_EXTRACT, input),
    }
}

#[derive(Clone, Debug)]
#[must_use = "jobs do nothing until you call attach()"]
pub struct AttachSignature<State> {
    job: NativeJob,
    _state: PhantomData<State>,
}

with_output!(AttachSignature);

impl AttachSignature<Ready> {
    pub fn new(
        input: impl AsRef<Path>,
        output: impl AsRef<Path>,
        signature: impl AsRef<Path>,
    ) -> Self {
        attach_from(
            input.as_ref().to_path_buf(),
            signature.as_ref().to_path_buf(),
        )
        .output(output)
    }

    /// Attach the signature and return a typed [`Signed`] handle for the output.
    pub fn attach(self) -> Result<Signed> {
        let output = self.job.output.clone().expect("Ready always has output");
        self.job.run("attach-signature")?;
        Ok(Signed::from_path_unchecked(output))
    }
}

impl<State> AttachSignature<State> {
    setter!(digest(digest: Digest) => job.digest);
    flag!(nest => job.options.nest);
}

pub(crate) fn attach_from(input: PathBuf, signature: PathBuf) -> AttachSignature<NeedsOutput> {
    let mut job = NativeJob::new(cmd_type_t::CMD_ATTACH, input);
    job.signature = Some(signature);
    AttachSignature {
        job,
        _state: PhantomData,
    }
}

#[derive(Clone, Debug)]
#[must_use = "jobs do nothing until you call strip()"]
pub struct RemoveSignature<State> {
    job: NativeJob,
    _state: PhantomData<State>,
}

with_output!(RemoveSignature);

impl RemoveSignature<Ready> {
    pub fn new(input: impl AsRef<Path>, output: impl AsRef<Path>) -> Self {
        remove_from(input.as_ref().to_path_buf()).output(output)
    }

    /// Strip the signature and return a typed [`Unsigned`] handle for the output.
    pub fn strip(self) -> Result<Unsigned> {
        let output = self.job.output.clone().expect("Ready always has output");
        self.job.run("remove-signature")?;
        Ok(Unsigned::from_path_unchecked(output))
    }
}

pub(crate) fn remove_from(input: PathBuf) -> RemoveSignature<NeedsOutput> {
    RemoveSignature {
        job: NativeJob::new(cmd_type_t::CMD_REMOVE, input),
        _state: PhantomData,
    }
}

/// A temp-file-backed extraction result. Implements [`io::Read`] directly —
/// pull only the bytes you need, or `read_to_end` into a `Vec` if you want
/// the whole thing in memory.
pub struct Extracted {
    file: File,
    _dir: tempfile::TempDir,
}

impl Extracted {
    /// Reserve a not-yet-existing path (native jobs refuse to overwrite),
    /// let `run` write the native job's output there, then open it for
    /// reading. The backing directory stays alive as long as `self` does.
    fn run(prefix: &str, run: impl FnOnce(PathBuf) -> Result<()>) -> Result<Self> {
        let dir = tempfile::Builder::new()
            .prefix(prefix)
            .tempdir()
            .map_err(|source| Error::Runtime {
                message: format!("failed to create temp dir: {source}"),
            })?;
        let path = dir.path().join("out");
        run(path.clone())?;
        let file = File::open(&path).map_err(|source| crate::error::io("output", &path, source))?;
        Ok(Self { file, _dir: dir })
    }
}

impl io::Read for Extracted {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        io::Read::read(&mut self.file, buf)
    }
}