2 * Copyright (c) 2006-2014 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
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
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.
21 * @APPLE_LICENSE_HEADER_END@
23 #include "bundlediskrep.h"
24 #include "filediskrep.h"
25 #include "dirscanner.h"
26 #include "notarization.h"
27 #include <CoreFoundation/CFBundlePriv.h>
28 #include <CoreFoundation/CFURLAccess.h>
29 #include <CoreFoundation/CFBundlePriv.h>
30 #include <security_utilities/cfmunge.h>
36 namespace CodeSigning
{
38 using namespace UnixPlusPlus
;
44 static std::string
findDistFile(const std::string
&directory
);
48 // We make a CFBundleRef immediately, but everything else is lazy
50 BundleDiskRep::BundleDiskRep(const char *path
, const Context
*ctx
)
51 : mBundle(_CFBundleCreateUnique(NULL
, CFTempURL(path
))), forcePlatform(false)
54 MacOSError::throwMe(errSecCSBadBundleFormat
);
56 forcePlatform
= mExecRep
->appleInternalForcePlatform();
57 CODESIGN_DISKREP_CREATE_BUNDLE_PATH(this, (char*)path
, (void*)ctx
, mExecRep
);
60 BundleDiskRep::BundleDiskRep(CFBundleRef ref
, const Context
*ctx
)
62 mBundle
= ref
; // retains
64 forcePlatform
= mExecRep
->appleInternalForcePlatform();
65 CODESIGN_DISKREP_CREATE_BUNDLE_REF(this, ref
, (void*)ctx
, mExecRep
);
68 BundleDiskRep::~BundleDiskRep()
72 void BundleDiskRep::checkMoved(CFURLRef oldPath
, CFURLRef newPath
)
76 // The realpath call is important because alot of Framework bundles have a symlink
77 // to their "Current" version binary in the main bundle
78 if (realpath(cfString(oldPath
).c_str(), cOld
) == NULL
||
79 realpath(cfString(newPath
).c_str(), cNew
) == NULL
)
80 MacOSError::throwMe(errSecCSAmbiguousBundleFormat
);
82 if (strcmp(cOld
, cNew
) != 0)
83 recordStrictError(errSecCSAmbiguousBundleFormat
);
86 // common construction code
87 void BundleDiskRep::setup(const Context
*ctx
)
89 mComponentsFromExecValid
= false; // not yet known
90 mInstallerPackage
= false; // default
91 mAppLike
= false; // pessimism first
92 bool appDisqualified
= false; // found reason to disqualify as app
94 // capture the path of the main executable before descending into a specific version
95 CFRef
<CFURLRef
> mainExecBefore
= CFBundleCopyExecutableURL(mBundle
);
96 CFRef
<CFURLRef
> infoPlistBefore
= _CFBundleCopyInfoPlistURL(mBundle
);
98 // validate the bundle root; fish around for the desired framework version
99 string root
= cfStringRelease(copyCanonicalPath());
100 if (filehasExtendedAttribute(root
, XATTR_FINDERINFO_NAME
))
101 recordStrictError(errSecCSInvalidAssociatedFileData
);
102 string contents
= root
+ "/Contents";
103 string supportFiles
= root
+ "/Support Files";
104 string version
= root
+ "/Versions/"
105 + ((ctx
&& ctx
->version
) ? ctx
->version
: "Current")
107 if (::access(contents
.c_str(), F_OK
) == 0) { // not shallow
109 val
.require("^Contents$", DirValidator::directory
); // duh
110 val
.allow("^(\\.LSOverride|\\.DS_Store|Icon\r|\\.SoftwareDepot\\.tracking)$", DirValidator::file
| DirValidator::noexec
);
112 val
.validate(root
, errSecCSUnsealedAppRoot
);
113 } catch (const MacOSError
&err
) {
114 recordStrictError(err
.error
);
116 } else if (::access(supportFiles
.c_str(), F_OK
) == 0) { // ancient legacy boondoggle bundle
117 // treat like a shallow bundle; do not allow Versions arbitration
118 appDisqualified
= true;
119 } else if (::access(version
.c_str(), F_OK
) == 0) { // versioned bundle
120 if (CFBundleRef versionBundle
= _CFBundleCreateUnique(NULL
, CFTempURL(version
)))
121 mBundle
.take(versionBundle
); // replace top bundle ref
123 MacOSError::throwMe(errSecCSStaticCodeNotFound
);
124 appDisqualified
= true;
125 validateFrameworkRoot(root
);
127 if (ctx
&& ctx
->version
) // explicitly specified
128 MacOSError::throwMe(errSecCSStaticCodeNotFound
);
131 CFDictionaryRef infoDict
= CFBundleGetInfoDictionary(mBundle
);
132 assert(infoDict
); // CFBundle will always make one up for us
133 CFTypeRef mainHTML
= CFDictionaryGetValue(infoDict
, CFSTR("MainHTML"));
134 CFTypeRef packageVersion
= CFDictionaryGetValue(infoDict
, CFSTR("IFMajorVersion"));
136 // conventional executable bundle: CFBundle identifies an executable for us
137 if (CFRef
<CFURLRef
> mainExec
= CFBundleCopyExecutableURL(mBundle
)) // if CFBundle claims an executable...
138 if (mainHTML
== NULL
) { // ... and it's not a widget
140 // Note that this check is skipped if there is a specific framework version checked.
141 // That's because you know what you are doing if you are looking at a specific version.
142 // This check is designed to stop someone who did a verification on an app root, from mistakenly
143 // verifying a framework
144 if (!ctx
|| !ctx
->version
) {
146 checkMoved(mainExecBefore
, mainExec
);
148 if (CFRef
<CFURLRef
> infoDictPath
= _CFBundleCopyInfoPlistURL(mBundle
))
149 checkMoved(infoPlistBefore
, infoDictPath
);
152 mMainExecutableURL
= mainExec
;
153 mExecRep
= DiskRep::bestFileGuess(this->mainExecutablePath(), ctx
);
154 checkPlainFile(mExecRep
->fd(), this->mainExecutablePath());
155 CFDictionaryRef infoDict
= CFBundleGetInfoDictionary(mBundle
);
156 bool isAppBundle
= false;
158 if (CFTypeRef packageType
= CFDictionaryGetValue(infoDict
, CFSTR("CFBundlePackageType")))
159 if (CFEqual(packageType
, CFSTR("APPL")))
161 mFormat
= "bundle with " + mExecRep
->format();
163 mFormat
= "app " + mFormat
;
164 mAppLike
= isAppBundle
&& !appDisqualified
;
170 if (CFGetTypeID(mainHTML
) != CFStringGetTypeID())
171 MacOSError::throwMe(errSecCSBadBundleFormat
);
172 mMainExecutableURL
.take(makeCFURL(cfString(CFStringRef(mainHTML
)), false,
173 CFRef
<CFURLRef
>(CFBundleCopySupportFilesDirectoryURL(mBundle
))));
174 if (!mMainExecutableURL
)
175 MacOSError::throwMe(errSecCSBadBundleFormat
);
176 mExecRep
= new FileDiskRep(this->mainExecutablePath().c_str());
177 checkPlainFile(mExecRep
->fd(), this->mainExecutablePath());
178 mFormat
= "widget bundle";
183 // do we have a real Info.plist here?
184 if (CFRef
<CFURLRef
> infoURL
= _CFBundleCopyInfoPlistURL(mBundle
)) {
185 // focus on the Info.plist (which we know exists) as the nominal "main executable" file
186 mMainExecutableURL
= infoURL
;
187 mExecRep
= new FileDiskRep(this->mainExecutablePath().c_str());
188 checkPlainFile(mExecRep
->fd(), this->mainExecutablePath());
189 if (packageVersion
) {
190 mInstallerPackage
= true;
191 mFormat
= "installer package bundle";
198 // we're getting desperate here. Perhaps an oldish-style installer package? Look for a *.dist file
199 std::string distFile
= findDistFile(this->resourcesRootPath());
200 if (!distFile
.empty()) {
201 mMainExecutableURL
= makeCFURL(distFile
);
202 mExecRep
= new FileDiskRep(this->mainExecutablePath().c_str());
203 checkPlainFile(mExecRep
->fd(), this->mainExecutablePath());
204 mInstallerPackage
= true;
205 mFormat
= "installer package bundle";
209 // this bundle cannot be signed
210 MacOSError::throwMe(errSecCSBadBundleFormat
);
215 // Return the full path to the one-and-only file named something.dist in a directory.
216 // Return empty string if none; throw an exception if multiple. Do not descend into subdirectories.
218 static std::string
findDistFile(const std::string
&directory
)
221 char *paths
[] = {(char *)directory
.c_str(), NULL
};
222 FTS
*fts
= fts_open(paths
, FTS_PHYSICAL
| FTS_NOCHDIR
| FTS_NOSTAT
, NULL
);
224 while (FTSENT
*ent
= fts_read(fts
)) {
225 switch (ent
->fts_info
) {
228 if (!strcmp(ent
->fts_path
+ ent
->fts_pathlen
- 5, ".dist")) { // found plain file foo.dist
229 if (found
.empty()) // first found
230 found
= ent
->fts_path
;
231 else // multiple *.dist files (bad)
232 MacOSError::throwMe(errSecCSBadBundleFormat
);
237 fts_set(fts
, ent
, FTS_SKIP
); // don't descend
250 // Try to create the meta-file directory in our bundle.
251 // Does nothing if the directory already exists.
252 // Throws if an error occurs.
254 void BundleDiskRep::createMeta()
256 string meta
= metaPath(NULL
);
258 if (::mkdir(meta
.c_str(), 0755) == 0) {
259 copyfile(cfStringRelease(copyCanonicalPath()).c_str(), meta
.c_str(), NULL
, COPYFILE_SECURITY
);
262 } else if (errno
!= EEXIST
)
263 UnixError::throwMe();
269 // Create a path to a bundle signing resource, by name.
270 // This is in the BUNDLEDISKREP_DIRECTORY directory in the bundle's support directory.
272 string
BundleDiskRep::metaPath(const char *name
)
274 if (mMetaPath
.empty()) {
275 string support
= cfStringRelease(CFBundleCopySupportFilesDirectoryURL(mBundle
));
276 mMetaPath
= support
+ "/" BUNDLEDISKREP_DIRECTORY
;
277 mMetaExists
= ::access(mMetaPath
.c_str(), F_OK
) == 0;
280 return mMetaPath
+ "/" + name
;
285 CFDataRef
BundleDiskRep::metaData(const char *name
)
287 if (CFRef
<CFURLRef
> url
= makeCFURL(metaPath(name
))) {
288 return cfLoadFile(url
);
290 secnotice("bundlediskrep", "no metapath for %s", name
);
295 CFDataRef
BundleDiskRep::metaData(CodeDirectory::SpecialSlot slot
)
297 if (const char *name
= CodeDirectory::canonicalSlotName(slot
))
298 return metaData(name
);
306 // Load's a CFURL and makes sure that it is a regular file and not a symlink (or fifo, etc.)
308 CFDataRef
BundleDiskRep::loadRegularFile(CFURLRef url
)
312 CFDataRef data
= NULL
;
314 std::string
path(cfString(url
));
316 AutoFileDesc
fd(path
);
318 checkPlainFile(fd
, path
);
320 data
= cfLoadFile(fd
, fd
.fileSize());
323 secinfo("bundlediskrep", "failed to load %s", cfString(url
).c_str());
324 MacOSError::throwMe(errSecCSInvalidSymlink
);
331 // Load and return a component, by slot number.
332 // Info.plist components come from the bundle, always (we don't look
333 // for Mach-O embedded versions).
334 // ResourceDirectory always comes from bundle files.
335 // Everything else comes from the embedded blobs of a Mach-O image, or from
336 // files located in the Contents directory of the bundle; but we must be consistent
337 // (no half-and-half situations).
339 CFDataRef
BundleDiskRep::component(CodeDirectory::SpecialSlot slot
)
342 // the Info.plist comes from the magic CFBundle-indicated place and ONLY from there
344 if (CFRef
<CFURLRef
> info
= _CFBundleCopyInfoPlistURL(mBundle
))
345 return loadRegularFile(info
);
348 case cdResourceDirSlot
:
349 mUsedComponents
.insert(slot
);
350 return metaData(slot
);
351 // by default, we take components from the executable image or files (but not both)
353 if (CFRef
<CFDataRef
> data
= mExecRep
->component(slot
)) {
354 componentFromExec(true);
357 if (CFRef
<CFDataRef
> data
= metaData(slot
)) {
358 componentFromExec(false);
359 mUsedComponents
.insert(slot
);
367 // Check that all components of this BundleDiskRep come from either the main
368 // executable or the _CodeSignature directory (not mix-and-match).
369 void BundleDiskRep::componentFromExec(bool fromExec
)
371 if (!mComponentsFromExecValid
) {
372 // first use; set latch
373 mComponentsFromExecValid
= true;
374 mComponentsFromExec
= fromExec
;
375 } else if (mComponentsFromExec
!= fromExec
) {
376 // subsequent use: check latch
377 MacOSError::throwMe(errSecCSSignatureFailed
);
383 // The binary identifier is taken directly from the main executable.
385 CFDataRef
BundleDiskRep::identification()
387 return mExecRep
->identification();
392 // Various aspects of our DiskRep personality.
394 CFURLRef
BundleDiskRep::copyCanonicalPath()
396 if (CFURLRef url
= CFBundleCopyBundleURL(mBundle
))
401 string
BundleDiskRep::mainExecutablePath()
403 return cfString(mMainExecutableURL
);
406 string
BundleDiskRep::resourcesRootPath()
408 return cfStringRelease(CFBundleCopySupportFilesDirectoryURL(mBundle
));
411 void BundleDiskRep::adjustResources(ResourceBuilder
&builder
)
413 // exclude entire contents of meta directory
414 builder
.addExclusion("^" BUNDLEDISKREP_DIRECTORY
"$");
415 builder
.addExclusion("^" CODERESOURCES_LINK
"$"); // ancient-ish symlink into it
417 // exclude the store manifest directory
418 builder
.addExclusion("^" STORE_RECEIPT_DIRECTORY
"$");
420 // exclude the main executable file
421 string resources
= resourcesRootPath();
422 if (resources
.compare(resources
.size() - 2, 2, "/.") == 0) // chop trailing /.
423 resources
= resources
.substr(0, resources
.size()-2);
424 string executable
= mainExecutablePath();
425 if (!executable
.compare(0, resources
.length(), resources
, 0, resources
.length())
426 && executable
[resources
.length()] == '/') // is proper directory prefix
427 builder
.addExclusion(string("^")
428 + ResourceBuilder::escapeRE(executable
.substr(resources
.length()+1)) + "$", ResourceBuilder::softTarget
);
433 Universal
*BundleDiskRep::mainExecutableImage()
435 return mExecRep
->mainExecutableImage();
438 void BundleDiskRep::prepareForSigning(SigningContext
&context
)
440 return mExecRep
->prepareForSigning(context
);
443 size_t BundleDiskRep::signingBase()
445 return mExecRep
->signingBase();
448 size_t BundleDiskRep::signingLimit()
450 return mExecRep
->signingLimit();
453 size_t BundleDiskRep::execSegBase(const Architecture
*arch
)
455 return mExecRep
->execSegBase(arch
);
458 size_t BundleDiskRep::execSegLimit(const Architecture
*arch
)
460 return mExecRep
->execSegLimit(arch
);
463 string
BundleDiskRep::format()
468 CFArrayRef
BundleDiskRep::modifiedFiles()
470 CFRef
<CFArrayRef
> execFiles
= mExecRep
->modifiedFiles();
471 CFRef
<CFMutableArrayRef
> files
= CFArrayCreateMutableCopy(NULL
, 0, execFiles
);
472 checkModifiedFile(files
, cdCodeDirectorySlot
);
473 checkModifiedFile(files
, cdSignatureSlot
);
474 checkModifiedFile(files
, cdResourceDirSlot
);
475 checkModifiedFile(files
, cdTopDirectorySlot
);
476 checkModifiedFile(files
, cdEntitlementSlot
);
477 checkModifiedFile(files
, cdEntitlementDERSlot
);
478 checkModifiedFile(files
, cdRepSpecificSlot
);
479 for (CodeDirectory::Slot slot
= cdAlternateCodeDirectorySlots
; slot
< cdAlternateCodeDirectoryLimit
; ++slot
)
480 checkModifiedFile(files
, slot
);
481 return files
.yield();
484 void BundleDiskRep::checkModifiedFile(CFMutableArrayRef files
, CodeDirectory::SpecialSlot slot
)
486 if (CFDataRef data
= mExecRep
->component(slot
)) // provided by executable file
488 else if (const char *resourceName
= CodeDirectory::canonicalSlotName(slot
)) {
489 string file
= metaPath(resourceName
);
490 if (::access(file
.c_str(), F_OK
) == 0)
491 CFArrayAppendValue(files
, CFTempURL(file
));
495 FileDesc
&BundleDiskRep::fd()
497 return mExecRep
->fd();
500 void BundleDiskRep::flush()
505 CFDictionaryRef
BundleDiskRep::diskRepInformation()
507 return mExecRep
->diskRepInformation();
511 // Defaults for signing operations
513 string
BundleDiskRep::recommendedIdentifier(const SigningContext
&)
515 if (CFStringRef identifier
= CFBundleGetIdentifier(mBundle
))
516 return cfString(identifier
);
517 if (CFDictionaryRef infoDict
= CFBundleGetInfoDictionary(mBundle
))
518 if (CFStringRef identifier
= CFStringRef(CFDictionaryGetValue(infoDict
, kCFBundleNameKey
)))
519 return cfString(identifier
);
521 // fall back to using the canonical path
522 return canonicalIdentifier(cfStringRelease(this->copyCanonicalPath()));
525 string
BundleDiskRep::resourcesRelativePath()
527 // figure out the resource directory base. Clean up some gunk inserted by CFBundle in frameworks
528 string rbase
= this->resourcesRootPath();
529 size_t pos
= rbase
.find("/./"); // gratuitously inserted by CFBundle in some frameworks
530 while (pos
!= std::string::npos
) {
531 rbase
= rbase
.replace(pos
, 2, "", 0);
532 pos
= rbase
.find("/./");
534 if (rbase
.substr(rbase
.length()-2, 2) == "/.") // produced by versioned bundle implicit "Current" case
535 rbase
= rbase
.substr(0, rbase
.length()-2); // ... so take it off for this
537 // find the resources directory relative to the resource base
538 string resources
= cfStringRelease(CFBundleCopyResourcesDirectoryURL(mBundle
));
539 if (resources
== rbase
)
541 else if (resources
.compare(0, rbase
.length(), rbase
, 0, rbase
.length()) != 0) // Resources not in resource root
542 MacOSError::throwMe(errSecCSBadBundleFormat
);
544 resources
= resources
.substr(rbase
.length() + 1) + "/"; // differential path segment
549 CFDictionaryRef
BundleDiskRep::defaultResourceRules(const SigningContext
&ctx
)
551 string resources
= this->resourcesRelativePath();
553 // installer package rules
554 if (mInstallerPackage
)
555 return cfmake
<CFDictionaryRef
>("{rules={"
556 "'^.*' = #T" // include everything, but...
557 "%s = {optional=#T, weight=1000}" // make localizations optional
558 "'^.*/.*\\.pkg/' = {omit=#T, weight=10000}" // and exclude all nested packages (by name)
560 (string("^") + resources
+ ".*\\.lproj/").c_str()
563 // old (V1) executable bundle rules - compatible with before
564 if (ctx
.signingFlags() & kSecCSSignV1
) // *** must be exactly the same as before ***
565 return cfmake
<CFDictionaryRef
>("{rules={"
566 "'^version.plist$' = #T" // include version.plist
567 "%s = #T" // include Resources
568 "%s = {optional=#T, weight=1000}" // make localizations optional
569 "%s = {omit=#T, weight=1100}" // exclude all locversion.plist files
571 (string("^") + resources
).c_str(),
572 (string("^") + resources
+ ".*\\.lproj/").c_str(),
573 (string("^") + resources
+ ".*\\.lproj/locversion.plist$").c_str()
576 // FMJ (everything is a resource) rules
577 if (ctx
.signingFlags() & kSecCSSignOpaque
) // Full Metal Jacket - everything is a resource file
578 return cfmake
<CFDictionaryRef
>("{rules={"
579 "'^.*' = #T" // everything is a resource
580 "'^Info\\.plist$' = {omit=#T,weight=10}" // explicitly exclude this for backward compatibility
583 // new (V2) executable bundle rules
584 if (!resources
.empty()) {
585 return cfmake
<CFDictionaryRef
>("{" // *** the new (V2) world ***
586 "rules={" // old (V1; legacy) version
587 "'^version.plist$' = #T" // include version.plist
588 "%s = #T" // include Resources
589 "%s = {optional=#T, weight=1000}" // make localizations optional
590 "%s = {weight=1010}" // ... except for Base.lproj which really isn't optional at all
591 "%s = {omit=#T, weight=1100}" // exclude all locversion.plist files
593 "'^.*' = #T" // include everything as a resource, with the following exceptions
594 "'^[^/]+$' = {nested=#T, weight=10}" // files directly in Contents
595 "'^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/' = {nested=#T, weight=10}" // dynamic repositories
596 "'.*\\.dSYM($|/)' = {weight=11}" // but allow dSYM directories in code locations (parallel to their code)
597 "'^(.*/)?\\.DS_Store$' = {omit=#T,weight=2000}" // ignore .DS_Store files
598 "'^Info\\.plist$' = {omit=#T, weight=20}" // excluded automatically now, but old systems need to be told
599 "'^version\\.plist$' = {weight=20}" // include version.plist as resource
600 "'^embedded\\.provisionprofile$' = {weight=20}" // include embedded.provisionprofile as resource
601 "'^PkgInfo$' = {omit=#T, weight=20}" // traditionally not included
602 "%s = {weight=20}" // Resources override default nested (widgets)
603 "%s = {optional=#T, weight=1000}" // make localizations optional
604 "%s = {weight=1010}" // ... except for Base.lproj which really isn't optional at all
605 "%s = {omit=#T, weight=1100}" // exclude all locversion.plist files
608 (string("^") + resources
).c_str(),
609 (string("^") + resources
+ ".*\\.lproj/").c_str(),
610 (string("^") + resources
+ "Base\\.lproj/").c_str(),
611 (string("^") + resources
+ ".*\\.lproj/locversion.plist$").c_str(),
613 (string("^") + resources
).c_str(),
614 (string("^") + resources
+ ".*\\.lproj/").c_str(),
615 (string("^") + resources
+ "Base\\.lproj/").c_str(),
616 (string("^") + resources
+ ".*\\.lproj/locversion.plist$").c_str()
619 /* This is a bundle format without a Resources directory, which means we need to omit
620 * Resources-directory specific rules that would create conflicts. */
622 /* We also declare that flat bundles do not use any nested code rules.
623 * Embedded, where flat bundles are used, currently does not support them,
624 * and we have no plans for allowing the replacement of nested code there.
625 * Should anyone actually intend to use nested code rules in a flat
626 * bundle, they are free to create their own rules. */
628 return cfmake
<CFDictionaryRef
>("{" // *** the new (V2) world ***
629 "rules={" // old (V1; legacy) version
630 "'^version.plist$' = #T" // include version.plist
631 "'^.*' = #T" // include Resources
632 "'^.*\\.lproj/' = {optional=#T, weight=1000}" // make localizations optional
633 "'^Base\\.lproj/' = {weight=1010}" // ... except for Base.lproj which really isn't optional at all
634 "'^.*\\.lproj/locversion.plist$' = {omit=#T, weight=1100}" // exclude all locversion.plist files
636 "'^.*' = #T" // include everything as a resource, with the following exceptions
637 "'.*\\.dSYM($|/)' = {weight=11}" // but allow dSYM directories in code locations (parallel to their code)
638 "'^(.*/)?\\.DS_Store$' = {omit=#T,weight=2000}" // ignore .DS_Store files
639 "'^Info\\.plist$' = {omit=#T, weight=20}" // excluded automatically now, but old systems need to be told
640 "'^version\\.plist$' = {weight=20}" // include version.plist as resource
641 "'^embedded\\.provisionprofile$' = {weight=20}" // include embedded.provisionprofile as resource
642 "'^PkgInfo$' = {omit=#T, weight=20}" // traditionally not included
643 "'^.*\\.lproj/' = {optional=#T, weight=1000}" // make localizations optional
644 "'^Base\\.lproj/' = {weight=1010}" // ... except for Base.lproj which really isn't optional at all
645 "'^.*\\.lproj/locversion.plist$' = {omit=#T, weight=1100}" // exclude all locversion.plist files
652 CFArrayRef
BundleDiskRep::allowedResourceOmissions()
654 return cfmake
<CFArrayRef
>("["
655 "'^(.*/)?\\.DS_Store$'"
660 (string("^") + this->resourcesRelativePath() + ".*\\.lproj/locversion.plist$").c_str()
665 const Requirements
*BundleDiskRep::defaultRequirements(const Architecture
*arch
, const SigningContext
&ctx
)
667 return mExecRep
->defaultRequirements(arch
, ctx
);
670 size_t BundleDiskRep::pageSize(const SigningContext
&ctx
)
672 return mExecRep
->pageSize(ctx
);
677 // Strict validation.
678 // Takes an array of CFNumbers of errors to tolerate.
680 void BundleDiskRep::strictValidate(const CodeDirectory
* cd
, const ToleratedErrors
& tolerated
, SecCSFlags flags
)
682 // scan our metadirectory (_CodeSignature) for unwanted guests
683 if (!(flags
& kSecCSQuickCheck
))
684 validateMetaDirectory(cd
);
686 // check accumulated strict errors and report them
687 if (!(flags
& kSecCSRestrictSidebandData
)) // tolerate resource forks etc.
688 mStrictErrors
.erase(errSecCSInvalidAssociatedFileData
);
690 std::vector
<OSStatus
> fatalErrors
;
691 set_difference(mStrictErrors
.begin(), mStrictErrors
.end(), tolerated
.begin(), tolerated
.end(), back_inserter(fatalErrors
));
692 if (!fatalErrors
.empty())
693 MacOSError::throwMe(fatalErrors
[0]);
695 // if app focus is requested and this doesn't look like an app, fail - but allow whitelist overrides
696 if (flags
& kSecCSRestrictToAppLike
)
698 if (tolerated
.find(kSecCSRestrictToAppLike
) == tolerated
.end())
699 MacOSError::throwMe(errSecCSNotAppLike
);
701 // now strict-check the main executable (which won't be an app-like object)
702 mExecRep
->strictValidate(cd
, tolerated
, flags
& ~kSecCSRestrictToAppLike
);
705 void BundleDiskRep::recordStrictError(OSStatus error
)
707 mStrictErrors
.insert(error
);
711 void BundleDiskRep::validateMetaDirectory(const CodeDirectory
* cd
)
713 // we know the resource directory will be checked after this call, so we'll give it a pass here
714 if (cd
->slotIsPresent(-cdResourceDirSlot
))
715 mUsedComponents
.insert(cdResourceDirSlot
);
717 // make a set of allowed (regular) filenames in this directory
718 std::set
<std::string
> allowedFiles
;
719 for (auto it
= mUsedComponents
.begin(); it
!= mUsedComponents
.end(); ++it
) {
722 break; // always from Info.plist, not from here
724 if (const char *name
= CodeDirectory::canonicalSlotName(*it
)) {
725 allowedFiles
.insert(name
);
730 DirScanner
scan(mMetaPath
);
731 if (scan
.initialized()) {
732 while (struct dirent
* ent
= scan
.getNext()) {
733 if (!scan
.isRegularFile(ent
))
734 MacOSError::throwMe(errSecCSUnsealedAppRoot
); // only regular files allowed
735 if (allowedFiles
.find(ent
->d_name
) == allowedFiles
.end()) { // not in expected set of files
736 if (strcmp(ent
->d_name
, kSecCS_SIGNATUREFILE
) == 0) {
737 // special case - might be empty and unused (adhoc signature)
738 AutoFileDesc
fd(metaPath(kSecCS_SIGNATUREFILE
));
739 if (fd
.fileSize() == 0)
740 continue; // that's okay, then
742 // not on list of needed files; it's a freeloading rogue!
743 recordStrictError(errSecCSUnsealedAppRoot
); // funnel through strict set so GKOpaque can override it
751 // Check framework root for unsafe symlinks and unsealed content.
753 void BundleDiskRep::validateFrameworkRoot(string root
)
755 // build regex element that matches either the "Current" symlink, or the name of the current version
756 string current
= "Current";
757 char currentVersion
[PATH_MAX
];
758 ssize_t len
= ::readlink((root
+ "/Versions/Current").c_str(), currentVersion
, sizeof(currentVersion
)-1);
760 currentVersion
[len
] = '\0';
761 current
= string("(Current|") + ResourceBuilder::escapeRE(currentVersion
) + ")";
765 val
.require("^Versions$", DirValidator::directory
| DirValidator::descend
); // descend into Versions directory
766 val
.require("^Versions/[^/]+$", DirValidator::directory
); // require at least one version
767 val
.require("^Versions/Current$", DirValidator::symlink
, // require Current symlink...
768 "^(\\./)?(\\.\\.[^/]+|\\.?[^\\./][^/]*)$"); // ...must point to a version
769 val
.allow("^(Versions/)?\\.DS_Store$", DirValidator::file
| DirValidator::noexec
); // allow .DS_Store files
770 val
.allow("^[^/]+$", DirValidator::symlink
, ^ string (const string
&name
, const string
&target
) {
771 // top-level symlinks must point to namesake in current version
772 return string("^(\\./)?Versions/") + current
+ "/" + ResourceBuilder::escapeRE(name
) + "$";
774 // module.map must be regular non-executable file, or symlink to module.map in current version
775 val
.allow("^module\\.map$", DirValidator::file
| DirValidator::noexec
| DirValidator::symlink
,
776 string("^(\\./)?Versions/") + current
+ "/module\\.map$");
779 val
.validate(root
, errSecCSUnsealedFrameworkRoot
);
780 } catch (const MacOSError
&err
) {
781 recordStrictError(err
.error
);
787 // Check a file descriptor for harmlessness. This is a strict check (only).
789 void BundleDiskRep::checkPlainFile(FileDesc fd
, const std::string
& path
)
791 if (!fd
.isPlainFile(path
))
792 recordStrictError(errSecCSRegularFile
);
796 void BundleDiskRep::checkForks(FileDesc fd
)
798 if (fd
.hasExtendedAttribute(XATTR_RESOURCEFORK_NAME
) || fd
.hasExtendedAttribute(XATTR_FINDERINFO_NAME
))
799 recordStrictError(errSecCSInvalidAssociatedFileData
);
806 DiskRep::Writer
*BundleDiskRep::writer()
808 return new Writer(this);
811 BundleDiskRep::Writer::Writer(BundleDiskRep
*r
)
812 : rep(r
), mMadeMetaDirectory(false)
814 execWriter
= rep
->mExecRep
->writer();
819 // Write a component.
820 // Note that this isn't concerned with Mach-O writing; this is handled at
821 // a much higher level. If we're called, we write to a file in the Bundle's meta directory.
823 void BundleDiskRep::Writer::component(CodeDirectory::SpecialSlot slot
, CFDataRef data
)
827 if (!execWriter
->attribute(writerLastResort
)) // willing to take the data...
828 return execWriter
->component(slot
, data
); // ... so hand it through
829 // execWriter doesn't want the data; store it as a resource file (below)
830 case cdResourceDirSlot
:
831 // the resource directory always goes into a bundle file
832 if (const char *name
= CodeDirectory::canonicalSlotName(slot
)) {
834 string path
= rep
->metaPath(name
);
837 // determine AFSC status if we are told to preserve compression
838 bool conductCompression
= false;
840 if (this->getPreserveAFSC()) {
841 struct stat statBuffer
;
842 if (stat(path
.c_str(), &statBuffer
) == 0) {
843 if (queryCompressionInfo(path
.c_str(), &cInfo
) == 0) {
844 if (cInfo
.compressionType
!= 0 && cInfo
.compressedSize
> 0) {
845 conductCompression
= true;
852 AutoFileDesc
fd(path
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0644);
853 fd
.writeAll(CFDataGetBytePtr(data
), CFDataGetLength(data
));
857 // if the original file was compressed, compress the new file after move
858 if (conductCompression
) {
859 CFMutableDictionaryRef options
= CFDictionaryCreateMutable(NULL
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
860 CFStringRef val
= CFStringCreateWithFormat(kCFAllocatorDefault
, NULL
, CFSTR("%d"), cInfo
.compressionType
);
861 CFDictionarySetValue(options
, kAFSCCompressionTypes
, val
);
864 CompressionQueueContext compressionQueue
= CreateCompressionQueue(NULL
, NULL
, NULL
, NULL
, options
);
866 if (!CompressFile(compressionQueue
, path
.c_str(), NULL
)) {
867 secinfo("bundlediskrep", "%p Failed to queue compression of file %s", this, path
.c_str());
868 MacOSError::throwMe(errSecCSInternalError
);
871 FinishCompressionAndCleanUp(compressionQueue
);
872 compressionQueue
= NULL
;
877 mWrittenFiles
.insert(name
);
879 MacOSError::throwMe(errSecCSBadBundleFormat
);
885 // Remove all signature data
887 void BundleDiskRep::Writer::remove()
889 // remove signature from the executable
890 execWriter
->remove();
892 // remove signature files from bundle
893 for (CodeDirectory::SpecialSlot slot
= 0; slot
< cdSlotCount
; slot
++)
895 remove(cdSignatureSlot
);
898 void BundleDiskRep::Writer::remove(CodeDirectory::SpecialSlot slot
)
900 if (const char *name
= CodeDirectory::canonicalSlotName(slot
))
901 if (::unlink(rep
->metaPath(name
).c_str()))
903 case ENOENT
: // not found - that's okay
906 UnixError::throwMe();
911 void BundleDiskRep::Writer::flush()
914 purgeMetaDirectory();
917 // purge _CodeSignature of all left-over files from any previous signature
918 void BundleDiskRep::Writer::purgeMetaDirectory()
920 DirScanner
scan(rep
->mMetaPath
);
921 if (scan
.initialized()) {
922 while (struct dirent
* ent
= scan
.getNext()) {
923 if (!scan
.isRegularFile(ent
))
924 MacOSError::throwMe(errSecCSUnsealedAppRoot
); // only regular files allowed
925 if (mWrittenFiles
.find(ent
->d_name
) == mWrittenFiles
.end()) { // we didn't write this!
933 void BundleDiskRep::registerStapledTicket()
935 string root
= cfStringRelease(copyCanonicalPath());
936 registerStapledTicketInBundle(root
);
939 } // end namespace CodeSigning
940 } // end namespace Security