]>
Commit | Line | Data |
---|---|---|
b1ab9ed8 A |
1 | /* |
2 | * Copyright (c) 2006-2012 Apple Inc. All Rights Reserved. | |
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" | |
37 | #include "csutilities.h" | |
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> |
b1ab9ed8 A |
51 | |
52 | ||
53 | namespace Security { | |
54 | namespace CodeSigning { | |
55 | ||
56 | using namespace UnixPlusPlus; | |
57 | ||
420ff9d9 A |
58 | // A requirement representing a Mac or iOS dev cert, a Mac or iOS distribution cert, or a developer ID |
59 | static const char WWDRRequirement[] = "anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.1] exists " | |
60 | "and ( cert leaf[subject.CN] = \"Mac Developer: \"* or cert leaf[subject.CN] = \"iPhone Developer: \"* )"; | |
61 | static const char developerID[] = "anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists" | |
62 | " and certificate leaf[field.1.2.840.113635.100.6.1.13] exists"; | |
63 | static const char distributionCertificate[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.7] exists"; | |
64 | static const char iPhoneDistributionCert[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.4] exists"; | |
b1ab9ed8 | 65 | |
427c49bc A |
66 | // |
67 | // Map a component slot number to a suitable error code for a failure | |
68 | // | |
69 | static inline OSStatus errorForSlot(CodeDirectory::SpecialSlot slot) | |
70 | { | |
71 | switch (slot) { | |
72 | case cdInfoSlot: | |
73 | return errSecCSInfoPlistFailed; | |
74 | case cdResourceDirSlot: | |
75 | return errSecCSResourceDirectoryFailed; | |
76 | default: | |
77 | return errSecCSSignatureFailed; | |
78 | } | |
79 | } | |
80 | ||
81 | ||
b1ab9ed8 A |
82 | // |
83 | // Construct a SecStaticCode object given a disk representation object | |
84 | // | |
85 | SecStaticCode::SecStaticCode(DiskRep *rep) | |
86 | : mRep(rep), | |
87 | mValidated(false), mExecutableValidated(false), mResourcesValidated(false), mResourcesValidContext(NULL), | |
427c49bc | 88 | mDesignatedReq(NULL), mGotResourceBase(false), mMonitor(NULL), mEvalDetails(NULL) |
b1ab9ed8 A |
89 | { |
90 | CODESIGN_STATIC_CREATE(this, rep); | |
91 | checkForSystemSignature(); | |
92 | } | |
93 | ||
94 | ||
95 | // | |
96 | // Clean up a SecStaticCode object | |
97 | // | |
98 | SecStaticCode::~SecStaticCode() throw() | |
99 | try { | |
100 | ::free(const_cast<Requirement *>(mDesignatedReq)); | |
101 | if (mResourcesValidContext) | |
102 | delete mResourcesValidContext; | |
103 | } catch (...) { | |
104 | return; | |
105 | } | |
106 | ||
107 | ||
108 | // | |
109 | // CF-level comparison of SecStaticCode objects compares CodeDirectory hashes if signed, | |
110 | // and falls back on comparing canonical paths if (both are) not. | |
111 | // | |
112 | bool SecStaticCode::equal(SecCFObject &secOther) | |
113 | { | |
114 | SecStaticCode *other = static_cast<SecStaticCode *>(&secOther); | |
115 | CFDataRef mine = this->cdHash(); | |
116 | CFDataRef his = other->cdHash(); | |
117 | if (mine || his) | |
118 | return mine && his && CFEqual(mine, his); | |
119 | else | |
120 | return CFEqual(this->canonicalPath(), other->canonicalPath()); | |
121 | } | |
122 | ||
123 | CFHashCode SecStaticCode::hash() | |
124 | { | |
125 | if (CFDataRef h = this->cdHash()) | |
126 | return CFHash(h); | |
127 | else | |
128 | return CFHash(this->canonicalPath()); | |
129 | } | |
130 | ||
131 | ||
427c49bc A |
132 | // |
133 | // Invoke a stage monitor if registered | |
134 | // | |
135 | CFTypeRef SecStaticCode::reportEvent(CFStringRef stage, CFDictionaryRef info) | |
136 | { | |
137 | if (mMonitor) | |
138 | return mMonitor(this->handle(false), stage, info); | |
139 | else | |
140 | return NULL; | |
141 | } | |
142 | ||
143 | ||
b1ab9ed8 A |
144 | // |
145 | // Attach a detached signature. | |
146 | // | |
147 | void SecStaticCode::detachedSignature(CFDataRef sigData) | |
148 | { | |
149 | if (sigData) { | |
427c49bc | 150 | mDetachedSig = sigData; |
b1ab9ed8 A |
151 | mRep = new DetachedRep(sigData, mRep->base(), "explicit detached"); |
152 | CODESIGN_STATIC_ATTACH_EXPLICIT(this, mRep); | |
153 | } else { | |
427c49bc | 154 | mDetachedSig = NULL; |
b1ab9ed8 A |
155 | mRep = mRep->base(); |
156 | CODESIGN_STATIC_ATTACH_EXPLICIT(this, NULL); | |
157 | } | |
158 | } | |
159 | ||
160 | ||
161 | // | |
162 | // Consult the system detached signature database to see if it contains | |
163 | // a detached signature for this StaticCode. If it does, fetch and attach it. | |
164 | // We do this only if the code has no signature already attached. | |
165 | // | |
166 | void SecStaticCode::checkForSystemSignature() | |
167 | { | |
427c49bc A |
168 | if (!this->isSigned()) { |
169 | SignatureDatabase db; | |
170 | if (db.isOpen()) | |
171 | try { | |
172 | if (RefPointer<DiskRep> dsig = db.findCode(mRep)) { | |
173 | CODESIGN_STATIC_ATTACH_SYSTEM(this, dsig); | |
174 | mRep = dsig; | |
175 | } | |
176 | } catch (...) { | |
b1ab9ed8 | 177 | } |
427c49bc | 178 | } |
b1ab9ed8 A |
179 | } |
180 | ||
181 | ||
182 | // | |
183 | // Return a descriptive string identifying the source of the code signature | |
184 | // | |
185 | string SecStaticCode::signatureSource() | |
186 | { | |
187 | if (!isSigned()) | |
188 | return "unsigned"; | |
189 | if (DetachedRep *rep = dynamic_cast<DetachedRep *>(mRep.get())) | |
190 | return rep->source(); | |
191 | return "embedded"; | |
192 | } | |
193 | ||
194 | ||
195 | // | |
196 | // Do ::required, but convert incoming SecCodeRefs to their SecStaticCodeRefs | |
197 | // (if possible). | |
198 | // | |
199 | SecStaticCode *SecStaticCode::requiredStatic(SecStaticCodeRef ref) | |
200 | { | |
201 | SecCFObject *object = SecCFObject::required(ref, errSecCSInvalidObjectRef); | |
202 | if (SecStaticCode *scode = dynamic_cast<SecStaticCode *>(object)) | |
203 | return scode; | |
204 | else if (SecCode *code = dynamic_cast<SecCode *>(object)) | |
205 | return code->staticCode(); | |
206 | else // neither (a SecSomethingElse) | |
207 | MacOSError::throwMe(errSecCSInvalidObjectRef); | |
208 | } | |
209 | ||
210 | SecCode *SecStaticCode::optionalDynamic(SecStaticCodeRef ref) | |
211 | { | |
212 | SecCFObject *object = SecCFObject::required(ref, errSecCSInvalidObjectRef); | |
213 | if (dynamic_cast<SecStaticCode *>(object)) | |
214 | return NULL; | |
215 | else if (SecCode *code = dynamic_cast<SecCode *>(object)) | |
216 | return code; | |
217 | else // neither (a SecSomethingElse) | |
218 | MacOSError::throwMe(errSecCSInvalidObjectRef); | |
219 | } | |
220 | ||
221 | ||
222 | // | |
223 | // Void all cached validity data. | |
224 | // | |
225 | // We also throw out cached components, because the new signature data may have | |
226 | // a different idea of what components should be present. We could reconcile the | |
227 | // cached data instead, if performance seems to be impacted. | |
228 | // | |
229 | void SecStaticCode::resetValidity() | |
230 | { | |
231 | CODESIGN_EVAL_STATIC_RESET(this); | |
232 | mValidated = false; | |
427c49bc | 233 | mExecutableValidated = mResourcesValidated = false; |
b1ab9ed8 A |
234 | if (mResourcesValidContext) { |
235 | delete mResourcesValidContext; | |
236 | mResourcesValidContext = NULL; | |
237 | } | |
238 | mDir = NULL; | |
239 | mSignature = NULL; | |
240 | for (unsigned n = 0; n < cdSlotCount; n++) | |
241 | mCache[n] = NULL; | |
242 | mInfoDict = NULL; | |
243 | mEntitlements = NULL; | |
244 | mResourceDict = NULL; | |
245 | mDesignatedReq = NULL; | |
246 | mGotResourceBase = false; | |
247 | mTrust = NULL; | |
248 | mCertChain = NULL; | |
249 | mEvalDetails = NULL; | |
250 | mRep->flush(); | |
251 | ||
252 | // we may just have updated the system database, so check again | |
253 | checkForSystemSignature(); | |
254 | } | |
255 | ||
256 | ||
257 | // | |
258 | // Retrieve a sealed component by special slot index. | |
259 | // If the CodeDirectory has already been validated, validate against that. | |
260 | // Otherwise, retrieve the component without validation (but cache it). Validation | |
261 | // will go through the cache and validate all cached components. | |
262 | // | |
263 | CFDataRef SecStaticCode::component(CodeDirectory::SpecialSlot slot, OSStatus fail /* = errSecCSSignatureFailed */) | |
264 | { | |
265 | assert(slot <= cdSlotMax); | |
266 | ||
267 | CFRef<CFDataRef> &cache = mCache[slot]; | |
268 | if (!cache) { | |
269 | if (CFRef<CFDataRef> data = mRep->component(slot)) { | |
270 | if (validated()) // if the directory has been validated... | |
271 | if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data), // ... and it's no good | |
272 | CFDataGetLength(data), -slot)) | |
427c49bc | 273 | MacOSError::throwMe(errorForSlot(slot)); // ... then bail |
b1ab9ed8 A |
274 | cache = data; // it's okay, cache it |
275 | } else { // absent, mark so | |
276 | if (validated()) // if directory has been validated... | |
277 | if (codeDirectory()->slotIsPresent(-slot)) // ... and the slot is NOT missing | |
427c49bc | 278 | MacOSError::throwMe(errorForSlot(slot)); // was supposed to be there |
b1ab9ed8 A |
279 | cache = CFDataRef(kCFNull); // white lie |
280 | } | |
281 | } | |
282 | return (cache == CFDataRef(kCFNull)) ? NULL : cache.get(); | |
283 | } | |
284 | ||
285 | ||
286 | // | |
287 | // Get the CodeDirectory. | |
288 | // Throws (if check==true) or returns NULL (check==false) if there is none. | |
289 | // Always throws if the CodeDirectory exists but is invalid. | |
290 | // NEVER validates against the signature. | |
291 | // | |
292 | const CodeDirectory *SecStaticCode::codeDirectory(bool check /* = true */) | |
293 | { | |
294 | if (!mDir) { | |
295 | if (mDir.take(mRep->codeDirectory())) { | |
296 | const CodeDirectory *dir = reinterpret_cast<const CodeDirectory *>(CFDataGetBytePtr(mDir)); | |
297 | dir->checkIntegrity(); | |
298 | } | |
299 | } | |
300 | if (mDir) | |
301 | return reinterpret_cast<const CodeDirectory *>(CFDataGetBytePtr(mDir)); | |
302 | if (check) | |
303 | MacOSError::throwMe(errSecCSUnsigned); | |
304 | return NULL; | |
305 | } | |
306 | ||
307 | ||
308 | // | |
309 | // Get the hash of the CodeDirectory. | |
310 | // Returns NULL if there is none. | |
311 | // | |
312 | CFDataRef SecStaticCode::cdHash() | |
313 | { | |
314 | if (!mCDHash) { | |
315 | if (const CodeDirectory *cd = codeDirectory(false)) { | |
316 | SHA1 hash; | |
317 | hash(cd, cd->length()); | |
318 | SHA1::Digest digest; | |
319 | hash.finish(digest); | |
320 | mCDHash.take(makeCFData(digest, sizeof(digest))); | |
321 | CODESIGN_STATIC_CDHASH(this, digest, sizeof(digest)); | |
322 | } | |
323 | } | |
324 | return mCDHash; | |
325 | } | |
326 | ||
327 | ||
328 | // | |
329 | // Return the CMS signature blob; NULL if none found. | |
330 | // | |
331 | CFDataRef SecStaticCode::signature() | |
332 | { | |
333 | if (!mSignature) | |
334 | mSignature.take(mRep->signature()); | |
335 | if (mSignature) | |
336 | return mSignature; | |
337 | MacOSError::throwMe(errSecCSUnsigned); | |
338 | } | |
339 | ||
340 | ||
341 | // | |
342 | // Verify the signature on the CodeDirectory. | |
343 | // If this succeeds (doesn't throw), the CodeDirectory is statically trustworthy. | |
344 | // Any outcome (successful or not) is cached for the lifetime of the StaticCode. | |
345 | // | |
346 | void SecStaticCode::validateDirectory() | |
347 | { | |
348 | // echo previous outcome, if any | |
349 | if (!validated()) | |
350 | try { | |
351 | // perform validation (or die trying) | |
352 | CODESIGN_EVAL_STATIC_DIRECTORY(this); | |
353 | mValidationExpired = verifySignature(); | |
b1ab9ed8 A |
354 | for (CodeDirectory::SpecialSlot slot = codeDirectory()->maxSpecialSlot(); slot >= 1; --slot) |
355 | if (mCache[slot]) // if we already loaded that resource... | |
427c49bc | 356 | validateComponent(slot, errorForSlot(slot)); // ... then check it now |
b1ab9ed8 | 357 | mValidated = true; // we've done the deed... |
427c49bc | 358 | mValidationResult = errSecSuccess; // ... and it was good |
b1ab9ed8 A |
359 | } catch (const CommonError &err) { |
360 | mValidated = true; | |
361 | mValidationResult = err.osStatus(); | |
362 | throw; | |
363 | } catch (...) { | |
364 | secdebug("staticCode", "%p validation threw non-common exception", this); | |
365 | mValidated = true; | |
366 | mValidationResult = errSecCSInternalError; | |
367 | throw; | |
368 | } | |
369 | assert(validated()); | |
427c49bc | 370 | if (mValidationResult == errSecSuccess) { |
b1ab9ed8 A |
371 | if (mValidationExpired) |
372 | if ((apiFlags() & kSecCSConsiderExpiration) | |
373 | || (codeDirectory()->flags & kSecCodeSignatureForceExpiration)) | |
374 | MacOSError::throwMe(CSSMERR_TP_CERT_EXPIRED); | |
375 | } else | |
376 | MacOSError::throwMe(mValidationResult); | |
377 | } | |
378 | ||
379 | ||
380 | // | |
381 | // Load and validate the CodeDirectory and all components *except* those related to the resource envelope. | |
382 | // Those latter components are checked by validateResources(). | |
383 | // | |
384 | void SecStaticCode::validateNonResourceComponents() | |
385 | { | |
386 | this->validateDirectory(); | |
387 | for (CodeDirectory::SpecialSlot slot = codeDirectory()->maxSpecialSlot(); slot >= 1; --slot) | |
388 | switch (slot) { | |
389 | case cdResourceDirSlot: // validated by validateResources | |
390 | break; | |
391 | default: | |
392 | this->component(slot); // loads and validates | |
393 | break; | |
394 | } | |
395 | } | |
396 | ||
397 | ||
398 | // | |
399 | // Get the (signed) signing date from the code signature. | |
400 | // Sadly, we need to validate the signature to get the date (as a side benefit). | |
401 | // This means that you can't get the signing time for invalidly signed code. | |
402 | // | |
403 | // We could run the decoder "almost to" verification to avoid this, but there seems | |
404 | // little practical point to such a duplication of effort. | |
405 | // | |
406 | CFAbsoluteTime SecStaticCode::signingTime() | |
407 | { | |
408 | validateDirectory(); | |
409 | return mSigningTime; | |
410 | } | |
411 | ||
412 | CFAbsoluteTime SecStaticCode::signingTimestamp() | |
413 | { | |
414 | validateDirectory(); | |
415 | return mSigningTimestamp; | |
416 | } | |
417 | ||
418 | ||
419 | // | |
420 | // Verify the CMS signature on the CodeDirectory. | |
421 | // This performs the cryptographic tango. It returns if the signature is valid, | |
422 | // or throws if it is not. As a side effect, a successful return sets up the | |
423 | // cached certificate chain for future use. | |
424 | // Returns true if the signature is expired (the X.509 sense), false if it's not. | |
313fa17b | 425 | // Expiration is fatal (throws) if a secure timestamp is included, but not otherwise. |
b1ab9ed8 A |
426 | // |
427 | bool SecStaticCode::verifySignature() | |
428 | { | |
429 | // ad-hoc signed code is considered validly signed by definition | |
430 | if (flag(kSecCodeSignatureAdhoc)) { | |
431 | CODESIGN_EVAL_STATIC_SIGNATURE_ADHOC(this); | |
432 | return false; | |
433 | } | |
434 | ||
435 | DTRACK(CODESIGN_EVAL_STATIC_SIGNATURE, this, (char*)this->mainExecutablePath().c_str()); | |
436 | ||
437 | // decode CMS and extract SecTrust for verification | |
438 | CFRef<CMSDecoderRef> cms; | |
439 | MacOSError::check(CMSDecoderCreate(&cms.aref())); // create decoder | |
440 | CFDataRef sig = this->signature(); | |
441 | MacOSError::check(CMSDecoderUpdateMessage(cms, CFDataGetBytePtr(sig), CFDataGetLength(sig))); | |
442 | this->codeDirectory(); // load CodeDirectory (sets mDir) | |
443 | MacOSError::check(CMSDecoderSetDetachedContent(cms, mDir)); | |
444 | MacOSError::check(CMSDecoderFinalizeMessage(cms)); | |
445 | MacOSError::check(CMSDecoderSetSearchKeychain(cms, cfEmptyArray())); | |
446 | CFRef<CFTypeRef> policy = verificationPolicy(apiFlags()); | |
447 | CMSSignerStatus status; | |
448 | MacOSError::check(CMSDecoderCopySignerStatus(cms, 0, policy, | |
449 | false, &status, &mTrust.aref(), NULL)); | |
450 | if (status != kCMSSignerValid) | |
451 | MacOSError::throwMe(errSecCSSignatureFailed); | |
452 | ||
453 | // internal signing time (as specified by the signer; optional) | |
454 | mSigningTime = 0; // "not present" marker (nobody could code sign on Jan 1, 2001 :-) | |
455 | switch (OSStatus rc = CMSDecoderCopySignerSigningTime(cms, 0, &mSigningTime)) { | |
427c49bc | 456 | case errSecSuccess: |
b1ab9ed8 A |
457 | case errSecSigningTimeMissing: |
458 | break; | |
459 | default: | |
460 | MacOSError::throwMe(rc); | |
461 | } | |
462 | ||
463 | // certified signing time (as specified by a TSA; optional) | |
464 | mSigningTimestamp = 0; | |
465 | switch (OSStatus rc = CMSDecoderCopySignerTimestamp(cms, 0, &mSigningTimestamp)) { | |
427c49bc | 466 | case errSecSuccess: |
b1ab9ed8 A |
467 | case errSecTimestampMissing: |
468 | break; | |
469 | default: | |
470 | MacOSError::throwMe(rc); | |
471 | } | |
472 | ||
473 | // set up the environment for SecTrust | |
474 | MacOSError::check(SecTrustSetAnchorCertificates(mTrust, cfEmptyArray())); // no anchors | |
475 | MacOSError::check(SecTrustSetKeychains(mTrust, cfEmptyArray())); // no keychains | |
476 | CSSM_APPLE_TP_ACTION_DATA actionData = { | |
477 | CSSM_APPLE_TP_ACTION_VERSION, // version of data structure | |
478 | CSSM_TP_ACTION_IMPLICIT_ANCHORS // action flags | |
479 | }; | |
480 | ||
481 | for (;;) { // at most twice | |
482 | MacOSError::check(SecTrustSetParameters(mTrust, | |
483 | CSSM_TP_ACTION_DEFAULT, CFTempData(&actionData, sizeof(actionData)))); | |
484 | ||
485 | // evaluate trust and extract results | |
486 | SecTrustResultType trustResult; | |
487 | MacOSError::check(SecTrustEvaluate(mTrust, &trustResult)); | |
488 | MacOSError::check(SecTrustGetResult(mTrust, &trustResult, &mCertChain.aref(), &mEvalDetails)); | |
420ff9d9 A |
489 | |
490 | // if this is an Apple developer cert.... | |
491 | if (teamID() && SecStaticCode::isAppleDeveloperCert(mCertChain)) { | |
492 | CFRef<CFStringRef> teamIDFromCert; | |
493 | if (CFArrayGetCount(mCertChain) > 0) { | |
494 | /* Note that SecCertificateCopySubjectComponent sets the out paramater to NULL if there is no field present */ | |
495 | MacOSError::check(SecCertificateCopySubjectComponent((SecCertificateRef)CFArrayGetValueAtIndex(mCertChain, Requirement::leafCert), | |
496 | &CSSMOID_OrganizationalUnitName, | |
497 | &teamIDFromCert.aref())); | |
498 | ||
499 | if (teamIDFromCert) { | |
500 | CFRef<CFStringRef> teamIDFromCD = CFStringCreateWithCString(NULL, teamID(), kCFStringEncodingUTF8); | |
501 | if (!teamIDFromCD) { | |
502 | MacOSError::throwMe(errSecCSInternalError); | |
503 | } | |
504 | ||
505 | if (CFStringCompare(teamIDFromCert, teamIDFromCD, 0) != kCFCompareEqualTo) { | |
506 | 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()); | |
507 | MacOSError::throwMe(errSecCSSignatureInvalid); | |
508 | } | |
509 | } | |
510 | } | |
511 | } | |
512 | ||
427c49bc | 513 | CODESIGN_EVAL_STATIC_SIGNATURE_RESULT(this, trustResult, mCertChain ? (int)CFArrayGetCount(mCertChain) : 0); |
b1ab9ed8 A |
514 | switch (trustResult) { |
515 | case kSecTrustResultProceed: | |
516 | case kSecTrustResultUnspecified: | |
517 | break; // success | |
518 | case kSecTrustResultDeny: | |
519 | MacOSError::throwMe(CSSMERR_APPLETP_TRUST_SETTING_DENY); // user reject | |
520 | case kSecTrustResultInvalid: | |
521 | assert(false); // should never happen | |
522 | MacOSError::throwMe(CSSMERR_TP_NOT_TRUSTED); | |
523 | default: | |
524 | { | |
525 | OSStatus result; | |
526 | MacOSError::check(SecTrustGetCssmResultCode(mTrust, &result)); | |
527 | // if we have a valid timestamp, CMS validates against (that) signing time and all is well. | |
528 | // If we don't have one, may validate against *now*, and must be able to tolerate expiration. | |
529 | if (mSigningTimestamp == 0) // no timestamp available | |
530 | if (((result == CSSMERR_TP_CERT_EXPIRED) || (result == CSSMERR_TP_CERT_NOT_VALID_YET)) | |
531 | && !(actionData.ActionFlags & CSSM_TP_ACTION_ALLOW_EXPIRED)) { | |
532 | CODESIGN_EVAL_STATIC_SIGNATURE_EXPIRED(this); | |
533 | actionData.ActionFlags |= CSSM_TP_ACTION_ALLOW_EXPIRED; // (this also allows postdated certs) | |
534 | continue; // retry validation while tolerating expiration | |
535 | } | |
536 | MacOSError::throwMe(result); | |
537 | } | |
538 | } | |
313fa17b A |
539 | |
540 | if (mSigningTimestamp) { | |
541 | CFIndex rootix = CFArrayGetCount(mCertChain); | |
542 | if (SecCertificateRef mainRoot = SecCertificateRef(CFArrayGetValueAtIndex(mCertChain, rootix-1))) | |
543 | if (isAppleCA(mainRoot)) { | |
544 | // impose policy: if the signature itself draws to Apple, then so must the timestamp signature | |
545 | CFRef<CFArrayRef> tsCerts; | |
546 | MacOSError::check(CMSDecoderCopySignerTimestampCertificates(cms, 0, &tsCerts.aref())); | |
547 | CFIndex tsn = CFArrayGetCount(tsCerts); | |
548 | bool good = tsn > 0 && isAppleCA(SecCertificateRef(CFArrayGetValueAtIndex(tsCerts, tsn-1))); | |
313fa17b A |
549 | if (!good) |
550 | MacOSError::throwMe(CSSMERR_TP_NOT_TRUSTED); | |
551 | } | |
552 | } | |
553 | ||
b1ab9ed8 A |
554 | return actionData.ActionFlags & CSSM_TP_ACTION_ALLOW_EXPIRED; |
555 | } | |
556 | } | |
557 | ||
558 | ||
559 | // | |
560 | // Return the TP policy used for signature verification. | |
561 | // This may be a simple SecPolicyRef or a CFArray of policies. | |
562 | // The caller owns the return value. | |
563 | // | |
564 | static SecPolicyRef makeCRLPolicy() | |
565 | { | |
566 | CFRef<SecPolicyRef> policy; | |
567 | MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_REVOCATION_CRL, &policy.aref())); | |
568 | CSSM_APPLE_TP_CRL_OPTIONS options; | |
569 | memset(&options, 0, sizeof(options)); | |
570 | options.Version = CSSM_APPLE_TP_CRL_OPTS_VERSION; | |
571 | options.CrlFlags = CSSM_TP_ACTION_FETCH_CRL_FROM_NET | CSSM_TP_ACTION_CRL_SUFFICIENT; | |
572 | CSSM_DATA optData = { sizeof(options), (uint8 *)&options }; | |
573 | MacOSError::check(SecPolicySetValue(policy, &optData)); | |
574 | return policy.yield(); | |
575 | } | |
576 | ||
577 | static SecPolicyRef makeOCSPPolicy() | |
578 | { | |
579 | CFRef<SecPolicyRef> policy; | |
580 | MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_REVOCATION_OCSP, &policy.aref())); | |
581 | CSSM_APPLE_TP_OCSP_OPTIONS options; | |
582 | memset(&options, 0, sizeof(options)); | |
583 | options.Version = CSSM_APPLE_TP_OCSP_OPTS_VERSION; | |
584 | options.Flags = CSSM_TP_ACTION_OCSP_SUFFICIENT; | |
585 | CSSM_DATA optData = { sizeof(options), (uint8 *)&options }; | |
586 | MacOSError::check(SecPolicySetValue(policy, &optData)); | |
587 | return policy.yield(); | |
588 | } | |
589 | ||
590 | CFTypeRef SecStaticCode::verificationPolicy(SecCSFlags flags) | |
591 | { | |
592 | CFRef<SecPolicyRef> core; | |
593 | MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3, | |
594 | &CSSMOID_APPLE_TP_CODE_SIGNING, &core.aref())); | |
595 | if (flags & kSecCSEnforceRevocationChecks) { | |
596 | CFRef<SecPolicyRef> crl = makeCRLPolicy(); | |
597 | CFRef<SecPolicyRef> ocsp = makeOCSPPolicy(); | |
598 | return makeCFArray(3, core.get(), crl.get(), ocsp.get()); | |
599 | } else { | |
600 | return core.yield(); | |
601 | } | |
602 | } | |
603 | ||
604 | ||
605 | // | |
606 | // Validate a particular sealed, cached resource against its (special) CodeDirectory slot. | |
607 | // The resource must already have been placed in the cache. | |
608 | // This does NOT perform basic validation. | |
609 | // | |
610 | void SecStaticCode::validateComponent(CodeDirectory::SpecialSlot slot, OSStatus fail /* = errSecCSSignatureFailed */) | |
611 | { | |
612 | assert(slot <= cdSlotMax); | |
613 | CFDataRef data = mCache[slot]; | |
614 | assert(data); // must be cached | |
615 | if (data == CFDataRef(kCFNull)) { | |
616 | if (codeDirectory()->slotIsPresent(-slot)) // was supposed to be there... | |
617 | MacOSError::throwMe(fail); // ... and is missing | |
618 | } else { | |
619 | if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data), CFDataGetLength(data), -slot)) | |
620 | MacOSError::throwMe(fail); | |
621 | } | |
622 | } | |
623 | ||
624 | ||
625 | // | |
626 | // Perform static validation of the main executable. | |
627 | // This reads the main executable from disk and validates it against the | |
628 | // CodeDirectory code slot array. | |
629 | // Note that this is NOT an in-memory validation, and is thus potentially | |
630 | // subject to timing attacks. | |
631 | // | |
632 | void SecStaticCode::validateExecutable() | |
633 | { | |
634 | if (!validatedExecutable()) { | |
635 | try { | |
636 | DTRACK(CODESIGN_EVAL_STATIC_EXECUTABLE, this, | |
637 | (char*)this->mainExecutablePath().c_str(), codeDirectory()->nCodeSlots); | |
638 | const CodeDirectory *cd = this->codeDirectory(); | |
639 | if (!cd) | |
640 | MacOSError::throwMe(errSecCSUnsigned); | |
641 | AutoFileDesc fd(mainExecutablePath(), O_RDONLY); | |
642 | fd.fcntl(F_NOCACHE, true); // turn off page caching (one-pass) | |
643 | if (Universal *fat = mRep->mainExecutableImage()) | |
644 | fd.seek(fat->archOffset()); | |
645 | size_t pageSize = cd->pageSize ? (1 << cd->pageSize) : 0; | |
646 | size_t remaining = cd->codeLimit; | |
427c49bc | 647 | for (uint32_t slot = 0; slot < cd->nCodeSlots; ++slot) { |
b1ab9ed8 A |
648 | size_t size = min(remaining, pageSize); |
649 | if (!cd->validateSlot(fd, size, slot)) { | |
427c49bc | 650 | CODESIGN_EVAL_STATIC_EXECUTABLE_FAIL(this, (int)slot); |
b1ab9ed8 A |
651 | MacOSError::throwMe(errSecCSSignatureFailed); |
652 | } | |
653 | remaining -= size; | |
654 | } | |
655 | mExecutableValidated = true; | |
427c49bc | 656 | mExecutableValidResult = errSecSuccess; |
b1ab9ed8 A |
657 | } catch (const CommonError &err) { |
658 | mExecutableValidated = true; | |
659 | mExecutableValidResult = err.osStatus(); | |
660 | throw; | |
661 | } catch (...) { | |
662 | secdebug("staticCode", "%p executable validation threw non-common exception", this); | |
663 | mExecutableValidated = true; | |
664 | mExecutableValidResult = errSecCSInternalError; | |
665 | throw; | |
666 | } | |
667 | } | |
668 | assert(validatedExecutable()); | |
427c49bc | 669 | if (mExecutableValidResult != errSecSuccess) |
b1ab9ed8 A |
670 | MacOSError::throwMe(mExecutableValidResult); |
671 | } | |
672 | ||
673 | ||
674 | // | |
427c49bc | 675 | // Perform static validation of sealed resources and nested code. |
b1ab9ed8 A |
676 | // |
677 | // This performs a whole-code static resource scan and effectively | |
678 | // computes a concordance between what's on disk and what's in the ResourceDirectory. | |
679 | // Any unsanctioned difference causes an error. | |
680 | // | |
427c49bc | 681 | void SecStaticCode::validateResources(SecCSFlags flags) |
b1ab9ed8 | 682 | { |
427c49bc A |
683 | // do we have a superset of this requested validation cached? |
684 | bool doit = true; | |
685 | if (mResourcesValidated) { // have cached outcome | |
686 | if (!(flags & kSecCSCheckNestedCode) || mResourcesDeep) // was deep or need no deep scan | |
687 | doit = false; | |
688 | } | |
689 | if (doit) { | |
b1ab9ed8 A |
690 | try { |
691 | // sanity first | |
692 | CFDictionaryRef sealedResources = resourceDictionary(); | |
693 | if (this->resourceBase()) // disk has resources | |
694 | if (sealedResources) | |
695 | /* go to work below */; | |
696 | else | |
697 | MacOSError::throwMe(errSecCSResourcesNotFound); | |
698 | else // disk has no resources | |
699 | if (sealedResources) | |
700 | MacOSError::throwMe(errSecCSResourcesNotFound); | |
701 | else | |
702 | return; // no resources, not sealed - fine (no work) | |
703 | ||
704 | // found resources, and they are sealed | |
b1ab9ed8 | 705 | DTRACK(CODESIGN_EVAL_STATIC_RESOURCES, this, |
427c49bc | 706 | (char*)this->mainExecutablePath().c_str(), 0); |
b1ab9ed8 A |
707 | |
708 | // scan through the resources on disk, checking each against the resourceDirectory | |
709 | mResourcesValidContext = new CollectingContext(*this); // collect all failures in here | |
427c49bc A |
710 | CFDictionaryRef rules; |
711 | CFDictionaryRef files; | |
712 | uint32_t version; | |
713 | if (CFDictionaryGetValue(sealedResources, CFSTR("files2"))) { // have V2 signature | |
714 | rules = cfget<CFDictionaryRef>(sealedResources, "rules2"); | |
715 | files = cfget<CFDictionaryRef>(sealedResources, "files2"); | |
716 | version = 2; | |
717 | } else { // only V1 available | |
718 | rules = cfget<CFDictionaryRef>(sealedResources, "rules"); | |
719 | files = cfget<CFDictionaryRef>(sealedResources, "files"); | |
720 | version = 1; | |
b1ab9ed8 | 721 | } |
427c49bc A |
722 | if (!rules || !files) |
723 | MacOSError::throwMe(errSecCSResourcesInvalid); | |
724 | __block CFRef<CFMutableDictionaryRef> resourceMap = makeCFMutableDictionary(files); | |
725 | ResourceBuilder resources(cfString(this->resourceBase()), rules, codeDirectory()->hashType); | |
726 | diskRep()->adjustResources(resources); | |
727 | resources.scan(^(FTSENT *ent, uint32_t ruleFlags, const char *relpath, ResourceBuilder::Rule *rule) { | |
728 | validateResource(files, relpath, *mResourcesValidContext, flags, version); | |
729 | CFDictionaryRemoveValue(resourceMap, CFTempString(relpath)); | |
730 | }); | |
b1ab9ed8 A |
731 | |
732 | if (CFDictionaryGetCount(resourceMap) > 0) { | |
733 | secdebug("staticCode", "%p sealed resource(s) not found in code", this); | |
734 | CFDictionaryApplyFunction(resourceMap, SecStaticCode::checkOptionalResource, mResourcesValidContext); | |
735 | } | |
736 | ||
737 | // now check for any errors found in the reporting context | |
738 | mResourcesValidated = true; | |
427c49bc A |
739 | mResourcesDeep = flags & kSecCSCheckNestedCode; |
740 | if (mResourcesValidContext->osStatus() != errSecSuccess) | |
b1ab9ed8 | 741 | mResourcesValidContext->throwMe(); |
b1ab9ed8 A |
742 | } catch (const CommonError &err) { |
743 | mResourcesValidated = true; | |
427c49bc | 744 | mResourcesDeep = flags & kSecCSCheckNestedCode; |
b1ab9ed8 A |
745 | mResourcesValidResult = err.osStatus(); |
746 | throw; | |
747 | } catch (...) { | |
748 | secdebug("staticCode", "%p executable validation threw non-common exception", this); | |
749 | mResourcesValidated = true; | |
427c49bc | 750 | mResourcesDeep = flags & kSecCSCheckNestedCode; |
b1ab9ed8 A |
751 | mResourcesValidResult = errSecCSInternalError; |
752 | throw; | |
753 | } | |
754 | } | |
755 | assert(validatedResources()); | |
756 | if (mResourcesValidResult) | |
757 | MacOSError::throwMe(mResourcesValidResult); | |
427c49bc | 758 | if (mResourcesValidContext->osStatus() != errSecSuccess) |
b1ab9ed8 A |
759 | mResourcesValidContext->throwMe(); |
760 | } | |
761 | ||
762 | ||
763 | void SecStaticCode::checkOptionalResource(CFTypeRef key, CFTypeRef value, void *context) | |
764 | { | |
765 | CollectingContext *ctx = static_cast<CollectingContext *>(context); | |
766 | ResourceSeal seal(value); | |
767 | if (!seal.optional()) { | |
768 | if (key && CFGetTypeID(key) == CFStringGetTypeID()) { | |
769 | ctx->reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, | |
770 | CFTempURL(CFStringRef(key), false, ctx->code.resourceBase())); | |
771 | } else { | |
772 | ctx->reportProblem(errSecCSBadResource, kSecCFErrorResourceSeal, key); | |
773 | } | |
774 | } | |
775 | } | |
776 | ||
777 | ||
778 | // | |
779 | // Load, validate, cache, and return CFDictionary forms of sealed resources. | |
780 | // | |
781 | CFDictionaryRef SecStaticCode::infoDictionary() | |
782 | { | |
783 | if (!mInfoDict) { | |
784 | mInfoDict.take(getDictionary(cdInfoSlot, errSecCSInfoPlistFailed)); | |
785 | secdebug("staticCode", "%p loaded InfoDict %p", this, mInfoDict.get()); | |
786 | } | |
787 | return mInfoDict; | |
788 | } | |
789 | ||
790 | CFDictionaryRef SecStaticCode::entitlements() | |
791 | { | |
792 | if (!mEntitlements) { | |
793 | validateDirectory(); | |
794 | if (CFDataRef entitlementData = component(cdEntitlementSlot)) { | |
795 | validateComponent(cdEntitlementSlot); | |
796 | const EntitlementBlob *blob = reinterpret_cast<const EntitlementBlob *>(CFDataGetBytePtr(entitlementData)); | |
797 | if (blob->validateBlob()) { | |
798 | mEntitlements.take(blob->entitlements()); | |
799 | secdebug("staticCode", "%p loaded Entitlements %p", this, mEntitlements.get()); | |
800 | } | |
801 | // we do not consider a different blob type to be an error. We think it's a new format we don't understand | |
802 | } | |
803 | } | |
804 | return mEntitlements; | |
805 | } | |
806 | ||
427c49bc | 807 | CFDictionaryRef SecStaticCode::resourceDictionary(bool check /* = true */) |
b1ab9ed8 A |
808 | { |
809 | if (mResourceDict) // cached | |
810 | return mResourceDict; | |
427c49bc | 811 | if (CFRef<CFDictionaryRef> dict = getDictionary(cdResourceDirSlot, check)) |
b1ab9ed8 A |
812 | if (cfscan(dict, "{rules=%Dn,files=%Dn}")) { |
813 | secdebug("staticCode", "%p loaded ResourceDict %p", | |
814 | this, mResourceDict.get()); | |
815 | return mResourceDict = dict; | |
816 | } | |
817 | // bad format | |
818 | return NULL; | |
819 | } | |
820 | ||
821 | ||
822 | // | |
823 | // Load and cache the resource directory base. | |
824 | // Note that the base is optional for each DiskRep. | |
825 | // | |
826 | CFURLRef SecStaticCode::resourceBase() | |
827 | { | |
828 | if (!mGotResourceBase) { | |
829 | string base = mRep->resourcesRootPath(); | |
830 | if (!base.empty()) | |
831 | mResourceBase.take(makeCFURL(base, true)); | |
832 | mGotResourceBase = true; | |
833 | } | |
834 | return mResourceBase; | |
835 | } | |
836 | ||
837 | ||
838 | // | |
839 | // Load a component, validate it, convert it to a CFDictionary, and return that. | |
840 | // This will force load and validation, which means that it will perform basic | |
841 | // validation if it hasn't been done yet. | |
842 | // | |
427c49bc | 843 | CFDictionaryRef SecStaticCode::getDictionary(CodeDirectory::SpecialSlot slot, bool check /* = true */) |
b1ab9ed8 | 844 | { |
427c49bc A |
845 | if (check) |
846 | validateDirectory(); | |
847 | if (CFDataRef infoData = component(slot)) { | |
848 | validateComponent(slot); | |
b1ab9ed8 A |
849 | if (CFDictionaryRef dict = makeCFDictionaryFrom(infoData)) |
850 | return dict; | |
851 | else | |
852 | MacOSError::throwMe(errSecCSBadDictionaryFormat); | |
853 | } | |
854 | return NULL; | |
855 | } | |
856 | ||
857 | ||
858 | // | |
859 | // Load, validate, and return a sealed resource. | |
860 | // The resource data (loaded in to memory as a blob) is returned and becomes | |
861 | // the responsibility of the caller; it is NOT cached by SecStaticCode. | |
862 | // | |
863 | // A resource that is not sealed will not be returned, and an error will be thrown. | |
864 | // A missing resource will cause an error unless it's marked optional in the Directory. | |
865 | // Under no circumstances will a corrupt resource be returned. | |
866 | // NULL will only be returned for a resource that is neither sealed nor present | |
867 | // (or that is sealed, absent, and marked optional). | |
868 | // If the ResourceDictionary itself is not sealed, this function will always fail. | |
869 | // | |
870 | // There is currently no interface for partial retrieval of the resource data. | |
871 | // (Since the ResourceDirectory does not currently support segmentation, all the | |
872 | // data would have to be read anyway, but it could be read into a reusable buffer.) | |
873 | // | |
874 | CFDataRef SecStaticCode::resource(string path, ValidationContext &ctx) | |
875 | { | |
876 | if (CFDictionaryRef rdict = resourceDictionary()) { | |
877 | if (CFTypeRef file = cfget(rdict, "files.%s", path.c_str())) { | |
878 | ResourceSeal seal = file; | |
879 | if (!resourceBase()) // no resources in DiskRep | |
880 | MacOSError::throwMe(errSecCSResourcesNotFound); | |
427c49bc A |
881 | if (seal.nested()) |
882 | MacOSError::throwMe(errSecCSResourcesNotSealed); // (it's nested code) | |
b1ab9ed8 A |
883 | CFRef<CFURLRef> fullpath = makeCFURL(path, false, resourceBase()); |
884 | if (CFRef<CFDataRef> data = cfLoadFile(fullpath)) { | |
885 | MakeHash<CodeDirectory> hasher(this->codeDirectory()); | |
886 | hasher->update(CFDataGetBytePtr(data), CFDataGetLength(data)); | |
887 | if (hasher->verify(seal.hash())) | |
888 | return data.yield(); // good | |
889 | else | |
890 | ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // altered | |
891 | } else { | |
892 | if (!seal.optional()) | |
893 | ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, fullpath); // was sealed but is now missing | |
894 | else | |
895 | return NULL; // validly missing | |
896 | } | |
897 | } else | |
898 | ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAdded, CFTempURL(path, false, resourceBase())); | |
899 | return NULL; | |
900 | } else | |
901 | MacOSError::throwMe(errSecCSResourcesNotSealed); | |
902 | } | |
903 | ||
904 | CFDataRef SecStaticCode::resource(string path) | |
905 | { | |
906 | ValidationContext ctx; | |
907 | return resource(path, ctx); | |
908 | } | |
909 | ||
910 | ||
427c49bc | 911 | void SecStaticCode::validateResource(CFDictionaryRef files, string path, ValidationContext &ctx, SecCSFlags flags, uint32_t version) |
b1ab9ed8 | 912 | { |
427c49bc A |
913 | if (!resourceBase()) // no resources in DiskRep |
914 | MacOSError::throwMe(errSecCSResourcesNotFound); | |
915 | CFRef<CFURLRef> fullpath = makeCFURL(path, false, resourceBase()); | |
916 | if (CFTypeRef file = CFDictionaryGetValue(files, CFTempString(path))) { | |
917 | ResourceSeal seal = file; | |
918 | if (seal.nested()) { | |
919 | validateNestedCode(fullpath, seal, flags); | |
920 | } else if (seal.link()) { | |
921 | char target[PATH_MAX]; | |
922 | ssize_t len = ::readlink(cfString(fullpath).c_str(), target, sizeof(target)-1); | |
923 | if (len < 0) | |
924 | UnixError::check(-1); | |
925 | target[len] = '\0'; | |
926 | if (cfString(seal.link()) != target) | |
927 | ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); | |
928 | } else if (seal.hash()) { // genuine file | |
929 | AutoFileDesc fd(cfString(fullpath), O_RDONLY, FileDesc::modeMissingOk); // open optional file | |
b1ab9ed8 A |
930 | if (fd) { |
931 | MakeHash<CodeDirectory> hasher(this->codeDirectory()); | |
932 | hashFileData(fd, hasher.get()); | |
933 | if (hasher->verify(seal.hash())) | |
934 | return; // verify good | |
935 | else | |
936 | ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // altered | |
937 | } else { | |
938 | if (!seal.optional()) | |
939 | ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, fullpath); // was sealed but is now missing | |
940 | else | |
941 | return; // validly missing | |
942 | } | |
943 | } else | |
427c49bc A |
944 | ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type |
945 | return; | |
946 | } | |
947 | if (version == 1) { // version 1 ignores symlinks altogether | |
948 | char target[PATH_MAX]; | |
949 | if (::readlink(cfString(fullpath).c_str(), target, sizeof(target)) > 0) | |
950 | return; | |
951 | } | |
952 | ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAdded, CFTempURL(path, false, resourceBase())); | |
953 | } | |
954 | ||
955 | void SecStaticCode::validateNestedCode(CFURLRef path, const ResourceSeal &seal, SecCSFlags flags) | |
956 | { | |
957 | CFRef<SecRequirementRef> req; | |
958 | if (SecRequirementCreateWithString(seal.requirement(), kSecCSDefaultFlags, &req.aref())) | |
959 | MacOSError::throwMe(errSecCSResourcesInvalid); | |
960 | ||
961 | // recursively verify this nested code | |
962 | try { | |
963 | if (!(flags & kSecCSCheckNestedCode)) | |
964 | flags |= kSecCSBasicValidateOnly; | |
965 | SecPointer<SecStaticCode> code = new SecStaticCode(DiskRep::bestGuess(cfString(path))); | |
966 | code->setMonitor(this->monitor()); | |
967 | code->staticValidate(flags, SecRequirement::required(req)); | |
968 | } catch (CSError &err) { | |
969 | if (err.error == errSecCSReqFailed) { | |
970 | mResourcesValidContext->reportProblem(errSecCSBadNestedCode, kSecCFErrorResourceAltered, path); | |
971 | return; | |
972 | } | |
973 | err.augment(kSecCFErrorPath, path); | |
974 | throw; | |
975 | } catch (const MacOSError &err) { | |
976 | if (err.error == errSecCSReqFailed) { | |
977 | mResourcesValidContext->reportProblem(errSecCSBadNestedCode, kSecCFErrorResourceAltered, path); | |
978 | return; | |
979 | } | |
980 | CSError::throwMe(err.error, kSecCFErrorPath, path); | |
981 | } | |
b1ab9ed8 A |
982 | } |
983 | ||
984 | ||
985 | // | |
986 | // Test a CodeDirectory flag. | |
987 | // Returns false if there is no CodeDirectory. | |
988 | // May throw if the CodeDirectory is present but somehow invalid. | |
989 | // | |
990 | bool SecStaticCode::flag(uint32_t tested) | |
991 | { | |
992 | if (const CodeDirectory *cd = this->codeDirectory(false)) | |
993 | return cd->flags & tested; | |
994 | else | |
995 | return false; | |
996 | } | |
997 | ||
998 | ||
999 | // | |
1000 | // Retrieve the full SuperBlob containing all internal requirements. | |
1001 | // | |
1002 | const Requirements *SecStaticCode::internalRequirements() | |
1003 | { | |
427c49bc A |
1004 | if (CFDataRef reqData = component(cdRequirementsSlot)) { |
1005 | const Requirements *req = (const Requirements *)CFDataGetBytePtr(reqData); | |
1006 | if (!req->validateBlob()) | |
1007 | MacOSError::throwMe(errSecCSReqInvalid); | |
1008 | return req; | |
1009 | } else | |
b1ab9ed8 A |
1010 | return NULL; |
1011 | } | |
1012 | ||
1013 | ||
1014 | // | |
1015 | // Retrieve a particular internal requirement by type. | |
1016 | // | |
1017 | const Requirement *SecStaticCode::internalRequirement(SecRequirementType type) | |
1018 | { | |
1019 | if (const Requirements *reqs = internalRequirements()) | |
1020 | return reqs->find<Requirement>(type); | |
1021 | else | |
1022 | return NULL; | |
1023 | } | |
1024 | ||
1025 | ||
1026 | // | |
1027 | // Return the Designated Requirement (DR). This can be either explicit in the | |
1028 | // Internal Requirements component, or implicitly generated on demand here. | |
1029 | // Note that an explicit DR may have been implicitly generated at signing time; | |
1030 | // we don't distinguish this case. | |
1031 | // | |
1032 | const Requirement *SecStaticCode::designatedRequirement() | |
1033 | { | |
1034 | if (const Requirement *req = internalRequirement(kSecDesignatedRequirementType)) { | |
1035 | return req; // explicit in signing data | |
1036 | } else { | |
1037 | if (!mDesignatedReq) | |
1038 | mDesignatedReq = defaultDesignatedRequirement(); | |
1039 | return mDesignatedReq; | |
1040 | } | |
1041 | } | |
1042 | ||
1043 | ||
1044 | // | |
1045 | // Generate the default Designated Requirement (DR) for this StaticCode. | |
1046 | // Ignore any explicit DR it may contain. | |
1047 | // | |
1048 | const Requirement *SecStaticCode::defaultDesignatedRequirement() | |
1049 | { | |
1050 | if (flag(kSecCodeSignatureAdhoc)) { | |
427c49bc A |
1051 | // adhoc signature: return a cdhash requirement for all architectures |
1052 | __block Requirement::Maker maker; | |
1053 | Requirement::Maker::Chain chain(maker, opOr); | |
1054 | ||
1055 | // insert cdhash requirement for all architectures | |
1056 | chain.add(); | |
1057 | maker.cdhash(this->cdHash()); | |
1058 | handleOtherArchitectures(^(SecStaticCode *subcode) { | |
1059 | if (CFDataRef cdhash = subcode->cdHash()) { | |
1060 | chain.add(); | |
1061 | maker.cdhash(cdhash); | |
1062 | } | |
1063 | }); | |
b1ab9ed8 A |
1064 | return maker.make(); |
1065 | } else { | |
1066 | // full signature: Gin up full context and let DRMaker do its thing | |
1067 | validateDirectory(); // need the cert chain | |
1068 | Requirement::Context context(this->certificates(), | |
1069 | this->infoDictionary(), | |
1070 | this->entitlements(), | |
1071 | this->identifier(), | |
1072 | this->codeDirectory() | |
1073 | ); | |
1074 | return DRMaker(context).make(); | |
1075 | } | |
1076 | } | |
1077 | ||
1078 | ||
1079 | // | |
1080 | // Validate a SecStaticCode against the internal requirement of a particular type. | |
1081 | // | |
1082 | void SecStaticCode::validateRequirements(SecRequirementType type, SecStaticCode *target, | |
427c49bc | 1083 | OSStatus nullError /* = errSecSuccess */) |
b1ab9ed8 A |
1084 | { |
1085 | DTRACK(CODESIGN_EVAL_STATIC_INTREQ, this, type, target, nullError); | |
1086 | if (const Requirement *req = internalRequirement(type)) | |
1087 | target->validateRequirement(req, nullError ? nullError : errSecCSReqFailed); | |
1088 | else if (nullError) | |
1089 | MacOSError::throwMe(nullError); | |
1090 | else | |
1091 | /* accept it */; | |
1092 | } | |
1093 | ||
1094 | ||
1095 | // | |
1096 | // Validate this StaticCode against an external Requirement | |
1097 | // | |
1098 | bool SecStaticCode::satisfiesRequirement(const Requirement *req, OSStatus failure) | |
1099 | { | |
1100 | assert(req); | |
1101 | validateDirectory(); | |
1102 | return req->validates(Requirement::Context(mCertChain, infoDictionary(), entitlements(), codeDirectory()->identifier(), codeDirectory()), failure); | |
1103 | } | |
1104 | ||
1105 | void SecStaticCode::validateRequirement(const Requirement *req, OSStatus failure) | |
1106 | { | |
1107 | if (!this->satisfiesRequirement(req, failure)) | |
1108 | MacOSError::throwMe(failure); | |
1109 | } | |
1110 | ||
1111 | ||
1112 | // | |
1113 | // Retrieve one certificate from the cert chain. | |
1114 | // Positive and negative indices can be used: | |
1115 | // [ leaf, intermed-1, ..., intermed-n, anchor ] | |
1116 | // 0 1 ... -2 -1 | |
1117 | // Returns NULL if unavailable for any reason. | |
1118 | // | |
1119 | SecCertificateRef SecStaticCode::cert(int ix) | |
1120 | { | |
1121 | validateDirectory(); // need cert chain | |
1122 | if (mCertChain) { | |
1123 | CFIndex length = CFArrayGetCount(mCertChain); | |
1124 | if (ix < 0) | |
1125 | ix += length; | |
1126 | if (ix >= 0 && ix < length) | |
1127 | return SecCertificateRef(CFArrayGetValueAtIndex(mCertChain, ix)); | |
1128 | } | |
1129 | return NULL; | |
1130 | } | |
1131 | ||
1132 | CFArrayRef SecStaticCode::certificates() | |
1133 | { | |
1134 | validateDirectory(); // need cert chain | |
1135 | return mCertChain; | |
1136 | } | |
1137 | ||
1138 | ||
1139 | // | |
1140 | // Gather (mostly) API-official information about this StaticCode. | |
1141 | // | |
1142 | // This method lives in the twilight between the API and internal layers, | |
1143 | // since it generates API objects (Sec*Refs) for return. | |
1144 | // | |
1145 | CFDictionaryRef SecStaticCode::signingInformation(SecCSFlags flags) | |
1146 | { | |
1147 | // | |
1148 | // Start with the pieces that we return even for unsigned code. | |
1149 | // This makes Sec[Static]CodeRefs useful as API-level replacements | |
1150 | // of our internal OSXCode objects. | |
1151 | // | |
1152 | CFRef<CFMutableDictionaryRef> dict = makeCFMutableDictionary(1, | |
1153 | kSecCodeInfoMainExecutable, CFTempURL(this->mainExecutablePath()).get() | |
1154 | ); | |
1155 | ||
1156 | // | |
1157 | // If we're not signed, this is all you get | |
1158 | // | |
1159 | if (!this->isSigned()) | |
1160 | return dict.yield(); | |
1161 | ||
1162 | // | |
1163 | // Add the generic attributes that we always include | |
1164 | // | |
1165 | CFDictionaryAddValue(dict, kSecCodeInfoIdentifier, CFTempString(this->identifier())); | |
427c49bc | 1166 | CFDictionaryAddValue(dict, kSecCodeInfoFlags, CFTempNumber(this->codeDirectory(false)->flags.get())); |
b1ab9ed8 A |
1167 | CFDictionaryAddValue(dict, kSecCodeInfoFormat, CFTempString(this->format())); |
1168 | CFDictionaryAddValue(dict, kSecCodeInfoSource, CFTempString(this->signatureSource())); | |
1169 | CFDictionaryAddValue(dict, kSecCodeInfoUnique, this->cdHash()); | |
1170 | CFDictionaryAddValue(dict, kSecCodeInfoDigestAlgorithm, CFTempNumber(this->codeDirectory(false)->hashType)); | |
1171 | ||
1172 | // | |
1173 | // Deliver any Info.plist only if it looks intact | |
1174 | // | |
1175 | try { | |
1176 | if (CFDictionaryRef info = this->infoDictionary()) | |
1177 | CFDictionaryAddValue(dict, kSecCodeInfoPList, info); | |
1178 | } catch (...) { } // don't deliver Info.plist if questionable | |
1179 | ||
1180 | // | |
1181 | // kSecCSSigningInformation adds information about signing certificates and chains | |
1182 | // | |
427c49bc A |
1183 | if (flags & kSecCSSigningInformation) |
1184 | try { | |
1185 | if (CFArrayRef certs = this->certificates()) | |
1186 | CFDictionaryAddValue(dict, kSecCodeInfoCertificates, certs); | |
1187 | if (CFDataRef sig = this->signature()) | |
1188 | CFDictionaryAddValue(dict, kSecCodeInfoCMS, sig); | |
1189 | if (mTrust) | |
1190 | CFDictionaryAddValue(dict, kSecCodeInfoTrust, mTrust); | |
1191 | if (CFAbsoluteTime time = this->signingTime()) | |
1192 | if (CFRef<CFDateRef> date = CFDateCreate(NULL, time)) | |
1193 | CFDictionaryAddValue(dict, kSecCodeInfoTime, date); | |
1194 | if (CFAbsoluteTime time = this->signingTimestamp()) | |
1195 | if (CFRef<CFDateRef> date = CFDateCreate(NULL, time)) | |
1196 | CFDictionaryAddValue(dict, kSecCodeInfoTimestamp, date); | |
420ff9d9 A |
1197 | if (const char *teamID = this->teamID()) |
1198 | CFDictionaryAddValue(dict, kSecCodeInfoTeamIdentifier, CFTempString(teamID)); | |
427c49bc | 1199 | } catch (...) { } |
b1ab9ed8 A |
1200 | |
1201 | // | |
1202 | // kSecCSRequirementInformation adds information on requirements | |
1203 | // | |
427c49bc A |
1204 | if (flags & kSecCSRequirementInformation) |
1205 | try { | |
1206 | if (const Requirements *reqs = this->internalRequirements()) { | |
1207 | CFDictionaryAddValue(dict, kSecCodeInfoRequirements, | |
1208 | CFTempString(Dumper::dump(reqs))); | |
1209 | CFDictionaryAddValue(dict, kSecCodeInfoRequirementData, CFTempData(*reqs)); | |
1210 | } | |
1211 | ||
1212 | const Requirement *dreq = this->designatedRequirement(); | |
1213 | CFRef<SecRequirementRef> dreqRef = (new SecRequirement(dreq))->handle(); | |
1214 | CFDictionaryAddValue(dict, kSecCodeInfoDesignatedRequirement, dreqRef); | |
1215 | if (this->internalRequirement(kSecDesignatedRequirementType)) { // explicit | |
1216 | CFRef<SecRequirementRef> ddreqRef = (new SecRequirement(this->defaultDesignatedRequirement(), true))->handle(); | |
1217 | CFDictionaryAddValue(dict, kSecCodeInfoImplicitDesignatedRequirement, ddreqRef); | |
1218 | } else { // implicit | |
1219 | CFDictionaryAddValue(dict, kSecCodeInfoImplicitDesignatedRequirement, dreqRef); | |
1220 | } | |
1221 | } catch (...) { } | |
b1ab9ed8 | 1222 | |
427c49bc A |
1223 | try { |
1224 | if (CFDataRef ent = this->component(cdEntitlementSlot)) { | |
1225 | CFDictionaryAddValue(dict, kSecCodeInfoEntitlements, ent); | |
1226 | if (CFDictionaryRef entdict = this->entitlements()) | |
1227 | CFDictionaryAddValue(dict, kSecCodeInfoEntitlementsDict, entdict); | |
1228 | } | |
1229 | } catch (...) { } | |
b1ab9ed8 A |
1230 | |
1231 | // | |
1232 | // kSecCSInternalInformation adds internal information meant to be for Apple internal | |
1233 | // use (SPI), and not guaranteed to be stable. Primarily, this is data we want | |
1234 | // to reliably transmit through the API wall so that code outside the Security.framework | |
1235 | // can use it without having to play nasty tricks to get it. | |
1236 | // | |
427c49bc A |
1237 | if (flags & kSecCSInternalInformation) |
1238 | try { | |
1239 | if (mDir) | |
1240 | CFDictionaryAddValue(dict, kSecCodeInfoCodeDirectory, mDir); | |
1241 | CFDictionaryAddValue(dict, kSecCodeInfoCodeOffset, CFTempNumber(mRep->signingBase())); | |
1242 | if (CFRef<CFDictionaryRef> rdict = getDictionary(cdResourceDirSlot, false)) // suppress validation | |
1243 | CFDictionaryAddValue(dict, kSecCodeInfoResourceDirectory, rdict); | |
1244 | } catch (...) { } | |
b1ab9ed8 A |
1245 | |
1246 | ||
1247 | // | |
1248 | // kSecCSContentInformation adds more information about the physical layout | |
1249 | // of the signed code. This is (only) useful for packaging or patching-oriented | |
1250 | // applications. | |
1251 | // | |
1252 | if (flags & kSecCSContentInformation) | |
1253 | if (CFRef<CFArrayRef> files = mRep->modifiedFiles()) | |
1254 | CFDictionaryAddValue(dict, kSecCodeInfoChangedFiles, files); | |
1255 | ||
1256 | return dict.yield(); | |
1257 | } | |
1258 | ||
1259 | ||
1260 | // | |
1261 | // Resource validation contexts. | |
1262 | // The default context simply throws a CSError, rudely terminating the operation. | |
1263 | // | |
1264 | SecStaticCode::ValidationContext::~ValidationContext() | |
1265 | { /* virtual */ } | |
1266 | ||
1267 | void SecStaticCode::ValidationContext::reportProblem(OSStatus rc, CFStringRef type, CFTypeRef value) | |
1268 | { | |
1269 | CSError::throwMe(rc, type, value); | |
1270 | } | |
1271 | ||
1272 | void SecStaticCode::CollectingContext::reportProblem(OSStatus rc, CFStringRef type, CFTypeRef value) | |
1273 | { | |
427c49bc | 1274 | if (mStatus == errSecSuccess) |
b1ab9ed8 A |
1275 | mStatus = rc; // record first failure for eventual error return |
1276 | if (type) { | |
1277 | if (!mCollection) | |
1278 | mCollection.take(makeCFMutableDictionary()); | |
1279 | CFMutableArrayRef element = CFMutableArrayRef(CFDictionaryGetValue(mCollection, type)); | |
1280 | if (!element) { | |
1281 | element = makeCFMutableArray(0); | |
1282 | if (!element) | |
1283 | CFError::throwMe(); | |
1284 | CFDictionaryAddValue(mCollection, type, element); | |
1285 | CFRelease(element); | |
1286 | } | |
1287 | CFArrayAppendValue(element, value); | |
1288 | } | |
1289 | } | |
1290 | ||
1291 | void SecStaticCode::CollectingContext::throwMe() | |
1292 | { | |
427c49bc | 1293 | assert(mStatus != errSecSuccess); |
b1ab9ed8 A |
1294 | throw CSError(mStatus, mCollection.retain()); |
1295 | } | |
1296 | ||
1297 | ||
1298 | // | |
427c49bc A |
1299 | // Master validation driver. |
1300 | // This is the static validation (only) driver for the API. | |
b1ab9ed8 | 1301 | // |
427c49bc A |
1302 | // SecStaticCode exposes an à la carte menu of topical validators applying |
1303 | // to a given object. The static validation API pulls the together reliably, | |
1304 | // but it also adds two matrix dimensions: architecture (for "fat" Mach-O binaries) | |
1305 | // and nested code. This function will crawl a suitable cross-section of this | |
1306 | // validation matrix based on which options it is given, creating temporary | |
1307 | // SecStaticCode objects on the fly to complete the task. | |
1308 | // (The point, of course, is to do as little duplicate work as possible.) | |
b1ab9ed8 | 1309 | // |
427c49bc | 1310 | void SecStaticCode::staticValidate(SecCSFlags flags, const SecRequirement *req) |
b1ab9ed8 | 1311 | { |
427c49bc A |
1312 | // core components: once per architecture (if any) |
1313 | this->staticValidateCore(flags, req); | |
1314 | if (flags & kSecCSCheckAllArchitectures) | |
1315 | handleOtherArchitectures(^(SecStaticCode* subcode) { | |
1316 | subcode->detachedSignature(this->mDetachedSig); // carry over explicit (but not implicit) architecture | |
1317 | subcode->staticValidateCore(flags, req); | |
1318 | }); | |
1319 | ||
1320 | // resources: once for all architectures | |
1321 | if (!(flags & kSecCSDoNotValidateResources)) | |
1322 | this->validateResources(flags); | |
1323 | ||
1324 | // allow monitor intervention | |
1325 | if (CFRef<CFTypeRef> veto = reportEvent(CFSTR("validated"), NULL)) { | |
1326 | if (CFGetTypeID(veto) == CFNumberGetTypeID()) | |
1327 | MacOSError::throwMe(cfNumber<OSStatus>(veto.as<CFNumberRef>())); | |
1328 | else | |
1329 | MacOSError::throwMe(errSecCSBadCallbackValue); | |
b1ab9ed8 A |
1330 | } |
1331 | } | |
1332 | ||
427c49bc | 1333 | void SecStaticCode::staticValidateCore(SecCSFlags flags, const SecRequirement *req) |
b1ab9ed8 | 1334 | { |
427c49bc A |
1335 | try { |
1336 | this->validateNonResourceComponents(); // also validates the CodeDirectory | |
1337 | if (!(flags & kSecCSDoNotValidateExecutable)) | |
1338 | this->validateExecutable(); | |
1339 | if (req) | |
1340 | this->validateRequirement(req->requirement(), errSecCSReqFailed); | |
1341 | } catch (CSError &err) { | |
1342 | if (Universal *fat = this->diskRep()->mainExecutableImage()) // Mach-O | |
1343 | if (MachO *mach = fat->architecture()) { | |
1344 | err.augment(kSecCFErrorArchitecture, CFTempString(mach->architecture().displayName())); | |
1345 | delete mach; | |
1346 | } | |
1347 | throw; | |
1348 | } catch (const MacOSError &err) { | |
1349 | // add architecture information if we can get it | |
1350 | if (Universal *fat = this->diskRep()->mainExecutableImage()) | |
1351 | if (MachO *mach = fat->architecture()) { | |
1352 | CFTempString arch(mach->architecture().displayName()); | |
1353 | delete mach; | |
1354 | CSError::throwMe(err.error, kSecCFErrorArchitecture, arch); | |
1355 | } | |
1356 | throw; | |
1357 | } | |
1358 | } | |
1359 | ||
1360 | ||
1361 | // | |
1362 | // A helper that generates SecStaticCode objects for all but the primary architecture | |
1363 | // of a fat binary and calls a block on them. | |
1364 | // If there's only one architecture (or this is an architecture-agnostic code), | |
1365 | // nothing happens quickly. | |
1366 | // | |
1367 | void SecStaticCode::handleOtherArchitectures(void (^handle)(SecStaticCode* other)) | |
1368 | { | |
1369 | if (Universal *fat = this->diskRep()->mainExecutableImage()) { | |
1370 | Universal::Architectures architectures; | |
1371 | fat->architectures(architectures); | |
1372 | if (architectures.size() > 1) { | |
1373 | DiskRep::Context ctx; | |
1374 | size_t activeOffset = fat->archOffset(); | |
1375 | for (Universal::Architectures::const_iterator arch = architectures.begin(); arch != architectures.end(); ++arch) { | |
1376 | ctx.offset = fat->archOffset(*arch); | |
1377 | if (ctx.offset != activeOffset) { // inactive architecture; check it | |
1378 | SecPointer<SecStaticCode> subcode = new SecStaticCode(DiskRep::bestGuess(this->mainExecutablePath(), &ctx)); | |
1379 | subcode->detachedSignature(this->mDetachedSig); // carry over explicit (but not implicit) detached signature | |
420ff9d9 A |
1380 | if (this->teamID() == NULL || subcode->teamID() == NULL) { |
1381 | if (this->teamID() != subcode->teamID()) | |
1382 | MacOSError::throwMe(errSecCSSignatureInvalid); | |
1383 | } else if (strcmp(this->teamID(), subcode->teamID()) != 0) | |
1384 | MacOSError::throwMe(errSecCSSignatureInvalid); | |
427c49bc A |
1385 | handle(subcode); |
1386 | } | |
b1ab9ed8 A |
1387 | } |
1388 | } | |
b1ab9ed8 A |
1389 | } |
1390 | } | |
1391 | ||
420ff9d9 A |
1392 | // |
1393 | // A method that takes a certificate chain (certs) and evaluates | |
1394 | // if it is a Mac or IPhone developer cert, an app store distribution cert, | |
1395 | // or a developer ID | |
1396 | // | |
1397 | bool SecStaticCode::isAppleDeveloperCert(CFArrayRef certs) | |
1398 | { | |
1399 | static const std::string appleDeveloperRequirement = "(" + std::string(WWDRRequirement) + ") or (" + developerID + ") or (" + distributionCertificate + ") or (" + iPhoneDistributionCert + ")"; | |
1400 | SecRequirement *req = new SecRequirement(parseRequirement(appleDeveloperRequirement), true); | |
1401 | Requirement::Context ctx(certs, NULL, NULL, "", NULL); | |
1402 | ||
1403 | return req->requirement()->validates(ctx); | |
1404 | } | |
b1ab9ed8 A |
1405 | |
1406 | } // end namespace CodeSigning | |
1407 | } // end namespace Security |