pub struct Stapler { /* private fields */ }
Expand description

Handles stapling operations.

Implementations§

Construct a new instance with defaults.

Examples found in repository?
src/cli.rs (line 1963)
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
fn command_notary_submit(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let path = PathBuf::from(
        args.get_one::<String>("path")
            .expect("clap should have validated arguments"),
    );
    let staple = args.get_flag("staple");
    let wait = args.get_flag("wait") || staple;

    let wait_limit = if wait {
        Some(notarizer_wait_duration(args)?)
    } else {
        None
    };
    let notarizer = notarizer_from_args(args)?;

    let upload = notarizer.notarize_path(&path, wait_limit)?;

    if staple {
        match upload {
            crate::notarization::NotarizationUpload::UploadId(_) => {
                panic!(
                    "NotarizationUpload::UploadId should not be returned if we waited successfully"
                );
            }
            crate::notarization::NotarizationUpload::NotaryResponse(_) => {
                let stapler = crate::stapling::Stapler::new()?;
                stapler.staple_path(&path)?;
            }
        }
    }

    Ok(())
}

fn command_notary_wait(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let wait_duration = notarizer_wait_duration(args)?;
    let notarizer = notarizer_from_args(args)?;
    let submission_id = args
        .get_one::<String>("submission_id")
        .expect("submission_id is required");

    notarizer.wait_on_notarization_and_fetch_log(submission_id, wait_duration)?;

    Ok(())
}

fn command_parse_code_signing_requirement(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let path = args
        .get_one::<String>("input_path")
        .expect("clap should have validated argument");

    let data = std::fs::read(path)?;

    let requirements = CodeRequirements::parse_blob(&data)?.0;

    for requirement in requirements.iter() {
        match args
            .get_one::<String>("format")
            .expect("clap should have validated argument")
            .as_str()
        {
            "csrl" => {
                println!("{requirement}");
            }
            "expression-tree" => {
                println!("{requirement:#?}");
            }
            format => panic!("unhandled format: {format}"),
        }
    }

    Ok(())
}

fn command_print_signature_info(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let path = args
        .get_one::<String>("path")
        .expect("clap should have validated argument");

    let reader = SignatureReader::from_path(path)?;

    let entities = reader.entities()?;
    serde_yaml::to_writer(std::io::stdout(), &entities)?;

    Ok(())
}

fn command_remote_sign(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let remote_url = args
        .get_one::<String>("remote_signing_url")
        .expect("remote signing URL should always be present");

    let session_join_string = if args.get_flag("session_join_string_editor") {
        let mut value = None;

        for _ in 0..3 {
            if let Some(content) = dialoguer::Editor::new()
                .require_save(true)
                .edit("# Please enter the -----BEGIN SESSION JOIN STRING---- content below.\n# Remember to save the file!")?
            {
                value = Some(content);
                break;
            }
        }

        value.ok_or_else(|| {
            AppleCodesignError::CliGeneralError("session join string not entered in editor".into())
        })?
    } else if let Some(path) = args.get_one::<String>("session_join_string_path") {
        std::fs::read_to_string(path)?
    } else if let Some(value) = args.get_one::<String>("session_join_string") {
        value.to_string()
    } else {
        return Err(AppleCodesignError::CliGeneralError(
            "session join string argument parsing failure".into(),
        ));
    };

    let mut joiner = create_session_joiner(session_join_string)?;

    if let Some(env) = args.get_one::<String>("remote_shared_secret_env") {
        let secret = std::env::var(env).map_err(|_| AppleCodesignError::CliBadArgument)?;
        joiner.register_state(SessionJoinState::SharedSecret(secret.as_bytes().to_vec()))?;
    } else if let Some(secret) = args.get_one::<String>("remote_shared_secret") {
        joiner.register_state(SessionJoinState::SharedSecret(secret.as_bytes().to_vec()))?;
    }

    let (private_keys, mut public_certificates) = collect_certificates_from_args(args, true)?;

    let private = private_keys
        .into_iter()
        .next()
        .ok_or(AppleCodesignError::NoSigningCertificate)?;

    let cert = public_certificates.remove(0);

    let certificates = if let Some(chain) = cert.apple_root_certificate_chain() {
        // The chain starts with self.
        chain.into_iter().skip(1).collect::<Vec<_>>()
    } else {
        public_certificates
    };

    joiner.register_state(SessionJoinState::PublicKeyDecrypt(
        private.to_public_key_peer_decrypt()?,
    ))?;

    let client = UnjoinedSigningClient::new_signer(
        joiner,
        private.as_key_info_signer(),
        cert,
        certificates,
        remote_url.to_string(),
    )?;
    client.run()?;

    Ok(())
}

fn command_sign(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let mut settings = SigningSettings::default();

    let (private_keys, mut public_certificates) = collect_certificates_from_args(args, true)?;

    if private_keys.len() > 1 {
        error!("at most 1 PRIVATE KEY can be present; aborting");
        return Err(AppleCodesignError::CliBadArgument);
    }

    let private = if private_keys.is_empty() {
        None
    } else {
        Some(&private_keys[0])
    };

    if let Some(signing_key) = &private {
        if public_certificates.is_empty() {
            error!("a PRIVATE KEY requires a corresponding CERTIFICATE to pair with it");
            return Err(AppleCodesignError::CliBadArgument);
        }

        let cert = public_certificates.remove(0);

        warn!("registering signing key");
        settings.set_signing_key(signing_key.as_key_info_signer(), cert);
        if let Some(certs) = settings.chain_apple_certificates() {
            for cert in certs {
                warn!(
                    "automatically registered Apple CA certificate: {}",
                    cert.subject_common_name()
                        .unwrap_or_else(|| "default".into())
                );
            }
        }

        if let Some(timestamp_url) = args.get_one::<String>("timestamp_url") {
            if timestamp_url != "none" {
                warn!("using time-stamp protocol server {}", timestamp_url);
                settings.set_time_stamp_url(timestamp_url)?;
            }
        }
    }

    if let Some(team_id) = settings.set_team_id_from_signing_certificate() {
        warn!(
            "automatically setting team ID from signing certificate: {}",
            team_id
        );
    }

    for cert in public_certificates {
        warn!("registering extra X.509 certificate");
        settings.chain_certificate(cert);
    }

    if let Some(team_name) = args.get_one::<String>("team_name") {
        settings.set_team_id(team_name);
    }

    if let Some(value) = args.get_one::<String>("digest") {
        let digest_type = DigestType::try_from(value.as_str())?;
        settings.set_digest_type(digest_type);
    }

    if let Some(values) = args.get_many::<String>("extra_digest") {
        for value in values {
            let (scope, digest_type) = parse_scoped_value(value)?;
            let digest_type = DigestType::try_from(digest_type)?;
            settings.add_extra_digest(scope, digest_type);
        }
    }

    if let Some(values) = args.get_many::<String>("exclude") {
        for pattern in values {
            settings.add_path_exclusion(pattern)?;
        }
    }

    if let Some(values) = args.get_many::<String>("binary_identifier") {
        for value in values {
            let (scope, identifier) = parse_scoped_value(value)?;
            settings.set_binary_identifier(scope, identifier);
        }
    }

    if let Some(values) = args.get_many::<String>("code_requirements_path") {
        for value in values {
            let (scope, path) = parse_scoped_value(value)?;

            let code_requirements_data = std::fs::read(path)?;
            let reqs = CodeRequirements::parse_blob(&code_requirements_data)?.0;
            for expr in reqs.iter() {
                warn!(
                    "setting designated code requirements for {}: {}",
                    scope, expr
                );
                settings.set_designated_requirement_expression(scope.clone(), expr)?;
            }
        }
    }

    if let Some(values) = args.get_many::<String>("code_resources") {
        for value in values {
            let (scope, path) = parse_scoped_value(value)?;

            warn!(
                "setting code resources data for {} from path {}",
                scope, path
            );
            let code_resources_data = std::fs::read(path)?;
            settings.set_code_resources_data(scope, code_resources_data);
        }
    }

    if let Some(values) = args.get_many::<String>("code_signature_flags_set") {
        for value in values {
            let (scope, value) = parse_scoped_value(value)?;

            let flags = CodeSignatureFlags::from_str(value)?;
            settings.set_code_signature_flags(scope, flags);
        }
    }

    if let Some(values) = args.get_many::<String>("entitlements_xml_path") {
        for value in values {
            let (scope, path) = parse_scoped_value(value)?;

            warn!("setting entitlments XML for {} from path {}", scope, path);
            let entitlements_data = std::fs::read_to_string(path)?;
            settings.set_entitlements_xml(scope, entitlements_data)?;
        }
    }

    if let Some(values) = args.get_many::<String>("runtime_version") {
        for value in values {
            let (scope, value) = parse_scoped_value(value)?;

            let version = semver::Version::parse(value)?;
            settings.set_runtime_version(scope, version);
        }
    }

    if let Some(values) = args.get_many::<String>("info_plist_path") {
        for value in values {
            let (scope, value) = parse_scoped_value(value)?;

            let content = std::fs::read(value)?;
            settings.set_info_plist_data(scope, content);
        }
    }

    let input_path = PathBuf::from(
        args.get_one::<String>("input_path")
            .expect("input_path presence should have been validated by clap"),
    );
    let output_path = args.get_one::<String>("output_path");

    let signer = UnifiedSigner::new(settings);

    if let Some(output_path) = output_path {
        warn!("signing {} to {}", input_path.display(), output_path);
        signer.sign_path(input_path, output_path)?;
    } else {
        warn!("signing {} in place", input_path.display());
        signer.sign_path_in_place(input_path)?;
    }

    if let Some(private) = &private {
        private.finish()?;
    }

    Ok(())
}

#[cfg(feature = "yubikey")]
fn command_smartcard_scan(_args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let mut ctx = ::yubikey::reader::Context::open()?;
    for (index, reader) in ctx.iter()?.enumerate() {
        println!("Device {}: {}", index, reader.name());

        if let Ok(yk) = reader.open() {
            let mut yk = crate::yubikey::YubiKey::from(yk);
            println!("Device {}: Serial: {}", index, yk.inner()?.serial());
            println!("Device {}: Version: {}", index, yk.inner()?.version());

            for (slot, cert) in yk.find_certificates()? {
                println!(
                    "Device {}: Certificate in slot {:?} / {}",
                    index,
                    slot,
                    hex::encode([u8::from(slot)])
                );
                print_certificate_info(&cert)?;
                println!();
            }
        }
    }

    Ok(())
}

#[cfg(not(feature = "yubikey"))]
fn command_smartcard_scan(_args: &ArgMatches) -> Result<(), AppleCodesignError> {
    eprintln!("smartcard reading requires the `yubikey` crate feature, which isn't enabled.");
    eprintln!("recompile the crate with `cargo build --features yubikey` to enable support");
    std::process::exit(1);
}

#[cfg(feature = "yubikey")]
fn command_smartcard_generate_key(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let slot_id = ::yubikey::piv::SlotId::from_str(
        args.get_one::<String>("smartcard_slot").ok_or_else(|| {
            error!("--smartcard-slot is required");
            AppleCodesignError::CliBadArgument
        })?,
    )?;

    let touch_policy = str_to_touch_policy(
        args.get_one::<String>("touch_policy")
            .expect("touch_policy argument is required"),
    )?;
    let pin_policy = str_to_pin_policy(
        args.get_one::<String>("pin_policy")
            .expect("pin_policy argument is required"),
    )?;

    let mut yk = YubiKey::new()?;
    yk.set_pin_callback(prompt_smartcard_pin);

    yk.generate_key(slot_id, touch_policy, pin_policy)?;

    Ok(())
}

#[cfg(not(feature = "yubikey"))]
fn command_smartcard_generate_key(_args: &ArgMatches) -> Result<(), AppleCodesignError> {
    eprintln!("smartcard integration requires the `yubikey` crate feature, which isn't enabled.");
    eprintln!("recompile the crate with `cargo build --features yubikey` to enable support");
    std::process::exit(1);
}

#[cfg(feature = "yubikey")]
fn command_smartcard_import(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let (keys, certs) = collect_certificates_from_args(args, false)?;

    let slot_id = ::yubikey::piv::SlotId::from_str(
        args.get_one::<String>("smartcard_slot").ok_or_else(|| {
            error!("--smartcard-slot is required");
            AppleCodesignError::CliBadArgument
        })?,
    )?;
    let touch_policy = str_to_touch_policy(
        args.get_one::<String>("touch_policy")
            .expect("touch_policy argument is required"),
    )?;
    let pin_policy = str_to_pin_policy(
        args.get_one::<String>("pin_policy")
            .expect("pin_policy argument is required"),
    )?;
    let use_existing_key = args.get_flag("existing_key");

    println!(
        "found {} private keys and {} public certificates",
        keys.len(),
        certs.len()
    );

    let key = if use_existing_key {
        println!("using existing private key in smartcard");

        if !keys.is_empty() {
            println!(
                "ignoring {} private keys specified via arguments",
                keys.len()
            );
        }

        None
    } else {
        Some(keys.into_iter().next().ok_or_else(|| {
            println!("no private key found");
            AppleCodesignError::CliBadArgument
        })?)
    };

    let cert = certs.into_iter().next().ok_or_else(|| {
        println!("no public certificates found");
        AppleCodesignError::CliBadArgument
    })?;

    println!(
        "Will import the following certificate into slot {}",
        hex::encode([u8::from(slot_id)])
    );
    print_certificate_info(&cert)?;

    let mut yk = YubiKey::new()?;
    yk.set_pin_callback(prompt_smartcard_pin);

    if args.get_flag("dry_run") {
        println!("dry run mode enabled; stopping");
        return Ok(());
    }

    if let Some(key) = key {
        yk.import_key(
            slot_id,
            key.as_key_info_signer(),
            &cert,
            touch_policy,
            pin_policy,
        )?;
    } else {
        yk.import_certificate(slot_id, &cert)?;
    }

    Ok(())
}

#[cfg(not(feature = "yubikey"))]
fn command_smartcard_import(_args: &ArgMatches) -> Result<(), AppleCodesignError> {
    eprintln!("smartcard import requires `yubikey` crate feature, which isn't enabled.");
    eprintln!("recompile the crate with `cargo build --features yubikey` to enable support");
    std::process::exit(1);
}

fn command_staple(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let path = args
        .get_one::<String>("path")
        .ok_or(AppleCodesignError::CliBadArgument)?;

    let stapler = crate::stapling::Stapler::new()?;
    stapler.staple_path(path)?;

    Ok(())
}

Set the HTTP client to use for ticket lookups.

Look up a notarization ticket for an app bundle.

This will resolve the notarization ticket record name from the contents of the bundle then attempt to look up that notarization ticket against Apple’s servers.

This errors if there is a problem deriving the notarization ticket record name or if a failure occurs when looking up the notarization ticket. This can include a notarization ticket not existing for the requested record.

Examples found in repository?
src/stapling.rs (line 180)
175
176
177
178
179
180
181
182
183
184
    pub fn staple_bundle(&self, bundle: &DirectoryBundle) -> Result<(), AppleCodesignError> {
        warn!(
            "attempting to find notarization ticket for bundle at {}",
            bundle.root_dir().display()
        );
        let ticket_data = self.lookup_ticket_for_executable_bundle(bundle)?;
        staple_ticket_to_bundle(bundle, &ticket_data)?;

        Ok(())
    }

Attempt to staple a bundle by obtaining a notarization ticket automatically.

Examples found in repository?
src/stapling.rs (line 318)
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
    pub fn staple_path(&self, path: impl AsRef<Path>) -> Result<(), AppleCodesignError> {
        let path = path.as_ref();
        warn!("attempting to staple {}", path.display());

        match PathType::from_path(path)? {
            PathType::MachO => {
                error!("cannot staple Mach-O binaries");
                Err(AppleCodesignError::StapleUnsupportedPath(
                    path.to_path_buf(),
                ))
            }
            PathType::Dmg => {
                warn!("activating DMG stapling mode");
                self.staple_dmg(path)
            }
            PathType::Bundle => {
                warn!("activating bundle stapling mode");
                let bundle = DirectoryBundle::new_from_path(path)
                    .map_err(AppleCodesignError::DirectoryBundle)?;
                self.staple_bundle(&bundle)
            }
            PathType::Xar => {
                warn!("activating XAR stapling mode");
                let xar = XarReader::new(File::options().read(true).write(true).open(path)?)?;
                self.staple_xar(xar)
            }
            PathType::Zip | PathType::Other => Err(AppleCodesignError::StapleUnsupportedPath(
                path.to_path_buf(),
            )),
        }
    }

Look up ticket data for DMG file.

Examples found in repository?
src/stapling.rs (line 220)
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
    pub fn staple_dmg(&self, path: &Path) -> Result<(), AppleCodesignError> {
        let mut fh = File::options().read(true).write(true).open(path)?;

        warn!(
            "attempting to find notarization ticket for DMG at {}",
            path.display()
        );
        let reader = DmgReader::new(&mut fh)?;

        let ticket_data = self.lookup_ticket_for_dmg(&reader)?;
        warn!("found notarization ticket; proceeding with stapling");

        let signer = DmgSigner::default();
        signer.staple_file(&mut fh, ticket_data)?;

        Ok(())
    }

Attempt to staple a DMG by obtaining a notarization ticket automatically.

Examples found in repository?
src/stapling.rs (line 312)
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
    pub fn staple_path(&self, path: impl AsRef<Path>) -> Result<(), AppleCodesignError> {
        let path = path.as_ref();
        warn!("attempting to staple {}", path.display());

        match PathType::from_path(path)? {
            PathType::MachO => {
                error!("cannot staple Mach-O binaries");
                Err(AppleCodesignError::StapleUnsupportedPath(
                    path.to_path_buf(),
                ))
            }
            PathType::Dmg => {
                warn!("activating DMG stapling mode");
                self.staple_dmg(path)
            }
            PathType::Bundle => {
                warn!("activating bundle stapling mode");
                let bundle = DirectoryBundle::new_from_path(path)
                    .map_err(AppleCodesignError::DirectoryBundle)?;
                self.staple_bundle(&bundle)
            }
            PathType::Xar => {
                warn!("activating XAR stapling mode");
                let xar = XarReader::new(File::options().read(true).write(true).open(path)?)?;
                self.staple_xar(xar)
            }
            PathType::Zip | PathType::Other => Err(AppleCodesignError::StapleUnsupportedPath(
                path.to_path_buf(),
            )),
        }
    }

Lookup ticket data for a XAR archive (e.g. a .pkg file).

Examples found in repository?
src/stapling.rs (line 258)
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
    pub fn staple_xar<F: Read + Write + Seek + Sized + Debug>(
        &self,
        mut xar: XarReader<F>,
    ) -> Result<(), AppleCodesignError> {
        let ticket_data = self.lookup_ticket_for_xar(&mut xar)?;

        warn!("found notarization ticket; proceeding with stapling");

        let mut fh = xar.into_inner();

        // As a convenience, we look for an existing ticket trailer so we can tell
        // the user we're effectively overwriting it. We could potentially try to
        // delete or overwrite the old trailer. BUt it is just easier to append,
        // as a writer likely only looks for the ticket trailer at the tail end
        // of the file.
        let trailer_size = 16;
        fh.seek(SeekFrom::End(-trailer_size))?;

        let trailer = fh.ioread_with::<XarNotarizationTrailer>(scroll::LE)?;
        if trailer.magic == XAR_NOTARIZATION_TRAILER_MAGIC {
            let trailer_type = match trailer.typ {
                x if x == XarNotarizationTrailerType::Invalid as u16 => "invalid",
                x if x == XarNotarizationTrailerType::Ticket as u16 => "ticket",
                x if x == XarNotarizationTrailerType::Terminator as u16 => "terminator",
                _ => "unknown",
            };

            warn!("found an existing XAR trailer of type {}", trailer_type);
            warn!("this existing trailer will be preserved and will likely be ignored");
        }

        let trailer = xar_notarization_trailer(&ticket_data)?;

        warn!(
            "stapling notarization ticket trailer ({} bytes) to end of XAR",
            trailer.len()
        );
        fh.write_all(&trailer)?;

        Ok(())
    }

Staple a XAR archive.

Takes the handle to a readable, writable, and seekable object.

The stream will be opened as a XAR file. If a ticket is found, that ticket will be appended to the end of the file.

Examples found in repository?
src/stapling.rs (line 323)
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
    pub fn staple_path(&self, path: impl AsRef<Path>) -> Result<(), AppleCodesignError> {
        let path = path.as_ref();
        warn!("attempting to staple {}", path.display());

        match PathType::from_path(path)? {
            PathType::MachO => {
                error!("cannot staple Mach-O binaries");
                Err(AppleCodesignError::StapleUnsupportedPath(
                    path.to_path_buf(),
                ))
            }
            PathType::Dmg => {
                warn!("activating DMG stapling mode");
                self.staple_dmg(path)
            }
            PathType::Bundle => {
                warn!("activating bundle stapling mode");
                let bundle = DirectoryBundle::new_from_path(path)
                    .map_err(AppleCodesignError::DirectoryBundle)?;
                self.staple_bundle(&bundle)
            }
            PathType::Xar => {
                warn!("activating XAR stapling mode");
                let xar = XarReader::new(File::options().read(true).write(true).open(path)?)?;
                self.staple_xar(xar)
            }
            PathType::Zip | PathType::Other => Err(AppleCodesignError::StapleUnsupportedPath(
                path.to_path_buf(),
            )),
        }
    }

Attempt to staple an entity at a given filesystem path.

The path will be modified on successful stapling operation.

Examples found in repository?
src/cli.rs (line 1964)
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
fn command_notary_submit(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let path = PathBuf::from(
        args.get_one::<String>("path")
            .expect("clap should have validated arguments"),
    );
    let staple = args.get_flag("staple");
    let wait = args.get_flag("wait") || staple;

    let wait_limit = if wait {
        Some(notarizer_wait_duration(args)?)
    } else {
        None
    };
    let notarizer = notarizer_from_args(args)?;

    let upload = notarizer.notarize_path(&path, wait_limit)?;

    if staple {
        match upload {
            crate::notarization::NotarizationUpload::UploadId(_) => {
                panic!(
                    "NotarizationUpload::UploadId should not be returned if we waited successfully"
                );
            }
            crate::notarization::NotarizationUpload::NotaryResponse(_) => {
                let stapler = crate::stapling::Stapler::new()?;
                stapler.staple_path(&path)?;
            }
        }
    }

    Ok(())
}

fn command_notary_wait(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let wait_duration = notarizer_wait_duration(args)?;
    let notarizer = notarizer_from_args(args)?;
    let submission_id = args
        .get_one::<String>("submission_id")
        .expect("submission_id is required");

    notarizer.wait_on_notarization_and_fetch_log(submission_id, wait_duration)?;

    Ok(())
}

fn command_parse_code_signing_requirement(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let path = args
        .get_one::<String>("input_path")
        .expect("clap should have validated argument");

    let data = std::fs::read(path)?;

    let requirements = CodeRequirements::parse_blob(&data)?.0;

    for requirement in requirements.iter() {
        match args
            .get_one::<String>("format")
            .expect("clap should have validated argument")
            .as_str()
        {
            "csrl" => {
                println!("{requirement}");
            }
            "expression-tree" => {
                println!("{requirement:#?}");
            }
            format => panic!("unhandled format: {format}"),
        }
    }

    Ok(())
}

fn command_print_signature_info(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let path = args
        .get_one::<String>("path")
        .expect("clap should have validated argument");

    let reader = SignatureReader::from_path(path)?;

    let entities = reader.entities()?;
    serde_yaml::to_writer(std::io::stdout(), &entities)?;

    Ok(())
}

fn command_remote_sign(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let remote_url = args
        .get_one::<String>("remote_signing_url")
        .expect("remote signing URL should always be present");

    let session_join_string = if args.get_flag("session_join_string_editor") {
        let mut value = None;

        for _ in 0..3 {
            if let Some(content) = dialoguer::Editor::new()
                .require_save(true)
                .edit("# Please enter the -----BEGIN SESSION JOIN STRING---- content below.\n# Remember to save the file!")?
            {
                value = Some(content);
                break;
            }
        }

        value.ok_or_else(|| {
            AppleCodesignError::CliGeneralError("session join string not entered in editor".into())
        })?
    } else if let Some(path) = args.get_one::<String>("session_join_string_path") {
        std::fs::read_to_string(path)?
    } else if let Some(value) = args.get_one::<String>("session_join_string") {
        value.to_string()
    } else {
        return Err(AppleCodesignError::CliGeneralError(
            "session join string argument parsing failure".into(),
        ));
    };

    let mut joiner = create_session_joiner(session_join_string)?;

    if let Some(env) = args.get_one::<String>("remote_shared_secret_env") {
        let secret = std::env::var(env).map_err(|_| AppleCodesignError::CliBadArgument)?;
        joiner.register_state(SessionJoinState::SharedSecret(secret.as_bytes().to_vec()))?;
    } else if let Some(secret) = args.get_one::<String>("remote_shared_secret") {
        joiner.register_state(SessionJoinState::SharedSecret(secret.as_bytes().to_vec()))?;
    }

    let (private_keys, mut public_certificates) = collect_certificates_from_args(args, true)?;

    let private = private_keys
        .into_iter()
        .next()
        .ok_or(AppleCodesignError::NoSigningCertificate)?;

    let cert = public_certificates.remove(0);

    let certificates = if let Some(chain) = cert.apple_root_certificate_chain() {
        // The chain starts with self.
        chain.into_iter().skip(1).collect::<Vec<_>>()
    } else {
        public_certificates
    };

    joiner.register_state(SessionJoinState::PublicKeyDecrypt(
        private.to_public_key_peer_decrypt()?,
    ))?;

    let client = UnjoinedSigningClient::new_signer(
        joiner,
        private.as_key_info_signer(),
        cert,
        certificates,
        remote_url.to_string(),
    )?;
    client.run()?;

    Ok(())
}

fn command_sign(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let mut settings = SigningSettings::default();

    let (private_keys, mut public_certificates) = collect_certificates_from_args(args, true)?;

    if private_keys.len() > 1 {
        error!("at most 1 PRIVATE KEY can be present; aborting");
        return Err(AppleCodesignError::CliBadArgument);
    }

    let private = if private_keys.is_empty() {
        None
    } else {
        Some(&private_keys[0])
    };

    if let Some(signing_key) = &private {
        if public_certificates.is_empty() {
            error!("a PRIVATE KEY requires a corresponding CERTIFICATE to pair with it");
            return Err(AppleCodesignError::CliBadArgument);
        }

        let cert = public_certificates.remove(0);

        warn!("registering signing key");
        settings.set_signing_key(signing_key.as_key_info_signer(), cert);
        if let Some(certs) = settings.chain_apple_certificates() {
            for cert in certs {
                warn!(
                    "automatically registered Apple CA certificate: {}",
                    cert.subject_common_name()
                        .unwrap_or_else(|| "default".into())
                );
            }
        }

        if let Some(timestamp_url) = args.get_one::<String>("timestamp_url") {
            if timestamp_url != "none" {
                warn!("using time-stamp protocol server {}", timestamp_url);
                settings.set_time_stamp_url(timestamp_url)?;
            }
        }
    }

    if let Some(team_id) = settings.set_team_id_from_signing_certificate() {
        warn!(
            "automatically setting team ID from signing certificate: {}",
            team_id
        );
    }

    for cert in public_certificates {
        warn!("registering extra X.509 certificate");
        settings.chain_certificate(cert);
    }

    if let Some(team_name) = args.get_one::<String>("team_name") {
        settings.set_team_id(team_name);
    }

    if let Some(value) = args.get_one::<String>("digest") {
        let digest_type = DigestType::try_from(value.as_str())?;
        settings.set_digest_type(digest_type);
    }

    if let Some(values) = args.get_many::<String>("extra_digest") {
        for value in values {
            let (scope, digest_type) = parse_scoped_value(value)?;
            let digest_type = DigestType::try_from(digest_type)?;
            settings.add_extra_digest(scope, digest_type);
        }
    }

    if let Some(values) = args.get_many::<String>("exclude") {
        for pattern in values {
            settings.add_path_exclusion(pattern)?;
        }
    }

    if let Some(values) = args.get_many::<String>("binary_identifier") {
        for value in values {
            let (scope, identifier) = parse_scoped_value(value)?;
            settings.set_binary_identifier(scope, identifier);
        }
    }

    if let Some(values) = args.get_many::<String>("code_requirements_path") {
        for value in values {
            let (scope, path) = parse_scoped_value(value)?;

            let code_requirements_data = std::fs::read(path)?;
            let reqs = CodeRequirements::parse_blob(&code_requirements_data)?.0;
            for expr in reqs.iter() {
                warn!(
                    "setting designated code requirements for {}: {}",
                    scope, expr
                );
                settings.set_designated_requirement_expression(scope.clone(), expr)?;
            }
        }
    }

    if let Some(values) = args.get_many::<String>("code_resources") {
        for value in values {
            let (scope, path) = parse_scoped_value(value)?;

            warn!(
                "setting code resources data for {} from path {}",
                scope, path
            );
            let code_resources_data = std::fs::read(path)?;
            settings.set_code_resources_data(scope, code_resources_data);
        }
    }

    if let Some(values) = args.get_many::<String>("code_signature_flags_set") {
        for value in values {
            let (scope, value) = parse_scoped_value(value)?;

            let flags = CodeSignatureFlags::from_str(value)?;
            settings.set_code_signature_flags(scope, flags);
        }
    }

    if let Some(values) = args.get_many::<String>("entitlements_xml_path") {
        for value in values {
            let (scope, path) = parse_scoped_value(value)?;

            warn!("setting entitlments XML for {} from path {}", scope, path);
            let entitlements_data = std::fs::read_to_string(path)?;
            settings.set_entitlements_xml(scope, entitlements_data)?;
        }
    }

    if let Some(values) = args.get_many::<String>("runtime_version") {
        for value in values {
            let (scope, value) = parse_scoped_value(value)?;

            let version = semver::Version::parse(value)?;
            settings.set_runtime_version(scope, version);
        }
    }

    if let Some(values) = args.get_many::<String>("info_plist_path") {
        for value in values {
            let (scope, value) = parse_scoped_value(value)?;

            let content = std::fs::read(value)?;
            settings.set_info_plist_data(scope, content);
        }
    }

    let input_path = PathBuf::from(
        args.get_one::<String>("input_path")
            .expect("input_path presence should have been validated by clap"),
    );
    let output_path = args.get_one::<String>("output_path");

    let signer = UnifiedSigner::new(settings);

    if let Some(output_path) = output_path {
        warn!("signing {} to {}", input_path.display(), output_path);
        signer.sign_path(input_path, output_path)?;
    } else {
        warn!("signing {} in place", input_path.display());
        signer.sign_path_in_place(input_path)?;
    }

    if let Some(private) = &private {
        private.finish()?;
    }

    Ok(())
}

#[cfg(feature = "yubikey")]
fn command_smartcard_scan(_args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let mut ctx = ::yubikey::reader::Context::open()?;
    for (index, reader) in ctx.iter()?.enumerate() {
        println!("Device {}: {}", index, reader.name());

        if let Ok(yk) = reader.open() {
            let mut yk = crate::yubikey::YubiKey::from(yk);
            println!("Device {}: Serial: {}", index, yk.inner()?.serial());
            println!("Device {}: Version: {}", index, yk.inner()?.version());

            for (slot, cert) in yk.find_certificates()? {
                println!(
                    "Device {}: Certificate in slot {:?} / {}",
                    index,
                    slot,
                    hex::encode([u8::from(slot)])
                );
                print_certificate_info(&cert)?;
                println!();
            }
        }
    }

    Ok(())
}

#[cfg(not(feature = "yubikey"))]
fn command_smartcard_scan(_args: &ArgMatches) -> Result<(), AppleCodesignError> {
    eprintln!("smartcard reading requires the `yubikey` crate feature, which isn't enabled.");
    eprintln!("recompile the crate with `cargo build --features yubikey` to enable support");
    std::process::exit(1);
}

#[cfg(feature = "yubikey")]
fn command_smartcard_generate_key(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let slot_id = ::yubikey::piv::SlotId::from_str(
        args.get_one::<String>("smartcard_slot").ok_or_else(|| {
            error!("--smartcard-slot is required");
            AppleCodesignError::CliBadArgument
        })?,
    )?;

    let touch_policy = str_to_touch_policy(
        args.get_one::<String>("touch_policy")
            .expect("touch_policy argument is required"),
    )?;
    let pin_policy = str_to_pin_policy(
        args.get_one::<String>("pin_policy")
            .expect("pin_policy argument is required"),
    )?;

    let mut yk = YubiKey::new()?;
    yk.set_pin_callback(prompt_smartcard_pin);

    yk.generate_key(slot_id, touch_policy, pin_policy)?;

    Ok(())
}

#[cfg(not(feature = "yubikey"))]
fn command_smartcard_generate_key(_args: &ArgMatches) -> Result<(), AppleCodesignError> {
    eprintln!("smartcard integration requires the `yubikey` crate feature, which isn't enabled.");
    eprintln!("recompile the crate with `cargo build --features yubikey` to enable support");
    std::process::exit(1);
}

#[cfg(feature = "yubikey")]
fn command_smartcard_import(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let (keys, certs) = collect_certificates_from_args(args, false)?;

    let slot_id = ::yubikey::piv::SlotId::from_str(
        args.get_one::<String>("smartcard_slot").ok_or_else(|| {
            error!("--smartcard-slot is required");
            AppleCodesignError::CliBadArgument
        })?,
    )?;
    let touch_policy = str_to_touch_policy(
        args.get_one::<String>("touch_policy")
            .expect("touch_policy argument is required"),
    )?;
    let pin_policy = str_to_pin_policy(
        args.get_one::<String>("pin_policy")
            .expect("pin_policy argument is required"),
    )?;
    let use_existing_key = args.get_flag("existing_key");

    println!(
        "found {} private keys and {} public certificates",
        keys.len(),
        certs.len()
    );

    let key = if use_existing_key {
        println!("using existing private key in smartcard");

        if !keys.is_empty() {
            println!(
                "ignoring {} private keys specified via arguments",
                keys.len()
            );
        }

        None
    } else {
        Some(keys.into_iter().next().ok_or_else(|| {
            println!("no private key found");
            AppleCodesignError::CliBadArgument
        })?)
    };

    let cert = certs.into_iter().next().ok_or_else(|| {
        println!("no public certificates found");
        AppleCodesignError::CliBadArgument
    })?;

    println!(
        "Will import the following certificate into slot {}",
        hex::encode([u8::from(slot_id)])
    );
    print_certificate_info(&cert)?;

    let mut yk = YubiKey::new()?;
    yk.set_pin_callback(prompt_smartcard_pin);

    if args.get_flag("dry_run") {
        println!("dry run mode enabled; stopping");
        return Ok(());
    }

    if let Some(key) = key {
        yk.import_key(
            slot_id,
            key.as_key_info_signer(),
            &cert,
            touch_policy,
            pin_policy,
        )?;
    } else {
        yk.import_certificate(slot_id, &cert)?;
    }

    Ok(())
}

#[cfg(not(feature = "yubikey"))]
fn command_smartcard_import(_args: &ArgMatches) -> Result<(), AppleCodesignError> {
    eprintln!("smartcard import requires `yubikey` crate feature, which isn't enabled.");
    eprintln!("recompile the crate with `cargo build --features yubikey` to enable support");
    std::process::exit(1);
}

fn command_staple(args: &ArgMatches) -> Result<(), AppleCodesignError> {
    let path = args
        .get_one::<String>("path")
        .ok_or(AppleCodesignError::CliBadArgument)?;

    let stapler = crate::stapling::Stapler::new()?;
    stapler.staple_path(path)?;

    Ok(())
}

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more
Converts self into T using Into<T>. Read more
Causes self to use its Binary implementation when Debug-formatted.
Causes self to use its Display implementation when Debug-formatted.
Causes self to use its LowerExp implementation when Debug-formatted.
Causes self to use its LowerHex implementation when Debug-formatted.
Causes self to use its Octal implementation when Debug-formatted.
Causes self to use its Pointer implementation when Debug-formatted.
Causes self to use its UpperExp implementation when Debug-formatted.
Causes self to use its UpperHex implementation when Debug-formatted.
Formats each item in a sequence. Read more

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Pipes by value. This is generally the method you want to use. Read more
Borrows self and passes that borrow into the pipe function. Read more
Mutably borrows self and passes that borrow into the pipe function. Read more
Borrows self, then passes self.borrow() into the pipe function. Read more
Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Borrows self, then passes self.as_ref() into the pipe function.
Mutably borrows self, then passes self.as_mut() into the pipe function.
Borrows self, then passes self.deref() into the pipe function.
Mutably borrows self, then passes self.deref_mut() into the pipe function.
The alignment of pointer.
The type for initializers.
Initializes a with the given initializer. Read more
Dereferences the given pointer. Read more
Mutably dereferences the given pointer. Read more
Drops the object pointed to by the given pointer. Read more
Should always be Self
Immutable access to a value. Read more
Mutable access to a value. Read more
Immutable access to the Borrow<B> of a value. Read more
Mutable access to the BorrowMut<B> of a value. Read more
Immutable access to the AsRef<R> view of a value. Read more
Mutable access to the AsMut<R> view of a value. Read more
Immutable access to the Deref::Target of a value. Read more
Mutable access to the Deref::Target of a value. Read more
Calls .tap() only in debug builds, and is erased in release builds.
Calls .tap_mut() only in debug builds, and is erased in release builds.
Calls .tap_borrow() only in debug builds, and is erased in release builds.
Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
Calls .tap_ref() only in debug builds, and is erased in release builds.
Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
Calls .tap_deref() only in debug builds, and is erased in release builds.
Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
Attempts to convert self into T using TryInto<T>. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more