]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_codesigning/lib/bundlediskrep.cpp
Security-59754.41.1.tar.gz
[apple/security.git] / OSX / libsecurity_codesigning / lib / bundlediskrep.cpp
1 /*
2 * Copyright (c) 2006-2014 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23 #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>
31 #include <copyfile.h>
32 #include <fts.h>
33 #include <sstream>
34
35 namespace Security {
36 namespace CodeSigning {
37
38 using namespace UnixPlusPlus;
39
40
41 //
42 // Local helpers
43 //
44 static std::string findDistFile(const std::string &directory);
45
46
47 //
48 // We make a CFBundleRef immediately, but everything else is lazy
49 //
50 BundleDiskRep::BundleDiskRep(const char *path, const Context *ctx)
51 : mBundle(_CFBundleCreateUnique(NULL, CFTempURL(path))), forcePlatform(false)
52 {
53 if (!mBundle)
54 MacOSError::throwMe(errSecCSBadBundleFormat);
55 setup(ctx);
56 forcePlatform = mExecRep->appleInternalForcePlatform();
57 CODESIGN_DISKREP_CREATE_BUNDLE_PATH(this, (char*)path, (void*)ctx, mExecRep);
58 }
59
60 BundleDiskRep::BundleDiskRep(CFBundleRef ref, const Context *ctx)
61 {
62 mBundle = ref; // retains
63 setup(ctx);
64 forcePlatform = mExecRep->appleInternalForcePlatform();
65 CODESIGN_DISKREP_CREATE_BUNDLE_REF(this, ref, (void*)ctx, mExecRep);
66 }
67
68 BundleDiskRep::~BundleDiskRep()
69 {
70 }
71
72 void BundleDiskRep::checkMoved(CFURLRef oldPath, CFURLRef newPath)
73 {
74 char cOld[PATH_MAX];
75 char cNew[PATH_MAX];
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);
81
82 if (strcmp(cOld, cNew) != 0)
83 recordStrictError(errSecCSAmbiguousBundleFormat);
84 }
85
86 // common construction code
87 void BundleDiskRep::setup(const Context *ctx)
88 {
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
93
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);
97
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")
106 + "/.";
107 if (::access(contents.c_str(), F_OK) == 0) { // not shallow
108 DirValidator val;
109 val.require("^Contents$", DirValidator::directory); // duh
110 val.allow("^(\\.LSOverride|\\.DS_Store|Icon\r|\\.SoftwareDepot\\.tracking)$", DirValidator::file | DirValidator::noexec);
111 try {
112 val.validate(root, errSecCSUnsealedAppRoot);
113 } catch (const MacOSError &err) {
114 recordStrictError(err.error);
115 }
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
122 else
123 MacOSError::throwMe(errSecCSStaticCodeNotFound);
124 appDisqualified = true;
125 validateFrameworkRoot(root);
126 } else {
127 if (ctx && ctx->version) // explicitly specified
128 MacOSError::throwMe(errSecCSStaticCodeNotFound);
129 }
130
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"));
135
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
139
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) {
145 if (mainExecBefore)
146 checkMoved(mainExecBefore, mainExec);
147 if (infoPlistBefore)
148 if (CFRef<CFURLRef> infoDictPath = _CFBundleCopyInfoPlistURL(mBundle))
149 checkMoved(infoPlistBefore, infoDictPath);
150 }
151
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;
157 if (infoDict)
158 if (CFTypeRef packageType = CFDictionaryGetValue(infoDict, CFSTR("CFBundlePackageType")))
159 if (CFEqual(packageType, CFSTR("APPL")))
160 isAppBundle = true;
161 mFormat = "bundle with " + mExecRep->format();
162 if (isAppBundle)
163 mFormat = "app " + mFormat;
164 mAppLike = isAppBundle && !appDisqualified;
165 return;
166 }
167
168 // widget
169 if (mainHTML) {
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";
179 mAppLike = true;
180 return;
181 }
182
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";
192 } else {
193 mFormat = "bundle";
194 }
195 return;
196 }
197
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.take(makeCFURL(distFile));
202 mExecRep = new FileDiskRep(this->mainExecutablePath().c_str());
203 checkPlainFile(mExecRep->fd(), this->mainExecutablePath());
204 mInstallerPackage = true;
205 mFormat = "installer package bundle";
206 return;
207 }
208
209 // this bundle cannot be signed
210 MacOSError::throwMe(errSecCSBadBundleFormat);
211 }
212
213
214 //
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.
217 //
218 static std::string findDistFile(const std::string &directory)
219 {
220 std::string found;
221 char *paths[] = {(char *)directory.c_str(), NULL};
222 FTS *fts = fts_open(paths, FTS_PHYSICAL | FTS_NOCHDIR | FTS_NOSTAT, NULL);
223 bool root = true;
224 while (FTSENT *ent = fts_read(fts)) {
225 switch (ent->fts_info) {
226 case FTS_F:
227 case FTS_NSOK:
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);
233 }
234 break;
235 case FTS_D:
236 if (!root)
237 fts_set(fts, ent, FTS_SKIP); // don't descend
238 root = false;
239 break;
240 default:
241 break;
242 }
243 }
244 fts_close(fts);
245 return found;
246 }
247
248
249 //
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.
253 //
254 void BundleDiskRep::createMeta()
255 {
256 string meta = metaPath(NULL);
257 if (!mMetaExists) {
258 if (::mkdir(meta.c_str(), 0755) == 0) {
259 copyfile(cfStringRelease(copyCanonicalPath()).c_str(), meta.c_str(), NULL, COPYFILE_SECURITY);
260 mMetaPath = meta;
261 mMetaExists = true;
262 } else if (errno != EEXIST)
263 UnixError::throwMe();
264 }
265 }
266
267
268 //
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.
271 //
272 string BundleDiskRep::metaPath(const char *name)
273 {
274 if (mMetaPath.empty()) {
275 string support = cfStringRelease(CFBundleCopySupportFilesDirectoryURL(mBundle));
276 mMetaPath = support + "/" BUNDLEDISKREP_DIRECTORY;
277 mMetaExists = ::access(mMetaPath.c_str(), F_OK) == 0;
278 }
279 if (name)
280 return mMetaPath + "/" + name;
281 else
282 return mMetaPath;
283 }
284
285 CFDataRef BundleDiskRep::metaData(const char *name)
286 {
287 if (CFRef<CFURLRef> url = makeCFURL(metaPath(name))) {
288 return cfLoadFile(url);
289 } else {
290 secnotice("bundlediskrep", "no metapath for %s", name);
291 return NULL;
292 }
293 }
294
295 CFDataRef BundleDiskRep::metaData(CodeDirectory::SpecialSlot slot)
296 {
297 if (const char *name = CodeDirectory::canonicalSlotName(slot))
298 return metaData(name);
299 else
300 return NULL;
301 }
302
303
304
305 //
306 // Load's a CFURL and makes sure that it is a regular file and not a symlink (or fifo, etc.)
307 //
308 CFDataRef BundleDiskRep::loadRegularFile(CFURLRef url)
309 {
310 assert(url);
311
312 CFDataRef data = NULL;
313
314 std::string path(cfString(url));
315
316 AutoFileDesc fd(path);
317
318 checkPlainFile(fd, path);
319
320 data = cfLoadFile(fd, fd.fileSize());
321
322 if (!data) {
323 secinfo("bundlediskrep", "failed to load %s", cfString(url).c_str());
324 MacOSError::throwMe(errSecCSInvalidSymlink);
325 }
326
327 return data;
328 }
329
330 //
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).
338 //
339 CFDataRef BundleDiskRep::component(CodeDirectory::SpecialSlot slot)
340 {
341 switch (slot) {
342 // the Info.plist comes from the magic CFBundle-indicated place and ONLY from there
343 case cdInfoSlot:
344 if (CFRef<CFURLRef> info = _CFBundleCopyInfoPlistURL(mBundle))
345 return loadRegularFile(info);
346 else
347 return NULL;
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)
352 default:
353 if (CFRef<CFDataRef> data = mExecRep->component(slot)) {
354 componentFromExec(true);
355 return data.yield();
356 }
357 if (CFRef<CFDataRef> data = metaData(slot)) {
358 componentFromExec(false);
359 mUsedComponents.insert(slot);
360 return data.yield();
361 }
362 return NULL;
363 }
364 }
365
366 BundleDiskRep::RawComponentMap BundleDiskRep::createRawComponents()
367 {
368 RawComponentMap map;
369
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.
373 */
374 int const slots[] = {
375 cdCodeDirectorySlot, cdSignatureSlot, cdResourceDirSlot,
376 cdTopDirectorySlot, cdEntitlementSlot, cdEntitlementDERSlot,
377 cdRepSpecificSlot};
378
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.
387 */
388 CFRef<CFDataRef> data = metaData(slot);
389
390 if (data) {
391 map[slot] = data;
392 }
393 }
394
395 for (CodeDirectory::Slot slot = cdAlternateCodeDirectorySlots; slot < cdAlternateCodeDirectoryLimit; ++slot) {
396 CFRef<CFDataRef> data = metaData(slot);
397
398 if (data) {
399 map[slot] = data;
400 }
401 }
402
403 return map;
404 }
405
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)
409 {
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);
417 }
418 }
419
420
421 //
422 // The binary identifier is taken directly from the main executable.
423 //
424 CFDataRef BundleDiskRep::identification()
425 {
426 return mExecRep->identification();
427 }
428
429
430 //
431 // Various aspects of our DiskRep personality.
432 //
433 CFURLRef BundleDiskRep::copyCanonicalPath()
434 {
435 if (CFURLRef url = CFBundleCopyBundleURL(mBundle))
436 return url;
437 CFError::throwMe();
438 }
439
440 string BundleDiskRep::mainExecutablePath()
441 {
442 return cfString(mMainExecutableURL);
443 }
444
445 string BundleDiskRep::resourcesRootPath()
446 {
447 return cfStringRelease(CFBundleCopySupportFilesDirectoryURL(mBundle));
448 }
449
450 void BundleDiskRep::adjustResources(ResourceBuilder &builder)
451 {
452 // exclude entire contents of meta directory
453 builder.addExclusion("^" BUNDLEDISKREP_DIRECTORY "$");
454 builder.addExclusion("^" CODERESOURCES_LINK "$"); // ancient-ish symlink into it
455
456 // exclude the store manifest directory
457 builder.addExclusion("^" STORE_RECEIPT_DIRECTORY "$");
458
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);
468 }
469
470
471
472 Universal *BundleDiskRep::mainExecutableImage()
473 {
474 return mExecRep->mainExecutableImage();
475 }
476
477 void BundleDiskRep::prepareForSigning(SigningContext &context)
478 {
479 return mExecRep->prepareForSigning(context);
480 }
481
482 size_t BundleDiskRep::signingBase()
483 {
484 return mExecRep->signingBase();
485 }
486
487 size_t BundleDiskRep::signingLimit()
488 {
489 return mExecRep->signingLimit();
490 }
491
492 size_t BundleDiskRep::execSegBase(const Architecture *arch)
493 {
494 return mExecRep->execSegBase(arch);
495 }
496
497 size_t BundleDiskRep::execSegLimit(const Architecture *arch)
498 {
499 return mExecRep->execSegLimit(arch);
500 }
501
502 string BundleDiskRep::format()
503 {
504 return mFormat;
505 }
506
507 CFArrayRef BundleDiskRep::modifiedFiles()
508 {
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();
521 }
522
523 void BundleDiskRep::checkModifiedFile(CFMutableArrayRef files, CodeDirectory::SpecialSlot slot)
524 {
525 if (CFDataRef data = mExecRep->component(slot)) // provided by executable file
526 CFRelease(data);
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));
531 }
532 }
533
534 FileDesc &BundleDiskRep::fd()
535 {
536 return mExecRep->fd();
537 }
538
539 void BundleDiskRep::flush()
540 {
541 mExecRep->flush();
542 }
543
544 CFDictionaryRef BundleDiskRep::diskRepInformation()
545 {
546 return mExecRep->diskRepInformation();
547 }
548
549 //
550 // Defaults for signing operations
551 //
552 string BundleDiskRep::recommendedIdentifier(const SigningContext &)
553 {
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);
559
560 // fall back to using the canonical path
561 return canonicalIdentifier(cfStringRelease(this->copyCanonicalPath()));
562 }
563
564 string BundleDiskRep::resourcesRelativePath()
565 {
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("/./");
572 }
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
575
576 // find the resources directory relative to the resource base
577 string resources = cfStringRelease(CFBundleCopyResourcesDirectoryURL(mBundle));
578 if (resources == rbase)
579 resources = "";
580 else if (resources.compare(0, rbase.length(), rbase, 0, rbase.length()) != 0) // Resources not in resource root
581 MacOSError::throwMe(errSecCSBadBundleFormat);
582 else
583 resources = resources.substr(rbase.length() + 1) + "/"; // differential path segment
584
585 return resources;
586 }
587
588 CFDictionaryRef BundleDiskRep::defaultResourceRules(const SigningContext &ctx)
589 {
590 string resources = this->resourcesRelativePath();
591
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)
598 "}}",
599 (string("^") + resources + ".*\\.lproj/").c_str()
600 );
601
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
609 "}}",
610 (string("^") + resources).c_str(),
611 (string("^") + resources + ".*\\.lproj/").c_str(),
612 (string("^") + resources + ".*\\.lproj/locversion.plist$").c_str()
613 );
614
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
620 "}}");
621
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
631 "},rules2={"
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
645 "}}",
646
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(),
651
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()
656 );
657 } else {
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. */
660
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. */
666
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
674 "},rules2={"
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
685 "}}"
686 );
687 }
688 }
689
690
691 CFArrayRef BundleDiskRep::allowedResourceOmissions()
692 {
693 return cfmake<CFArrayRef>("["
694 "'^(.*/)?\\.DS_Store$'"
695 "'^Info\\.plist$'"
696 "'^PkgInfo$'"
697 "%s"
698 "]",
699 (string("^") + this->resourcesRelativePath() + ".*\\.lproj/locversion.plist$").c_str()
700 );
701 }
702
703
704 const Requirements *BundleDiskRep::defaultRequirements(const Architecture *arch, const SigningContext &ctx)
705 {
706 return mExecRep->defaultRequirements(arch, ctx);
707 }
708
709 size_t BundleDiskRep::pageSize(const SigningContext &ctx)
710 {
711 return mExecRep->pageSize(ctx);
712 }
713
714
715 //
716 // Strict validation.
717 // Takes an array of CFNumbers of errors to tolerate.
718 //
719 void BundleDiskRep::strictValidate(const CodeDirectory* cd, const ToleratedErrors& tolerated, SecCSFlags flags)
720 {
721 strictValidateStructure(cd, tolerated, flags);
722
723 // now strict-check the main executable (which won't be an app-like object)
724 mExecRep->strictValidate(cd, tolerated, flags & ~kSecCSRestrictToAppLike);
725 }
726
727 void BundleDiskRep::strictValidateStructure(const CodeDirectory* cd, const ToleratedErrors& tolerated, SecCSFlags flags)
728 {
729 // scan our metadirectory (_CodeSignature) for unwanted guests
730 if (!(flags & kSecCSQuickCheck))
731 validateMetaDirectory(cd);
732
733 // check accumulated strict errors and report them
734 if (!(flags & kSecCSRestrictSidebandData)) // tolerate resource forks etc.
735 mStrictErrors.erase(errSecCSInvalidAssociatedFileData);
736
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]);
741
742 // if app focus is requested and this doesn't look like an app, fail - but allow whitelist overrides
743 if (flags & kSecCSRestrictToAppLike)
744 if (!mAppLike)
745 if (tolerated.find(kSecCSRestrictToAppLike) == tolerated.end())
746 MacOSError::throwMe(errSecCSNotAppLike);
747 }
748
749 void BundleDiskRep::recordStrictError(OSStatus error)
750 {
751 mStrictErrors.insert(error);
752 }
753
754
755 void BundleDiskRep::validateMetaDirectory(const CodeDirectory* cd)
756 {
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);
760
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) {
764 switch (*it) {
765 case cdInfoSlot:
766 break; // always from Info.plist, not from here
767 default:
768 if (const char *name = CodeDirectory::canonicalSlotName(*it)) {
769 allowedFiles.insert(name);
770 }
771 break;
772 }
773 }
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
785 }
786 // not on list of needed files; it's a freeloading rogue!
787 recordStrictError(errSecCSUnsealedAppRoot); // funnel through strict set so GKOpaque can override it
788 }
789 }
790 }
791 }
792
793
794 //
795 // Check framework root for unsafe symlinks and unsealed content.
796 //
797 void BundleDiskRep::validateFrameworkRoot(string root)
798 {
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);
803 if (len > 0) {
804 currentVersion[len] = '\0';
805 current = string("(Current|") + ResourceBuilder::escapeRE(currentVersion) + ")";
806 }
807
808 DirValidator val;
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) + "$";
817 });
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$");
821
822 try {
823 val.validate(root, errSecCSUnsealedFrameworkRoot);
824 } catch (const MacOSError &err) {
825 recordStrictError(err.error);
826 }
827 }
828
829
830 //
831 // Check a file descriptor for harmlessness. This is a strict check (only).
832 //
833 void BundleDiskRep::checkPlainFile(FileDesc fd, const std::string& path)
834 {
835 if (!fd.isPlainFile(path))
836 recordStrictError(errSecCSRegularFile);
837 checkForks(fd);
838 }
839
840 void BundleDiskRep::checkForks(FileDesc fd)
841 {
842 if (fd.hasExtendedAttribute(XATTR_RESOURCEFORK_NAME) || fd.hasExtendedAttribute(XATTR_FINDERINFO_NAME))
843 recordStrictError(errSecCSInvalidAssociatedFileData);
844 }
845
846
847 //
848 // Writers
849 //
850 DiskRep::Writer *BundleDiskRep::writer()
851 {
852 return new Writer(this);
853 }
854
855 BundleDiskRep::Writer::Writer(BundleDiskRep *r)
856 : rep(r), mMadeMetaDirectory(false)
857 {
858 execWriter = rep->mExecRep->writer();
859 }
860
861
862 //
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.
866 //
867 void BundleDiskRep::Writer::component(CodeDirectory::SpecialSlot slot, CFDataRef data)
868 {
869 switch (slot) {
870 default:
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)) {
877 rep->createMeta();
878 string path = rep->metaPath(name);
879
880 #if TARGET_OS_OSX
881 // determine AFSC status if we are told to preserve compression
882 bool conductCompression = false;
883 cmpInfo cInfo;
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;
890 }
891 }
892 }
893 }
894 #endif
895
896 AutoFileDesc fd(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
897 fd.writeAll(CFDataGetBytePtr(data), CFDataGetLength(data));
898 fd.close();
899
900 #if TARGET_OS_OSX
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);
906 CFRelease(val);
907
908 CompressionQueueContext compressionQueue = CreateCompressionQueue(NULL, NULL, NULL, NULL, options);
909
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);
913 }
914
915 FinishCompressionAndCleanUp(compressionQueue);
916 compressionQueue = NULL;
917 CFRelease(options);
918 }
919 #endif
920
921 mWrittenFiles.insert(name);
922 } else
923 MacOSError::throwMe(errSecCSBadBundleFormat);
924 }
925 }
926
927
928 //
929 // Remove all signature data
930 //
931 void BundleDiskRep::Writer::remove()
932 {
933 // remove signature from the executable
934 execWriter->remove();
935
936 // remove signature files from bundle
937 for (CodeDirectory::SpecialSlot slot = 0; slot < cdSlotCount; slot++)
938 remove(slot);
939 remove(cdSignatureSlot);
940 }
941
942 void BundleDiskRep::Writer::remove(CodeDirectory::SpecialSlot slot)
943 {
944 if (const char *name = CodeDirectory::canonicalSlotName(slot))
945 if (::unlink(rep->metaPath(name).c_str()))
946 switch (errno) {
947 case ENOENT: // not found - that's okay
948 break;
949 default:
950 UnixError::throwMe();
951 }
952 }
953
954
955 void BundleDiskRep::Writer::flush()
956 {
957 execWriter->flush();
958 purgeMetaDirectory();
959 }
960
961 // purge _CodeSignature of all left-over files from any previous signature
962 void BundleDiskRep::Writer::purgeMetaDirectory()
963 {
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!
970 scan.unlink(ent, 0);
971 }
972 }
973 }
974
975 }
976
977 void BundleDiskRep::registerStapledTicket()
978 {
979 string root = cfStringRelease(copyCanonicalPath());
980 registerStapledTicketInBundle(root);
981 }
982
983 } // end namespace CodeSigning
984 } // end namespace Security