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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
use {
crate::{
code_hash::compute_code_hashes,
embedded_signature::EmbeddedSignature,
error::AppleCodesignError,
signing_settings::{SettingsScope, SigningSettings},
},
cryptographic_message_syntax::time_stamp_message_http,
goblin::mach::{
constants::{SEG_LINKEDIT, SEG_PAGEZERO, SEG_TEXT},
load_command::{
CommandVariant, LinkeditDataCommand, LC_BUILD_VERSION, SIZEOF_LINKEDIT_DATA_COMMAND,
},
parse_magic_and_ctx, Mach, MachO,
},
scroll::Pread,
x509_certificate::DigestAlgorithm,
};
pub trait AppleSignable {
fn code_signature(&self) -> Result<Option<EmbeddedSignature>, AppleCodesignError>;
fn executable_segment_boundary(&self) -> Result<(u64, u64), AppleCodesignError>;
fn code_signature_linkedit_start_offset(&self) -> Option<u32>;
fn code_signature_linkedit_end_offset(&self) -> Option<u32>;
fn code_limit_binary_offset(&self) -> Result<u64, AppleCodesignError>;
fn linkedit_data_before_signature(&self) -> Option<&[u8]>;
fn digestable_segment_data(&self) -> Vec<&[u8]>;
fn code_signature_load_command(&self) -> Option<LinkeditDataCommand>;
fn check_signing_capability(&self) -> Result<(), AppleCodesignError>;
fn estimate_embedded_signature_size(
&self,
settings: &SigningSettings,
) -> Result<usize, AppleCodesignError>;
}
impl<'a> AppleSignable for MachO<'a> {
fn code_signature(&self) -> Result<Option<EmbeddedSignature>, AppleCodesignError> {
if let Some(signature) = find_signature_data(self)? {
Ok(Some(EmbeddedSignature::from_bytes(
signature.signature_data,
)?))
} else {
Ok(None)
}
}
fn executable_segment_boundary(&self) -> Result<(u64, u64), AppleCodesignError> {
let segment = self
.segments
.iter()
.find(|segment| matches!(segment.name(), Ok(SEG_TEXT)))
.ok_or_else(|| AppleCodesignError::InvalidBinary("no __TEXT segment".into()))?;
Ok((segment.fileoff, segment.fileoff + segment.data.len() as u64))
}
fn code_signature_linkedit_start_offset(&self) -> Option<u32> {
let segment = self
.segments
.iter()
.find(|segment| matches!(segment.name(), Ok(SEG_LINKEDIT)));
if let (Some(segment), Some(command)) = (segment, self.code_signature_load_command()) {
Some((command.dataoff as u64 - segment.fileoff) as u32)
} else {
None
}
}
fn code_signature_linkedit_end_offset(&self) -> Option<u32> {
let start_offset = self.code_signature_linkedit_start_offset()?;
self.code_signature_load_command()
.map(|command| start_offset + command.datasize)
}
fn code_limit_binary_offset(&self) -> Result<u64, AppleCodesignError> {
let last_segment = self
.segments
.last()
.ok_or(AppleCodesignError::MissingLinkedit)?;
if !matches!(last_segment.name(), Ok(SEG_LINKEDIT)) {
return Err(AppleCodesignError::LinkeditNotLast);
}
if let Some(offset) = self.code_signature_linkedit_start_offset() {
Ok(last_segment.fileoff + offset as u64)
} else {
Ok(last_segment.fileoff + last_segment.data.len() as u64)
}
}
fn linkedit_data_before_signature(&self) -> Option<&[u8]> {
let segment = self
.segments
.iter()
.find(|segment| matches!(segment.name(), Ok(SEG_LINKEDIT)));
if let Some(segment) = segment {
if let Some(offset) = self.code_signature_linkedit_start_offset() {
Some(&segment.data[0..offset as usize])
} else {
Some(segment.data)
}
} else {
None
}
}
fn digestable_segment_data(&self) -> Vec<&[u8]> {
self.segments
.iter()
.filter(|segment| !matches!(segment.name(), Ok(SEG_PAGEZERO)))
.map(|segment| {
if matches!(segment.name(), Ok(SEG_LINKEDIT)) {
self.linkedit_data_before_signature()
.expect("__LINKEDIT data should resolve")
} else {
segment.data
}
})
.collect::<Vec<_>>()
}
fn code_signature_load_command(&self) -> Option<LinkeditDataCommand> {
self.load_commands.iter().find_map(|lc| {
if let CommandVariant::CodeSignature(command) = lc.command {
Some(command)
} else {
None
}
})
}
fn check_signing_capability(&self) -> Result<(), AppleCodesignError> {
let last_segment = self
.segments
.iter()
.last()
.ok_or(AppleCodesignError::MissingLinkedit)?;
if !matches!(last_segment.name(), Ok(SEG_LINKEDIT)) {
return Err(AppleCodesignError::LinkeditNotLast);
}
if let Some(offset) = self.code_signature_linkedit_end_offset() {
if offset as usize == last_segment.data.len() {
Ok(())
} else {
Err(AppleCodesignError::DataAfterSignature)
}
} else {
let last_load_command = self
.load_commands
.iter()
.last()
.ok_or_else(|| AppleCodesignError::InvalidBinary("no load commands".into()))?;
let first_section = self
.segments
.iter()
.map(|segment| segment.sections())
.collect::<Result<Vec<_>, _>>()?
.into_iter()
.flatten()
.next()
.ok_or_else(|| AppleCodesignError::InvalidBinary("no sections".into()))?;
let load_commands_end_offset =
last_load_command.offset + last_load_command.command.cmdsize();
if first_section.0.offset as usize - load_commands_end_offset
>= SIZEOF_LINKEDIT_DATA_COMMAND
{
Ok(())
} else {
Err(AppleCodesignError::LoadCommandNoRoom)
}
}
}
fn estimate_embedded_signature_size(
&self,
settings: &SigningSettings,
) -> Result<usize, AppleCodesignError> {
let code_directory_count = 1 + settings
.extra_digests(SettingsScope::Main)
.map(|x| x.len())
.unwrap_or_default();
let mut size = 1024 * code_directory_count;
size += compute_code_hashes(self, *settings.digest_type(), None)?
.into_iter()
.map(|x| x.len())
.sum::<usize>();
if let Some(digests) = settings.extra_digests(SettingsScope::Main) {
for digest in digests {
size += compute_code_hashes(self, *digest, None)?
.into_iter()
.map(|x| x.len())
.sum::<usize>();
}
}
if settings.signing_key().is_some() {
size += 4096;
}
for cert in settings.certificate_chain() {
size += cert.constructed_data().len();
}
if let Some(timestamp_url) = settings.time_stamp_url() {
let message = b"deadbeef".repeat(32);
if let Ok(response) =
time_stamp_message_http(timestamp_url.clone(), &message, DigestAlgorithm::Sha256)
{
if response.is_success() {
if let Some(l) = response.token_content_size() {
size += l;
} else {
size += 8192;
}
} else {
size += 8192;
}
} else {
size += 8192;
}
}
size += 1024 - size % 1024;
Ok(size)
}
}
pub fn iter_macho(
macho_data: &[u8],
) -> Result<impl Iterator<Item = MachO<'_>>, AppleCodesignError> {
let mach = Mach::parse(macho_data)?;
let machos = match mach {
Mach::Binary(macho) => {
vec![macho]
}
Mach::Fat(multiarch) => {
let mut machos = vec![];
for index in 0..multiarch.narches {
let macho = multiarch.get(index)?;
machos.push(macho);
}
machos
}
};
Ok(machos.into_iter())
}
pub struct MachOSignatureData<'a> {
pub linkedit_segment_index: usize,
pub linkedit_segment_start_offset: usize,
pub linkedit_segment_end_offset: usize,
pub linkedit_signature_start_offset: usize,
pub linkedit_signature_end_offset: usize,
pub signature_start_offset: usize,
pub signature_end_offset: usize,
pub linkedit_segment_data: &'a [u8],
pub signature_data: &'a [u8],
}
pub fn find_signature_data<'a>(
obj: &'a MachO,
) -> Result<Option<MachOSignatureData<'a>>, AppleCodesignError> {
if let Some(linkedit_data_command) = obj.load_commands.iter().find_map(|load_command| {
if let CommandVariant::CodeSignature(command) = &load_command.command {
Some(command)
} else {
None
}
}) {
let (linkedit_segment_index, linkedit) = obj
.segments
.iter()
.enumerate()
.find(|(_, segment)| {
if let Ok(name) = segment.name() {
name == SEG_LINKEDIT
} else {
false
}
})
.ok_or(AppleCodesignError::MissingLinkedit)?;
let linkedit_segment_start_offset = linkedit.fileoff as usize;
let linkedit_segment_end_offset = linkedit_segment_start_offset + linkedit.data.len();
let linkedit_signature_start_offset = linkedit_data_command.dataoff as usize;
let linkedit_signature_end_offset =
linkedit_signature_start_offset + linkedit_data_command.datasize as usize;
let signature_start_offset =
linkedit_data_command.dataoff as usize - linkedit.fileoff as usize;
let signature_end_offset = signature_start_offset + linkedit_data_command.datasize as usize;
let signature_data = &linkedit.data[signature_start_offset..signature_end_offset];
Ok(Some(MachOSignatureData {
linkedit_segment_index,
linkedit_segment_start_offset,
linkedit_segment_end_offset,
linkedit_signature_start_offset,
linkedit_signature_end_offset,
signature_start_offset,
signature_end_offset,
linkedit_segment_data: linkedit.data,
signature_data,
}))
} else {
Ok(None)
}
}
#[derive(Clone, Debug, Pread)]
pub struct BuildVersionCommand {
pub cmd: u32,
pub cmdsize: u32,
pub platform: u32,
pub minos: u32,
pub sdk: u32,
pub ntools: u32,
}
pub enum Platform {
MacOs,
IOs,
TvOs,
WatchOs,
BridgeOs,
MacCatalyst,
IosSimulator,
TvOsSimulator,
WatchOsSimulator,
DriverKit,
Unknown(u32),
}
impl std::fmt::Display for Platform {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::MacOs => f.write_str("macOS"),
Self::IOs => f.write_str("iOS"),
Self::TvOs => f.write_str("tvOS"),
Self::WatchOs => f.write_str("watchOS"),
Self::BridgeOs => f.write_str("bridgeOS"),
Self::MacCatalyst => f.write_str("macCatalyst"),
Self::IosSimulator => f.write_str("iOSSimulator"),
Self::TvOsSimulator => f.write_str("tvOSSimulator"),
Self::WatchOsSimulator => f.write_str("watchOSSimulator"),
Self::DriverKit => f.write_str("driverKit"),
Self::Unknown(v) => f.write_fmt(format_args!("Unknown ({})", v)),
}
}
}
impl From<u32> for Platform {
fn from(v: u32) -> Self {
match v {
1 => Self::MacOs,
2 => Self::IOs,
3 => Self::TvOs,
4 => Self::WatchOs,
5 => Self::BridgeOs,
6 => Self::MacCatalyst,
7 => Self::IosSimulator,
8 => Self::TvOsSimulator,
9 => Self::WatchOsSimulator,
10 => Self::DriverKit,
_ => Self::Unknown(v),
}
}
}
pub struct MachoTarget {
pub platform: Platform,
pub minimum_os_version: semver::Version,
pub sdk_version: semver::Version,
}
pub fn parse_version_nibbles(v: u32) -> semver::Version {
let major = v >> 16;
let minor = v << 16 >> 24;
let patch = v & 0xff;
semver::Version::new(major as _, minor as _, patch as _)
}
pub fn semver_to_macho_target_version(version: &semver::Version) -> u32 {
let major = version.major as u32;
let minor = version.minor as u32;
let patch = version.patch as u32;
(major << 16) | ((minor & 0xff) << 8) | (patch & 0xff)
}
pub fn find_macho_targeting(
macho_data: &[u8],
macho: &MachO,
) -> Result<Option<MachoTarget>, AppleCodesignError> {
let ctx = parse_magic_and_ctx(macho_data, 0)?
.1
.expect("context should have been parsed before");
for lc in &macho.load_commands {
if lc.command.cmd() == LC_BUILD_VERSION {
let build_version = macho_data.pread_with::<BuildVersionCommand>(lc.offset, ctx.le)?;
return Ok(Some(MachoTarget {
platform: build_version.platform.into(),
minimum_os_version: parse_version_nibbles(build_version.minos),
sdk_version: parse_version_nibbles(build_version.sdk),
}));
}
}
for lc in &macho.load_commands {
let command = match lc.command {
CommandVariant::VersionMinMacosx(c) => Some((c, Platform::MacOs)),
CommandVariant::VersionMinIphoneos(c) => Some((c, Platform::IOs)),
CommandVariant::VersionMinTvos(c) => Some((c, Platform::TvOs)),
CommandVariant::VersionMinWatchos(c) => Some((c, Platform::WatchOs)),
_ => None,
};
if let Some((command, platform)) = command {
return Ok(Some(MachoTarget {
platform,
minimum_os_version: parse_version_nibbles(command.version),
sdk_version: parse_version_nibbles(command.sdk),
}));
}
}
Ok(None)
}
#[cfg(test)]
mod tests {
use {
super::*,
crate::embedded_signature::Blob,
std::{
io::Read,
path::{Path, PathBuf},
},
};
const MACHO_UNIVERSAL_MAGIC: [u8; 4] = [0xca, 0xfe, 0xba, 0xbe];
const MACHO_64BIT_MAGIC: [u8; 4] = [0xfe, 0xed, 0xfa, 0xcf];
fn find_likely_macho_files(path: &Path) -> Vec<PathBuf> {
let mut res = Vec::new();
let dir = std::fs::read_dir(path).unwrap();
for entry in dir {
let entry = entry.unwrap();
if let Ok(mut fh) = std::fs::File::open(&entry.path()) {
let mut magic = [0; 4];
if let Ok(size) = fh.read(&mut magic) {
if size == 4 && (magic == MACHO_UNIVERSAL_MAGIC || magic == MACHO_64BIT_MAGIC) {
res.push(entry.path());
}
}
}
}
res
}
fn find_apple_embedded_signature<'a>(
macho: &'a goblin::mach::MachO,
) -> Option<EmbeddedSignature<'a>> {
if let Ok(Some(signature)) = macho.code_signature() {
Some(signature)
} else {
None
}
}
fn validate_macho(path: &Path, macho: &MachO) {
if let Some(signature) = find_apple_embedded_signature(macho) {
for blob in &signature.blobs {
match blob.clone().into_parsed_blob() {
Ok(parsed) => {
match parsed.blob.to_blob_bytes() {
Ok(serialized) => {
if serialized != blob.data {
println!("blob serialization roundtrip failure on {}: index {}, magic {:?}",
path.display(),
blob.index,
blob.magic,
);
}
}
Err(e) => {
println!(
"blob serialization failure on {}; index {}, magic {:?}: {:?}",
path.display(),
blob.index,
blob.magic,
e
);
}
}
}
Err(e) => {
println!(
"blob parse failure on {}; index {}, magic {:?}: {:?}",
path.display(),
blob.index,
blob.magic,
e
);
}
}
}
if matches!(signature.signature_data(), Ok(Some(_))) {
match signature.signed_data() {
Ok(Some(signed_data)) => {
for signer in signed_data.signers() {
if let Err(e) = signer.verify_signature_with_signed_data(&signed_data) {
println!(
"signature verification failed for {}: {}",
path.display(),
e
);
}
if let Ok(()) =
signer.verify_message_digest_with_signed_data(&signed_data)
{
println!(
"message digest verification unexpectedly correct for {}",
path.display()
);
}
}
}
Ok(None) => {
panic!("this shouln't happen (validated signature data is present");
}
Err(e) => {
println!("error performing CMS parse of {}: {:?}", path.display(), e);
}
}
}
}
}
fn validate_macho_in_dir(dir: &Path) {
for path in find_likely_macho_files(dir).into_iter() {
if let Ok(file_data) = std::fs::read(&path) {
if let Ok(mach) = goblin::mach::Mach::parse(&file_data) {
match mach {
goblin::mach::Mach::Binary(macho) => {
validate_macho(&path, &macho);
}
goblin::mach::Mach::Fat(multiarch) => {
for i in 0..multiarch.narches {
if let Ok(macho) = multiarch.get(i) {
validate_macho(&path, &macho);
}
}
}
}
}
}
}
}
#[test]
fn parse_applications_macho_signatures() {
if let Ok(dir) = std::fs::read_dir("/Applications") {
for entry in dir {
let entry = entry.unwrap();
let search_dir = entry.path().join("Contents").join("MacOS");
if search_dir.exists() {
validate_macho_in_dir(&search_dir);
}
}
}
for dir in &["/usr/bin", "/usr/local/bin", "/opt/homebrew/bin"] {
let dir = PathBuf::from(dir);
if dir.exists() {
validate_macho_in_dir(&dir);
}
}
}
#[test]
fn version_nibbles() {
assert_eq!(
parse_version_nibbles(12 << 16 | 1 << 8 | 2),
semver::Version::new(12, 1, 2)
);
assert_eq!(
parse_version_nibbles(11 << 16 | 10 << 8 | 15),
semver::Version::new(11, 10, 15)
);
assert_eq!(
semver_to_macho_target_version(&semver::Version::new(12, 1, 2)),
12 << 16 | 1 << 8 | 2
);
}
}