]>
Commit | Line | Data |
---|---|---|
b1ab9ed8 | 1 | /* |
d8f41ccd | 2 | * Copyright (c) 2006-2014 Apple Inc. All Rights Reserved. |
b1ab9ed8 A |
3 | * |
4 | * @APPLE_LICENSE_HEADER_START@ | |
5 | * | |
6 | * This file contains Original Code and/or Modifications of Original Code | |
7 | * as defined in and that are subject to the Apple Public Source License | |
8 | * Version 2.0 (the 'License'). You may not use this file except in | |
9 | * compliance with the License. Please obtain a copy of the License at | |
10 | * http://www.opensource.apple.com/apsl/ and read it before using this | |
11 | * file. | |
12 | * | |
13 | * The Original Code and all software distributed under the License are | |
14 | * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER | |
15 | * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, | |
16 | * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, | |
17 | * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. | |
18 | * Please see the License for the specific language governing rights and | |
19 | * limitations under the License. | |
20 | * | |
21 | * @APPLE_LICENSE_HEADER_END@ | |
22 | */ | |
23 | ||
24 | // | |
25 | // StaticCode - SecStaticCode API objects | |
26 | // | |
27 | #include "StaticCode.h" | |
28 | #include "Code.h" | |
29 | #include "reqmaker.h" | |
30 | #include "drmaker.h" | |
31 | #include "reqdumper.h" | |
427c49bc | 32 | #include "reqparser.h" |
b1ab9ed8 A |
33 | #include "sigblob.h" |
34 | #include "resources.h" | |
b1ab9ed8 A |
35 | #include "detachedrep.h" |
36 | #include "csdatabase.h" | |
80e23899 | 37 | #include "dirscanner.h" |
b1ab9ed8 A |
38 | #include <CoreFoundation/CFURLAccess.h> |
39 | #include <Security/SecPolicyPriv.h> | |
40 | #include <Security/SecTrustPriv.h> | |
41 | #include <Security/SecCertificatePriv.h> | |
42 | #include <Security/CMSPrivate.h> | |
43 | #include <Security/SecCmsContentInfo.h> | |
44 | #include <Security/SecCmsSignerInfo.h> | |
45 | #include <Security/SecCmsSignedData.h> | |
46 | #include <Security/cssmapplePriv.h> | |
47 | #include <security_utilities/unix++.h> | |
48 | #include <security_utilities/cfmunge.h> | |
49 | #include <Security/CMSDecoder.h> | |
420ff9d9 | 50 | #include <security_utilities/logging.h> |
80e23899 A |
51 | #include <dirent.h> |
52 | #include <sstream> | |
d87e1158 | 53 | #include <IOKit/storage/IOStorageDeviceCharacteristics.h> |
b1ab9ed8 A |
54 | |
55 | ||
56 | namespace Security { | |
57 | namespace CodeSigning { | |
58 | ||
59 | using namespace UnixPlusPlus; | |
60 | ||
420ff9d9 | 61 | // A requirement representing a Mac or iOS dev cert, a Mac or iOS distribution cert, or a developer ID |
d8f41ccd A |
62 | static const char WWDRRequirement[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.2] exists"; |
63 | static const char MACWWDRRequirement[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.12] exists"; | |
420ff9d9 A |
64 | static const char developerID[] = "anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists" |
65 | " and certificate leaf[field.1.2.840.113635.100.6.1.13] exists"; | |
66 | static const char distributionCertificate[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.7] exists"; | |
67 | static const char iPhoneDistributionCert[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.4] exists"; | |
b1ab9ed8 | 68 | |
427c49bc A |
69 | // |
70 | // Map a component slot number to a suitable error code for a failure | |
71 | // | |
72 | static inline OSStatus errorForSlot(CodeDirectory::SpecialSlot slot) | |
73 | { | |
74 | switch (slot) { | |
75 | case cdInfoSlot: | |
76 | return errSecCSInfoPlistFailed; | |
77 | case cdResourceDirSlot: | |
78 | return errSecCSResourceDirectoryFailed; | |
79 | default: | |
80 | return errSecCSSignatureFailed; | |
81 | } | |
82 | } | |
83 | ||
84 | ||
b1ab9ed8 A |
85 | // |
86 | // Construct a SecStaticCode object given a disk representation object | |
87 | // | |
88 | SecStaticCode::SecStaticCode(DiskRep *rep) | |
89 | : mRep(rep), | |
90 | mValidated(false), mExecutableValidated(false), mResourcesValidated(false), mResourcesValidContext(NULL), | |
d87e1158 A |
91 | mProgressQueue("com.apple.security.validation-progress", false, DISPATCH_QUEUE_PRIORITY_DEFAULT), |
92 | mDesignatedReq(NULL), mGotResourceBase(false), mMonitor(NULL), mLimitedAsync(NULL), mEvalDetails(NULL) | |
b1ab9ed8 A |
93 | { |
94 | CODESIGN_STATIC_CREATE(this, rep); | |
d8f41ccd A |
95 | CFRef<CFDataRef> codeDirectory = rep->codeDirectory(); |
96 | if (codeDirectory && CFDataGetLength(codeDirectory) <= 0) | |
97 | MacOSError::throwMe(errSecCSSignatureInvalid); | |
b1ab9ed8 A |
98 | checkForSystemSignature(); |
99 | } | |
100 | ||
101 | ||
102 | // | |
103 | // Clean up a SecStaticCode object | |
104 | // | |
105 | SecStaticCode::~SecStaticCode() throw() | |
106 | try { | |
107 | ::free(const_cast<Requirement *>(mDesignatedReq)); | |
d87e1158 A |
108 | delete mResourcesValidContext; |
109 | delete mLimitedAsync; | |
b1ab9ed8 A |
110 | } catch (...) { |
111 | return; | |
112 | } | |
113 | ||
d87e1158 A |
114 | // |
115 | // Initialize a nested SecStaticCode object from its parent | |
116 | // | |
117 | void SecStaticCode::initializeFromParent(const SecStaticCode& parent) { | |
118 | setMonitor(parent.monitor()); | |
119 | if (parent.mLimitedAsync) | |
120 | mLimitedAsync = new LimitedAsync(*parent.mLimitedAsync); | |
121 | } | |
b1ab9ed8 A |
122 | |
123 | // | |
124 | // CF-level comparison of SecStaticCode objects compares CodeDirectory hashes if signed, | |
125 | // and falls back on comparing canonical paths if (both are) not. | |
126 | // | |
127 | bool SecStaticCode::equal(SecCFObject &secOther) | |
128 | { | |
129 | SecStaticCode *other = static_cast<SecStaticCode *>(&secOther); | |
130 | CFDataRef mine = this->cdHash(); | |
131 | CFDataRef his = other->cdHash(); | |
132 | if (mine || his) | |
133 | return mine && his && CFEqual(mine, his); | |
134 | else | |
80e23899 | 135 | return CFEqual(CFRef<CFURLRef>(this->copyCanonicalPath()), CFRef<CFURLRef>(other->copyCanonicalPath())); |
b1ab9ed8 A |
136 | } |
137 | ||
138 | CFHashCode SecStaticCode::hash() | |
139 | { | |
140 | if (CFDataRef h = this->cdHash()) | |
141 | return CFHash(h); | |
142 | else | |
80e23899 | 143 | return CFHash(CFRef<CFURLRef>(this->copyCanonicalPath())); |
b1ab9ed8 A |
144 | } |
145 | ||
146 | ||
427c49bc A |
147 | // |
148 | // Invoke a stage monitor if registered | |
149 | // | |
150 | CFTypeRef SecStaticCode::reportEvent(CFStringRef stage, CFDictionaryRef info) | |
151 | { | |
152 | if (mMonitor) | |
153 | return mMonitor(this->handle(false), stage, info); | |
154 | else | |
155 | return NULL; | |
156 | } | |
d8f41ccd A |
157 | |
158 | void SecStaticCode::prepareProgress(unsigned int workload) | |
159 | { | |
d87e1158 | 160 | dispatch_sync(mProgressQueue, ^{ |
d8f41ccd | 161 | mCancelPending = false; // not cancelled |
d87e1158 | 162 | }); |
d8f41ccd A |
163 | if (mValidationFlags & kSecCSReportProgress) { |
164 | mCurrentWork = 0; // nothing done yet | |
165 | mTotalWork = workload; // totally fake - we don't know how many files we'll get to chew | |
166 | } | |
167 | } | |
168 | ||
169 | void SecStaticCode::reportProgress(unsigned amount /* = 1 */) | |
170 | { | |
171 | if (mMonitor && (mValidationFlags & kSecCSReportProgress)) { | |
d8f41ccd | 172 | // update progress and report |
d87e1158 A |
173 | __block bool cancel = false; |
174 | dispatch_sync(mProgressQueue, ^{ | |
175 | if (mCancelPending) | |
176 | cancel = true; | |
177 | mCurrentWork += amount; | |
178 | mMonitor(this->handle(false), CFSTR("progress"), CFTemp<CFDictionaryRef>("{current=%d,total=%d}", mCurrentWork, mTotalWork)); | |
179 | }); | |
180 | // if cancellation is pending, abort now | |
181 | if (cancel) | |
182 | MacOSError::throwMe(errSecCSCancelled); | |
d8f41ccd A |
183 | } |
184 | } | |
185 | ||
186 | ||
80e23899 A |
187 | // |
188 | // Set validation conditions for fine-tuning legacy tolerance | |
189 | // | |
190 | static void addError(CFTypeRef cfError, void* context) | |
191 | { | |
192 | if (CFGetTypeID(cfError) == CFNumberGetTypeID()) { | |
193 | int64_t error; | |
194 | CFNumberGetValue(CFNumberRef(cfError), kCFNumberSInt64Type, (void*)&error); | |
195 | MacOSErrorSet* errors = (MacOSErrorSet*)context; | |
196 | errors->insert(OSStatus(error)); | |
197 | } | |
198 | } | |
199 | ||
200 | void SecStaticCode::setValidationModifiers(CFDictionaryRef conditions) | |
201 | { | |
202 | if (conditions) { | |
203 | CFDictionary source(conditions, errSecCSDbCorrupt); | |
204 | mAllowOmissions = source.get<CFArrayRef>("omissions"); | |
205 | if (CFArrayRef errors = source.get<CFArrayRef>("errors")) | |
206 | CFArrayApplyFunction(errors, CFRangeMake(0, CFArrayGetCount(errors)), addError, &this->mTolerateErrors); | |
207 | } | |
208 | } | |
427c49bc | 209 | |
d8f41ccd A |
210 | |
211 | // | |
212 | // Request cancellation of a validation in progress. | |
213 | // We do this by posting an abort flag that is checked periodically. | |
214 | // | |
215 | void SecStaticCode::cancelValidation() | |
216 | { | |
d8f41ccd A |
217 | if (!(mValidationFlags & kSecCSReportProgress)) // not using progress reporting; cancel won't make it through |
218 | MacOSError::throwMe(errSecCSInvalidFlags); | |
d87e1158 A |
219 | dispatch_sync(mProgressQueue, ^{ |
220 | mCancelPending = true; | |
221 | }); | |
d8f41ccd A |
222 | } |
223 | ||
427c49bc | 224 | |
b1ab9ed8 A |
225 | // |
226 | // Attach a detached signature. | |
227 | // | |
228 | void SecStaticCode::detachedSignature(CFDataRef sigData) | |
229 | { | |
230 | if (sigData) { | |
427c49bc | 231 | mDetachedSig = sigData; |
b1ab9ed8 A |
232 | mRep = new DetachedRep(sigData, mRep->base(), "explicit detached"); |
233 | CODESIGN_STATIC_ATTACH_EXPLICIT(this, mRep); | |
234 | } else { | |
427c49bc | 235 | mDetachedSig = NULL; |
b1ab9ed8 A |
236 | mRep = mRep->base(); |
237 | CODESIGN_STATIC_ATTACH_EXPLICIT(this, NULL); | |
238 | } | |
239 | } | |
240 | ||
241 | ||
242 | // | |
243 | // Consult the system detached signature database to see if it contains | |
244 | // a detached signature for this StaticCode. If it does, fetch and attach it. | |
245 | // We do this only if the code has no signature already attached. | |
246 | // | |
247 | void SecStaticCode::checkForSystemSignature() | |
248 | { | |
427c49bc A |
249 | if (!this->isSigned()) { |
250 | SignatureDatabase db; | |
251 | if (db.isOpen()) | |
252 | try { | |
253 | if (RefPointer<DiskRep> dsig = db.findCode(mRep)) { | |
254 | CODESIGN_STATIC_ATTACH_SYSTEM(this, dsig); | |
255 | mRep = dsig; | |
256 | } | |
257 | } catch (...) { | |
b1ab9ed8 | 258 | } |
427c49bc | 259 | } |
b1ab9ed8 A |
260 | } |
261 | ||
262 | ||
263 | // | |
264 | // Return a descriptive string identifying the source of the code signature | |
265 | // | |
266 | string SecStaticCode::signatureSource() | |
267 | { | |
268 | if (!isSigned()) | |
269 | return "unsigned"; | |
270 | if (DetachedRep *rep = dynamic_cast<DetachedRep *>(mRep.get())) | |
271 | return rep->source(); | |
272 | return "embedded"; | |
273 | } | |
274 | ||
275 | ||
276 | // | |
277 | // Do ::required, but convert incoming SecCodeRefs to their SecStaticCodeRefs | |
278 | // (if possible). | |
279 | // | |
280 | SecStaticCode *SecStaticCode::requiredStatic(SecStaticCodeRef ref) | |
281 | { | |
282 | SecCFObject *object = SecCFObject::required(ref, errSecCSInvalidObjectRef); | |
283 | if (SecStaticCode *scode = dynamic_cast<SecStaticCode *>(object)) | |
284 | return scode; | |
285 | else if (SecCode *code = dynamic_cast<SecCode *>(object)) | |
286 | return code->staticCode(); | |
287 | else // neither (a SecSomethingElse) | |
288 | MacOSError::throwMe(errSecCSInvalidObjectRef); | |
289 | } | |
290 | ||
291 | SecCode *SecStaticCode::optionalDynamic(SecStaticCodeRef ref) | |
292 | { | |
293 | SecCFObject *object = SecCFObject::required(ref, errSecCSInvalidObjectRef); | |
294 | if (dynamic_cast<SecStaticCode *>(object)) | |
295 | return NULL; | |
296 | else if (SecCode *code = dynamic_cast<SecCode *>(object)) | |
297 | return code; | |
298 | else // neither (a SecSomethingElse) | |
299 | MacOSError::throwMe(errSecCSInvalidObjectRef); | |
300 | } | |
301 | ||
302 | ||
303 | // | |
304 | // Void all cached validity data. | |
305 | // | |
306 | // We also throw out cached components, because the new signature data may have | |
307 | // a different idea of what components should be present. We could reconcile the | |
308 | // cached data instead, if performance seems to be impacted. | |
309 | // | |
310 | void SecStaticCode::resetValidity() | |
311 | { | |
312 | CODESIGN_EVAL_STATIC_RESET(this); | |
313 | mValidated = false; | |
427c49bc | 314 | mExecutableValidated = mResourcesValidated = false; |
b1ab9ed8 A |
315 | if (mResourcesValidContext) { |
316 | delete mResourcesValidContext; | |
317 | mResourcesValidContext = NULL; | |
318 | } | |
319 | mDir = NULL; | |
320 | mSignature = NULL; | |
321 | for (unsigned n = 0; n < cdSlotCount; n++) | |
322 | mCache[n] = NULL; | |
323 | mInfoDict = NULL; | |
324 | mEntitlements = NULL; | |
325 | mResourceDict = NULL; | |
326 | mDesignatedReq = NULL; | |
e3d3b979 | 327 | mCDHash = NULL; |
b1ab9ed8 A |
328 | mGotResourceBase = false; |
329 | mTrust = NULL; | |
330 | mCertChain = NULL; | |
331 | mEvalDetails = NULL; | |
332 | mRep->flush(); | |
333 | ||
334 | // we may just have updated the system database, so check again | |
335 | checkForSystemSignature(); | |
336 | } | |
337 | ||
338 | ||
339 | // | |
340 | // Retrieve a sealed component by special slot index. | |
341 | // If the CodeDirectory has already been validated, validate against that. | |
342 | // Otherwise, retrieve the component without validation (but cache it). Validation | |
343 | // will go through the cache and validate all cached components. | |
344 | // | |
345 | CFDataRef SecStaticCode::component(CodeDirectory::SpecialSlot slot, OSStatus fail /* = errSecCSSignatureFailed */) | |
346 | { | |
347 | assert(slot <= cdSlotMax); | |
348 | ||
349 | CFRef<CFDataRef> &cache = mCache[slot]; | |
350 | if (!cache) { | |
351 | if (CFRef<CFDataRef> data = mRep->component(slot)) { | |
352 | if (validated()) // if the directory has been validated... | |
353 | if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data), // ... and it's no good | |
354 | CFDataGetLength(data), -slot)) | |
427c49bc | 355 | MacOSError::throwMe(errorForSlot(slot)); // ... then bail |
b1ab9ed8 A |
356 | cache = data; // it's okay, cache it |
357 | } else { // absent, mark so | |
358 | if (validated()) // if directory has been validated... | |
359 | if (codeDirectory()->slotIsPresent(-slot)) // ... and the slot is NOT missing | |
427c49bc | 360 | MacOSError::throwMe(errorForSlot(slot)); // was supposed to be there |
b1ab9ed8 A |
361 | cache = CFDataRef(kCFNull); // white lie |
362 | } | |
363 | } | |
364 | return (cache == CFDataRef(kCFNull)) ? NULL : cache.get(); | |
365 | } | |
366 | ||
367 | ||
368 | // | |
369 | // Get the CodeDirectory. | |
370 | // Throws (if check==true) or returns NULL (check==false) if there is none. | |
371 | // Always throws if the CodeDirectory exists but is invalid. | |
372 | // NEVER validates against the signature. | |
373 | // | |
374 | const CodeDirectory *SecStaticCode::codeDirectory(bool check /* = true */) | |
375 | { | |
376 | if (!mDir) { | |
377 | if (mDir.take(mRep->codeDirectory())) { | |
378 | const CodeDirectory *dir = reinterpret_cast<const CodeDirectory *>(CFDataGetBytePtr(mDir)); | |
379 | dir->checkIntegrity(); | |
380 | } | |
381 | } | |
382 | if (mDir) | |
383 | return reinterpret_cast<const CodeDirectory *>(CFDataGetBytePtr(mDir)); | |
384 | if (check) | |
385 | MacOSError::throwMe(errSecCSUnsigned); | |
386 | return NULL; | |
387 | } | |
388 | ||
389 | ||
390 | // | |
391 | // Get the hash of the CodeDirectory. | |
392 | // Returns NULL if there is none. | |
393 | // | |
394 | CFDataRef SecStaticCode::cdHash() | |
395 | { | |
396 | if (!mCDHash) { | |
397 | if (const CodeDirectory *cd = codeDirectory(false)) { | |
398 | SHA1 hash; | |
399 | hash(cd, cd->length()); | |
400 | SHA1::Digest digest; | |
401 | hash.finish(digest); | |
402 | mCDHash.take(makeCFData(digest, sizeof(digest))); | |
403 | CODESIGN_STATIC_CDHASH(this, digest, sizeof(digest)); | |
404 | } | |
405 | } | |
406 | return mCDHash; | |
407 | } | |
408 | ||
409 | ||
410 | // | |
411 | // Return the CMS signature blob; NULL if none found. | |
412 | // | |
413 | CFDataRef SecStaticCode::signature() | |
414 | { | |
415 | if (!mSignature) | |
416 | mSignature.take(mRep->signature()); | |
417 | if (mSignature) | |
418 | return mSignature; | |
419 | MacOSError::throwMe(errSecCSUnsigned); | |
420 | } | |
421 | ||
422 | ||
423 | // | |
424 | // Verify the signature on the CodeDirectory. | |
425 | // If this succeeds (doesn't throw), the CodeDirectory is statically trustworthy. | |
426 | // Any outcome (successful or not) is cached for the lifetime of the StaticCode. | |
427 | // | |
428 | void SecStaticCode::validateDirectory() | |
429 | { | |
430 | // echo previous outcome, if any | |
949d2ff0 A |
431 | // track revocation separately, as it may not have been checked |
432 | // during the initial validation | |
433 | if (!validated() || ((mValidationFlags & kSecCSEnforceRevocationChecks) && !revocationChecked())) | |
b1ab9ed8 A |
434 | try { |
435 | // perform validation (or die trying) | |
436 | CODESIGN_EVAL_STATIC_DIRECTORY(this); | |
437 | mValidationExpired = verifySignature(); | |
949d2ff0 A |
438 | if (mValidationFlags & kSecCSEnforceRevocationChecks) |
439 | mRevocationChecked = true; | |
440 | ||
b1ab9ed8 A |
441 | for (CodeDirectory::SpecialSlot slot = codeDirectory()->maxSpecialSlot(); slot >= 1; --slot) |
442 | if (mCache[slot]) // if we already loaded that resource... | |
427c49bc | 443 | validateComponent(slot, errorForSlot(slot)); // ... then check it now |
b1ab9ed8 | 444 | mValidated = true; // we've done the deed... |
427c49bc | 445 | mValidationResult = errSecSuccess; // ... and it was good |
b1ab9ed8 A |
446 | } catch (const CommonError &err) { |
447 | mValidated = true; | |
448 | mValidationResult = err.osStatus(); | |
449 | throw; | |
450 | } catch (...) { | |
451 | secdebug("staticCode", "%p validation threw non-common exception", this); | |
452 | mValidated = true; | |
453 | mValidationResult = errSecCSInternalError; | |
454 | throw; | |
455 | } | |
456 | assert(validated()); | |
427c49bc | 457 | if (mValidationResult == errSecSuccess) { |
b1ab9ed8 | 458 | if (mValidationExpired) |
d8f41ccd | 459 | if ((mValidationFlags & kSecCSConsiderExpiration) |
b1ab9ed8 A |
460 | || (codeDirectory()->flags & kSecCodeSignatureForceExpiration)) |
461 | MacOSError::throwMe(CSSMERR_TP_CERT_EXPIRED); | |
462 | } else | |
463 | MacOSError::throwMe(mValidationResult); | |
464 | } | |
465 | ||
466 | ||
467 | // | |
468 | // Load and validate the CodeDirectory and all components *except* those related to the resource envelope. | |
469 | // Those latter components are checked by validateResources(). | |
470 | // | |
471 | void SecStaticCode::validateNonResourceComponents() | |
472 | { | |
473 | this->validateDirectory(); | |
474 | for (CodeDirectory::SpecialSlot slot = codeDirectory()->maxSpecialSlot(); slot >= 1; --slot) | |
475 | switch (slot) { | |
476 | case cdResourceDirSlot: // validated by validateResources | |
477 | break; | |
478 | default: | |
479 | this->component(slot); // loads and validates | |
480 | break; | |
481 | } | |
482 | } | |
483 | ||
484 | ||
485 | // | |
486 | // Get the (signed) signing date from the code signature. | |
487 | // Sadly, we need to validate the signature to get the date (as a side benefit). | |
488 | // This means that you can't get the signing time for invalidly signed code. | |
489 | // | |
490 | // We could run the decoder "almost to" verification to avoid this, but there seems | |
491 | // little practical point to such a duplication of effort. | |
492 | // | |
493 | CFAbsoluteTime SecStaticCode::signingTime() | |
494 | { | |
495 | validateDirectory(); | |
496 | return mSigningTime; | |
497 | } | |
498 | ||
499 | CFAbsoluteTime SecStaticCode::signingTimestamp() | |
500 | { | |
501 | validateDirectory(); | |
502 | return mSigningTimestamp; | |
503 | } | |
504 | ||
505 | ||
506 | // | |
507 | // Verify the CMS signature on the CodeDirectory. | |
508 | // This performs the cryptographic tango. It returns if the signature is valid, | |
509 | // or throws if it is not. As a side effect, a successful return sets up the | |
510 | // cached certificate chain for future use. | |
511 | // Returns true if the signature is expired (the X.509 sense), false if it's not. | |
313fa17b | 512 | // Expiration is fatal (throws) if a secure timestamp is included, but not otherwise. |
b1ab9ed8 A |
513 | // |
514 | bool SecStaticCode::verifySignature() | |
515 | { | |
516 | // ad-hoc signed code is considered validly signed by definition | |
517 | if (flag(kSecCodeSignatureAdhoc)) { | |
518 | CODESIGN_EVAL_STATIC_SIGNATURE_ADHOC(this); | |
519 | return false; | |
520 | } | |
d8f41ccd | 521 | |
b1ab9ed8 A |
522 | DTRACK(CODESIGN_EVAL_STATIC_SIGNATURE, this, (char*)this->mainExecutablePath().c_str()); |
523 | ||
524 | // decode CMS and extract SecTrust for verification | |
525 | CFRef<CMSDecoderRef> cms; | |
526 | MacOSError::check(CMSDecoderCreate(&cms.aref())); // create decoder | |
527 | CFDataRef sig = this->signature(); | |
528 | MacOSError::check(CMSDecoderUpdateMessage(cms, CFDataGetBytePtr(sig), CFDataGetLength(sig))); | |
529 | this->codeDirectory(); // load CodeDirectory (sets mDir) | |
530 | MacOSError::check(CMSDecoderSetDetachedContent(cms, mDir)); | |
531 | MacOSError::check(CMSDecoderFinalizeMessage(cms)); | |
532 | MacOSError::check(CMSDecoderSetSearchKeychain(cms, cfEmptyArray())); | |
d8f41ccd A |
533 | CFRef<CFArrayRef> vf_policies = verificationPolicies(); |
534 | CFRef<CFArrayRef> ts_policies = SecPolicyCreateAppleTimeStampingAndRevocationPolicies(vf_policies); | |
b1ab9ed8 | 535 | CMSSignerStatus status; |
d8f41ccd A |
536 | MacOSError::check(CMSDecoderCopySignerStatus(cms, 0, vf_policies, |
537 | false, &status, &mTrust.aref(), NULL)); | |
538 | ||
b1ab9ed8 A |
539 | if (status != kCMSSignerValid) |
540 | MacOSError::throwMe(errSecCSSignatureFailed); | |
d8f41ccd | 541 | |
b1ab9ed8 A |
542 | // internal signing time (as specified by the signer; optional) |
543 | mSigningTime = 0; // "not present" marker (nobody could code sign on Jan 1, 2001 :-) | |
544 | switch (OSStatus rc = CMSDecoderCopySignerSigningTime(cms, 0, &mSigningTime)) { | |
427c49bc | 545 | case errSecSuccess: |
b1ab9ed8 A |
546 | case errSecSigningTimeMissing: |
547 | break; | |
548 | default: | |
549 | MacOSError::throwMe(rc); | |
550 | } | |
551 | ||
552 | // certified signing time (as specified by a TSA; optional) | |
553 | mSigningTimestamp = 0; | |
d8f41ccd | 554 | switch (OSStatus rc = CMSDecoderCopySignerTimestampWithPolicy(cms, ts_policies, 0, &mSigningTimestamp)) { |
427c49bc | 555 | case errSecSuccess: |
b1ab9ed8 A |
556 | case errSecTimestampMissing: |
557 | break; | |
558 | default: | |
559 | MacOSError::throwMe(rc); | |
560 | } | |
561 | ||
562 | // set up the environment for SecTrust | |
d8f41ccd A |
563 | if (mValidationFlags & kSecCSNoNetworkAccess) { |
564 | MacOSError::check(SecTrustSetNetworkFetchAllowed(mTrust,false)); // no network? | |
565 | } | |
b1ab9ed8 A |
566 | MacOSError::check(SecTrustSetAnchorCertificates(mTrust, cfEmptyArray())); // no anchors |
567 | MacOSError::check(SecTrustSetKeychains(mTrust, cfEmptyArray())); // no keychains | |
568 | CSSM_APPLE_TP_ACTION_DATA actionData = { | |
569 | CSSM_APPLE_TP_ACTION_VERSION, // version of data structure | |
570 | CSSM_TP_ACTION_IMPLICIT_ANCHORS // action flags | |
571 | }; | |
572 | ||
573 | for (;;) { // at most twice | |
574 | MacOSError::check(SecTrustSetParameters(mTrust, | |
575 | CSSM_TP_ACTION_DEFAULT, CFTempData(&actionData, sizeof(actionData)))); | |
576 | ||
577 | // evaluate trust and extract results | |
578 | SecTrustResultType trustResult; | |
579 | MacOSError::check(SecTrustEvaluate(mTrust, &trustResult)); | |
580 | MacOSError::check(SecTrustGetResult(mTrust, &trustResult, &mCertChain.aref(), &mEvalDetails)); | |
420ff9d9 A |
581 | |
582 | // if this is an Apple developer cert.... | |
583 | if (teamID() && SecStaticCode::isAppleDeveloperCert(mCertChain)) { | |
584 | CFRef<CFStringRef> teamIDFromCert; | |
585 | if (CFArrayGetCount(mCertChain) > 0) { | |
586 | /* Note that SecCertificateCopySubjectComponent sets the out paramater to NULL if there is no field present */ | |
587 | MacOSError::check(SecCertificateCopySubjectComponent((SecCertificateRef)CFArrayGetValueAtIndex(mCertChain, Requirement::leafCert), | |
588 | &CSSMOID_OrganizationalUnitName, | |
589 | &teamIDFromCert.aref())); | |
590 | ||
591 | if (teamIDFromCert) { | |
592 | CFRef<CFStringRef> teamIDFromCD = CFStringCreateWithCString(NULL, teamID(), kCFStringEncodingUTF8); | |
593 | if (!teamIDFromCD) { | |
594 | MacOSError::throwMe(errSecCSInternalError); | |
595 | } | |
596 | ||
597 | if (CFStringCompare(teamIDFromCert, teamIDFromCD, 0) != kCFCompareEqualTo) { | |
598 | Security::Syslog::error("Team identifier in the signing certificate (%s) does not match the team identifier (%s) in the code directory", cfString(teamIDFromCert).c_str(), teamID()); | |
599 | MacOSError::throwMe(errSecCSSignatureInvalid); | |
600 | } | |
601 | } | |
602 | } | |
603 | } | |
604 | ||
427c49bc | 605 | CODESIGN_EVAL_STATIC_SIGNATURE_RESULT(this, trustResult, mCertChain ? (int)CFArrayGetCount(mCertChain) : 0); |
b1ab9ed8 A |
606 | switch (trustResult) { |
607 | case kSecTrustResultProceed: | |
608 | case kSecTrustResultUnspecified: | |
609 | break; // success | |
610 | case kSecTrustResultDeny: | |
611 | MacOSError::throwMe(CSSMERR_APPLETP_TRUST_SETTING_DENY); // user reject | |
612 | case kSecTrustResultInvalid: | |
613 | assert(false); // should never happen | |
614 | MacOSError::throwMe(CSSMERR_TP_NOT_TRUSTED); | |
615 | default: | |
616 | { | |
617 | OSStatus result; | |
618 | MacOSError::check(SecTrustGetCssmResultCode(mTrust, &result)); | |
619 | // if we have a valid timestamp, CMS validates against (that) signing time and all is well. | |
620 | // If we don't have one, may validate against *now*, and must be able to tolerate expiration. | |
621 | if (mSigningTimestamp == 0) // no timestamp available | |
622 | if (((result == CSSMERR_TP_CERT_EXPIRED) || (result == CSSMERR_TP_CERT_NOT_VALID_YET)) | |
623 | && !(actionData.ActionFlags & CSSM_TP_ACTION_ALLOW_EXPIRED)) { | |
624 | CODESIGN_EVAL_STATIC_SIGNATURE_EXPIRED(this); | |
625 | actionData.ActionFlags |= CSSM_TP_ACTION_ALLOW_EXPIRED; // (this also allows postdated certs) | |
626 | continue; // retry validation while tolerating expiration | |
627 | } | |
628 | MacOSError::throwMe(result); | |
629 | } | |
630 | } | |
313fa17b A |
631 | |
632 | if (mSigningTimestamp) { | |
633 | CFIndex rootix = CFArrayGetCount(mCertChain); | |
634 | if (SecCertificateRef mainRoot = SecCertificateRef(CFArrayGetValueAtIndex(mCertChain, rootix-1))) | |
635 | if (isAppleCA(mainRoot)) { | |
636 | // impose policy: if the signature itself draws to Apple, then so must the timestamp signature | |
637 | CFRef<CFArrayRef> tsCerts; | |
638 | MacOSError::check(CMSDecoderCopySignerTimestampCertificates(cms, 0, &tsCerts.aref())); | |
639 | CFIndex tsn = CFArrayGetCount(tsCerts); | |
640 | bool good = tsn > 0 && isAppleCA(SecCertificateRef(CFArrayGetValueAtIndex(tsCerts, tsn-1))); | |
313fa17b A |
641 | if (!good) |
642 | MacOSError::throwMe(CSSMERR_TP_NOT_TRUSTED); | |
643 | } | |
644 | } | |
645 | ||
b1ab9ed8 A |
646 | return actionData.ActionFlags & CSSM_TP_ACTION_ALLOW_EXPIRED; |
647 | } | |
648 | } | |
649 | ||
650 | ||
651 | // | |
652 | // Return the TP policy used for signature verification. | |
653 | // This may be a simple SecPolicyRef or a CFArray of policies. | |
654 | // The caller owns the return value. | |
655 | // | |
656 | static SecPolicyRef makeCRLPolicy() | |
657 | { | |
658 | CFRef<SecPolicyRef> policy; | |
659 | MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_REVOCATION_CRL, &policy.aref())); | |
660 | CSSM_APPLE_TP_CRL_OPTIONS options; | |
661 | memset(&options, 0, sizeof(options)); | |
662 | options.Version = CSSM_APPLE_TP_CRL_OPTS_VERSION; | |
663 | options.CrlFlags = CSSM_TP_ACTION_FETCH_CRL_FROM_NET | CSSM_TP_ACTION_CRL_SUFFICIENT; | |
664 | CSSM_DATA optData = { sizeof(options), (uint8 *)&options }; | |
665 | MacOSError::check(SecPolicySetValue(policy, &optData)); | |
666 | return policy.yield(); | |
667 | } | |
668 | ||
669 | static SecPolicyRef makeOCSPPolicy() | |
670 | { | |
671 | CFRef<SecPolicyRef> policy; | |
672 | MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_REVOCATION_OCSP, &policy.aref())); | |
673 | CSSM_APPLE_TP_OCSP_OPTIONS options; | |
674 | memset(&options, 0, sizeof(options)); | |
675 | options.Version = CSSM_APPLE_TP_OCSP_OPTS_VERSION; | |
676 | options.Flags = CSSM_TP_ACTION_OCSP_SUFFICIENT; | |
677 | CSSM_DATA optData = { sizeof(options), (uint8 *)&options }; | |
678 | MacOSError::check(SecPolicySetValue(policy, &optData)); | |
679 | return policy.yield(); | |
680 | } | |
681 | ||
d8f41ccd | 682 | CFArrayRef SecStaticCode::verificationPolicies() |
b1ab9ed8 A |
683 | { |
684 | CFRef<SecPolicyRef> core; | |
685 | MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3, | |
686 | &CSSMOID_APPLE_TP_CODE_SIGNING, &core.aref())); | |
d8f41ccd A |
687 | if (mValidationFlags & kSecCSNoNetworkAccess) { |
688 | // Skips all revocation since they require network connectivity | |
689 | // therefore annihilates kSecCSEnforceRevocationChecks if present | |
690 | CFRef<SecPolicyRef> no_revoc = SecPolicyCreateRevocation(kSecRevocationNetworkAccessDisabled); | |
691 | return makeCFArray(2, core.get(), no_revoc.get()); | |
692 | } | |
693 | else if (mValidationFlags & kSecCSEnforceRevocationChecks) { | |
694 | // Add CRL and OCSPPolicies | |
b1ab9ed8 A |
695 | CFRef<SecPolicyRef> crl = makeCRLPolicy(); |
696 | CFRef<SecPolicyRef> ocsp = makeOCSPPolicy(); | |
697 | return makeCFArray(3, core.get(), crl.get(), ocsp.get()); | |
698 | } else { | |
d8f41ccd | 699 | return makeCFArray(1, core.get()); |
b1ab9ed8 A |
700 | } |
701 | } | |
702 | ||
703 | ||
704 | // | |
705 | // Validate a particular sealed, cached resource against its (special) CodeDirectory slot. | |
706 | // The resource must already have been placed in the cache. | |
707 | // This does NOT perform basic validation. | |
708 | // | |
709 | void SecStaticCode::validateComponent(CodeDirectory::SpecialSlot slot, OSStatus fail /* = errSecCSSignatureFailed */) | |
710 | { | |
711 | assert(slot <= cdSlotMax); | |
712 | CFDataRef data = mCache[slot]; | |
713 | assert(data); // must be cached | |
714 | if (data == CFDataRef(kCFNull)) { | |
715 | if (codeDirectory()->slotIsPresent(-slot)) // was supposed to be there... | |
716 | MacOSError::throwMe(fail); // ... and is missing | |
717 | } else { | |
718 | if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data), CFDataGetLength(data), -slot)) | |
719 | MacOSError::throwMe(fail); | |
720 | } | |
721 | } | |
722 | ||
723 | ||
724 | // | |
725 | // Perform static validation of the main executable. | |
726 | // This reads the main executable from disk and validates it against the | |
727 | // CodeDirectory code slot array. | |
728 | // Note that this is NOT an in-memory validation, and is thus potentially | |
729 | // subject to timing attacks. | |
730 | // | |
731 | void SecStaticCode::validateExecutable() | |
732 | { | |
733 | if (!validatedExecutable()) { | |
734 | try { | |
735 | DTRACK(CODESIGN_EVAL_STATIC_EXECUTABLE, this, | |
736 | (char*)this->mainExecutablePath().c_str(), codeDirectory()->nCodeSlots); | |
737 | const CodeDirectory *cd = this->codeDirectory(); | |
738 | if (!cd) | |
739 | MacOSError::throwMe(errSecCSUnsigned); | |
740 | AutoFileDesc fd(mainExecutablePath(), O_RDONLY); | |
741 | fd.fcntl(F_NOCACHE, true); // turn off page caching (one-pass) | |
742 | if (Universal *fat = mRep->mainExecutableImage()) | |
743 | fd.seek(fat->archOffset()); | |
744 | size_t pageSize = cd->pageSize ? (1 << cd->pageSize) : 0; | |
745 | size_t remaining = cd->codeLimit; | |
427c49bc | 746 | for (uint32_t slot = 0; slot < cd->nCodeSlots; ++slot) { |
b1ab9ed8 A |
747 | size_t size = min(remaining, pageSize); |
748 | if (!cd->validateSlot(fd, size, slot)) { | |
427c49bc | 749 | CODESIGN_EVAL_STATIC_EXECUTABLE_FAIL(this, (int)slot); |
b1ab9ed8 A |
750 | MacOSError::throwMe(errSecCSSignatureFailed); |
751 | } | |
752 | remaining -= size; | |
753 | } | |
754 | mExecutableValidated = true; | |
427c49bc | 755 | mExecutableValidResult = errSecSuccess; |
b1ab9ed8 A |
756 | } catch (const CommonError &err) { |
757 | mExecutableValidated = true; | |
758 | mExecutableValidResult = err.osStatus(); | |
759 | throw; | |
760 | } catch (...) { | |
761 | secdebug("staticCode", "%p executable validation threw non-common exception", this); | |
762 | mExecutableValidated = true; | |
763 | mExecutableValidResult = errSecCSInternalError; | |
764 | throw; | |
765 | } | |
766 | } | |
767 | assert(validatedExecutable()); | |
427c49bc | 768 | if (mExecutableValidResult != errSecSuccess) |
b1ab9ed8 A |
769 | MacOSError::throwMe(mExecutableValidResult); |
770 | } | |
771 | ||
772 | ||
773 | // | |
427c49bc | 774 | // Perform static validation of sealed resources and nested code. |
b1ab9ed8 A |
775 | // |
776 | // This performs a whole-code static resource scan and effectively | |
777 | // computes a concordance between what's on disk and what's in the ResourceDirectory. | |
778 | // Any unsanctioned difference causes an error. | |
779 | // | |
d8f41ccd A |
780 | unsigned SecStaticCode::estimateResourceWorkload() |
781 | { | |
782 | // workload estimate = number of sealed files | |
783 | CFDictionaryRef sealedResources = resourceDictionary(); | |
784 | CFDictionaryRef files = cfget<CFDictionaryRef>(sealedResources, "files2"); | |
785 | if (files == NULL) | |
786 | files = cfget<CFDictionaryRef>(sealedResources, "files"); | |
787 | return files ? unsigned(CFDictionaryGetCount(files)) : 0; | |
788 | } | |
789 | ||
427c49bc | 790 | void SecStaticCode::validateResources(SecCSFlags flags) |
b1ab9ed8 | 791 | { |
427c49bc A |
792 | // do we have a superset of this requested validation cached? |
793 | bool doit = true; | |
794 | if (mResourcesValidated) { // have cached outcome | |
795 | if (!(flags & kSecCSCheckNestedCode) || mResourcesDeep) // was deep or need no deep scan | |
796 | doit = false; | |
797 | } | |
d87e1158 | 798 | |
427c49bc | 799 | if (doit) { |
d87e1158 A |
800 | if (mLimitedAsync == NULL) { |
801 | mLimitedAsync = new LimitedAsync(diskRep()->fd().mediumType() == kIOPropertyMediumTypeSolidStateKey); | |
802 | } | |
803 | ||
b1ab9ed8 A |
804 | try { |
805 | // sanity first | |
806 | CFDictionaryRef sealedResources = resourceDictionary(); | |
80e23899 | 807 | if (this->resourceBase()) // disk has resources |
b1ab9ed8 A |
808 | if (sealedResources) |
809 | /* go to work below */; | |
810 | else | |
811 | MacOSError::throwMe(errSecCSResourcesNotFound); | |
812 | else // disk has no resources | |
813 | if (sealedResources) | |
814 | MacOSError::throwMe(errSecCSResourcesNotFound); | |
815 | else | |
816 | return; // no resources, not sealed - fine (no work) | |
817 | ||
818 | // found resources, and they are sealed | |
b1ab9ed8 | 819 | DTRACK(CODESIGN_EVAL_STATIC_RESOURCES, this, |
427c49bc | 820 | (char*)this->mainExecutablePath().c_str(), 0); |
b1ab9ed8 A |
821 | |
822 | // scan through the resources on disk, checking each against the resourceDirectory | |
60c433a9 | 823 | mResourcesValidContext = new CollectingContext(*this); // collect all failures in here |
d8f41ccd | 824 | |
d87e1158 | 825 | // use V2 resource seal if available, otherwise fall back to V1 |
427c49bc A |
826 | CFDictionaryRef rules; |
827 | CFDictionaryRef files; | |
828 | uint32_t version; | |
829 | if (CFDictionaryGetValue(sealedResources, CFSTR("files2"))) { // have V2 signature | |
830 | rules = cfget<CFDictionaryRef>(sealedResources, "rules2"); | |
831 | files = cfget<CFDictionaryRef>(sealedResources, "files2"); | |
832 | version = 2; | |
833 | } else { // only V1 available | |
834 | rules = cfget<CFDictionaryRef>(sealedResources, "rules"); | |
835 | files = cfget<CFDictionaryRef>(sealedResources, "files"); | |
836 | version = 1; | |
b1ab9ed8 | 837 | } |
427c49bc A |
838 | if (!rules || !files) |
839 | MacOSError::throwMe(errSecCSResourcesInvalid); | |
d87e1158 | 840 | |
80e23899 A |
841 | // check for weak resource rules |
842 | bool strict = flags & kSecCSStrictValidate; | |
d8f41ccd A |
843 | if (strict) { |
844 | if (hasWeakResourceRules(rules, version, mAllowOmissions)) | |
845 | if (mTolerateErrors.find(errSecCSWeakResourceRules) == mTolerateErrors.end()) | |
846 | MacOSError::throwMe(errSecCSWeakResourceRules); | |
847 | if (version == 1) | |
848 | if (mTolerateErrors.find(errSecCSWeakResourceEnvelope) == mTolerateErrors.end()) | |
849 | MacOSError::throwMe(errSecCSWeakResourceEnvelope); | |
850 | } | |
d87e1158 A |
851 | |
852 | Dispatch::Group group; | |
853 | Dispatch::Group &groupRef = group; // (into block) | |
854 | ||
855 | // scan through the resources on disk, checking each against the resourceDirectory | |
427c49bc | 856 | __block CFRef<CFMutableDictionaryRef> resourceMap = makeCFMutableDictionary(files); |
80e23899 A |
857 | string base = cfString(this->resourceBase()); |
858 | ResourceBuilder resources(base, base, rules, codeDirectory()->hashType, strict, mTolerateErrors); | |
427c49bc | 859 | diskRep()->adjustResources(resources); |
d87e1158 A |
860 | |
861 | resources.scan(^(FTSENT *ent, uint32_t ruleFlags, const string relpath, ResourceBuilder::Rule *rule) { | |
427c49bc | 862 | CFDictionaryRemoveValue(resourceMap, CFTempString(relpath)); |
d87e1158 A |
863 | bool isSymlink = (ent->fts_info == FTS_SL); |
864 | ||
865 | void (^validate)() = ^{ | |
866 | validateResource(files, relpath, isSymlink, *mResourcesValidContext, flags, version); | |
867 | reportProgress(); | |
868 | }; | |
869 | ||
870 | mLimitedAsync->perform(groupRef, validate); | |
427c49bc | 871 | }); |
d87e1158 A |
872 | group.wait(); // wait until all async resources have been validated as well |
873 | ||
d8f41ccd A |
874 | unsigned leftovers = unsigned(CFDictionaryGetCount(resourceMap)); |
875 | if (leftovers > 0) { | |
876 | secdebug("staticCode", "%d sealed resource(s) not found in code", int(leftovers)); | |
b1ab9ed8 A |
877 | CFDictionaryApplyFunction(resourceMap, SecStaticCode::checkOptionalResource, mResourcesValidContext); |
878 | } | |
879 | ||
880 | // now check for any errors found in the reporting context | |
881 | mResourcesValidated = true; | |
427c49bc A |
882 | mResourcesDeep = flags & kSecCSCheckNestedCode; |
883 | if (mResourcesValidContext->osStatus() != errSecSuccess) | |
b1ab9ed8 | 884 | mResourcesValidContext->throwMe(); |
b1ab9ed8 A |
885 | } catch (const CommonError &err) { |
886 | mResourcesValidated = true; | |
427c49bc | 887 | mResourcesDeep = flags & kSecCSCheckNestedCode; |
b1ab9ed8 A |
888 | mResourcesValidResult = err.osStatus(); |
889 | throw; | |
890 | } catch (...) { | |
891 | secdebug("staticCode", "%p executable validation threw non-common exception", this); | |
892 | mResourcesValidated = true; | |
427c49bc | 893 | mResourcesDeep = flags & kSecCSCheckNestedCode; |
b1ab9ed8 A |
894 | mResourcesValidResult = errSecCSInternalError; |
895 | throw; | |
896 | } | |
897 | } | |
898 | assert(validatedResources()); | |
899 | if (mResourcesValidResult) | |
900 | MacOSError::throwMe(mResourcesValidResult); | |
427c49bc | 901 | if (mResourcesValidContext->osStatus() != errSecSuccess) |
b1ab9ed8 A |
902 | mResourcesValidContext->throwMe(); |
903 | } | |
904 | ||
905 | ||
906 | void SecStaticCode::checkOptionalResource(CFTypeRef key, CFTypeRef value, void *context) | |
907 | { | |
d8f41ccd | 908 | ValidationContext *ctx = static_cast<ValidationContext *>(context); |
b1ab9ed8 A |
909 | ResourceSeal seal(value); |
910 | if (!seal.optional()) { | |
911 | if (key && CFGetTypeID(key) == CFStringGetTypeID()) { | |
d8f41ccd A |
912 | CFTempURL tempURL(CFStringRef(key), false, ctx->code.resourceBase()); |
913 | if (!tempURL.get()) { | |
914 | ctx->reportProblem(errSecCSBadDictionaryFormat, kSecCFErrorResourceSeal, key); | |
915 | } else { | |
916 | ctx->reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, tempURL); | |
917 | } | |
b1ab9ed8 A |
918 | } else { |
919 | ctx->reportProblem(errSecCSBadResource, kSecCFErrorResourceSeal, key); | |
920 | } | |
921 | } | |
922 | } | |
923 | ||
924 | ||
80e23899 A |
925 | static bool isOmitRule(CFTypeRef value) |
926 | { | |
927 | if (CFGetTypeID(value) == CFBooleanGetTypeID()) | |
928 | return value == kCFBooleanFalse; | |
929 | CFDictionary rule(value, errSecCSResourceRulesInvalid); | |
930 | return rule.get<CFBooleanRef>("omit") == kCFBooleanTrue; | |
931 | } | |
932 | ||
d8f41ccd | 933 | bool SecStaticCode::hasWeakResourceRules(CFDictionaryRef rulesDict, uint32_t version, CFArrayRef allowedOmissions) |
80e23899 A |
934 | { |
935 | // compute allowed omissions | |
936 | CFRef<CFArrayRef> defaultOmissions = this->diskRep()->allowedResourceOmissions(); | |
d8f41ccd A |
937 | if (!defaultOmissions) |
938 | MacOSError::throwMe(errSecCSInternalError); | |
80e23899 A |
939 | CFRef<CFMutableArrayRef> allowed = CFArrayCreateMutableCopy(NULL, 0, defaultOmissions); |
940 | if (allowedOmissions) | |
941 | CFArrayAppendArray(allowed, allowedOmissions, CFRangeMake(0, CFArrayGetCount(allowedOmissions))); | |
942 | CFRange range = CFRangeMake(0, CFArrayGetCount(allowed)); | |
943 | ||
944 | // check all resource rules for weakness | |
d8f41ccd | 945 | string catchAllRule = (version == 1) ? "^Resources/" : "^.*"; |
80e23899 A |
946 | __block bool coversAll = false; |
947 | __block bool forbiddenOmission = false; | |
d87e1158 | 948 | CFArrayRef allowedRef = allowed.get(); // (into block) |
80e23899 A |
949 | CFDictionary rules(rulesDict, errSecCSResourceRulesInvalid); |
950 | rules.apply(^(CFStringRef key, CFTypeRef value) { | |
951 | string pattern = cfString(key, errSecCSResourceRulesInvalid); | |
d8f41ccd | 952 | if (pattern == catchAllRule && value == kCFBooleanTrue) { |
80e23899 A |
953 | coversAll = true; |
954 | return; | |
955 | } | |
956 | if (isOmitRule(value)) | |
d87e1158 | 957 | forbiddenOmission |= !CFArrayContainsValue(allowedRef, range, key); |
80e23899 A |
958 | }); |
959 | ||
960 | return !coversAll || forbiddenOmission; | |
961 | } | |
962 | ||
963 | ||
b1ab9ed8 A |
964 | // |
965 | // Load, validate, cache, and return CFDictionary forms of sealed resources. | |
966 | // | |
967 | CFDictionaryRef SecStaticCode::infoDictionary() | |
968 | { | |
969 | if (!mInfoDict) { | |
970 | mInfoDict.take(getDictionary(cdInfoSlot, errSecCSInfoPlistFailed)); | |
971 | secdebug("staticCode", "%p loaded InfoDict %p", this, mInfoDict.get()); | |
972 | } | |
973 | return mInfoDict; | |
974 | } | |
975 | ||
976 | CFDictionaryRef SecStaticCode::entitlements() | |
977 | { | |
978 | if (!mEntitlements) { | |
979 | validateDirectory(); | |
980 | if (CFDataRef entitlementData = component(cdEntitlementSlot)) { | |
981 | validateComponent(cdEntitlementSlot); | |
982 | const EntitlementBlob *blob = reinterpret_cast<const EntitlementBlob *>(CFDataGetBytePtr(entitlementData)); | |
983 | if (blob->validateBlob()) { | |
984 | mEntitlements.take(blob->entitlements()); | |
985 | secdebug("staticCode", "%p loaded Entitlements %p", this, mEntitlements.get()); | |
986 | } | |
987 | // we do not consider a different blob type to be an error. We think it's a new format we don't understand | |
988 | } | |
989 | } | |
990 | return mEntitlements; | |
991 | } | |
992 | ||
427c49bc | 993 | CFDictionaryRef SecStaticCode::resourceDictionary(bool check /* = true */) |
b1ab9ed8 A |
994 | { |
995 | if (mResourceDict) // cached | |
996 | return mResourceDict; | |
427c49bc | 997 | if (CFRef<CFDictionaryRef> dict = getDictionary(cdResourceDirSlot, check)) |
b1ab9ed8 A |
998 | if (cfscan(dict, "{rules=%Dn,files=%Dn}")) { |
999 | secdebug("staticCode", "%p loaded ResourceDict %p", | |
1000 | this, mResourceDict.get()); | |
1001 | return mResourceDict = dict; | |
1002 | } | |
1003 | // bad format | |
1004 | return NULL; | |
1005 | } | |
1006 | ||
1007 | ||
1008 | // | |
1009 | // Load and cache the resource directory base. | |
1010 | // Note that the base is optional for each DiskRep. | |
1011 | // | |
1012 | CFURLRef SecStaticCode::resourceBase() | |
1013 | { | |
1014 | if (!mGotResourceBase) { | |
1015 | string base = mRep->resourcesRootPath(); | |
1016 | if (!base.empty()) | |
1017 | mResourceBase.take(makeCFURL(base, true)); | |
1018 | mGotResourceBase = true; | |
1019 | } | |
1020 | return mResourceBase; | |
1021 | } | |
1022 | ||
1023 | ||
1024 | // | |
1025 | // Load a component, validate it, convert it to a CFDictionary, and return that. | |
1026 | // This will force load and validation, which means that it will perform basic | |
1027 | // validation if it hasn't been done yet. | |
1028 | // | |
427c49bc | 1029 | CFDictionaryRef SecStaticCode::getDictionary(CodeDirectory::SpecialSlot slot, bool check /* = true */) |
b1ab9ed8 | 1030 | { |
427c49bc A |
1031 | if (check) |
1032 | validateDirectory(); | |
1033 | if (CFDataRef infoData = component(slot)) { | |
1034 | validateComponent(slot); | |
b1ab9ed8 A |
1035 | if (CFDictionaryRef dict = makeCFDictionaryFrom(infoData)) |
1036 | return dict; | |
1037 | else | |
1038 | MacOSError::throwMe(errSecCSBadDictionaryFormat); | |
1039 | } | |
1040 | return NULL; | |
1041 | } | |
1042 | ||
1043 | ||
1044 | // | |
1045 | // Load, validate, and return a sealed resource. | |
1046 | // The resource data (loaded in to memory as a blob) is returned and becomes | |
1047 | // the responsibility of the caller; it is NOT cached by SecStaticCode. | |
1048 | // | |
1049 | // A resource that is not sealed will not be returned, and an error will be thrown. | |
1050 | // A missing resource will cause an error unless it's marked optional in the Directory. | |
1051 | // Under no circumstances will a corrupt resource be returned. | |
1052 | // NULL will only be returned for a resource that is neither sealed nor present | |
1053 | // (or that is sealed, absent, and marked optional). | |
1054 | // If the ResourceDictionary itself is not sealed, this function will always fail. | |
1055 | // | |
1056 | // There is currently no interface for partial retrieval of the resource data. | |
1057 | // (Since the ResourceDirectory does not currently support segmentation, all the | |
1058 | // data would have to be read anyway, but it could be read into a reusable buffer.) | |
1059 | // | |
1060 | CFDataRef SecStaticCode::resource(string path, ValidationContext &ctx) | |
1061 | { | |
1062 | if (CFDictionaryRef rdict = resourceDictionary()) { | |
1063 | if (CFTypeRef file = cfget(rdict, "files.%s", path.c_str())) { | |
1064 | ResourceSeal seal = file; | |
1065 | if (!resourceBase()) // no resources in DiskRep | |
1066 | MacOSError::throwMe(errSecCSResourcesNotFound); | |
427c49bc A |
1067 | if (seal.nested()) |
1068 | MacOSError::throwMe(errSecCSResourcesNotSealed); // (it's nested code) | |
b1ab9ed8 A |
1069 | CFRef<CFURLRef> fullpath = makeCFURL(path, false, resourceBase()); |
1070 | if (CFRef<CFDataRef> data = cfLoadFile(fullpath)) { | |
1071 | MakeHash<CodeDirectory> hasher(this->codeDirectory()); | |
1072 | hasher->update(CFDataGetBytePtr(data), CFDataGetLength(data)); | |
1073 | if (hasher->verify(seal.hash())) | |
1074 | return data.yield(); // good | |
1075 | else | |
1076 | ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // altered | |
1077 | } else { | |
1078 | if (!seal.optional()) | |
1079 | ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, fullpath); // was sealed but is now missing | |
1080 | else | |
1081 | return NULL; // validly missing | |
1082 | } | |
1083 | } else | |
1084 | ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAdded, CFTempURL(path, false, resourceBase())); | |
1085 | return NULL; | |
1086 | } else | |
1087 | MacOSError::throwMe(errSecCSResourcesNotSealed); | |
1088 | } | |
1089 | ||
1090 | CFDataRef SecStaticCode::resource(string path) | |
1091 | { | |
d8f41ccd | 1092 | ValidationContext ctx(*this); |
b1ab9ed8 A |
1093 | return resource(path, ctx); |
1094 | } | |
1095 | ||
80e23899 | 1096 | void SecStaticCode::validateResource(CFDictionaryRef files, string path, bool isSymlink, ValidationContext &ctx, SecCSFlags flags, uint32_t version) |
b1ab9ed8 | 1097 | { |
427c49bc A |
1098 | if (!resourceBase()) // no resources in DiskRep |
1099 | MacOSError::throwMe(errSecCSResourcesNotFound); | |
1100 | CFRef<CFURLRef> fullpath = makeCFURL(path, false, resourceBase()); | |
1101 | if (CFTypeRef file = CFDictionaryGetValue(files, CFTempString(path))) { | |
1102 | ResourceSeal seal = file; | |
1103 | if (seal.nested()) { | |
80e23899 A |
1104 | if (isSymlink) |
1105 | return ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type | |
1106 | string suffix = ".framework"; | |
1107 | bool isFramework = (path.length() > suffix.length()) | |
1108 | && (path.compare(path.length()-suffix.length(), suffix.length(), suffix) == 0); | |
1109 | validateNestedCode(fullpath, seal, flags, isFramework); | |
427c49bc A |
1110 | } else if (seal.link()) { |
1111 | char target[PATH_MAX]; | |
1112 | ssize_t len = ::readlink(cfString(fullpath).c_str(), target, sizeof(target)-1); | |
1113 | if (len < 0) | |
1114 | UnixError::check(-1); | |
1115 | target[len] = '\0'; | |
1116 | if (cfString(seal.link()) != target) | |
1117 | ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); | |
1118 | } else if (seal.hash()) { // genuine file | |
60c433a9 A |
1119 | if (isSymlink) |
1120 | return ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type | |
427c49bc | 1121 | AutoFileDesc fd(cfString(fullpath), O_RDONLY, FileDesc::modeMissingOk); // open optional file |
b1ab9ed8 A |
1122 | if (fd) { |
1123 | MakeHash<CodeDirectory> hasher(this->codeDirectory()); | |
1124 | hashFileData(fd, hasher.get()); | |
1125 | if (hasher->verify(seal.hash())) | |
1126 | return; // verify good | |
1127 | else | |
1128 | ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // altered | |
1129 | } else { | |
1130 | if (!seal.optional()) | |
1131 | ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, fullpath); // was sealed but is now missing | |
1132 | else | |
1133 | return; // validly missing | |
1134 | } | |
1135 | } else | |
427c49bc A |
1136 | ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type |
1137 | return; | |
1138 | } | |
1139 | if (version == 1) { // version 1 ignores symlinks altogether | |
1140 | char target[PATH_MAX]; | |
1141 | if (::readlink(cfString(fullpath).c_str(), target, sizeof(target)) > 0) | |
1142 | return; | |
1143 | } | |
1144 | ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAdded, CFTempURL(path, false, resourceBase())); | |
1145 | } | |
1146 | ||
80e23899 | 1147 | void SecStaticCode::validateNestedCode(CFURLRef path, const ResourceSeal &seal, SecCSFlags flags, bool isFramework) |
427c49bc A |
1148 | { |
1149 | CFRef<SecRequirementRef> req; | |
1150 | if (SecRequirementCreateWithString(seal.requirement(), kSecCSDefaultFlags, &req.aref())) | |
1151 | MacOSError::throwMe(errSecCSResourcesInvalid); | |
1152 | ||
1153 | // recursively verify this nested code | |
1154 | try { | |
1155 | if (!(flags & kSecCSCheckNestedCode)) | |
1156 | flags |= kSecCSBasicValidateOnly; | |
1157 | SecPointer<SecStaticCode> code = new SecStaticCode(DiskRep::bestGuess(cfString(path))); | |
d87e1158 | 1158 | code->initializeFromParent(*this); |
427c49bc | 1159 | code->staticValidate(flags, SecRequirement::required(req)); |
80e23899 A |
1160 | |
1161 | if (isFramework && (flags & kSecCSStrictValidate)) | |
1162 | try { | |
1163 | validateOtherVersions(path, flags, req, code); | |
1164 | } catch (const CSError &err) { | |
1165 | MacOSError::throwMe(errSecCSBadFrameworkVersion); | |
1166 | } catch (const MacOSError &err) { | |
1167 | MacOSError::throwMe(errSecCSBadFrameworkVersion); | |
1168 | } | |
1169 | ||
427c49bc A |
1170 | } catch (CSError &err) { |
1171 | if (err.error == errSecCSReqFailed) { | |
1172 | mResourcesValidContext->reportProblem(errSecCSBadNestedCode, kSecCFErrorResourceAltered, path); | |
1173 | return; | |
1174 | } | |
1175 | err.augment(kSecCFErrorPath, path); | |
1176 | throw; | |
1177 | } catch (const MacOSError &err) { | |
1178 | if (err.error == errSecCSReqFailed) { | |
1179 | mResourcesValidContext->reportProblem(errSecCSBadNestedCode, kSecCFErrorResourceAltered, path); | |
1180 | return; | |
1181 | } | |
1182 | CSError::throwMe(err.error, kSecCFErrorPath, path); | |
1183 | } | |
b1ab9ed8 A |
1184 | } |
1185 | ||
80e23899 A |
1186 | void SecStaticCode::validateOtherVersions(CFURLRef path, SecCSFlags flags, SecRequirementRef req, SecStaticCode *code) |
1187 | { | |
1188 | // Find out what current points to and do not revalidate | |
1189 | std::string mainPath = cfStringRelease(code->diskRep()->copyCanonicalPath()); | |
1190 | ||
1191 | char main_path[PATH_MAX]; | |
1192 | bool foundTarget = false; | |
1193 | ||
1194 | /* If it failed to get the target of the symlink, do not fail. It is a performance loss, | |
1195 | not a security hole */ | |
1196 | if (realpath(mainPath.c_str(), main_path) != NULL) | |
1197 | foundTarget = true; | |
1198 | ||
1199 | std::ostringstream versionsPath; | |
1200 | versionsPath << cfString(path) << "/Versions/"; | |
1201 | ||
1202 | DirScanner scanner(versionsPath.str()); | |
1203 | ||
1204 | if (scanner.initialized()) { | |
1205 | struct dirent *entry = NULL; | |
1206 | while ((entry = scanner.getNext()) != NULL) { | |
1207 | std::ostringstream fullPath; | |
1208 | ||
1209 | if (entry->d_type != DT_DIR || | |
1210 | strcmp(entry->d_name, ".") == 0 || | |
1211 | strcmp(entry->d_name, "..") == 0 || | |
1212 | strcmp(entry->d_name, "Current") == 0) | |
1213 | continue; | |
1214 | ||
1215 | fullPath << versionsPath.str() << entry->d_name; | |
1216 | ||
1217 | char real_full_path[PATH_MAX]; | |
1218 | if (realpath(fullPath.str().c_str(), real_full_path) == NULL) | |
1219 | UnixError::check(-1); | |
1220 | ||
1221 | // Do case insensitive comparions because realpath() was called for both paths | |
1222 | if (foundTarget && strcmp(main_path, real_full_path) == 0) | |
1223 | continue; | |
1224 | ||
1225 | SecPointer<SecStaticCode> frameworkVersion = new SecStaticCode(DiskRep::bestGuess(real_full_path)); | |
d87e1158 | 1226 | frameworkVersion->initializeFromParent(*this); |
80e23899 A |
1227 | frameworkVersion->staticValidate(flags, SecRequirement::required(req)); |
1228 | } | |
1229 | } | |
1230 | } | |
1231 | ||
b1ab9ed8 A |
1232 | |
1233 | // | |
1234 | // Test a CodeDirectory flag. | |
1235 | // Returns false if there is no CodeDirectory. | |
1236 | // May throw if the CodeDirectory is present but somehow invalid. | |
1237 | // | |
1238 | bool SecStaticCode::flag(uint32_t tested) | |
1239 | { | |
1240 | if (const CodeDirectory *cd = this->codeDirectory(false)) | |
1241 | return cd->flags & tested; | |
1242 | else | |
1243 | return false; | |
1244 | } | |
1245 | ||
1246 | ||
1247 | // | |
1248 | // Retrieve the full SuperBlob containing all internal requirements. | |
1249 | // | |
1250 | const Requirements *SecStaticCode::internalRequirements() | |
1251 | { | |
427c49bc A |
1252 | if (CFDataRef reqData = component(cdRequirementsSlot)) { |
1253 | const Requirements *req = (const Requirements *)CFDataGetBytePtr(reqData); | |
1254 | if (!req->validateBlob()) | |
1255 | MacOSError::throwMe(errSecCSReqInvalid); | |
1256 | return req; | |
1257 | } else | |
b1ab9ed8 A |
1258 | return NULL; |
1259 | } | |
1260 | ||
1261 | ||
1262 | // | |
1263 | // Retrieve a particular internal requirement by type. | |
1264 | // | |
1265 | const Requirement *SecStaticCode::internalRequirement(SecRequirementType type) | |
1266 | { | |
1267 | if (const Requirements *reqs = internalRequirements()) | |
1268 | return reqs->find<Requirement>(type); | |
1269 | else | |
1270 | return NULL; | |
1271 | } | |
1272 | ||
1273 | ||
1274 | // | |
1275 | // Return the Designated Requirement (DR). This can be either explicit in the | |
1276 | // Internal Requirements component, or implicitly generated on demand here. | |
1277 | // Note that an explicit DR may have been implicitly generated at signing time; | |
1278 | // we don't distinguish this case. | |
1279 | // | |
1280 | const Requirement *SecStaticCode::designatedRequirement() | |
1281 | { | |
1282 | if (const Requirement *req = internalRequirement(kSecDesignatedRequirementType)) { | |
1283 | return req; // explicit in signing data | |
1284 | } else { | |
1285 | if (!mDesignatedReq) | |
1286 | mDesignatedReq = defaultDesignatedRequirement(); | |
1287 | return mDesignatedReq; | |
1288 | } | |
1289 | } | |
1290 | ||
1291 | ||
1292 | // | |
1293 | // Generate the default Designated Requirement (DR) for this StaticCode. | |
1294 | // Ignore any explicit DR it may contain. | |
1295 | // | |
1296 | const Requirement *SecStaticCode::defaultDesignatedRequirement() | |
1297 | { | |
1298 | if (flag(kSecCodeSignatureAdhoc)) { | |
427c49bc A |
1299 | // adhoc signature: return a cdhash requirement for all architectures |
1300 | __block Requirement::Maker maker; | |
1301 | Requirement::Maker::Chain chain(maker, opOr); | |
1302 | ||
1303 | // insert cdhash requirement for all architectures | |
1304 | chain.add(); | |
1305 | maker.cdhash(this->cdHash()); | |
1306 | handleOtherArchitectures(^(SecStaticCode *subcode) { | |
1307 | if (CFDataRef cdhash = subcode->cdHash()) { | |
1308 | chain.add(); | |
1309 | maker.cdhash(cdhash); | |
1310 | } | |
1311 | }); | |
b1ab9ed8 A |
1312 | return maker.make(); |
1313 | } else { | |
1314 | // full signature: Gin up full context and let DRMaker do its thing | |
1315 | validateDirectory(); // need the cert chain | |
1316 | Requirement::Context context(this->certificates(), | |
1317 | this->infoDictionary(), | |
1318 | this->entitlements(), | |
1319 | this->identifier(), | |
1320 | this->codeDirectory() | |
1321 | ); | |
1322 | return DRMaker(context).make(); | |
1323 | } | |
1324 | } | |
1325 | ||
1326 | ||
1327 | // | |
1328 | // Validate a SecStaticCode against the internal requirement of a particular type. | |
1329 | // | |
1330 | void SecStaticCode::validateRequirements(SecRequirementType type, SecStaticCode *target, | |
427c49bc | 1331 | OSStatus nullError /* = errSecSuccess */) |
b1ab9ed8 A |
1332 | { |
1333 | DTRACK(CODESIGN_EVAL_STATIC_INTREQ, this, type, target, nullError); | |
1334 | if (const Requirement *req = internalRequirement(type)) | |
1335 | target->validateRequirement(req, nullError ? nullError : errSecCSReqFailed); | |
1336 | else if (nullError) | |
1337 | MacOSError::throwMe(nullError); | |
1338 | else | |
1339 | /* accept it */; | |
1340 | } | |
1341 | ||
1342 | ||
1343 | // | |
1344 | // Validate this StaticCode against an external Requirement | |
1345 | // | |
1346 | bool SecStaticCode::satisfiesRequirement(const Requirement *req, OSStatus failure) | |
1347 | { | |
1348 | assert(req); | |
1349 | validateDirectory(); | |
1350 | return req->validates(Requirement::Context(mCertChain, infoDictionary(), entitlements(), codeDirectory()->identifier(), codeDirectory()), failure); | |
1351 | } | |
1352 | ||
1353 | void SecStaticCode::validateRequirement(const Requirement *req, OSStatus failure) | |
1354 | { | |
1355 | if (!this->satisfiesRequirement(req, failure)) | |
1356 | MacOSError::throwMe(failure); | |
1357 | } | |
1358 | ||
1359 | ||
1360 | // | |
1361 | // Retrieve one certificate from the cert chain. | |
1362 | // Positive and negative indices can be used: | |
1363 | // [ leaf, intermed-1, ..., intermed-n, anchor ] | |
1364 | // 0 1 ... -2 -1 | |
1365 | // Returns NULL if unavailable for any reason. | |
1366 | // | |
1367 | SecCertificateRef SecStaticCode::cert(int ix) | |
1368 | { | |
1369 | validateDirectory(); // need cert chain | |
1370 | if (mCertChain) { | |
1371 | CFIndex length = CFArrayGetCount(mCertChain); | |
1372 | if (ix < 0) | |
1373 | ix += length; | |
1374 | if (ix >= 0 && ix < length) | |
1375 | return SecCertificateRef(CFArrayGetValueAtIndex(mCertChain, ix)); | |
1376 | } | |
1377 | return NULL; | |
1378 | } | |
1379 | ||
1380 | CFArrayRef SecStaticCode::certificates() | |
1381 | { | |
1382 | validateDirectory(); // need cert chain | |
1383 | return mCertChain; | |
1384 | } | |
1385 | ||
1386 | ||
1387 | // | |
1388 | // Gather (mostly) API-official information about this StaticCode. | |
1389 | // | |
1390 | // This method lives in the twilight between the API and internal layers, | |
1391 | // since it generates API objects (Sec*Refs) for return. | |
1392 | // | |
1393 | CFDictionaryRef SecStaticCode::signingInformation(SecCSFlags flags) | |
1394 | { | |
1395 | // | |
1396 | // Start with the pieces that we return even for unsigned code. | |
1397 | // This makes Sec[Static]CodeRefs useful as API-level replacements | |
1398 | // of our internal OSXCode objects. | |
1399 | // | |
1400 | CFRef<CFMutableDictionaryRef> dict = makeCFMutableDictionary(1, | |
1401 | kSecCodeInfoMainExecutable, CFTempURL(this->mainExecutablePath()).get() | |
1402 | ); | |
1403 | ||
1404 | // | |
1405 | // If we're not signed, this is all you get | |
1406 | // | |
1407 | if (!this->isSigned()) | |
1408 | return dict.yield(); | |
1409 | ||
1410 | // | |
1411 | // Add the generic attributes that we always include | |
1412 | // | |
1413 | CFDictionaryAddValue(dict, kSecCodeInfoIdentifier, CFTempString(this->identifier())); | |
427c49bc | 1414 | CFDictionaryAddValue(dict, kSecCodeInfoFlags, CFTempNumber(this->codeDirectory(false)->flags.get())); |
b1ab9ed8 A |
1415 | CFDictionaryAddValue(dict, kSecCodeInfoFormat, CFTempString(this->format())); |
1416 | CFDictionaryAddValue(dict, kSecCodeInfoSource, CFTempString(this->signatureSource())); | |
1417 | CFDictionaryAddValue(dict, kSecCodeInfoUnique, this->cdHash()); | |
1418 | CFDictionaryAddValue(dict, kSecCodeInfoDigestAlgorithm, CFTempNumber(this->codeDirectory(false)->hashType)); | |
1419 | ||
1420 | // | |
1421 | // Deliver any Info.plist only if it looks intact | |
1422 | // | |
1423 | try { | |
1424 | if (CFDictionaryRef info = this->infoDictionary()) | |
1425 | CFDictionaryAddValue(dict, kSecCodeInfoPList, info); | |
1426 | } catch (...) { } // don't deliver Info.plist if questionable | |
1427 | ||
1428 | // | |
1429 | // kSecCSSigningInformation adds information about signing certificates and chains | |
1430 | // | |
427c49bc A |
1431 | if (flags & kSecCSSigningInformation) |
1432 | try { | |
1433 | if (CFArrayRef certs = this->certificates()) | |
1434 | CFDictionaryAddValue(dict, kSecCodeInfoCertificates, certs); | |
1435 | if (CFDataRef sig = this->signature()) | |
1436 | CFDictionaryAddValue(dict, kSecCodeInfoCMS, sig); | |
1437 | if (mTrust) | |
1438 | CFDictionaryAddValue(dict, kSecCodeInfoTrust, mTrust); | |
1439 | if (CFAbsoluteTime time = this->signingTime()) | |
1440 | if (CFRef<CFDateRef> date = CFDateCreate(NULL, time)) | |
1441 | CFDictionaryAddValue(dict, kSecCodeInfoTime, date); | |
1442 | if (CFAbsoluteTime time = this->signingTimestamp()) | |
1443 | if (CFRef<CFDateRef> date = CFDateCreate(NULL, time)) | |
1444 | CFDictionaryAddValue(dict, kSecCodeInfoTimestamp, date); | |
420ff9d9 A |
1445 | if (const char *teamID = this->teamID()) |
1446 | CFDictionaryAddValue(dict, kSecCodeInfoTeamIdentifier, CFTempString(teamID)); | |
427c49bc | 1447 | } catch (...) { } |
b1ab9ed8 A |
1448 | |
1449 | // | |
1450 | // kSecCSRequirementInformation adds information on requirements | |
1451 | // | |
427c49bc A |
1452 | if (flags & kSecCSRequirementInformation) |
1453 | try { | |
1454 | if (const Requirements *reqs = this->internalRequirements()) { | |
1455 | CFDictionaryAddValue(dict, kSecCodeInfoRequirements, | |
1456 | CFTempString(Dumper::dump(reqs))); | |
1457 | CFDictionaryAddValue(dict, kSecCodeInfoRequirementData, CFTempData(*reqs)); | |
1458 | } | |
1459 | ||
1460 | const Requirement *dreq = this->designatedRequirement(); | |
1461 | CFRef<SecRequirementRef> dreqRef = (new SecRequirement(dreq))->handle(); | |
1462 | CFDictionaryAddValue(dict, kSecCodeInfoDesignatedRequirement, dreqRef); | |
1463 | if (this->internalRequirement(kSecDesignatedRequirementType)) { // explicit | |
1464 | CFRef<SecRequirementRef> ddreqRef = (new SecRequirement(this->defaultDesignatedRequirement(), true))->handle(); | |
1465 | CFDictionaryAddValue(dict, kSecCodeInfoImplicitDesignatedRequirement, ddreqRef); | |
1466 | } else { // implicit | |
1467 | CFDictionaryAddValue(dict, kSecCodeInfoImplicitDesignatedRequirement, dreqRef); | |
1468 | } | |
1469 | } catch (...) { } | |
b1ab9ed8 | 1470 | |
427c49bc A |
1471 | try { |
1472 | if (CFDataRef ent = this->component(cdEntitlementSlot)) { | |
1473 | CFDictionaryAddValue(dict, kSecCodeInfoEntitlements, ent); | |
1474 | if (CFDictionaryRef entdict = this->entitlements()) | |
1475 | CFDictionaryAddValue(dict, kSecCodeInfoEntitlementsDict, entdict); | |
1476 | } | |
1477 | } catch (...) { } | |
b1ab9ed8 A |
1478 | |
1479 | // | |
1480 | // kSecCSInternalInformation adds internal information meant to be for Apple internal | |
1481 | // use (SPI), and not guaranteed to be stable. Primarily, this is data we want | |
1482 | // to reliably transmit through the API wall so that code outside the Security.framework | |
1483 | // can use it without having to play nasty tricks to get it. | |
1484 | // | |
427c49bc A |
1485 | if (flags & kSecCSInternalInformation) |
1486 | try { | |
1487 | if (mDir) | |
1488 | CFDictionaryAddValue(dict, kSecCodeInfoCodeDirectory, mDir); | |
1489 | CFDictionaryAddValue(dict, kSecCodeInfoCodeOffset, CFTempNumber(mRep->signingBase())); | |
1490 | if (CFRef<CFDictionaryRef> rdict = getDictionary(cdResourceDirSlot, false)) // suppress validation | |
1491 | CFDictionaryAddValue(dict, kSecCodeInfoResourceDirectory, rdict); | |
1492 | } catch (...) { } | |
b1ab9ed8 A |
1493 | |
1494 | ||
1495 | // | |
1496 | // kSecCSContentInformation adds more information about the physical layout | |
1497 | // of the signed code. This is (only) useful for packaging or patching-oriented | |
1498 | // applications. | |
1499 | // | |
1500 | if (flags & kSecCSContentInformation) | |
1501 | if (CFRef<CFArrayRef> files = mRep->modifiedFiles()) | |
1502 | CFDictionaryAddValue(dict, kSecCodeInfoChangedFiles, files); | |
1503 | ||
1504 | return dict.yield(); | |
1505 | } | |
1506 | ||
1507 | ||
1508 | // | |
1509 | // Resource validation contexts. | |
1510 | // The default context simply throws a CSError, rudely terminating the operation. | |
1511 | // | |
1512 | SecStaticCode::ValidationContext::~ValidationContext() | |
1513 | { /* virtual */ } | |
1514 | ||
1515 | void SecStaticCode::ValidationContext::reportProblem(OSStatus rc, CFStringRef type, CFTypeRef value) | |
1516 | { | |
1517 | CSError::throwMe(rc, type, value); | |
1518 | } | |
1519 | ||
1520 | void SecStaticCode::CollectingContext::reportProblem(OSStatus rc, CFStringRef type, CFTypeRef value) | |
1521 | { | |
d87e1158 | 1522 | StLock<Mutex> _(mLock); |
427c49bc | 1523 | if (mStatus == errSecSuccess) |
b1ab9ed8 A |
1524 | mStatus = rc; // record first failure for eventual error return |
1525 | if (type) { | |
1526 | if (!mCollection) | |
1527 | mCollection.take(makeCFMutableDictionary()); | |
1528 | CFMutableArrayRef element = CFMutableArrayRef(CFDictionaryGetValue(mCollection, type)); | |
1529 | if (!element) { | |
1530 | element = makeCFMutableArray(0); | |
1531 | if (!element) | |
1532 | CFError::throwMe(); | |
1533 | CFDictionaryAddValue(mCollection, type, element); | |
1534 | CFRelease(element); | |
1535 | } | |
1536 | CFArrayAppendValue(element, value); | |
1537 | } | |
1538 | } | |
1539 | ||
1540 | void SecStaticCode::CollectingContext::throwMe() | |
1541 | { | |
427c49bc | 1542 | assert(mStatus != errSecSuccess); |
b1ab9ed8 A |
1543 | throw CSError(mStatus, mCollection.retain()); |
1544 | } | |
1545 | ||
1546 | ||
1547 | // | |
427c49bc A |
1548 | // Master validation driver. |
1549 | // This is the static validation (only) driver for the API. | |
b1ab9ed8 | 1550 | // |
d8f41ccd A |
1551 | // SecStaticCode exposes an a la carte menu of topical validators applying |
1552 | // to a given object. The static validation API pulls them together reliably, | |
427c49bc A |
1553 | // but it also adds two matrix dimensions: architecture (for "fat" Mach-O binaries) |
1554 | // and nested code. This function will crawl a suitable cross-section of this | |
1555 | // validation matrix based on which options it is given, creating temporary | |
1556 | // SecStaticCode objects on the fly to complete the task. | |
1557 | // (The point, of course, is to do as little duplicate work as possible.) | |
b1ab9ed8 | 1558 | // |
427c49bc | 1559 | void SecStaticCode::staticValidate(SecCSFlags flags, const SecRequirement *req) |
b1ab9ed8 | 1560 | { |
d8f41ccd A |
1561 | setValidationFlags(flags); |
1562 | ||
1563 | // initialize progress/cancellation state | |
60c433a9 | 1564 | if (flags & kSecCSReportProgress) |
d8f41ccd A |
1565 | prepareProgress(estimateResourceWorkload() + 2); // +1 head, +1 tail |
1566 | ||
427c49bc A |
1567 | // core components: once per architecture (if any) |
1568 | this->staticValidateCore(flags, req); | |
1569 | if (flags & kSecCSCheckAllArchitectures) | |
1570 | handleOtherArchitectures(^(SecStaticCode* subcode) { | |
d87e1158 A |
1571 | if (flags & kSecCSCheckGatekeeperArchitectures) { |
1572 | Universal *fat = subcode->diskRep()->mainExecutableImage(); | |
1573 | assert(fat && fat->narrowed()); // handleOtherArchitectures gave us a focused architecture slice | |
1574 | Architecture arch = fat->bestNativeArch(); // actually, the ONLY one | |
1575 | if ((arch.cpuType() & ~CPU_ARCH_MASK) == CPU_TYPE_POWERPC) | |
1576 | return; // irrelevant to Gatekeeper | |
1577 | } | |
427c49bc A |
1578 | subcode->detachedSignature(this->mDetachedSig); // carry over explicit (but not implicit) architecture |
1579 | subcode->staticValidateCore(flags, req); | |
1580 | }); | |
d8f41ccd | 1581 | reportProgress(); |
427c49bc | 1582 | |
80e23899 A |
1583 | // allow monitor intervention in source validation phase |
1584 | reportEvent(CFSTR("prepared"), NULL); | |
1585 | ||
427c49bc A |
1586 | // resources: once for all architectures |
1587 | if (!(flags & kSecCSDoNotValidateResources)) | |
1588 | this->validateResources(flags); | |
1589 | ||
80e23899 A |
1590 | // perform strict validation if desired |
1591 | if (flags & kSecCSStrictValidate) | |
60c433a9 | 1592 | mRep->strictValidate(codeDirectory(), mTolerateErrors); |
d8f41ccd | 1593 | reportProgress(); |
80e23899 | 1594 | |
427c49bc A |
1595 | // allow monitor intervention |
1596 | if (CFRef<CFTypeRef> veto = reportEvent(CFSTR("validated"), NULL)) { | |
1597 | if (CFGetTypeID(veto) == CFNumberGetTypeID()) | |
1598 | MacOSError::throwMe(cfNumber<OSStatus>(veto.as<CFNumberRef>())); | |
1599 | else | |
1600 | MacOSError::throwMe(errSecCSBadCallbackValue); | |
b1ab9ed8 A |
1601 | } |
1602 | } | |
1603 | ||
427c49bc | 1604 | void SecStaticCode::staticValidateCore(SecCSFlags flags, const SecRequirement *req) |
b1ab9ed8 | 1605 | { |
427c49bc A |
1606 | try { |
1607 | this->validateNonResourceComponents(); // also validates the CodeDirectory | |
1608 | if (!(flags & kSecCSDoNotValidateExecutable)) | |
1609 | this->validateExecutable(); | |
1610 | if (req) | |
1611 | this->validateRequirement(req->requirement(), errSecCSReqFailed); | |
1612 | } catch (CSError &err) { | |
1613 | if (Universal *fat = this->diskRep()->mainExecutableImage()) // Mach-O | |
1614 | if (MachO *mach = fat->architecture()) { | |
1615 | err.augment(kSecCFErrorArchitecture, CFTempString(mach->architecture().displayName())); | |
1616 | delete mach; | |
1617 | } | |
1618 | throw; | |
1619 | } catch (const MacOSError &err) { | |
1620 | // add architecture information if we can get it | |
1621 | if (Universal *fat = this->diskRep()->mainExecutableImage()) | |
1622 | if (MachO *mach = fat->architecture()) { | |
1623 | CFTempString arch(mach->architecture().displayName()); | |
1624 | delete mach; | |
1625 | CSError::throwMe(err.error, kSecCFErrorArchitecture, arch); | |
1626 | } | |
1627 | throw; | |
1628 | } | |
1629 | } | |
1630 | ||
1631 | ||
1632 | // | |
1633 | // A helper that generates SecStaticCode objects for all but the primary architecture | |
1634 | // of a fat binary and calls a block on them. | |
1635 | // If there's only one architecture (or this is an architecture-agnostic code), | |
1636 | // nothing happens quickly. | |
1637 | // | |
1638 | void SecStaticCode::handleOtherArchitectures(void (^handle)(SecStaticCode* other)) | |
1639 | { | |
1640 | if (Universal *fat = this->diskRep()->mainExecutableImage()) { | |
1641 | Universal::Architectures architectures; | |
1642 | fat->architectures(architectures); | |
1643 | if (architectures.size() > 1) { | |
1644 | DiskRep::Context ctx; | |
1645 | size_t activeOffset = fat->archOffset(); | |
1646 | for (Universal::Architectures::const_iterator arch = architectures.begin(); arch != architectures.end(); ++arch) { | |
1647 | ctx.offset = fat->archOffset(*arch); | |
80e23899 A |
1648 | if (ctx.offset > SIZE_MAX) |
1649 | MacOSError::throwMe(errSecCSInternalError); | |
1650 | ctx.size = fat->lengthOfSlice((size_t)ctx.offset); | |
427c49bc A |
1651 | if (ctx.offset != activeOffset) { // inactive architecture; check it |
1652 | SecPointer<SecStaticCode> subcode = new SecStaticCode(DiskRep::bestGuess(this->mainExecutablePath(), &ctx)); | |
1653 | subcode->detachedSignature(this->mDetachedSig); // carry over explicit (but not implicit) detached signature | |
420ff9d9 A |
1654 | if (this->teamID() == NULL || subcode->teamID() == NULL) { |
1655 | if (this->teamID() != subcode->teamID()) | |
1656 | MacOSError::throwMe(errSecCSSignatureInvalid); | |
1657 | } else if (strcmp(this->teamID(), subcode->teamID()) != 0) | |
1658 | MacOSError::throwMe(errSecCSSignatureInvalid); | |
427c49bc A |
1659 | handle(subcode); |
1660 | } | |
b1ab9ed8 A |
1661 | } |
1662 | } | |
b1ab9ed8 A |
1663 | } |
1664 | } | |
1665 | ||
420ff9d9 A |
1666 | // |
1667 | // A method that takes a certificate chain (certs) and evaluates | |
1668 | // if it is a Mac or IPhone developer cert, an app store distribution cert, | |
1669 | // or a developer ID | |
1670 | // | |
1671 | bool SecStaticCode::isAppleDeveloperCert(CFArrayRef certs) | |
1672 | { | |
d8f41ccd A |
1673 | static const std::string appleDeveloperRequirement = "(" + std::string(WWDRRequirement) + ") or (" + MACWWDRRequirement + ") or (" + developerID + ") or (" + distributionCertificate + ") or (" + iPhoneDistributionCert + ")"; |
1674 | SecPointer<SecRequirement> req = new SecRequirement(parseRequirement(appleDeveloperRequirement), true); | |
420ff9d9 A |
1675 | Requirement::Context ctx(certs, NULL, NULL, "", NULL); |
1676 | ||
1677 | return req->requirement()->validates(ctx); | |
1678 | } | |
b1ab9ed8 A |
1679 | |
1680 | } // end namespace CodeSigning | |
1681 | } // end namespace Security |