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