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 <CoreFoundation/CFBundlePriv.h>
27 #include <CoreFoundation/CFURLAccess.h>
28 #include <CoreFoundation/CFBundlePriv.h>
29 #include <security_utilities/cfmunge.h>
35 namespace CodeSigning
{
37 using namespace UnixPlusPlus
;
43 static std::string
findDistFile(const std::string
&directory
);
47 // We make a CFBundleRef immediately, but everything else is lazy
49 BundleDiskRep::BundleDiskRep(const char *path
, const Context
*ctx
)
50 : mBundle(_CFBundleCreateUnique(NULL
, CFTempURL(path
)))
53 MacOSError::throwMe(errSecCSBadBundleFormat
);
55 CODESIGN_DISKREP_CREATE_BUNDLE_PATH(this, (char*)path
, (void*)ctx
, mExecRep
);
58 BundleDiskRep::BundleDiskRep(CFBundleRef ref
, const Context
*ctx
)
60 mBundle
= ref
; // retains
62 CODESIGN_DISKREP_CREATE_BUNDLE_REF(this, ref
, (void*)ctx
, mExecRep
);
65 BundleDiskRep::~BundleDiskRep()
69 void BundleDiskRep::checkMoved(CFURLRef oldPath
, CFURLRef newPath
)
73 // The realpath call is important because alot of Framework bundles have a symlink
74 // to their "Current" version binary in the main bundle
75 if (realpath(cfString(oldPath
).c_str(), cOld
) == NULL
||
76 realpath(cfString(newPath
).c_str(), cNew
) == NULL
)
77 MacOSError::throwMe(errSecCSAmbiguousBundleFormat
);
79 if (strcmp(cOld
, cNew
) != 0)
80 recordStrictError(errSecCSAmbiguousBundleFormat
);
83 // common construction code
84 void BundleDiskRep::setup(const Context
*ctx
)
86 mComponentsFromExecValid
= false; // not yet known
87 mInstallerPackage
= false; // default
88 mAppLike
= false; // pessimism first
89 bool appDisqualified
= false; // found reason to disqualify as app
91 // capture the path of the main executable before descending into a specific version
92 CFRef
<CFURLRef
> mainExecBefore
= CFBundleCopyExecutableURL(mBundle
);
93 CFRef
<CFURLRef
> infoPlistBefore
= _CFBundleCopyInfoPlistURL(mBundle
);
95 // validate the bundle root; fish around for the desired framework version
96 string root
= cfStringRelease(copyCanonicalPath());
97 if (filehasExtendedAttribute(root
, XATTR_FINDERINFO_NAME
))
98 recordStrictError(errSecCSInvalidAssociatedFileData
);
99 string contents
= root
+ "/Contents";
100 string supportFiles
= root
+ "/Support Files";
101 string version
= root
+ "/Versions/"
102 + ((ctx
&& ctx
->version
) ? ctx
->version
: "Current")
104 if (::access(contents
.c_str(), F_OK
) == 0) { // not shallow
106 val
.require("^Contents$", DirValidator::directory
); // duh
107 val
.allow("^(\\.LSOverride|\\.DS_Store|Icon\r|\\.SoftwareDepot\\.tracking)$", DirValidator::file
| DirValidator::noexec
);
109 val
.validate(root
, errSecCSUnsealedAppRoot
);
110 } catch (const MacOSError
&err
) {
111 recordStrictError(err
.error
);
113 } else if (::access(supportFiles
.c_str(), F_OK
) == 0) { // ancient legacy boondoggle bundle
114 // treat like a shallow bundle; do not allow Versions arbitration
115 appDisqualified
= true;
116 } else if (::access(version
.c_str(), F_OK
) == 0) { // versioned bundle
117 if (CFBundleRef versionBundle
= _CFBundleCreateUnique(NULL
, CFTempURL(version
)))
118 mBundle
.take(versionBundle
); // replace top bundle ref
120 MacOSError::throwMe(errSecCSStaticCodeNotFound
);
121 appDisqualified
= true;
122 validateFrameworkRoot(root
);
124 if (ctx
&& ctx
->version
) // explicitly specified
125 MacOSError::throwMe(errSecCSStaticCodeNotFound
);
128 CFDictionaryRef infoDict
= CFBundleGetInfoDictionary(mBundle
);
129 assert(infoDict
); // CFBundle will always make one up for us
130 CFTypeRef mainHTML
= CFDictionaryGetValue(infoDict
, CFSTR("MainHTML"));
131 CFTypeRef packageVersion
= CFDictionaryGetValue(infoDict
, CFSTR("IFMajorVersion"));
133 // conventional executable bundle: CFBundle identifies an executable for us
134 if (CFRef
<CFURLRef
> mainExec
= CFBundleCopyExecutableURL(mBundle
)) // if CFBundle claims an executable...
135 if (mainHTML
== NULL
) { // ... and it's not a widget
137 // Note that this check is skipped if there is a specific framework version checked.
138 // That's because you know what you are doing if you are looking at a specific version.
139 // This check is designed to stop someone who did a verification on an app root, from mistakenly
140 // verifying a framework
141 if (!ctx
|| !ctx
->version
) {
143 checkMoved(mainExecBefore
, mainExec
);
145 if (CFRef
<CFURLRef
> infoDictPath
= _CFBundleCopyInfoPlistURL(mBundle
))
146 checkMoved(infoPlistBefore
, infoDictPath
);
149 mMainExecutableURL
= mainExec
;
150 mExecRep
= DiskRep::bestFileGuess(this->mainExecutablePath(), ctx
);
151 checkPlainFile(mExecRep
->fd(), this->mainExecutablePath());
152 CFDictionaryRef infoDict
= CFBundleGetInfoDictionary(mBundle
);
153 bool isAppBundle
= false;
155 if (CFTypeRef packageType
= CFDictionaryGetValue(infoDict
, CFSTR("CFBundlePackageType")))
156 if (CFEqual(packageType
, CFSTR("APPL")))
158 mFormat
= "bundle with " + mExecRep
->format();
160 mFormat
= "app " + mFormat
;
161 mAppLike
= isAppBundle
&& !appDisqualified
;
167 if (CFGetTypeID(mainHTML
) != CFStringGetTypeID())
168 MacOSError::throwMe(errSecCSBadBundleFormat
);
169 mMainExecutableURL
.take(makeCFURL(cfString(CFStringRef(mainHTML
)), false,
170 CFRef
<CFURLRef
>(CFBundleCopySupportFilesDirectoryURL(mBundle
))));
171 if (!mMainExecutableURL
)
172 MacOSError::throwMe(errSecCSBadBundleFormat
);
173 mExecRep
= new FileDiskRep(this->mainExecutablePath().c_str());
174 checkPlainFile(mExecRep
->fd(), this->mainExecutablePath());
175 mFormat
= "widget bundle";
180 // do we have a real Info.plist here?
181 if (CFRef
<CFURLRef
> infoURL
= _CFBundleCopyInfoPlistURL(mBundle
)) {
182 // focus on the Info.plist (which we know exists) as the nominal "main executable" file
183 mMainExecutableURL
= infoURL
;
184 mExecRep
= new FileDiskRep(this->mainExecutablePath().c_str());
185 checkPlainFile(mExecRep
->fd(), this->mainExecutablePath());
186 if (packageVersion
) {
187 mInstallerPackage
= true;
188 mFormat
= "installer package bundle";
195 // we're getting desperate here. Perhaps an oldish-style installer package? Look for a *.dist file
196 std::string distFile
= findDistFile(this->resourcesRootPath());
197 if (!distFile
.empty()) {
198 mMainExecutableURL
= makeCFURL(distFile
);
199 mExecRep
= new FileDiskRep(this->mainExecutablePath().c_str());
200 checkPlainFile(mExecRep
->fd(), this->mainExecutablePath());
201 mInstallerPackage
= true;
202 mFormat
= "installer package bundle";
206 // this bundle cannot be signed
207 MacOSError::throwMe(errSecCSBadBundleFormat
);
212 // Return the full path to the one-and-only file named something.dist in a directory.
213 // Return empty string if none; throw an exception if multiple. Do not descend into subdirectories.
215 static std::string
findDistFile(const std::string
&directory
)
218 char *paths
[] = {(char *)directory
.c_str(), NULL
};
219 FTS
*fts
= fts_open(paths
, FTS_PHYSICAL
| FTS_NOCHDIR
| FTS_NOSTAT
, NULL
);
221 while (FTSENT
*ent
= fts_read(fts
)) {
222 switch (ent
->fts_info
) {
225 if (!strcmp(ent
->fts_path
+ ent
->fts_pathlen
- 5, ".dist")) { // found plain file foo.dist
226 if (found
.empty()) // first found
227 found
= ent
->fts_path
;
228 else // multiple *.dist files (bad)
229 MacOSError::throwMe(errSecCSBadBundleFormat
);
234 fts_set(fts
, ent
, FTS_SKIP
); // don't descend
247 // Try to create the meta-file directory in our bundle.
248 // Does nothing if the directory already exists.
249 // Throws if an error occurs.
251 void BundleDiskRep::createMeta()
253 string meta
= metaPath(NULL
);
255 if (::mkdir(meta
.c_str(), 0755) == 0) {
256 copyfile(cfStringRelease(copyCanonicalPath()).c_str(), meta
.c_str(), NULL
, COPYFILE_SECURITY
);
259 } else if (errno
!= EEXIST
)
260 UnixError::throwMe();
266 // Create a path to a bundle signing resource, by name.
267 // This is in the BUNDLEDISKREP_DIRECTORY directory in the bundle's support directory.
269 string
BundleDiskRep::metaPath(const char *name
)
271 if (mMetaPath
.empty()) {
272 string support
= cfStringRelease(CFBundleCopySupportFilesDirectoryURL(mBundle
));
273 mMetaPath
= support
+ "/" BUNDLEDISKREP_DIRECTORY
;
274 mMetaExists
= ::access(mMetaPath
.c_str(), F_OK
) == 0;
277 return mMetaPath
+ "/" + name
;
282 CFDataRef
BundleDiskRep::metaData(const char *name
)
284 if (CFRef
<CFURLRef
> url
= makeCFURL(metaPath(name
))) {
285 return cfLoadFile(url
);
287 secnotice("bundlediskrep", "no metapath for %s", name
);
292 CFDataRef
BundleDiskRep::metaData(CodeDirectory::SpecialSlot slot
)
294 if (const char *name
= CodeDirectory::canonicalSlotName(slot
))
295 return metaData(name
);
303 // Load's a CFURL and makes sure that it is a regular file and not a symlink (or fifo, etc.)
305 CFDataRef
BundleDiskRep::loadRegularFile(CFURLRef url
)
309 CFDataRef data
= NULL
;
311 std::string
path(cfString(url
));
313 AutoFileDesc
fd(path
);
315 checkPlainFile(fd
, path
);
317 data
= cfLoadFile(fd
, fd
.fileSize());
320 secinfo("bundlediskrep", "failed to load %s", cfString(url
).c_str());
321 MacOSError::throwMe(errSecCSInvalidSymlink
);
328 // Load and return a component, by slot number.
329 // Info.plist components come from the bundle, always (we don't look
330 // for Mach-O embedded versions).
331 // ResourceDirectory always comes from bundle files.
332 // Everything else comes from the embedded blobs of a Mach-O image, or from
333 // files located in the Contents directory of the bundle; but we must be consistent
334 // (no half-and-half situations).
336 CFDataRef
BundleDiskRep::component(CodeDirectory::SpecialSlot slot
)
339 // the Info.plist comes from the magic CFBundle-indicated place and ONLY from there
341 if (CFRef
<CFURLRef
> info
= _CFBundleCopyInfoPlistURL(mBundle
))
342 return loadRegularFile(info
);
345 case cdResourceDirSlot
:
346 mUsedComponents
.insert(slot
);
347 return metaData(slot
);
348 // by default, we take components from the executable image or files (but not both)
350 if (CFRef
<CFDataRef
> data
= mExecRep
->component(slot
)) {
351 componentFromExec(true);
354 if (CFRef
<CFDataRef
> data
= metaData(slot
)) {
355 componentFromExec(false);
356 mUsedComponents
.insert(slot
);
364 // Check that all components of this BundleDiskRep come from either the main
365 // executable or the _CodeSignature directory (not mix-and-match).
366 void BundleDiskRep::componentFromExec(bool fromExec
)
368 if (!mComponentsFromExecValid
) {
369 // first use; set latch
370 mComponentsFromExecValid
= true;
371 mComponentsFromExec
= fromExec
;
372 } else if (mComponentsFromExec
!= fromExec
) {
373 // subsequent use: check latch
374 MacOSError::throwMe(errSecCSSignatureFailed
);
380 // The binary identifier is taken directly from the main executable.
382 CFDataRef
BundleDiskRep::identification()
384 return mExecRep
->identification();
389 // Various aspects of our DiskRep personality.
391 CFURLRef
BundleDiskRep::copyCanonicalPath()
393 if (CFURLRef url
= CFBundleCopyBundleURL(mBundle
))
398 string
BundleDiskRep::mainExecutablePath()
400 return cfString(mMainExecutableURL
);
403 string
BundleDiskRep::resourcesRootPath()
405 return cfStringRelease(CFBundleCopySupportFilesDirectoryURL(mBundle
));
408 void BundleDiskRep::adjustResources(ResourceBuilder
&builder
)
410 // exclude entire contents of meta directory
411 builder
.addExclusion("^" BUNDLEDISKREP_DIRECTORY
"$");
412 builder
.addExclusion("^" CODERESOURCES_LINK
"$"); // ancient-ish symlink into it
414 // exclude the store manifest directory
415 builder
.addExclusion("^" STORE_RECEIPT_DIRECTORY
"$");
417 // exclude the main executable file
418 string resources
= resourcesRootPath();
419 if (resources
.compare(resources
.size() - 2, 2, "/.") == 0) // chop trailing /.
420 resources
= resources
.substr(0, resources
.size()-2);
421 string executable
= mainExecutablePath();
422 if (!executable
.compare(0, resources
.length(), resources
, 0, resources
.length())
423 && executable
[resources
.length()] == '/') // is proper directory prefix
424 builder
.addExclusion(string("^")
425 + ResourceBuilder::escapeRE(executable
.substr(resources
.length()+1)) + "$", ResourceBuilder::softTarget
);
430 Universal
*BundleDiskRep::mainExecutableImage()
432 return mExecRep
->mainExecutableImage();
435 void BundleDiskRep::prepareForSigning(SigningContext
&context
)
437 return mExecRep
->prepareForSigning(context
);
440 size_t BundleDiskRep::signingBase()
442 return mExecRep
->signingBase();
445 size_t BundleDiskRep::signingLimit()
447 return mExecRep
->signingLimit();
450 size_t BundleDiskRep::execSegBase(const Architecture
*arch
)
452 return mExecRep
->execSegBase(arch
);
455 size_t BundleDiskRep::execSegLimit(const Architecture
*arch
)
457 return mExecRep
->execSegLimit(arch
);
460 string
BundleDiskRep::format()
465 CFArrayRef
BundleDiskRep::modifiedFiles()
467 CFRef
<CFArrayRef
> execFiles
= mExecRep
->modifiedFiles();
468 CFRef
<CFMutableArrayRef
> files
= CFArrayCreateMutableCopy(NULL
, 0, execFiles
);
469 checkModifiedFile(files
, cdCodeDirectorySlot
);
470 checkModifiedFile(files
, cdSignatureSlot
);
471 checkModifiedFile(files
, cdResourceDirSlot
);
472 checkModifiedFile(files
, cdTopDirectorySlot
);
473 checkModifiedFile(files
, cdEntitlementSlot
);
474 checkModifiedFile(files
, cdEntitlementDERSlot
);
475 checkModifiedFile(files
, cdRepSpecificSlot
);
476 for (CodeDirectory::Slot slot
= cdAlternateCodeDirectorySlots
; slot
< cdAlternateCodeDirectoryLimit
; ++slot
)
477 checkModifiedFile(files
, slot
);
478 return files
.yield();
481 void BundleDiskRep::checkModifiedFile(CFMutableArrayRef files
, CodeDirectory::SpecialSlot slot
)
483 if (CFDataRef data
= mExecRep
->component(slot
)) // provided by executable file
485 else if (const char *resourceName
= CodeDirectory::canonicalSlotName(slot
)) {
486 string file
= metaPath(resourceName
);
487 if (::access(file
.c_str(), F_OK
) == 0)
488 CFArrayAppendValue(files
, CFTempURL(file
));
492 FileDesc
&BundleDiskRep::fd()
494 return mExecRep
->fd();
497 void BundleDiskRep::flush()
502 CFDictionaryRef
BundleDiskRep::diskRepInformation()
504 return mExecRep
->diskRepInformation();
508 // Defaults for signing operations
510 string
BundleDiskRep::recommendedIdentifier(const SigningContext
&)
512 if (CFStringRef identifier
= CFBundleGetIdentifier(mBundle
))
513 return cfString(identifier
);
514 if (CFDictionaryRef infoDict
= CFBundleGetInfoDictionary(mBundle
))
515 if (CFStringRef identifier
= CFStringRef(CFDictionaryGetValue(infoDict
, kCFBundleNameKey
)))
516 return cfString(identifier
);
518 // fall back to using the canonical path
519 return canonicalIdentifier(cfStringRelease(this->copyCanonicalPath()));
522 string
BundleDiskRep::resourcesRelativePath()
524 // figure out the resource directory base. Clean up some gunk inserted by CFBundle in frameworks
525 string rbase
= this->resourcesRootPath();
526 size_t pos
= rbase
.find("/./"); // gratuitously inserted by CFBundle in some frameworks
527 while (pos
!= std::string::npos
) {
528 rbase
= rbase
.replace(pos
, 2, "", 0);
529 pos
= rbase
.find("/./");
531 if (rbase
.substr(rbase
.length()-2, 2) == "/.") // produced by versioned bundle implicit "Current" case
532 rbase
= rbase
.substr(0, rbase
.length()-2); // ... so take it off for this
534 // find the resources directory relative to the resource base
535 string resources
= cfStringRelease(CFBundleCopyResourcesDirectoryURL(mBundle
));
536 if (resources
== rbase
)
538 else if (resources
.compare(0, rbase
.length(), rbase
, 0, rbase
.length()) != 0) // Resources not in resource root
539 MacOSError::throwMe(errSecCSBadBundleFormat
);
541 resources
= resources
.substr(rbase
.length() + 1) + "/"; // differential path segment
546 CFDictionaryRef
BundleDiskRep::defaultResourceRules(const SigningContext
&ctx
)
548 string resources
= this->resourcesRelativePath();
550 // installer package rules
551 if (mInstallerPackage
)
552 return cfmake
<CFDictionaryRef
>("{rules={"
553 "'^.*' = #T" // include everything, but...
554 "%s = {optional=#T, weight=1000}" // make localizations optional
555 "'^.*/.*\\.pkg/' = {omit=#T, weight=10000}" // and exclude all nested packages (by name)
557 (string("^") + resources
+ ".*\\.lproj/").c_str()
560 // old (V1) executable bundle rules - compatible with before
561 if (ctx
.signingFlags() & kSecCSSignV1
) // *** must be exactly the same as before ***
562 return cfmake
<CFDictionaryRef
>("{rules={"
563 "'^version.plist$' = #T" // include version.plist
564 "%s = #T" // include Resources
565 "%s = {optional=#T, weight=1000}" // make localizations optional
566 "%s = {omit=#T, weight=1100}" // exclude all locversion.plist files
568 (string("^") + resources
).c_str(),
569 (string("^") + resources
+ ".*\\.lproj/").c_str(),
570 (string("^") + resources
+ ".*\\.lproj/locversion.plist$").c_str()
573 // FMJ (everything is a resource) rules
574 if (ctx
.signingFlags() & kSecCSSignOpaque
) // Full Metal Jacket - everything is a resource file
575 return cfmake
<CFDictionaryRef
>("{rules={"
576 "'^.*' = #T" // everything is a resource
577 "'^Info\\.plist$' = {omit=#T,weight=10}" // explicitly exclude this for backward compatibility
580 // new (V2) executable bundle rules
581 return cfmake
<CFDictionaryRef
>("{" // *** the new (V2) world ***
582 "rules={" // old (V1; legacy) version
583 "'^version.plist$' = #T" // include version.plist
584 "%s = #T" // include Resources
585 "%s = {optional=#T, weight=1000}" // make localizations optional
586 "%s = {weight=1010}" // ... except for Base.lproj which really isn't optional at all
587 "%s = {omit=#T, weight=1100}" // exclude all locversion.plist files
589 "'^.*' = #T" // include everything as a resource, with the following exceptions
590 "'^[^/]+$' = {nested=#T, weight=10}" // files directly in Contents
591 "'^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/' = {nested=#T, weight=10}" // dynamic repositories
592 "'.*\\.dSYM($|/)' = {weight=11}" // but allow dSYM directories in code locations (parallel to their code)
593 "'^(.*/)?\\.DS_Store$' = {omit=#T,weight=2000}" // ignore .DS_Store files
594 "'^Info\\.plist$' = {omit=#T, weight=20}" // excluded automatically now, but old systems need to be told
595 "'^version\\.plist$' = {weight=20}" // include version.plist as resource
596 "'^embedded\\.provisionprofile$' = {weight=20}" // include embedded.provisionprofile as resource
597 "'^PkgInfo$' = {omit=#T, weight=20}" // traditionally not included
598 "%s = {weight=20}" // Resources override default nested (widgets)
599 "%s = {optional=#T, weight=1000}" // make localizations optional
600 "%s = {weight=1010}" // ... except for Base.lproj which really isn't optional at all
601 "%s = {omit=#T, weight=1100}" // exclude all locversion.plist files
604 (string("^") + resources
).c_str(),
605 (string("^") + resources
+ ".*\\.lproj/").c_str(),
606 (string("^") + resources
+ "Base\\.lproj/").c_str(),
607 (string("^") + resources
+ ".*\\.lproj/locversion.plist$").c_str(),
609 (string("^") + resources
).c_str(),
610 (string("^") + resources
+ ".*\\.lproj/").c_str(),
611 (string("^") + resources
+ "Base\\.lproj/").c_str(),
612 (string("^") + resources
+ ".*\\.lproj/locversion.plist$").c_str()
617 CFArrayRef
BundleDiskRep::allowedResourceOmissions()
619 return cfmake
<CFArrayRef
>("["
620 "'^(.*/)?\\.DS_Store$'"
625 (string("^") + this->resourcesRelativePath() + ".*\\.lproj/locversion.plist$").c_str()
630 const Requirements
*BundleDiskRep::defaultRequirements(const Architecture
*arch
, const SigningContext
&ctx
)
632 return mExecRep
->defaultRequirements(arch
, ctx
);
635 size_t BundleDiskRep::pageSize(const SigningContext
&ctx
)
637 return mExecRep
->pageSize(ctx
);
642 // Strict validation.
643 // Takes an array of CFNumbers of errors to tolerate.
645 void BundleDiskRep::strictValidate(const CodeDirectory
* cd
, const ToleratedErrors
& tolerated
, SecCSFlags flags
)
647 // scan our metadirectory (_CodeSignature) for unwanted guests
648 if (!(flags
& kSecCSQuickCheck
))
649 validateMetaDirectory(cd
);
651 // check accumulated strict errors and report them
652 if (!(flags
& kSecCSRestrictSidebandData
)) // tolerate resource forks etc.
653 mStrictErrors
.erase(errSecCSInvalidAssociatedFileData
);
655 std::vector
<OSStatus
> fatalErrors
;
656 set_difference(mStrictErrors
.begin(), mStrictErrors
.end(), tolerated
.begin(), tolerated
.end(), back_inserter(fatalErrors
));
657 if (!fatalErrors
.empty())
658 MacOSError::throwMe(fatalErrors
[0]);
660 // if app focus is requested and this doesn't look like an app, fail - but allow whitelist overrides
661 if (flags
& kSecCSRestrictToAppLike
)
663 if (tolerated
.find(kSecCSRestrictToAppLike
) == tolerated
.end())
664 MacOSError::throwMe(errSecCSNotAppLike
);
666 // now strict-check the main executable (which won't be an app-like object)
667 mExecRep
->strictValidate(cd
, tolerated
, flags
& ~kSecCSRestrictToAppLike
);
670 void BundleDiskRep::recordStrictError(OSStatus error
)
672 mStrictErrors
.insert(error
);
676 void BundleDiskRep::validateMetaDirectory(const CodeDirectory
* cd
)
678 // we know the resource directory will be checked after this call, so we'll give it a pass here
679 if (cd
->slotIsPresent(-cdResourceDirSlot
))
680 mUsedComponents
.insert(cdResourceDirSlot
);
682 // make a set of allowed (regular) filenames in this directory
683 std::set
<std::string
> allowedFiles
;
684 for (auto it
= mUsedComponents
.begin(); it
!= mUsedComponents
.end(); ++it
) {
687 break; // always from Info.plist, not from here
689 if (const char *name
= CodeDirectory::canonicalSlotName(*it
)) {
690 allowedFiles
.insert(name
);
695 DirScanner
scan(mMetaPath
);
696 if (scan
.initialized()) {
697 while (struct dirent
* ent
= scan
.getNext()) {
698 if (!scan
.isRegularFile(ent
))
699 MacOSError::throwMe(errSecCSUnsealedAppRoot
); // only regular files allowed
700 if (allowedFiles
.find(ent
->d_name
) == allowedFiles
.end()) { // not in expected set of files
701 if (strcmp(ent
->d_name
, kSecCS_SIGNATUREFILE
) == 0) {
702 // special case - might be empty and unused (adhoc signature)
703 AutoFileDesc
fd(metaPath(kSecCS_SIGNATUREFILE
));
704 if (fd
.fileSize() == 0)
705 continue; // that's okay, then
707 // not on list of needed files; it's a freeloading rogue!
708 recordStrictError(errSecCSUnsealedAppRoot
); // funnel through strict set so GKOpaque can override it
716 // Check framework root for unsafe symlinks and unsealed content.
718 void BundleDiskRep::validateFrameworkRoot(string root
)
720 // build regex element that matches either the "Current" symlink, or the name of the current version
721 string current
= "Current";
722 char currentVersion
[PATH_MAX
];
723 ssize_t len
= ::readlink((root
+ "/Versions/Current").c_str(), currentVersion
, sizeof(currentVersion
)-1);
725 currentVersion
[len
] = '\0';
726 current
= string("(Current|") + ResourceBuilder::escapeRE(currentVersion
) + ")";
730 val
.require("^Versions$", DirValidator::directory
| DirValidator::descend
); // descend into Versions directory
731 val
.require("^Versions/[^/]+$", DirValidator::directory
); // require at least one version
732 val
.require("^Versions/Current$", DirValidator::symlink
, // require Current symlink...
733 "^(\\./)?(\\.\\.[^/]+|\\.?[^\\./][^/]*)$"); // ...must point to a version
734 val
.allow("^(Versions/)?\\.DS_Store$", DirValidator::file
| DirValidator::noexec
); // allow .DS_Store files
735 val
.allow("^[^/]+$", DirValidator::symlink
, ^ string (const string
&name
, const string
&target
) {
736 // top-level symlinks must point to namesake in current version
737 return string("^(\\./)?Versions/") + current
+ "/" + ResourceBuilder::escapeRE(name
) + "$";
739 // module.map must be regular non-executable file, or symlink to module.map in current version
740 val
.allow("^module\\.map$", DirValidator::file
| DirValidator::noexec
| DirValidator::symlink
,
741 string("^(\\./)?Versions/") + current
+ "/module\\.map$");
744 val
.validate(root
, errSecCSUnsealedFrameworkRoot
);
745 } catch (const MacOSError
&err
) {
746 recordStrictError(err
.error
);
752 // Check a file descriptor for harmlessness. This is a strict check (only).
754 void BundleDiskRep::checkPlainFile(FileDesc fd
, const std::string
& path
)
756 if (!fd
.isPlainFile(path
))
757 recordStrictError(errSecCSRegularFile
);
761 void BundleDiskRep::checkForks(FileDesc fd
)
763 if (fd
.hasExtendedAttribute(XATTR_RESOURCEFORK_NAME
) || fd
.hasExtendedAttribute(XATTR_FINDERINFO_NAME
))
764 recordStrictError(errSecCSInvalidAssociatedFileData
);
771 DiskRep::Writer
*BundleDiskRep::writer()
773 return new Writer(this);
776 BundleDiskRep::Writer::Writer(BundleDiskRep
*r
)
777 : rep(r
), mMadeMetaDirectory(false)
779 execWriter
= rep
->mExecRep
->writer();
784 // Write a component.
785 // Note that this isn't concerned with Mach-O writing; this is handled at
786 // a much higher level. If we're called, we write to a file in the Bundle's meta directory.
788 void BundleDiskRep::Writer::component(CodeDirectory::SpecialSlot slot
, CFDataRef data
)
792 if (!execWriter
->attribute(writerLastResort
)) // willing to take the data...
793 return execWriter
->component(slot
, data
); // ... so hand it through
794 // execWriter doesn't want the data; store it as a resource file (below)
795 case cdResourceDirSlot
:
796 // the resource directory always goes into a bundle file
797 if (const char *name
= CodeDirectory::canonicalSlotName(slot
)) {
799 string path
= rep
->metaPath(name
);
800 AutoFileDesc
fd(path
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0644);
801 fd
.writeAll(CFDataGetBytePtr(data
), CFDataGetLength(data
));
802 mWrittenFiles
.insert(name
);
804 MacOSError::throwMe(errSecCSBadBundleFormat
);
810 // Remove all signature data
812 void BundleDiskRep::Writer::remove()
814 // remove signature from the executable
815 execWriter
->remove();
817 // remove signature files from bundle
818 for (CodeDirectory::SpecialSlot slot
= 0; slot
< cdSlotCount
; slot
++)
820 remove(cdSignatureSlot
);
823 void BundleDiskRep::Writer::remove(CodeDirectory::SpecialSlot slot
)
825 if (const char *name
= CodeDirectory::canonicalSlotName(slot
))
826 if (::unlink(rep
->metaPath(name
).c_str()))
828 case ENOENT
: // not found - that's okay
831 UnixError::throwMe();
836 void BundleDiskRep::Writer::flush()
839 purgeMetaDirectory();
843 // purge _CodeSignature of all left-over files from any previous signature
844 void BundleDiskRep::Writer::purgeMetaDirectory()
846 DirScanner
scan(rep
->mMetaPath
);
847 if (scan
.initialized()) {
848 while (struct dirent
* ent
= scan
.getNext()) {
849 if (!scan
.isRegularFile(ent
))
850 MacOSError::throwMe(errSecCSUnsealedAppRoot
); // only regular files allowed
851 if (mWrittenFiles
.find(ent
->d_name
) == mWrittenFiles
.end()) { // we didn't write this!
860 } // end namespace CodeSigning
861 } // end namespace Security