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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
use {
crate::{
code_directory::CodeDirectoryBlob,
code_requirement::RequirementType,
code_resources::{CodeResourcesBuilder, CodeResourcesRule},
embedded_signature::{Blob, BlobData, DigestType},
error::AppleCodesignError,
macho::{find_macho_targeting, iter_macho, AppleSignable},
macho_signing::{write_macho_file, MachOSigner},
signing_settings::{SettingsScope, SigningSettings},
},
apple_bundles::{BundlePackageType, DirectoryBundle, DirectoryBundleFile},
goblin::mach::Mach,
log::{info, warn},
std::{
collections::BTreeMap,
io::Write,
path::{Path, PathBuf},
},
tugger_file_manifest::create_symlink,
};
pub fn copy_bundle(bundle: &DirectoryBundle, dest_dir: &Path) -> Result<(), AppleCodesignError> {
let settings = SigningSettings::default();
let handler = SingleBundleHandler {
dest_dir: dest_dir.to_path_buf(),
settings: &settings,
};
for file in bundle
.files(false)
.map_err(AppleCodesignError::DirectoryBundle)?
{
handler.install_file(&file)?;
}
Ok(())
}
pub struct BundleSigner {
bundles: BTreeMap<Option<String>, SingleBundleSigner>,
}
impl BundleSigner {
pub fn new_from_path(path: impl AsRef<Path>) -> Result<Self, AppleCodesignError> {
let main_bundle = DirectoryBundle::new_from_path(path.as_ref())
.map_err(AppleCodesignError::DirectoryBundle)?;
let mut bundles = main_bundle
.nested_bundles(true)
.map_err(AppleCodesignError::DirectoryBundle)?
.into_iter()
.map(|(k, bundle)| (Some(k), SingleBundleSigner::new(bundle)))
.collect::<BTreeMap<Option<String>, SingleBundleSigner>>();
bundles.insert(None, SingleBundleSigner::new(main_bundle));
Ok(Self { bundles })
}
pub fn write_signed_bundle(
&self,
dest_dir: impl AsRef<Path>,
settings: &SigningSettings,
) -> Result<DirectoryBundle, AppleCodesignError> {
let dest_dir = dest_dir.as_ref();
let mut bundles = self
.bundles
.iter()
.filter_map(|(rel, bundle)| rel.as_ref().map(|rel| (rel, bundle)))
.collect::<Vec<_>>();
bundles.sort_by(|(a, _), (b, _)| b.len().cmp(&a.len()));
warn!(
"signing {} nested bundles in the following order:",
bundles.len()
);
for bundle in &bundles {
warn!("{}", bundle.0);
}
for (rel, nested) in bundles {
let nested_dest_dir = dest_dir.join(rel);
info!(
"entering nested bundle {}",
nested.bundle.root_dir().display(),
);
if settings
.path_exclusion_patterns()
.iter()
.any(|pattern| pattern.matches(rel))
{
warn!("bundle is in exclusion list; it will be copied instead of signed");
copy_bundle(&nested.bundle, &nested_dest_dir)?;
} else {
nested.write_signed_bundle(
nested_dest_dir,
&settings.as_nested_bundle_settings(rel),
)?;
}
info!(
"leaving nested bundle {}",
nested.bundle.root_dir().display()
);
}
let main = self
.bundles
.get(&None)
.expect("main bundle should have a key");
main.write_signed_bundle(dest_dir, settings)
}
}
pub struct SignedMachOInfo {
pub code_directory_blob: Vec<u8>,
pub designated_code_requirement: Option<String>,
}
impl SignedMachOInfo {
pub fn parse_data(data: &[u8]) -> Result<Self, AppleCodesignError> {
let macho = match Mach::parse(data)? {
Mach::Binary(macho) => macho,
Mach::Fat(multi_arch) => multi_arch.get(0)?,
};
let signature = macho
.code_signature()?
.ok_or(AppleCodesignError::BinaryNoCodeSignature)?;
let cd = if let Some(cd) = signature.code_directory_for_digest(DigestType::Sha256)? {
cd
} else if let Some(cd) = signature.code_directory_for_digest(DigestType::Sha1)? {
cd
} else if let Some(cd) = signature.code_directory()? {
cd
} else {
return Err(AppleCodesignError::BinaryNoCodeSignature);
};
let code_directory_blob = cd.to_blob_bytes()?;
let designated_code_requirement = if let Some(requirements) =
signature.code_requirements()?
{
if let Some(designated) = requirements.requirements.get(&RequirementType::Designated) {
let req = designated.parse_expressions()?;
Some(format!("{}", req[0]))
} else {
None
}
} else {
None
};
Ok(SignedMachOInfo {
code_directory_blob,
designated_code_requirement,
})
}
pub fn code_directory(&self) -> Result<Box<CodeDirectoryBlob<'_>>, AppleCodesignError> {
let blob = BlobData::from_blob_bytes(&self.code_directory_blob)?;
if let BlobData::CodeDirectory(cd) = blob {
Ok(cd)
} else {
Err(AppleCodesignError::BinaryNoCodeSignature)
}
}
pub fn notarization_ticket_record_name(&self) -> Result<String, AppleCodesignError> {
let cd = self.code_directory()?;
let digest_type: u8 = cd.digest_type.into();
let mut digest = cd.digest_with(cd.digest_type)?;
digest.truncate(20);
let digest = hex::encode(digest);
Ok(format!("2/{}/{}", digest_type, digest))
}
}
pub trait BundleFileHandler {
fn install_file(&self, file: &DirectoryBundleFile) -> Result<(), AppleCodesignError>;
fn sign_and_install_macho(
&self,
file: &DirectoryBundleFile,
) -> Result<SignedMachOInfo, AppleCodesignError>;
}
struct SingleBundleHandler<'a, 'key> {
settings: &'a SigningSettings<'key>,
dest_dir: PathBuf,
}
impl<'a, 'key> BundleFileHandler for SingleBundleHandler<'a, 'key> {
fn install_file(&self, file: &DirectoryBundleFile) -> Result<(), AppleCodesignError> {
let source_path = file.absolute_path();
let dest_path = self.dest_dir.join(file.relative_path());
if source_path != dest_path {
std::fs::create_dir_all(
dest_path
.parent()
.expect("parent directory should be available"),
)?;
let metadata = source_path.symlink_metadata()?;
let mtime = filetime::FileTime::from_last_modification_time(&metadata);
if let Some(target) = file
.symlink_target()
.map_err(AppleCodesignError::DirectoryBundle)?
{
info!(
"replicating symlink {} -> {}",
dest_path.display(),
target.display()
);
create_symlink(&dest_path, target)?;
filetime::set_symlink_file_times(
&dest_path,
filetime::FileTime::from_last_access_time(&metadata),
mtime,
)?;
} else {
info!(
"copying file {} -> {}",
source_path.display(),
dest_path.display()
);
std::fs::copy(&source_path, &dest_path)?;
filetime::set_file_mtime(&dest_path, mtime)?;
}
}
Ok(())
}
fn sign_and_install_macho(
&self,
file: &DirectoryBundleFile,
) -> Result<SignedMachOInfo, AppleCodesignError> {
info!("signing Mach-O file {}", file.relative_path().display());
let macho_data = std::fs::read(file.absolute_path())?;
let signer = MachOSigner::new(&macho_data)?;
let mut settings = self
.settings
.as_bundle_macho_settings(file.relative_path().to_string_lossy().as_ref());
settings.import_settings_from_macho(&macho_data)?;
if settings.binary_identifier(SettingsScope::Main).is_none() {
let identifier = file
.relative_path()
.file_name()
.expect("failure to extract filename (this should never happen)")
.to_string_lossy();
let identifier = identifier
.strip_suffix(".dylib")
.unwrap_or_else(|| identifier.as_ref());
info!(
"Mach-O is missing binary identifier; setting to {} based on file name",
identifier
);
settings.set_binary_identifier(SettingsScope::Main, identifier);
}
let mut new_data = Vec::<u8>::with_capacity(macho_data.len() + 2_usize.pow(17));
signer.write_signed_binary(&settings, &mut new_data)?;
let dest_path = self.dest_dir.join(file.relative_path());
info!("writing Mach-O to {}", dest_path.display());
write_macho_file(file.absolute_path(), &dest_path, &new_data)?;
SignedMachOInfo::parse_data(&new_data)
}
}
pub struct SingleBundleSigner {
bundle: DirectoryBundle,
}
impl SingleBundleSigner {
pub fn new(bundle: DirectoryBundle) -> Self {
Self { bundle }
}
pub fn write_signed_bundle(
&self,
dest_dir: impl AsRef<Path>,
settings: &SigningSettings,
) -> Result<DirectoryBundle, AppleCodesignError> {
let dest_dir = dest_dir.as_ref();
warn!(
"signing bundle at {} into {}",
self.bundle.root_dir().display(),
dest_dir.display()
);
if self.bundle.package_type() == BundlePackageType::Framework {
if self.bundle.root_dir().join("Versions").is_dir() {
warn!("found a versioned framework; each version will be signed as its own bundle");
let handler = SingleBundleHandler {
dest_dir: dest_dir.to_path_buf(),
settings,
};
for file in self
.bundle
.files(false)
.map_err(AppleCodesignError::DirectoryBundle)?
{
handler.install_file(&file)?;
}
return DirectoryBundle::new_from_path(dest_dir)
.map_err(AppleCodesignError::DirectoryBundle);
} else {
warn!("found an unversioned framework; signing like normal");
}
}
let dest_dir_root = dest_dir.to_path_buf();
let dest_dir = if self.bundle.shallow() {
dest_dir_root.clone()
} else {
dest_dir.join("Contents")
};
self.bundle
.identifier()
.map_err(AppleCodesignError::DirectoryBundle)?
.ok_or_else(|| AppleCodesignError::BundleNoIdentifier(self.bundle.info_plist_path()))?;
let mut resources_digests = settings.all_digests(SettingsScope::Main);
let main_exe = self
.bundle
.files(false)
.map_err(AppleCodesignError::DirectoryBundle)?
.into_iter()
.find(|f| matches!(f.is_main_executable(), Ok(true)));
if let Some(exe) = &main_exe {
let macho_data = std::fs::read(exe.absolute_path())?;
for (macho, macho_data) in iter_macho(&macho_data)? {
if let Some(targeting) = find_macho_targeting(macho_data, &macho)? {
let sha256_version = targeting.platform.sha256_digest_support()?;
if !sha256_version.matches(&targeting.minimum_os_version)
&& resources_digests != vec![DigestType::Sha1, DigestType::Sha256]
{
info!("main executable targets OS requiring SHA-1 signatures; activating SHA-1 + SHA-256 signing");
resources_digests = vec![DigestType::Sha1, DigestType::Sha256];
break;
}
}
}
}
warn!("collecting code resources files");
let mut resources_builder =
if self.bundle.resolve_path("Resources").is_dir() || !self.bundle.shallow() {
CodeResourcesBuilder::default_resources_rules()?
} else {
CodeResourcesBuilder::default_no_resources_rules()?
};
resources_builder.set_digests(resources_digests.into_iter());
resources_builder.add_exclusion_rule(CodeResourcesRule::new("^_CodeSignature/")?.exclude());
resources_builder.add_exclusion_rule(CodeResourcesRule::new("^CodeResources$")?.exclude());
let handler = SingleBundleHandler {
dest_dir: dest_dir_root.clone(),
settings,
};
let mut info_plist_data = None;
for file in self
.bundle
.files(true)
.map_err(AppleCodesignError::DirectoryBundle)?
{
if file
.is_main_executable()
.map_err(AppleCodesignError::DirectoryBundle)?
{
continue;
} else if file.is_info_plist() {
info!(
"{} is the Info.plist file; handling specially",
file.relative_path().display()
);
resources_builder.process_file(&file, &handler)?;
info_plist_data = Some(std::fs::read(file.absolute_path())?);
} else {
resources_builder.process_file(&file, &handler)?;
}
}
if self.bundle.package_type() != BundlePackageType::Framework {
let dest_bundle = DirectoryBundle::new_from_path(&dest_dir)
.map_err(AppleCodesignError::DirectoryBundle)?;
for (rel_path, nested_bundle) in dest_bundle
.nested_bundles(false)
.map_err(AppleCodesignError::DirectoryBundle)?
{
resources_builder.process_nested_bundle(&rel_path, &nested_bundle)?;
}
}
let code_resources_path = dest_dir.join("_CodeSignature").join("CodeResources");
warn!(
"writing sealed resources to {}",
code_resources_path.display()
);
std::fs::create_dir_all(code_resources_path.parent().unwrap())?;
let mut resources_data = Vec::<u8>::new();
resources_builder.write_code_resources(&mut resources_data)?;
{
let mut fh = std::fs::File::create(&code_resources_path)?;
fh.write_all(&resources_data)?;
}
if let Some(exe) = main_exe {
warn!("signing main executable {}", exe.relative_path().display());
let macho_data = std::fs::read(exe.absolute_path())?;
let signer = MachOSigner::new(&macho_data)?;
let mut settings = settings.clone();
settings.import_settings_from_macho(&macho_data)?;
if let Some(ident) = self
.bundle
.identifier()
.map_err(AppleCodesignError::DirectoryBundle)?
{
info!("setting main executable binary identifier to {} (derived from CFBundleIdentifier in Info.plist)", ident);
settings.set_binary_identifier(SettingsScope::Main, ident);
} else {
info!("unable to determine binary identifier from bundle's Info.plist (CFBundleIdentifier not set?)");
}
settings.set_code_resources_data(SettingsScope::Main, resources_data);
if let Some(info_plist_data) = info_plist_data {
settings.set_info_plist_data(SettingsScope::Main, info_plist_data);
}
let mut new_data = Vec::<u8>::with_capacity(macho_data.len() + 2_usize.pow(17));
signer.write_signed_binary(&settings, &mut new_data)?;
let dest_path = dest_dir_root.join(exe.relative_path());
info!("writing signed main executable to {}", dest_path.display());
write_macho_file(exe.absolute_path(), &dest_path, &new_data)?;
} else {
warn!("bundle has no main executable to sign specially");
}
DirectoryBundle::new_from_path(&dest_dir_root).map_err(AppleCodesignError::DirectoryBundle)
}
}