osslsigncode 0.1.0

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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
//! Fill upstream `GLOBAL_OPTIONS` in Rust and drive `FILE_FORMAT` directly.
//!
//! No argv, no `main_configure`, no `main_execute`: jobs map onto the bindgen
//! layout of `GLOBAL_OPTIONS`, then [`crate::drive::run`].

use std::cell::RefCell;
use std::ffi::{CStr, CString, NulError, OsStr};
use std::os::raw::{c_char, c_int};
use std::path::{Path, PathBuf};
use std::ptr;
use std::sync::{Mutex, Once};

use openssl::hash::MessageDigest;
use openssl::nid::Nid;
use openssl_sys::CRYPTO_malloc;

use crate::credential::{Credential, Secret};
use crate::digest::{Digest, JpLevel};
use crate::error::Error;
use crate::format::AuthenticodeOptions;
use crate::policy::{Network, Timestamp};
use crate::sys::{GLOBAL_OPTIONS, cmd_type_t, engine_control_set, free_options};

#[inline]
fn c_bool(value: bool) -> c_int {
    c_int::from(value)
}

pub(crate) static RUN_LOCK: Mutex<()> = Mutex::new(());
const MAX_TS_SERVERS: usize = 256;
const INVALID_TIME: i64 = -1;

thread_local! {
    static LAST_ERROR: RefCell<String> = const { RefCell::new(String::new()) };
}

static OPENSSL_READY: Once = Once::new();

#[cfg(not(windows))]
const DEFAULT_CA_FILES: &[&str] = &[
    "/etc/ssl/certs/ca-certificates.crt",
    "/etc/pki/tls/certs/ca-bundle.crt",
    "/usr/share/ssl/certs/ca-bundle.crt",
    "/usr/local/share/certs/ca-root-nss.crt",
    "/etc/ssl/cert.pem",
];

#[derive(Clone, Debug)]
pub(crate) struct NativeJob {
    pub cmd: cmd_type_t,
    pub digest: Digest,
    pub input: PathBuf,
    pub output: Option<PathBuf>,
    pub signature: Option<PathBuf>,
    pub credential: Option<Credential>,
    pub additional_certs: Option<PathBuf>,
    pub timestamps: Vec<Timestamp>,
    pub network: Network,
    pub options: AuthenticodeOptions,
    pub catalog: Option<PathBuf>,
    pub ca_file: Option<PathBuf>,
    pub crl_file: Option<PathBuf>,
    pub tsa_ca: Option<PathBuf>,
    pub tsa_crl: Option<PathBuf>,
    pub leafhash: Option<String>,
    pub index: Option<i32>,
    pub time: Option<i64>,
    pub ignore_timestamp: bool,
    pub ignore_cdp: bool,
    pub ignore_crl: bool,
    pub verbose: bool,
    pub no_legacy: bool,
}

impl NativeJob {
    pub(crate) fn new(cmd: cmd_type_t, input: PathBuf) -> Self {
        Self {
            cmd,
            digest: Digest::Sha256,
            input,
            output: None,
            signature: None,
            credential: None,
            additional_certs: None,
            timestamps: Vec::new(),
            network: Network::default(),
            options: AuthenticodeOptions::default(),
            catalog: None,
            ca_file: None,
            crl_file: None,
            tsa_ca: None,
            tsa_crl: None,
            leafhash: None,
            index: None,
            time: None,
            ignore_timestamp: false,
            ignore_cdp: false,
            ignore_crl: false,
            verbose: false,
            no_legacy: false,
        }
    }

    pub(crate) fn run(self, operation: &'static str) -> Result<(), Error> {
        require_readable(&self.input, "input")?;
        if let Some(credential) = &self.credential {
            require_credential(credential)?;
        }
        if let Some(signature) = &self.signature {
            require_readable(signature, "signature")?;
        }
        if let Some(catalog) = &self.catalog {
            require_readable(catalog, "catalog")?;
        }

        let mut arena = Arena::new();
        let mut prepared = PreparedOptions {
            options: unsafe { std::mem::zeroed() },
            ran: false,
        };
        apply_job(&mut prepared.options, &mut arena, &self)?;

        let _guard = RUN_LOCK.lock().unwrap_or_else(|error| error.into_inner());
        init_openssl()?;
        LAST_ERROR.with(|slot| slot.borrow_mut().clear());

        // SAFETY: `options` is fully initialized. Arena strings stay alive for the
        // duration of the call; OPENSSL-owned fields are freed inside the driver.
        let status = unsafe { crate::drive::run(&mut prepared.options) };
        prepared.ran = true;
        if status == 0 {
            Ok(())
        } else {
            Err(crate::error::failed(operation, status, last_error()))
        }
    }
}

/// Owns a `GLOBAL_OPTIONS` until the native body runs (and frees OPENSSL fields).
struct PreparedOptions {
    options: GLOBAL_OPTIONS,
    ran: bool,
}

impl Drop for PreparedOptions {
    fn drop(&mut self) {
        if !self.ran {
            unsafe { free_options(&mut self.options) };
        }
    }
}

pub(crate) fn last_error() -> Option<String> {
    LAST_ERROR.with(|slot| {
        let message = slot.borrow();
        (!message.is_empty()).then(|| message.clone())
    })
}

pub(crate) fn set_last_error(message: impl Into<String>) {
    LAST_ERROR.with(|slot| *slot.borrow_mut() = message.into());
}

fn init_openssl() -> Result<(), Error> {
    let mut failed = None;
    OPENSSL_READY.call_once(|| {
        openssl::init();
        const OIDS: &[(&str, &str, &str)] = &[
            (
                "1.3.6.1.4.1.311.2.1.11",
                "spcStatementType",
                "spcStatementType",
            ),
            ("1.3.6.1.4.1.311.15.1", "msJavaSomething", "msJavaSomething"),
            ("1.3.6.1.4.1.311.2.1.12", "spcSpOpusInfo", "spcSpOpusInfo"),
            (
                "1.3.6.1.4.1.311.2.4.1",
                "spcNestedSignature",
                "spcNestedSignature",
            ),
            (
                "1.3.6.1.4.1.42921.1.2.1",
                "spcUnauthenticatedData",
                "spcUnauthenticatedData",
            ),
            ("1.3.6.1.4.1.311.3.3.1", "spcRfc3161", "spcRfc3161"),
            (
                "1.2.840.113549.1.9.25.4",
                "pkcs9SequenceNumber",
                "pkcs9SequenceNumber",
            ),
        ];
        for &(oid, sn, ln) in OIDS {
            if Nid::create(oid, sn, ln).is_err() {
                failed = Some("failed to create Authenticode OpenSSL objects");
                return;
            }
        }
    });
    match failed {
        Some(message) => Err(Error::Runtime {
            message: message.to_owned(),
        }),
        None => Ok(()),
    }
}

/// C-string storage for one native call.
///
/// `GLOBAL_OPTIONS` holds two kinds of `char *`, distinguished only by who
/// frees them:
///
/// * **borrowed** ([`Arena::borrowed`]) — the pointer only has to stay valid
///   while the native body runs. Backed by a [`CString`] this arena owns and
///   drops when the call returns. Every field uses this *except* the seven
///   below.
/// * **owned** ([`owned`]) — the fields `free_options` calls `OPENSSL_free` on:
///   `cafile`, `crlfile`, `https_cafile`, `https_crlfile`, `tsa_cafile`,
///   `tsa_crlfile`, and `pass`. These are `CRYPTO_malloc`ed so the C free path
///   matches the C alloc path, and ownership passes to the driver.
struct Arena {
    strings: Vec<CString>,
}

impl Arena {
    fn new() -> Self {
        Self {
            strings: Vec::new(),
        }
    }

    /// A pointer valid until this arena drops (i.e. after the native call).
    fn borrowed(
        &mut self,
        value: impl AsRef<OsStr>,
        field: &'static str,
    ) -> Result<*mut c_char, Error> {
        let cstr = cstring(value.as_ref(), field)?;
        let pointer = cstr.as_ptr() as *mut c_char;
        self.strings.push(cstr);
        Ok(pointer)
    }

    /// Like [`Arena::borrowed`], or null for [`None`].
    fn borrowed_opt(
        &mut self,
        value: Option<impl AsRef<OsStr>>,
        field: &'static str,
    ) -> Result<*mut c_char, Error> {
        match value {
            Some(value) => self.borrowed(value, field),
            None => Ok(ptr::null_mut()),
        }
    }
}

fn cstring(value: &OsStr, field: &'static str) -> Result<CString, Error> {
    os_to_cstring(value).map_err(|source| Error::InvalidCString { field, source })
}

fn apply_job(
    options: &mut GLOBAL_OPTIONS,
    arena: &mut Arena,
    job: &NativeJob,
) -> Result<(), Error> {
    options.cmd = job.cmd;
    options.md = digest_md(job.digest);
    options.time = job.time.unwrap_or(INVALID_TIME);
    options.tsa_time = 0;
    options.jp = job.options.jp.map(c_int::from).unwrap_or(-1);
    options.index = job.index.unwrap_or(-1);
    options.nested_number = -1;
    options.legacy = c_bool(!job.no_legacy);

    options.infile = arena.borrowed(&job.input, "input")?;
    options.outfile = arena.borrowed_opt(job.output.as_deref(), "output")?;
    options.sigfile = arena.borrowed_opt(job.signature.as_deref(), "signature")?;
    options.catalog = arena.borrowed_opt(job.catalog.as_deref(), "catalog")?;
    options.leafhash = arena.borrowed_opt(job.leafhash.as_deref(), "leafhash")?;
    options.desc = arena.borrowed_opt(job.options.description.as_deref(), "description")?;
    options.url = arena.borrowed_opt(job.options.url.as_deref(), "url")?;
    options.proxy = arena.borrowed_opt(job.network.proxy.as_deref(), "proxy")?;
    options.blob_file = arena.borrowed_opt(job.options.blob.as_deref(), "blob")? as *const c_char;

    apply_credential(options, arena, job.credential.as_ref())?;
    // A job-level `-ac` overrides whatever the credential set, so it works with
    // any credential kind, not just certificate+key.
    if job.additional_certs.is_some() {
        options.xcertfile =
            arena.borrowed_opt(job.additional_certs.as_deref(), "additional_certs")?;
    }
    apply_timestamps(options, arena, &job.timestamps)?;

    options.output_pkcs7 = c_bool(job.options.pem);
    options.comm = c_bool(job.options.commercial);
    options.pagehash = c_bool(job.options.page_hashes);
    options.noverifypeer = c_bool(!job.network.verify_peer);
    options.addBlob = c_bool(job.options.blob.is_some());
    options.nest = c_bool(job.options.nest);
    options.ignore_timestamp = c_bool(job.ignore_timestamp);
    options.ignore_cdp = c_bool(job.ignore_cdp);
    options.ignore_crl = c_bool(job.ignore_crl);
    options.verbose = c_bool(job.verbose);
    options.add_msi_dse = c_bool(job.options.msi_dse);

    // The seven `free_options`-owned fields: CA files fall back to the system
    // bundle on sign/verify; CRL files are optional with no default.
    options.cafile = ca_field(job.ca_file.as_deref(), job.cmd, "ca_file")?;
    options.https_cafile = ca_field(job.network.https_ca.as_deref(), job.cmd, "https_ca")?;
    options.tsa_cafile = ca_field(job.tsa_ca.as_deref(), job.cmd, "tsa_ca")?;
    options.crlfile = owned_opt(job.crl_file.as_deref(), "crl_file")?;
    options.https_crlfile = owned_opt(job.network.https_crl.as_deref(), "https_crl")?;
    options.tsa_crlfile = owned_opt(job.tsa_crl.as_deref(), "tsa_crl")?;

    if !matches!(job.cmd, cmd_type_t::CMD_VERIFY) {
        if options.outfile.is_null() {
            return Err(Error::Runtime {
                message: "output path is required".to_owned(),
            });
        }
        let out = unsafe { CStr::from_ptr(options.outfile) }.to_string_lossy();
        if Path::new(out.as_ref()).exists() {
            return Err(Error::Runtime {
                message: "refusing to overwrite existing output file".to_owned(),
            });
        }
    }

    if matches!(job.cmd, cmd_type_t::CMD_SIGN)
        && options.pkcs12file.is_null()
        && (options.certfile.is_null() || options.keyfile.is_null())
        && options.p11module.is_null()
        && options.p11engine.is_null()
        && options.provider.is_null()
    {
        return Err(Error::Runtime {
            message: "signing requires a PKCS#12 file, certificate+key, or PKCS#11 credential"
                .to_owned(),
        });
    }
    Ok(())
}

fn apply_credential(
    options: &mut GLOBAL_OPTIONS,
    arena: &mut Arena,
    credential: Option<&Credential>,
) -> Result<(), Error> {
    let Some(credential) = credential else {
        return Ok(());
    };
    match credential {
        Credential::Pkcs12 { path, secret } => {
            options.pkcs12file = arena.borrowed(path, "pkcs12")?;
            apply_secret(options, arena, secret)?;
        }
        Credential::CertificateKey {
            certificates,
            key,
            additional,
            secret,
        } => {
            options.certfile = arena.borrowed(certificates, "certificates")?;
            options.keyfile = arena.borrowed(key, "key")?;
            options.xcertfile = arena.borrowed_opt(additional.as_deref(), "additional_certs")?;
            apply_secret(options, arena, secret)?;
        }
        Credential::Pkcs11(pkcs11) => {
            options.p11module = arena.borrowed(&pkcs11.module, "pkcs11module")?;
            options.p11cert = arena.borrowed_opt(pkcs11.cert.as_deref(), "pkcs11cert")?;
            options.p11engine = arena.borrowed_opt(pkcs11.engine.as_deref(), "engine")?;
            options.provider = arena.borrowed_opt(pkcs11.provider.as_deref(), "provider")?;
            options.login = c_bool(pkcs11.login);
            apply_secret(options, arena, &pkcs11.secret)?;
            for ctrl in &pkcs11.engine_ctrls {
                let cstr = cstring(OsStr::new(ctrl), "engine_ctrl")?;
                // engine_control_set splits the buffer on ':' in place.
                let ptr = cstr.into_raw();
                unsafe {
                    engine_control_set(options, ptr);
                    let _ = CString::from_raw(ptr);
                }
            }
        }
    }
    Ok(())
}

fn apply_secret(
    options: &mut GLOBAL_OPTIONS,
    arena: &mut Arena,
    secret: &Secret,
) -> Result<(), Error> {
    match secret {
        Secret::Prompt => options.askpass = 1,
        Secret::Stdin => options.readpass = arena.borrowed("-", "readpass")?,
        Secret::File(path) => options.readpass = arena.borrowed(path, "readpass")?,
        // `pass` is one of the seven fields `free_options` frees (and wipes).
        Secret::Value(value) => options.pass = owned(value.as_str(), "password")?,
    }
    Ok(())
}

fn apply_timestamps(
    options: &mut GLOBAL_OPTIONS,
    arena: &mut Arena,
    timestamps: &[Timestamp],
) -> Result<(), Error> {
    let mut authenticode = 0usize;
    let mut rfc3161 = 0usize;
    for timestamp in timestamps {
        match timestamp {
            Timestamp::Authenticode(url) => {
                if authenticode >= MAX_TS_SERVERS {
                    return Err(Error::Runtime {
                        message: "too many Authenticode timestamp URLs".to_owned(),
                    });
                }
                options.turl[authenticode] =
                    arena.borrowed(url.as_str(), "authenticode_timestamp")?;
                authenticode += 1;
            }
            Timestamp::Rfc3161(url) => {
                if rfc3161 >= MAX_TS_SERVERS {
                    return Err(Error::Runtime {
                        message: "too many RFC-3161 timestamp URLs".to_owned(),
                    });
                }
                options.tsurl[rfc3161] = arena.borrowed(url.as_str(), "rfc3161_timestamp")?;
                rfc3161 += 1;
            }
            Timestamp::Authority {
                certificates,
                key,
                unix_time,
            } => {
                options.tsa_certfile = arena.borrowed(certificates, "tsa_certs")?;
                options.tsa_keyfile = arena.borrowed(key, "tsa_key")?;
                if let Some(time) = unix_time {
                    options.tsa_time = *time;
                }
            }
        }
    }
    options.nturl = authenticode as c_int;
    options.ntsurl = rfc3161 as c_int;
    Ok(())
}

/// A `CRYPTO_malloc`ed copy handed to the driver; released by `free_options`.
fn owned(value: impl AsRef<OsStr>, field: &'static str) -> Result<*mut c_char, Error> {
    let cstr = cstring(value.as_ref(), field)?;
    openssl_dup(cstr.as_bytes_with_nul()).ok_or_else(|| Error::Runtime {
        message: format!("out of memory copying {field}"),
    })
}

/// Like [`owned`], or null for [`None`].
fn owned_opt(value: Option<impl AsRef<OsStr>>, field: &'static str) -> Result<*mut c_char, Error> {
    match value {
        Some(value) => owned(value, field),
        None => Ok(ptr::null_mut()),
    }
}

/// An owned CA field: the explicit path, else the system bundle on sign/verify.
fn ca_field(
    path: Option<&Path>,
    cmd: cmd_type_t,
    field: &'static str,
) -> Result<*mut c_char, Error> {
    match path {
        Some(path) => owned(path, field),
        None if matches!(cmd, cmd_type_t::CMD_SIGN | cmd_type_t::CMD_VERIFY) => {
            default_cafile(field)
        }
        None => Ok(ptr::null_mut()),
    }
}

fn default_cafile(field: &'static str) -> Result<*mut c_char, Error> {
    #[cfg(windows)]
    {
        let _ = field;
        Ok(ptr::null_mut())
    }
    #[cfg(not(windows))]
    match DEFAULT_CA_FILES
        .iter()
        .find(|path| Path::new(path).is_file())
    {
        Some(path) => owned(*path, field),
        None => Ok(ptr::null_mut()),
    }
}

/// Copy `bytes` (including its trailing NUL) into `CRYPTO_malloc`ed memory that
/// OpenSSL owns. Returns [`None`] on allocation failure.
fn openssl_dup(bytes: &[u8]) -> Option<*mut c_char> {
    let copy = unsafe {
        CRYPTO_malloc(
            bytes.len(),
            c"osslsigncode/native.rs".as_ptr(),
            line!() as c_int,
        )
    };
    if copy.is_null() {
        return None;
    }
    unsafe { ptr::copy_nonoverlapping(bytes.as_ptr(), copy.cast::<u8>(), bytes.len()) };
    Some(copy.cast::<c_char>())
}

fn digest_md(digest: Digest) -> *const openssl_sys::EVP_MD {
    let md = match digest {
        Digest::Md5 => MessageDigest::md5(),
        Digest::Sha1 => MessageDigest::sha1(),
        Digest::Sha256 => MessageDigest::sha256(),
        Digest::Sha384 => MessageDigest::sha384(),
        Digest::Sha512 => MessageDigest::sha512(),
    };
    md.as_ptr()
}

impl From<JpLevel> for c_int {
    fn from(level: JpLevel) -> Self {
        // Declaration order is the upstream `-jp` code: Low=0, Medium=1, High=2.
        level as Self
    }
}

pub(crate) fn require_readable(path: &Path, field: &'static str) -> Result<(), Error> {
    std::fs::metadata(path)
        .map(|_| ())
        .map_err(|source| crate::error::io(field, path, source))
}

fn require_credential(credential: &Credential) -> Result<(), Error> {
    match credential {
        Credential::Pkcs12 { path, .. } => require_readable(path, "pkcs12"),
        Credential::CertificateKey {
            certificates,
            key,
            additional,
            ..
        } => {
            require_readable(certificates, "certificates")?;
            require_readable(key, "key")?;
            if let Some(additional) = additional {
                require_readable(additional, "additional_certs")?;
            }
            Ok(())
        }
        Credential::Pkcs11(pkcs11) => require_readable(&pkcs11.module, "pkcs11module"),
    }
}

#[cfg(unix)]
fn os_to_cstring(value: &OsStr) -> Result<CString, NulError> {
    use std::os::unix::ffi::OsStrExt;
    CString::new(value.as_bytes())
}

#[cfg(not(unix))]
fn os_to_cstring(value: &OsStr) -> Result<CString, NulError> {
    CString::new(value.to_string_lossy().as_bytes())
}