]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_codesigning/lib/bundlediskrep.cpp
Security-58286.251.4.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 = 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 // scan our metadirectory (_CodeSignature) for unwanted guests
722 if (!(flags & kSecCSQuickCheck))
723 validateMetaDirectory(cd);
724
725 // check accumulated strict errors and report them
726 if (!(flags & kSecCSRestrictSidebandData)) // tolerate resource forks etc.
727 mStrictErrors.erase(errSecCSInvalidAssociatedFileData);
728
729 std::vector<OSStatus> fatalErrors;
730 set_difference(mStrictErrors.begin(), mStrictErrors.end(), tolerated.begin(), tolerated.end(), back_inserter(fatalErrors));
731 if (!fatalErrors.empty())
732 MacOSError::throwMe(fatalErrors[0]);
733
734 // if app focus is requested and this doesn't look like an app, fail - but allow whitelist overrides
735 if (flags & kSecCSRestrictToAppLike)
736 if (!mAppLike)
737 if (tolerated.find(kSecCSRestrictToAppLike) == tolerated.end())
738 MacOSError::throwMe(errSecCSNotAppLike);
739
740 // now strict-check the main executable (which won't be an app-like object)
741 mExecRep->strictValidate(cd, tolerated, flags & ~kSecCSRestrictToAppLike);
742 }
743
744 void BundleDiskRep::recordStrictError(OSStatus error)
745 {
746 mStrictErrors.insert(error);
747 }
748
749
750 void BundleDiskRep::validateMetaDirectory(const CodeDirectory* cd)
751 {
752 // we know the resource directory will be checked after this call, so we'll give it a pass here
753 if (cd->slotIsPresent(-cdResourceDirSlot))
754 mUsedComponents.insert(cdResourceDirSlot);
755
756 // make a set of allowed (regular) filenames in this directory
757 std::set<std::string> allowedFiles;
758 for (auto it = mUsedComponents.begin(); it != mUsedComponents.end(); ++it) {
759 switch (*it) {
760 case cdInfoSlot:
761 break; // always from Info.plist, not from here
762 default:
763 if (const char *name = CodeDirectory::canonicalSlotName(*it)) {
764 allowedFiles.insert(name);
765 }
766 break;
767 }
768 }
769 DirScanner scan(mMetaPath);
770 if (scan.initialized()) {
771 while (struct dirent* ent = scan.getNext()) {
772 if (!scan.isRegularFile(ent))
773 MacOSError::throwMe(errSecCSUnsealedAppRoot); // only regular files allowed
774 if (allowedFiles.find(ent->d_name) == allowedFiles.end()) { // not in expected set of files
775 if (strcmp(ent->d_name, kSecCS_SIGNATUREFILE) == 0) {
776 // special case - might be empty and unused (adhoc signature)
777 AutoFileDesc fd(metaPath(kSecCS_SIGNATUREFILE));
778 if (fd.fileSize() == 0)
779 continue; // that's okay, then
780 }
781 // not on list of needed files; it's a freeloading rogue!
782 recordStrictError(errSecCSUnsealedAppRoot); // funnel through strict set so GKOpaque can override it
783 }
784 }
785 }
786 }
787
788
789 //
790 // Check framework root for unsafe symlinks and unsealed content.
791 //
792 void BundleDiskRep::validateFrameworkRoot(string root)
793 {
794 // build regex element that matches either the "Current" symlink, or the name of the current version
795 string current = "Current";
796 char currentVersion[PATH_MAX];
797 ssize_t len = ::readlink((root + "/Versions/Current").c_str(), currentVersion, sizeof(currentVersion)-1);
798 if (len > 0) {
799 currentVersion[len] = '\0';
800 current = string("(Current|") + ResourceBuilder::escapeRE(currentVersion) + ")";
801 }
802
803 DirValidator val;
804 val.require("^Versions$", DirValidator::directory | DirValidator::descend); // descend into Versions directory
805 val.require("^Versions/[^/]+$", DirValidator::directory); // require at least one version
806 val.require("^Versions/Current$", DirValidator::symlink, // require Current symlink...
807 "^(\\./)?(\\.\\.[^/]+|\\.?[^\\./][^/]*)$"); // ...must point to a version
808 val.allow("^(Versions/)?\\.DS_Store$", DirValidator::file | DirValidator::noexec); // allow .DS_Store files
809 val.allow("^[^/]+$", DirValidator::symlink, ^ string (const string &name, const string &target) {
810 // top-level symlinks must point to namesake in current version
811 return string("^(\\./)?Versions/") + current + "/" + ResourceBuilder::escapeRE(name) + "$";
812 });
813 // module.map must be regular non-executable file, or symlink to module.map in current version
814 val.allow("^module\\.map$", DirValidator::file | DirValidator::noexec | DirValidator::symlink,
815 string("^(\\./)?Versions/") + current + "/module\\.map$");
816
817 try {
818 val.validate(root, errSecCSUnsealedFrameworkRoot);
819 } catch (const MacOSError &err) {
820 recordStrictError(err.error);
821 }
822 }
823
824
825 //
826 // Check a file descriptor for harmlessness. This is a strict check (only).
827 //
828 void BundleDiskRep::checkPlainFile(FileDesc fd, const std::string& path)
829 {
830 if (!fd.isPlainFile(path))
831 recordStrictError(errSecCSRegularFile);
832 checkForks(fd);
833 }
834
835 void BundleDiskRep::checkForks(FileDesc fd)
836 {
837 if (fd.hasExtendedAttribute(XATTR_RESOURCEFORK_NAME) || fd.hasExtendedAttribute(XATTR_FINDERINFO_NAME))
838 recordStrictError(errSecCSInvalidAssociatedFileData);
839 }
840
841
842 //
843 // Writers
844 //
845 DiskRep::Writer *BundleDiskRep::writer()
846 {
847 return new Writer(this);
848 }
849
850 BundleDiskRep::Writer::Writer(BundleDiskRep *r)
851 : rep(r), mMadeMetaDirectory(false)
852 {
853 execWriter = rep->mExecRep->writer();
854 }
855
856
857 //
858 // Write a component.
859 // Note that this isn't concerned with Mach-O writing; this is handled at
860 // a much higher level. If we're called, we write to a file in the Bundle's meta directory.
861 //
862 void BundleDiskRep::Writer::component(CodeDirectory::SpecialSlot slot, CFDataRef data)
863 {
864 switch (slot) {
865 default:
866 if (!execWriter->attribute(writerLastResort)) // willing to take the data...
867 return execWriter->component(slot, data); // ... so hand it through
868 // execWriter doesn't want the data; store it as a resource file (below)
869 case cdResourceDirSlot:
870 // the resource directory always goes into a bundle file
871 if (const char *name = CodeDirectory::canonicalSlotName(slot)) {
872 rep->createMeta();
873 string path = rep->metaPath(name);
874
875 #if TARGET_OS_OSX
876 // determine AFSC status if we are told to preserve compression
877 bool conductCompression = false;
878 cmpInfo cInfo;
879 if (this->getPreserveAFSC()) {
880 struct stat statBuffer;
881 if (stat(path.c_str(), &statBuffer) == 0) {
882 if (queryCompressionInfo(path.c_str(), &cInfo) == 0) {
883 if (cInfo.compressionType != 0 && cInfo.compressedSize > 0) {
884 conductCompression = true;
885 }
886 }
887 }
888 }
889 #endif
890
891 AutoFileDesc fd(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
892 fd.writeAll(CFDataGetBytePtr(data), CFDataGetLength(data));
893 fd.close();
894
895 #if TARGET_OS_OSX
896 // if the original file was compressed, compress the new file after move
897 if (conductCompression) {
898 CFMutableDictionaryRef options = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
899 CFStringRef val = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%d"), cInfo.compressionType);
900 CFDictionarySetValue(options, kAFSCCompressionTypes, val);
901 CFRelease(val);
902
903 CompressionQueueContext compressionQueue = CreateCompressionQueue(NULL, NULL, NULL, NULL, options);
904
905 if (!CompressFile(compressionQueue, path.c_str(), NULL)) {
906 secinfo("bundlediskrep", "%p Failed to queue compression of file %s", this, path.c_str());
907 MacOSError::throwMe(errSecCSInternalError);
908 }
909
910 FinishCompressionAndCleanUp(compressionQueue);
911 compressionQueue = NULL;
912 CFRelease(options);
913 }
914 #endif
915
916 mWrittenFiles.insert(name);
917 } else
918 MacOSError::throwMe(errSecCSBadBundleFormat);
919 }
920 }
921
922
923 //
924 // Remove all signature data
925 //
926 void BundleDiskRep::Writer::remove()
927 {
928 // remove signature from the executable
929 execWriter->remove();
930
931 // remove signature files from bundle
932 for (CodeDirectory::SpecialSlot slot = 0; slot < cdSlotCount; slot++)
933 remove(slot);
934 remove(cdSignatureSlot);
935 }
936
937 void BundleDiskRep::Writer::remove(CodeDirectory::SpecialSlot slot)
938 {
939 if (const char *name = CodeDirectory::canonicalSlotName(slot))
940 if (::unlink(rep->metaPath(name).c_str()))
941 switch (errno) {
942 case ENOENT: // not found - that's okay
943 break;
944 default:
945 UnixError::throwMe();
946 }
947 }
948
949
950 void BundleDiskRep::Writer::flush()
951 {
952 execWriter->flush();
953 purgeMetaDirectory();
954 }
955
956 // purge _CodeSignature of all left-over files from any previous signature
957 void BundleDiskRep::Writer::purgeMetaDirectory()
958 {
959 DirScanner scan(rep->mMetaPath);
960 if (scan.initialized()) {
961 while (struct dirent* ent = scan.getNext()) {
962 if (!scan.isRegularFile(ent))
963 MacOSError::throwMe(errSecCSUnsealedAppRoot); // only regular files allowed
964 if (mWrittenFiles.find(ent->d_name) == mWrittenFiles.end()) { // we didn't write this!
965 scan.unlink(ent, 0);
966 }
967 }
968 }
969
970 }
971
972 void BundleDiskRep::registerStapledTicket()
973 {
974 string root = cfStringRelease(copyCanonicalPath());
975 registerStapledTicketInBundle(root);
976 }
977
978 } // end namespace CodeSigning
979 } // end namespace Security