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
);
366 BundleDiskRep::RawComponentMap
BundleDiskRep::createRawComponents()
370 /* Those are the slots known to BundleDiskReps.
371 * Unlike e.g. MachOReps, we cannot handle unknown slots,
372 * as we won't know their slot <-> filename mapping.
374 int const slots
[] = {
375 cdCodeDirectorySlot
, cdSignatureSlot
, cdResourceDirSlot
,
376 cdTopDirectorySlot
, cdEntitlementSlot
, cdEntitlementDERSlot
,
379 for (int slot
= 0; slot
< (int)(sizeof(slots
)/sizeof(slots
[0])); ++slot
) {
380 /* Here, we only handle metaData slots, i.e. slots that
381 * are explicit files in the _CodeSignature directory.
382 * Main executable slots (if the main executable is a
383 * EditableDiskRep) are handled when editing the
384 * main executable's rep explicitly.
385 * There is also an Info.plist slot, which is not a
386 * real part of the code signature.
388 CFRef
<CFDataRef
> data
= metaData(slot
);
395 for (CodeDirectory::Slot slot
= cdAlternateCodeDirectorySlots
; slot
< cdAlternateCodeDirectoryLimit
; ++slot
) {
396 CFRef
<CFDataRef
> data
= metaData(slot
);
406 // Check that all components of this BundleDiskRep come from either the main
407 // executable or the _CodeSignature directory (not mix-and-match).
408 void BundleDiskRep::componentFromExec(bool fromExec
)
410 if (!mComponentsFromExecValid
) {
411 // first use; set latch
412 mComponentsFromExecValid
= true;
413 mComponentsFromExec
= fromExec
;
414 } else if (mComponentsFromExec
!= fromExec
) {
415 // subsequent use: check latch
416 MacOSError::throwMe(errSecCSSignatureFailed
);
422 // The binary identifier is taken directly from the main executable.
424 CFDataRef
BundleDiskRep::identification()
426 return mExecRep
->identification();
431 // Various aspects of our DiskRep personality.
433 CFURLRef
BundleDiskRep::copyCanonicalPath()
435 if (CFURLRef url
= CFBundleCopyBundleURL(mBundle
))
440 string
BundleDiskRep::mainExecutablePath()
442 return cfString(mMainExecutableURL
);
445 string
BundleDiskRep::resourcesRootPath()
447 return cfStringRelease(CFBundleCopySupportFilesDirectoryURL(mBundle
));
450 void BundleDiskRep::adjustResources(ResourceBuilder
&builder
)
452 // exclude entire contents of meta directory
453 builder
.addExclusion("^" BUNDLEDISKREP_DIRECTORY
"$");
454 builder
.addExclusion("^" CODERESOURCES_LINK
"$"); // ancient-ish symlink into it
456 // exclude the store manifest directory
457 builder
.addExclusion("^" STORE_RECEIPT_DIRECTORY
"$");
459 // exclude the main executable file
460 string resources
= resourcesRootPath();
461 if (resources
.compare(resources
.size() - 2, 2, "/.") == 0) // chop trailing /.
462 resources
= resources
.substr(0, resources
.size()-2);
463 string executable
= mainExecutablePath();
464 if (!executable
.compare(0, resources
.length(), resources
, 0, resources
.length())
465 && executable
[resources
.length()] == '/') // is proper directory prefix
466 builder
.addExclusion(string("^")
467 + ResourceBuilder::escapeRE(executable
.substr(resources
.length()+1)) + "$", ResourceBuilder::softTarget
);
472 Universal
*BundleDiskRep::mainExecutableImage()
474 return mExecRep
->mainExecutableImage();
477 void BundleDiskRep::prepareForSigning(SigningContext
&context
)
479 return mExecRep
->prepareForSigning(context
);
482 size_t BundleDiskRep::signingBase()
484 return mExecRep
->signingBase();
487 size_t BundleDiskRep::signingLimit()
489 return mExecRep
->signingLimit();
492 size_t BundleDiskRep::execSegBase(const Architecture
*arch
)
494 return mExecRep
->execSegBase(arch
);
497 size_t BundleDiskRep::execSegLimit(const Architecture
*arch
)
499 return mExecRep
->execSegLimit(arch
);
502 string
BundleDiskRep::format()
507 CFArrayRef
BundleDiskRep::modifiedFiles()
509 CFRef
<CFArrayRef
> execFiles
= mExecRep
->modifiedFiles();
510 CFRef
<CFMutableArrayRef
> files
= CFArrayCreateMutableCopy(NULL
, 0, execFiles
);
511 checkModifiedFile(files
, cdCodeDirectorySlot
);
512 checkModifiedFile(files
, cdSignatureSlot
);
513 checkModifiedFile(files
, cdResourceDirSlot
);
514 checkModifiedFile(files
, cdTopDirectorySlot
);
515 checkModifiedFile(files
, cdEntitlementSlot
);
516 checkModifiedFile(files
, cdEntitlementDERSlot
);
517 checkModifiedFile(files
, cdRepSpecificSlot
);
518 for (CodeDirectory::Slot slot
= cdAlternateCodeDirectorySlots
; slot
< cdAlternateCodeDirectoryLimit
; ++slot
)
519 checkModifiedFile(files
, slot
);
520 return files
.yield();
523 void BundleDiskRep::checkModifiedFile(CFMutableArrayRef files
, CodeDirectory::SpecialSlot slot
)
525 if (CFDataRef data
= mExecRep
->component(slot
)) // provided by executable file
527 else if (const char *resourceName
= CodeDirectory::canonicalSlotName(slot
)) {
528 string file
= metaPath(resourceName
);
529 if (::access(file
.c_str(), F_OK
) == 0)
530 CFArrayAppendValue(files
, CFTempURL(file
));
534 FileDesc
&BundleDiskRep::fd()
536 return mExecRep
->fd();
539 void BundleDiskRep::flush()
544 CFDictionaryRef
BundleDiskRep::diskRepInformation()
546 return mExecRep
->diskRepInformation();
550 // Defaults for signing operations
552 string
BundleDiskRep::recommendedIdentifier(const SigningContext
&)
554 if (CFStringRef identifier
= CFBundleGetIdentifier(mBundle
))
555 return cfString(identifier
);
556 if (CFDictionaryRef infoDict
= CFBundleGetInfoDictionary(mBundle
))
557 if (CFStringRef identifier
= CFStringRef(CFDictionaryGetValue(infoDict
, kCFBundleNameKey
)))
558 return cfString(identifier
);
560 // fall back to using the canonical path
561 return canonicalIdentifier(cfStringRelease(this->copyCanonicalPath()));
564 string
BundleDiskRep::resourcesRelativePath()
566 // figure out the resource directory base. Clean up some gunk inserted by CFBundle in frameworks
567 string rbase
= this->resourcesRootPath();
568 size_t pos
= rbase
.find("/./"); // gratuitously inserted by CFBundle in some frameworks
569 while (pos
!= std::string::npos
) {
570 rbase
= rbase
.replace(pos
, 2, "", 0);
571 pos
= rbase
.find("/./");
573 if (rbase
.substr(rbase
.length()-2, 2) == "/.") // produced by versioned bundle implicit "Current" case
574 rbase
= rbase
.substr(0, rbase
.length()-2); // ... so take it off for this
576 // find the resources directory relative to the resource base
577 string resources
= cfStringRelease(CFBundleCopyResourcesDirectoryURL(mBundle
));
578 if (resources
== rbase
)
580 else if (resources
.compare(0, rbase
.length(), rbase
, 0, rbase
.length()) != 0) // Resources not in resource root
581 MacOSError::throwMe(errSecCSBadBundleFormat
);
583 resources
= resources
.substr(rbase
.length() + 1) + "/"; // differential path segment
588 CFDictionaryRef
BundleDiskRep::defaultResourceRules(const SigningContext
&ctx
)
590 string resources
= this->resourcesRelativePath();
592 // installer package rules
593 if (mInstallerPackage
)
594 return cfmake
<CFDictionaryRef
>("{rules={"
595 "'^.*' = #T" // include everything, but...
596 "%s = {optional=#T, weight=1000}" // make localizations optional
597 "'^.*/.*\\.pkg/' = {omit=#T, weight=10000}" // and exclude all nested packages (by name)
599 (string("^") + resources
+ ".*\\.lproj/").c_str()
602 // old (V1) executable bundle rules - compatible with before
603 if (ctx
.signingFlags() & kSecCSSignV1
) // *** must be exactly the same as before ***
604 return cfmake
<CFDictionaryRef
>("{rules={"
605 "'^version.plist$' = #T" // include version.plist
606 "%s = #T" // include Resources
607 "%s = {optional=#T, weight=1000}" // make localizations optional
608 "%s = {omit=#T, weight=1100}" // exclude all locversion.plist files
610 (string("^") + resources
).c_str(),
611 (string("^") + resources
+ ".*\\.lproj/").c_str(),
612 (string("^") + resources
+ ".*\\.lproj/locversion.plist$").c_str()
615 // FMJ (everything is a resource) rules
616 if (ctx
.signingFlags() & kSecCSSignOpaque
) // Full Metal Jacket - everything is a resource file
617 return cfmake
<CFDictionaryRef
>("{rules={"
618 "'^.*' = #T" // everything is a resource
619 "'^Info\\.plist$' = {omit=#T,weight=10}" // explicitly exclude this for backward compatibility
622 // new (V2) executable bundle rules
623 if (!resources
.empty()) {
624 return cfmake
<CFDictionaryRef
>("{" // *** the new (V2) world ***
625 "rules={" // old (V1; legacy) version
626 "'^version.plist$' = #T" // include version.plist
627 "%s = #T" // include Resources
628 "%s = {optional=#T, weight=1000}" // make localizations optional
629 "%s = {weight=1010}" // ... except for Base.lproj which really isn't optional at all
630 "%s = {omit=#T, weight=1100}" // exclude all locversion.plist files
632 "'^.*' = #T" // include everything as a resource, with the following exceptions
633 "'^[^/]+$' = {nested=#T, weight=10}" // files directly in Contents
634 "'^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/' = {nested=#T, weight=10}" // dynamic repositories
635 "'.*\\.dSYM($|/)' = {weight=11}" // but allow dSYM directories in code locations (parallel to their code)
636 "'^(.*/)?\\.DS_Store$' = {omit=#T,weight=2000}" // ignore .DS_Store files
637 "'^Info\\.plist$' = {omit=#T, weight=20}" // excluded automatically now, but old systems need to be told
638 "'^version\\.plist$' = {weight=20}" // include version.plist as resource
639 "'^embedded\\.provisionprofile$' = {weight=20}" // include embedded.provisionprofile as resource
640 "'^PkgInfo$' = {omit=#T, weight=20}" // traditionally not included
641 "%s = {weight=20}" // Resources override default nested (widgets)
642 "%s = {optional=#T, weight=1000}" // make localizations optional
643 "%s = {weight=1010}" // ... except for Base.lproj which really isn't optional at all
644 "%s = {omit=#T, weight=1100}" // exclude all locversion.plist files
647 (string("^") + resources
).c_str(),
648 (string("^") + resources
+ ".*\\.lproj/").c_str(),
649 (string("^") + resources
+ "Base\\.lproj/").c_str(),
650 (string("^") + resources
+ ".*\\.lproj/locversion.plist$").c_str(),
652 (string("^") + resources
).c_str(),
653 (string("^") + resources
+ ".*\\.lproj/").c_str(),
654 (string("^") + resources
+ "Base\\.lproj/").c_str(),
655 (string("^") + resources
+ ".*\\.lproj/locversion.plist$").c_str()
658 /* This is a bundle format without a Resources directory, which means we need to omit
659 * Resources-directory specific rules that would create conflicts. */
661 /* We also declare that flat bundles do not use any nested code rules.
662 * Embedded, where flat bundles are used, currently does not support them,
663 * and we have no plans for allowing the replacement of nested code there.
664 * Should anyone actually intend to use nested code rules in a flat
665 * bundle, they are free to create their own rules. */
667 return cfmake
<CFDictionaryRef
>("{" // *** the new (V2) world ***
668 "rules={" // old (V1; legacy) version
669 "'^version.plist$' = #T" // include version.plist
670 "'^.*' = #T" // include Resources
671 "'^.*\\.lproj/' = {optional=#T, weight=1000}" // make localizations optional
672 "'^Base\\.lproj/' = {weight=1010}" // ... except for Base.lproj which really isn't optional at all
673 "'^.*\\.lproj/locversion.plist$' = {omit=#T, weight=1100}" // exclude all locversion.plist files
675 "'^.*' = #T" // include everything as a resource, with the following exceptions
676 "'.*\\.dSYM($|/)' = {weight=11}" // but allow dSYM directories in code locations (parallel to their code)
677 "'^(.*/)?\\.DS_Store$' = {omit=#T,weight=2000}" // ignore .DS_Store files
678 "'^Info\\.plist$' = {omit=#T, weight=20}" // excluded automatically now, but old systems need to be told
679 "'^version\\.plist$' = {weight=20}" // include version.plist as resource
680 "'^embedded\\.provisionprofile$' = {weight=20}" // include embedded.provisionprofile as resource
681 "'^PkgInfo$' = {omit=#T, weight=20}" // traditionally not included
682 "'^.*\\.lproj/' = {optional=#T, weight=1000}" // make localizations optional
683 "'^Base\\.lproj/' = {weight=1010}" // ... except for Base.lproj which really isn't optional at all
684 "'^.*\\.lproj/locversion.plist$' = {omit=#T, weight=1100}" // exclude all locversion.plist files
691 CFArrayRef
BundleDiskRep::allowedResourceOmissions()
693 return cfmake
<CFArrayRef
>("["
694 "'^(.*/)?\\.DS_Store$'"
699 (string("^") + this->resourcesRelativePath() + ".*\\.lproj/locversion.plist$").c_str()
704 const Requirements
*BundleDiskRep::defaultRequirements(const Architecture
*arch
, const SigningContext
&ctx
)
706 return mExecRep
->defaultRequirements(arch
, ctx
);
709 size_t BundleDiskRep::pageSize(const SigningContext
&ctx
)
711 return mExecRep
->pageSize(ctx
);
716 // Strict validation.
717 // Takes an array of CFNumbers of errors to tolerate.
719 void BundleDiskRep::strictValidate(const CodeDirectory
* cd
, const ToleratedErrors
& tolerated
, SecCSFlags flags
)
721 strictValidateStructure(cd
, tolerated
, flags
);
723 // now strict-check the main executable (which won't be an app-like object)
724 mExecRep
->strictValidate(cd
, tolerated
, flags
& ~kSecCSRestrictToAppLike
);
727 void BundleDiskRep::strictValidateStructure(const CodeDirectory
* cd
, const ToleratedErrors
& tolerated
, SecCSFlags flags
)
729 // scan our metadirectory (_CodeSignature) for unwanted guests
730 if (!(flags
& kSecCSQuickCheck
))
731 validateMetaDirectory(cd
);
733 // check accumulated strict errors and report them
734 if (!(flags
& kSecCSRestrictSidebandData
)) // tolerate resource forks etc.
735 mStrictErrors
.erase(errSecCSInvalidAssociatedFileData
);
737 std::vector
<OSStatus
> fatalErrors
;
738 set_difference(mStrictErrors
.begin(), mStrictErrors
.end(), tolerated
.begin(), tolerated
.end(), back_inserter(fatalErrors
));
739 if (!fatalErrors
.empty())
740 MacOSError::throwMe(fatalErrors
[0]);
742 // if app focus is requested and this doesn't look like an app, fail - but allow whitelist overrides
743 if (flags
& kSecCSRestrictToAppLike
)
745 if (tolerated
.find(kSecCSRestrictToAppLike
) == tolerated
.end())
746 MacOSError::throwMe(errSecCSNotAppLike
);
749 void BundleDiskRep::recordStrictError(OSStatus error
)
751 mStrictErrors
.insert(error
);
755 void BundleDiskRep::validateMetaDirectory(const CodeDirectory
* cd
)
757 // we know the resource directory will be checked after this call, so we'll give it a pass here
758 if (cd
->slotIsPresent(-cdResourceDirSlot
))
759 mUsedComponents
.insert(cdResourceDirSlot
);
761 // make a set of allowed (regular) filenames in this directory
762 std::set
<std::string
> allowedFiles
;
763 for (auto it
= mUsedComponents
.begin(); it
!= mUsedComponents
.end(); ++it
) {
766 break; // always from Info.plist, not from here
768 if (const char *name
= CodeDirectory::canonicalSlotName(*it
)) {
769 allowedFiles
.insert(name
);
774 DirScanner
scan(mMetaPath
);
775 if (scan
.initialized()) {
776 while (struct dirent
* ent
= scan
.getNext()) {
777 if (!scan
.isRegularFile(ent
))
778 MacOSError::throwMe(errSecCSUnsealedAppRoot
); // only regular files allowed
779 if (allowedFiles
.find(ent
->d_name
) == allowedFiles
.end()) { // not in expected set of files
780 if (strcmp(ent
->d_name
, kSecCS_SIGNATUREFILE
) == 0) {
781 // special case - might be empty and unused (adhoc signature)
782 AutoFileDesc
fd(metaPath(kSecCS_SIGNATUREFILE
));
783 if (fd
.fileSize() == 0)
784 continue; // that's okay, then
786 // not on list of needed files; it's a freeloading rogue!
787 recordStrictError(errSecCSUnsealedAppRoot
); // funnel through strict set so GKOpaque can override it
795 // Check framework root for unsafe symlinks and unsealed content.
797 void BundleDiskRep::validateFrameworkRoot(string root
)
799 // build regex element that matches either the "Current" symlink, or the name of the current version
800 string current
= "Current";
801 char currentVersion
[PATH_MAX
];
802 ssize_t len
= ::readlink((root
+ "/Versions/Current").c_str(), currentVersion
, sizeof(currentVersion
)-1);
804 currentVersion
[len
] = '\0';
805 current
= string("(Current|") + ResourceBuilder::escapeRE(currentVersion
) + ")";
809 val
.require("^Versions$", DirValidator::directory
| DirValidator::descend
); // descend into Versions directory
810 val
.require("^Versions/[^/]+$", DirValidator::directory
); // require at least one version
811 val
.require("^Versions/Current$", DirValidator::symlink
, // require Current symlink...
812 "^(\\./)?(\\.\\.[^/]+|\\.?[^\\./][^/]*)$"); // ...must point to a version
813 val
.allow("^(Versions/)?\\.DS_Store$", DirValidator::file
| DirValidator::noexec
); // allow .DS_Store files
814 val
.allow("^[^/]+$", DirValidator::symlink
, ^ string (const string
&name
, const string
&target
) {
815 // top-level symlinks must point to namesake in current version
816 return string("^(\\./)?Versions/") + current
+ "/" + ResourceBuilder::escapeRE(name
) + "$";
818 // module.map must be regular non-executable file, or symlink to module.map in current version
819 val
.allow("^module\\.map$", DirValidator::file
| DirValidator::noexec
| DirValidator::symlink
,
820 string("^(\\./)?Versions/") + current
+ "/module\\.map$");
823 val
.validate(root
, errSecCSUnsealedFrameworkRoot
);
824 } catch (const MacOSError
&err
) {
825 recordStrictError(err
.error
);
831 // Check a file descriptor for harmlessness. This is a strict check (only).
833 void BundleDiskRep::checkPlainFile(FileDesc fd
, const std::string
& path
)
835 if (!fd
.isPlainFile(path
))
836 recordStrictError(errSecCSRegularFile
);
840 void BundleDiskRep::checkForks(FileDesc fd
)
842 if (fd
.hasExtendedAttribute(XATTR_RESOURCEFORK_NAME
) || fd
.hasExtendedAttribute(XATTR_FINDERINFO_NAME
))
843 recordStrictError(errSecCSInvalidAssociatedFileData
);
850 DiskRep::Writer
*BundleDiskRep::writer()
852 return new Writer(this);
855 BundleDiskRep::Writer::Writer(BundleDiskRep
*r
)
856 : rep(r
), mMadeMetaDirectory(false)
858 execWriter
= rep
->mExecRep
->writer();
863 // Write a component.
864 // Note that this isn't concerned with Mach-O writing; this is handled at
865 // a much higher level. If we're called, we write to a file in the Bundle's meta directory.
867 void BundleDiskRep::Writer::component(CodeDirectory::SpecialSlot slot
, CFDataRef data
)
871 if (!execWriter
->attribute(writerLastResort
)) // willing to take the data...
872 return execWriter
->component(slot
, data
); // ... so hand it through
873 // execWriter doesn't want the data; store it as a resource file (below)
874 case cdResourceDirSlot
:
875 // the resource directory always goes into a bundle file
876 if (const char *name
= CodeDirectory::canonicalSlotName(slot
)) {
878 string path
= rep
->metaPath(name
);
881 // determine AFSC status if we are told to preserve compression
882 bool conductCompression
= false;
884 if (this->getPreserveAFSC()) {
885 struct stat statBuffer
;
886 if (stat(path
.c_str(), &statBuffer
) == 0) {
887 if (queryCompressionInfo(path
.c_str(), &cInfo
) == 0) {
888 if (cInfo
.compressionType
!= 0 && cInfo
.compressedSize
> 0) {
889 conductCompression
= true;
896 AutoFileDesc
fd(path
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0644);
897 fd
.writeAll(CFDataGetBytePtr(data
), CFDataGetLength(data
));
901 // if the original file was compressed, compress the new file after move
902 if (conductCompression
) {
903 CFMutableDictionaryRef options
= CFDictionaryCreateMutable(NULL
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
904 CFStringRef val
= CFStringCreateWithFormat(kCFAllocatorDefault
, NULL
, CFSTR("%d"), cInfo
.compressionType
);
905 CFDictionarySetValue(options
, kAFSCCompressionTypes
, val
);
908 CompressionQueueContext compressionQueue
= CreateCompressionQueue(NULL
, NULL
, NULL
, NULL
, options
);
910 if (!CompressFile(compressionQueue
, path
.c_str(), NULL
)) {
911 secinfo("bundlediskrep", "%p Failed to queue compression of file %s", this, path
.c_str());
912 MacOSError::throwMe(errSecCSInternalError
);
915 FinishCompressionAndCleanUp(compressionQueue
);
916 compressionQueue
= NULL
;
921 mWrittenFiles
.insert(name
);
923 MacOSError::throwMe(errSecCSBadBundleFormat
);
929 // Remove all signature data
931 void BundleDiskRep::Writer::remove()
933 // remove signature from the executable
934 execWriter
->remove();
936 // remove signature files from bundle
937 for (CodeDirectory::SpecialSlot slot
= 0; slot
< cdSlotCount
; slot
++)
939 remove(cdSignatureSlot
);
942 void BundleDiskRep::Writer::remove(CodeDirectory::SpecialSlot slot
)
944 if (const char *name
= CodeDirectory::canonicalSlotName(slot
))
945 if (::unlink(rep
->metaPath(name
).c_str()))
947 case ENOENT
: // not found - that's okay
950 UnixError::throwMe();
955 void BundleDiskRep::Writer::flush()
958 purgeMetaDirectory();
961 // purge _CodeSignature of all left-over files from any previous signature
962 void BundleDiskRep::Writer::purgeMetaDirectory()
964 DirScanner
scan(rep
->mMetaPath
);
965 if (scan
.initialized()) {
966 while (struct dirent
* ent
= scan
.getNext()) {
967 if (!scan
.isRegularFile(ent
))
968 MacOSError::throwMe(errSecCSUnsealedAppRoot
); // only regular files allowed
969 if (mWrittenFiles
.find(ent
->d_name
) == mWrittenFiles
.end()) { // we didn't write this!
977 void BundleDiskRep::registerStapledTicket()
979 string root
= cfStringRelease(copyCanonicalPath());
980 registerStapledTicketInBundle(root
);
983 } // end namespace CodeSigning
984 } // end namespace Security