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 return cfLoadFile(CFTempURL(metaPath(name
)));
287 CFDataRef
BundleDiskRep::metaData(CodeDirectory::SpecialSlot slot
)
289 if (const char *name
= CodeDirectory::canonicalSlotName(slot
))
290 return metaData(name
);
298 // Load's a CFURL and makes sure that it is a regular file and not a symlink (or fifo, etc.)
300 CFDataRef
BundleDiskRep::loadRegularFile(CFURLRef url
)
304 CFDataRef data
= NULL
;
306 std::string
path(cfString(url
));
308 AutoFileDesc
fd(path
);
310 checkPlainFile(fd
, path
);
312 data
= cfLoadFile(fd
, fd
.fileSize());
315 secinfo("bundlediskrep", "failed to load %s", cfString(url
).c_str());
316 MacOSError::throwMe(errSecCSInvalidSymlink
);
323 // Load and return a component, by slot number.
324 // Info.plist components come from the bundle, always (we don't look
325 // for Mach-O embedded versions).
326 // ResourceDirectory always comes from bundle files.
327 // Everything else comes from the embedded blobs of a Mach-O image, or from
328 // files located in the Contents directory of the bundle; but we must be consistent
329 // (no half-and-half situations).
331 CFDataRef
BundleDiskRep::component(CodeDirectory::SpecialSlot slot
)
334 // the Info.plist comes from the magic CFBundle-indicated place and ONLY from there
336 if (CFRef
<CFURLRef
> info
= _CFBundleCopyInfoPlistURL(mBundle
))
337 return loadRegularFile(info
);
340 case cdResourceDirSlot
:
341 mUsedComponents
.insert(slot
);
342 return metaData(slot
);
343 // by default, we take components from the executable image or files (but not both)
345 if (CFRef
<CFDataRef
> data
= mExecRep
->component(slot
)) {
346 componentFromExec(true);
349 if (CFRef
<CFDataRef
> data
= metaData(slot
)) {
350 componentFromExec(false);
351 mUsedComponents
.insert(slot
);
359 // Check that all components of this BundleDiskRep come from either the main
360 // executable or the _CodeSignature directory (not mix-and-match).
361 void BundleDiskRep::componentFromExec(bool fromExec
)
363 if (!mComponentsFromExecValid
) {
364 // first use; set latch
365 mComponentsFromExecValid
= true;
366 mComponentsFromExec
= fromExec
;
367 } else if (mComponentsFromExec
!= fromExec
) {
368 // subsequent use: check latch
369 MacOSError::throwMe(errSecCSSignatureFailed
);
375 // The binary identifier is taken directly from the main executable.
377 CFDataRef
BundleDiskRep::identification()
379 return mExecRep
->identification();
384 // Various aspects of our DiskRep personality.
386 CFURLRef
BundleDiskRep::copyCanonicalPath()
388 if (CFURLRef url
= CFBundleCopyBundleURL(mBundle
))
393 string
BundleDiskRep::mainExecutablePath()
395 return cfString(mMainExecutableURL
);
398 string
BundleDiskRep::resourcesRootPath()
400 return cfStringRelease(CFBundleCopySupportFilesDirectoryURL(mBundle
));
403 void BundleDiskRep::adjustResources(ResourceBuilder
&builder
)
405 // exclude entire contents of meta directory
406 builder
.addExclusion("^" BUNDLEDISKREP_DIRECTORY
"$");
407 builder
.addExclusion("^" CODERESOURCES_LINK
"$"); // ancient-ish symlink into it
409 // exclude the store manifest directory
410 builder
.addExclusion("^" STORE_RECEIPT_DIRECTORY
"$");
412 // exclude the main executable file
413 string resources
= resourcesRootPath();
414 if (resources
.compare(resources
.size() - 2, 2, "/.") == 0) // chop trailing /.
415 resources
= resources
.substr(0, resources
.size()-2);
416 string executable
= mainExecutablePath();
417 if (!executable
.compare(0, resources
.length(), resources
, 0, resources
.length())
418 && executable
[resources
.length()] == '/') // is proper directory prefix
419 builder
.addExclusion(string("^")
420 + ResourceBuilder::escapeRE(executable
.substr(resources
.length()+1)) + "$", ResourceBuilder::softTarget
);
425 Universal
*BundleDiskRep::mainExecutableImage()
427 return mExecRep
->mainExecutableImage();
430 void BundleDiskRep::prepareForSigning(SigningContext
&context
)
432 return mExecRep
->prepareForSigning(context
);
435 size_t BundleDiskRep::signingBase()
437 return mExecRep
->signingBase();
440 size_t BundleDiskRep::signingLimit()
442 return mExecRep
->signingLimit();
445 string
BundleDiskRep::format()
450 CFArrayRef
BundleDiskRep::modifiedFiles()
452 CFMutableArrayRef files
= CFArrayCreateMutableCopy(NULL
, 0, mExecRep
->modifiedFiles());
453 checkModifiedFile(files
, cdCodeDirectorySlot
);
454 checkModifiedFile(files
, cdSignatureSlot
);
455 checkModifiedFile(files
, cdResourceDirSlot
);
456 checkModifiedFile(files
, cdTopDirectorySlot
);
457 checkModifiedFile(files
, cdEntitlementSlot
);
458 checkModifiedFile(files
, cdRepSpecificSlot
);
459 for (CodeDirectory::Slot slot
= cdAlternateCodeDirectorySlots
; slot
< cdAlternateCodeDirectoryLimit
; ++slot
)
460 checkModifiedFile(files
, slot
);
464 void BundleDiskRep::checkModifiedFile(CFMutableArrayRef files
, CodeDirectory::SpecialSlot slot
)
466 if (CFDataRef data
= mExecRep
->component(slot
)) // provided by executable file
468 else if (const char *resourceName
= CodeDirectory::canonicalSlotName(slot
)) {
469 string file
= metaPath(resourceName
);
470 if (::access(file
.c_str(), F_OK
) == 0)
471 CFArrayAppendValue(files
, CFTempURL(file
));
475 FileDesc
&BundleDiskRep::fd()
477 return mExecRep
->fd();
480 void BundleDiskRep::flush()
485 CFDictionaryRef
BundleDiskRep::diskRepInformation()
487 return mExecRep
->diskRepInformation();
491 // Defaults for signing operations
493 string
BundleDiskRep::recommendedIdentifier(const SigningContext
&)
495 if (CFStringRef identifier
= CFBundleGetIdentifier(mBundle
))
496 return cfString(identifier
);
497 if (CFDictionaryRef infoDict
= CFBundleGetInfoDictionary(mBundle
))
498 if (CFStringRef identifier
= CFStringRef(CFDictionaryGetValue(infoDict
, kCFBundleNameKey
)))
499 return cfString(identifier
);
501 // fall back to using the canonical path
502 return canonicalIdentifier(cfStringRelease(this->copyCanonicalPath()));
505 string
BundleDiskRep::resourcesRelativePath()
507 // figure out the resource directory base. Clean up some gunk inserted by CFBundle in frameworks
508 string rbase
= this->resourcesRootPath();
509 size_t pos
= rbase
.find("/./"); // gratuitously inserted by CFBundle in some frameworks
510 while (pos
!= std::string::npos
) {
511 rbase
= rbase
.replace(pos
, 2, "", 0);
512 pos
= rbase
.find("/./");
514 if (rbase
.substr(rbase
.length()-2, 2) == "/.") // produced by versioned bundle implicit "Current" case
515 rbase
= rbase
.substr(0, rbase
.length()-2); // ... so take it off for this
517 // find the resources directory relative to the resource base
518 string resources
= cfStringRelease(CFBundleCopyResourcesDirectoryURL(mBundle
));
519 if (resources
== rbase
)
521 else if (resources
.compare(0, rbase
.length(), rbase
, 0, rbase
.length()) != 0) // Resources not in resource root
522 MacOSError::throwMe(errSecCSBadBundleFormat
);
524 resources
= resources
.substr(rbase
.length() + 1) + "/"; // differential path segment
529 CFDictionaryRef
BundleDiskRep::defaultResourceRules(const SigningContext
&ctx
)
531 string resources
= this->resourcesRelativePath();
533 // installer package rules
534 if (mInstallerPackage
)
535 return cfmake
<CFDictionaryRef
>("{rules={"
536 "'^.*' = #T" // include everything, but...
537 "%s = {optional=#T, weight=1000}" // make localizations optional
538 "'^.*/.*\\.pkg/' = {omit=#T, weight=10000}" // and exclude all nested packages (by name)
540 (string("^") + resources
+ ".*\\.lproj/").c_str()
543 // old (V1) executable bundle rules - compatible with before
544 if (ctx
.signingFlags() & kSecCSSignV1
) // *** must be exactly the same as before ***
545 return cfmake
<CFDictionaryRef
>("{rules={"
546 "'^version.plist$' = #T" // include version.plist
547 "%s = #T" // include Resources
548 "%s = {optional=#T, weight=1000}" // make localizations optional
549 "%s = {omit=#T, weight=1100}" // exclude all locversion.plist files
551 (string("^") + resources
).c_str(),
552 (string("^") + resources
+ ".*\\.lproj/").c_str(),
553 (string("^") + resources
+ ".*\\.lproj/locversion.plist$").c_str()
556 // FMJ (everything is a resource) rules
557 if (ctx
.signingFlags() & kSecCSSignOpaque
) // Full Metal Jacket - everything is a resource file
558 return cfmake
<CFDictionaryRef
>("{rules={"
559 "'^.*' = #T" // everything is a resource
560 "'^Info\\.plist$' = {omit=#T,weight=10}" // explicitly exclude this for backward compatibility
563 // new (V2) executable bundle rules
564 return cfmake
<CFDictionaryRef
>("{" // *** the new (V2) world ***
565 "rules={" // old (V1; legacy) version
566 "'^version.plist$' = #T" // include version.plist
567 "%s = #T" // include Resources
568 "%s = {optional=#T, weight=1000}" // make localizations optional
569 "%s = {weight=1010}" // ... except for Base.lproj which really isn't optional at all
570 "%s = {omit=#T, weight=1100}" // exclude all locversion.plist files
572 "'^.*' = #T" // include everything as a resource, with the following exceptions
573 "'^[^/]+$' = {nested=#T, weight=10}" // files directly in Contents
574 "'^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/' = {nested=#T, weight=10}" // dynamic repositories
575 "'.*\\.dSYM($|/)' = {weight=11}" // but allow dSYM directories in code locations (parallel to their code)
576 "'^(.*/)?\\.DS_Store$' = {omit=#T,weight=2000}" // ignore .DS_Store files
577 "'^Info\\.plist$' = {omit=#T, weight=20}" // excluded automatically now, but old systems need to be told
578 "'^version\\.plist$' = {weight=20}" // include version.plist as resource
579 "'^embedded\\.provisionprofile$' = {weight=20}" // include embedded.provisionprofile as resource
580 "'^PkgInfo$' = {omit=#T, weight=20}" // traditionally not included
581 "%s = {weight=20}" // Resources override default nested (widgets)
582 "%s = {optional=#T, weight=1000}" // make localizations optional
583 "%s = {weight=1010}" // ... except for Base.lproj which really isn't optional at all
584 "%s = {omit=#T, weight=1100}" // exclude all locversion.plist files
587 (string("^") + resources
).c_str(),
588 (string("^") + resources
+ ".*\\.lproj/").c_str(),
589 (string("^") + resources
+ "Base\\.lproj/").c_str(),
590 (string("^") + resources
+ ".*\\.lproj/locversion.plist$").c_str(),
592 (string("^") + resources
).c_str(),
593 (string("^") + resources
+ ".*\\.lproj/").c_str(),
594 (string("^") + resources
+ "Base\\.lproj/").c_str(),
595 (string("^") + resources
+ ".*\\.lproj/locversion.plist$").c_str()
600 CFArrayRef
BundleDiskRep::allowedResourceOmissions()
602 return cfmake
<CFArrayRef
>("["
603 "'^(.*/)?\\.DS_Store$'"
608 (string("^") + this->resourcesRelativePath() + ".*\\.lproj/locversion.plist$").c_str()
613 const Requirements
*BundleDiskRep::defaultRequirements(const Architecture
*arch
, const SigningContext
&ctx
)
615 return mExecRep
->defaultRequirements(arch
, ctx
);
618 size_t BundleDiskRep::pageSize(const SigningContext
&ctx
)
620 return mExecRep
->pageSize(ctx
);
625 // Strict validation.
626 // Takes an array of CFNumbers of errors to tolerate.
628 void BundleDiskRep::strictValidate(const CodeDirectory
* cd
, const ToleratedErrors
& tolerated
, SecCSFlags flags
)
630 // scan our metadirectory (_CodeSignature) for unwanted guests
631 if (!(flags
& kSecCSQuickCheck
))
632 validateMetaDirectory(cd
);
634 // check accumulated strict errors and report them
635 if (!(flags
& kSecCSRestrictSidebandData
)) // tolerate resource forks etc.
636 mStrictErrors
.erase(errSecCSInvalidAssociatedFileData
);
638 std::vector
<OSStatus
> fatalErrors
;
639 set_difference(mStrictErrors
.begin(), mStrictErrors
.end(), tolerated
.begin(), tolerated
.end(), back_inserter(fatalErrors
));
640 if (!fatalErrors
.empty())
641 MacOSError::throwMe(fatalErrors
[0]);
643 // if app focus is requested and this doesn't look like an app, fail - but allow whitelist overrides
644 if (flags
& kSecCSRestrictToAppLike
)
646 if (tolerated
.find(kSecCSRestrictToAppLike
) == tolerated
.end())
647 MacOSError::throwMe(errSecCSNotAppLike
);
649 // now strict-check the main executable (which won't be an app-like object)
650 mExecRep
->strictValidate(cd
, tolerated
, flags
& ~kSecCSRestrictToAppLike
);
653 void BundleDiskRep::recordStrictError(OSStatus error
)
655 mStrictErrors
.insert(error
);
659 void BundleDiskRep::validateMetaDirectory(const CodeDirectory
* cd
)
661 // we know the resource directory will be checked after this call, so we'll give it a pass here
662 if (cd
->slotIsPresent(-cdResourceDirSlot
))
663 mUsedComponents
.insert(cdResourceDirSlot
);
665 // make a set of allowed (regular) filenames in this directory
666 std::set
<std::string
> allowedFiles
;
667 for (auto it
= mUsedComponents
.begin(); it
!= mUsedComponents
.end(); ++it
) {
670 break; // always from Info.plist, not from here
672 if (const char *name
= CodeDirectory::canonicalSlotName(*it
)) {
673 allowedFiles
.insert(name
);
678 DirScanner
scan(mMetaPath
);
679 if (scan
.initialized()) {
680 while (struct dirent
* ent
= scan
.getNext()) {
681 if (!scan
.isRegularFile(ent
))
682 MacOSError::throwMe(errSecCSUnsealedAppRoot
); // only regular files allowed
683 if (allowedFiles
.find(ent
->d_name
) == allowedFiles
.end()) { // not in expected set of files
684 if (strcmp(ent
->d_name
, kSecCS_SIGNATUREFILE
) == 0) {
685 // special case - might be empty and unused (adhoc signature)
686 AutoFileDesc
fd(metaPath(kSecCS_SIGNATUREFILE
));
687 if (fd
.fileSize() == 0)
688 continue; // that's okay, then
690 // not on list of needed files; it's a freeloading rogue!
691 recordStrictError(errSecCSUnsealedAppRoot
); // funnel through strict set so GKOpaque can override it
699 // Check framework root for unsafe symlinks and unsealed content.
701 void BundleDiskRep::validateFrameworkRoot(string root
)
703 // build regex element that matches either the "Current" symlink, or the name of the current version
704 string current
= "Current";
705 char currentVersion
[PATH_MAX
];
706 ssize_t len
= ::readlink((root
+ "/Versions/Current").c_str(), currentVersion
, sizeof(currentVersion
)-1);
708 currentVersion
[len
] = '\0';
709 current
= string("(Current|") + ResourceBuilder::escapeRE(currentVersion
) + ")";
713 val
.require("^Versions$", DirValidator::directory
| DirValidator::descend
); // descend into Versions directory
714 val
.require("^Versions/[^/]+$", DirValidator::directory
); // require at least one version
715 val
.require("^Versions/Current$", DirValidator::symlink
, // require Current symlink...
716 "^(\\./)?(\\.\\.[^/]+|\\.?[^\\./][^/]*)$"); // ...must point to a version
717 val
.allow("^(Versions/)?\\.DS_Store$", DirValidator::file
| DirValidator::noexec
); // allow .DS_Store files
718 val
.allow("^[^/]+$", DirValidator::symlink
, ^ string (const string
&name
, const string
&target
) {
719 // top-level symlinks must point to namesake in current version
720 return string("^(\\./)?Versions/") + current
+ "/" + ResourceBuilder::escapeRE(name
) + "$";
722 // module.map must be regular non-executable file, or symlink to module.map in current version
723 val
.allow("^module\\.map$", DirValidator::file
| DirValidator::noexec
| DirValidator::symlink
,
724 string("^(\\./)?Versions/") + current
+ "/module\\.map$");
727 val
.validate(root
, errSecCSUnsealedFrameworkRoot
);
728 } catch (const MacOSError
&err
) {
729 recordStrictError(err
.error
);
735 // Check a file descriptor for harmlessness. This is a strict check (only).
737 void BundleDiskRep::checkPlainFile(FileDesc fd
, const std::string
& path
)
739 if (!fd
.isPlainFile(path
))
740 recordStrictError(errSecCSRegularFile
);
744 void BundleDiskRep::checkForks(FileDesc fd
)
746 if (fd
.hasExtendedAttribute(XATTR_RESOURCEFORK_NAME
) || fd
.hasExtendedAttribute(XATTR_FINDERINFO_NAME
))
747 recordStrictError(errSecCSInvalidAssociatedFileData
);
754 DiskRep::Writer
*BundleDiskRep::writer()
756 return new Writer(this);
759 BundleDiskRep::Writer::Writer(BundleDiskRep
*r
)
760 : rep(r
), mMadeMetaDirectory(false)
762 execWriter
= rep
->mExecRep
->writer();
767 // Write a component.
768 // Note that this isn't concerned with Mach-O writing; this is handled at
769 // a much higher level. If we're called, we write to a file in the Bundle's meta directory.
771 void BundleDiskRep::Writer::component(CodeDirectory::SpecialSlot slot
, CFDataRef data
)
775 if (!execWriter
->attribute(writerLastResort
)) // willing to take the data...
776 return execWriter
->component(slot
, data
); // ... so hand it through
777 // execWriter doesn't want the data; store it as a resource file (below)
778 case cdResourceDirSlot
:
779 // the resource directory always goes into a bundle file
780 if (const char *name
= CodeDirectory::canonicalSlotName(slot
)) {
782 string path
= rep
->metaPath(name
);
783 AutoFileDesc
fd(path
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0644);
784 fd
.writeAll(CFDataGetBytePtr(data
), CFDataGetLength(data
));
785 mWrittenFiles
.insert(name
);
787 MacOSError::throwMe(errSecCSBadBundleFormat
);
793 // Remove all signature data
795 void BundleDiskRep::Writer::remove()
797 // remove signature from the executable
798 execWriter
->remove();
800 // remove signature files from bundle
801 for (CodeDirectory::SpecialSlot slot
= 0; slot
< cdSlotCount
; slot
++)
803 remove(cdSignatureSlot
);
806 void BundleDiskRep::Writer::remove(CodeDirectory::SpecialSlot slot
)
808 if (const char *name
= CodeDirectory::canonicalSlotName(slot
))
809 if (::unlink(rep
->metaPath(name
).c_str()))
811 case ENOENT
: // not found - that's okay
814 UnixError::throwMe();
819 void BundleDiskRep::Writer::flush()
822 purgeMetaDirectory();
826 // purge _CodeSignature of all left-over files from any previous signature
827 void BundleDiskRep::Writer::purgeMetaDirectory()
829 DirScanner
scan(rep
->mMetaPath
);
830 if (scan
.initialized()) {
831 while (struct dirent
* ent
= scan
.getNext()) {
832 if (!scan
.isRegularFile(ent
))
833 MacOSError::throwMe(errSecCSUnsealedAppRoot
); // only regular files allowed
834 if (mWrittenFiles
.find(ent
->d_name
) == mWrittenFiles
.end()) { // we didn't write this!
843 } // end namespace CodeSigning
844 } // end namespace Security