]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_codesigning/lib/bundlediskrep.cpp
Security-58286.70.7.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 <CoreFoundation/CFBundlePriv.h>
27 #include <CoreFoundation/CFURLAccess.h>
28 #include <CoreFoundation/CFBundlePriv.h>
29 #include <security_utilities/cfmunge.h>
30 #include <copyfile.h>
31 #include <fts.h>
32 #include <sstream>
33
34 namespace Security {
35 namespace CodeSigning {
36
37 using namespace UnixPlusPlus;
38
39
40 //
41 // Local helpers
42 //
43 static std::string findDistFile(const std::string &directory);
44
45
46 //
47 // We make a CFBundleRef immediately, but everything else is lazy
48 //
49 BundleDiskRep::BundleDiskRep(const char *path, const Context *ctx)
50 : mBundle(_CFBundleCreateUnique(NULL, CFTempURL(path)))
51 {
52 if (!mBundle)
53 MacOSError::throwMe(errSecCSBadBundleFormat);
54 setup(ctx);
55 CODESIGN_DISKREP_CREATE_BUNDLE_PATH(this, (char*)path, (void*)ctx, mExecRep);
56 }
57
58 BundleDiskRep::BundleDiskRep(CFBundleRef ref, const Context *ctx)
59 {
60 mBundle = ref; // retains
61 setup(ctx);
62 CODESIGN_DISKREP_CREATE_BUNDLE_REF(this, ref, (void*)ctx, mExecRep);
63 }
64
65 BundleDiskRep::~BundleDiskRep()
66 {
67 }
68
69 void BundleDiskRep::checkMoved(CFURLRef oldPath, CFURLRef newPath)
70 {
71 char cOld[PATH_MAX];
72 char cNew[PATH_MAX];
73 // The realpath call is important because alot of Framework bundles have a symlink
74 // to their "Current" version binary in the main bundle
75 if (realpath(cfString(oldPath).c_str(), cOld) == NULL ||
76 realpath(cfString(newPath).c_str(), cNew) == NULL)
77 MacOSError::throwMe(errSecCSAmbiguousBundleFormat);
78
79 if (strcmp(cOld, cNew) != 0)
80 recordStrictError(errSecCSAmbiguousBundleFormat);
81 }
82
83 // common construction code
84 void BundleDiskRep::setup(const Context *ctx)
85 {
86 mComponentsFromExecValid = false; // not yet known
87 mInstallerPackage = false; // default
88 mAppLike = false; // pessimism first
89 bool appDisqualified = false; // found reason to disqualify as app
90
91 // capture the path of the main executable before descending into a specific version
92 CFRef<CFURLRef> mainExecBefore = CFBundleCopyExecutableURL(mBundle);
93 CFRef<CFURLRef> infoPlistBefore = _CFBundleCopyInfoPlistURL(mBundle);
94
95 // validate the bundle root; fish around for the desired framework version
96 string root = cfStringRelease(copyCanonicalPath());
97 if (filehasExtendedAttribute(root, XATTR_FINDERINFO_NAME))
98 recordStrictError(errSecCSInvalidAssociatedFileData);
99 string contents = root + "/Contents";
100 string supportFiles = root + "/Support Files";
101 string version = root + "/Versions/"
102 + ((ctx && ctx->version) ? ctx->version : "Current")
103 + "/.";
104 if (::access(contents.c_str(), F_OK) == 0) { // not shallow
105 DirValidator val;
106 val.require("^Contents$", DirValidator::directory); // duh
107 val.allow("^(\\.LSOverride|\\.DS_Store|Icon\r|\\.SoftwareDepot\\.tracking)$", DirValidator::file | DirValidator::noexec);
108 try {
109 val.validate(root, errSecCSUnsealedAppRoot);
110 } catch (const MacOSError &err) {
111 recordStrictError(err.error);
112 }
113 } else if (::access(supportFiles.c_str(), F_OK) == 0) { // ancient legacy boondoggle bundle
114 // treat like a shallow bundle; do not allow Versions arbitration
115 appDisqualified = true;
116 } else if (::access(version.c_str(), F_OK) == 0) { // versioned bundle
117 if (CFBundleRef versionBundle = _CFBundleCreateUnique(NULL, CFTempURL(version)))
118 mBundle.take(versionBundle); // replace top bundle ref
119 else
120 MacOSError::throwMe(errSecCSStaticCodeNotFound);
121 appDisqualified = true;
122 validateFrameworkRoot(root);
123 } else {
124 if (ctx && ctx->version) // explicitly specified
125 MacOSError::throwMe(errSecCSStaticCodeNotFound);
126 }
127
128 CFDictionaryRef infoDict = CFBundleGetInfoDictionary(mBundle);
129 assert(infoDict); // CFBundle will always make one up for us
130 CFTypeRef mainHTML = CFDictionaryGetValue(infoDict, CFSTR("MainHTML"));
131 CFTypeRef packageVersion = CFDictionaryGetValue(infoDict, CFSTR("IFMajorVersion"));
132
133 // conventional executable bundle: CFBundle identifies an executable for us
134 if (CFRef<CFURLRef> mainExec = CFBundleCopyExecutableURL(mBundle)) // if CFBundle claims an executable...
135 if (mainHTML == NULL) { // ... and it's not a widget
136
137 // Note that this check is skipped if there is a specific framework version checked.
138 // That's because you know what you are doing if you are looking at a specific version.
139 // This check is designed to stop someone who did a verification on an app root, from mistakenly
140 // verifying a framework
141 if (!ctx || !ctx->version) {
142 if (mainExecBefore)
143 checkMoved(mainExecBefore, mainExec);
144 if (infoPlistBefore)
145 if (CFRef<CFURLRef> infoDictPath = _CFBundleCopyInfoPlistURL(mBundle))
146 checkMoved(infoPlistBefore, infoDictPath);
147 }
148
149 mMainExecutableURL = mainExec;
150 mExecRep = DiskRep::bestFileGuess(this->mainExecutablePath(), ctx);
151 checkPlainFile(mExecRep->fd(), this->mainExecutablePath());
152 CFDictionaryRef infoDict = CFBundleGetInfoDictionary(mBundle);
153 bool isAppBundle = false;
154 if (infoDict)
155 if (CFTypeRef packageType = CFDictionaryGetValue(infoDict, CFSTR("CFBundlePackageType")))
156 if (CFEqual(packageType, CFSTR("APPL")))
157 isAppBundle = true;
158 mFormat = "bundle with " + mExecRep->format();
159 if (isAppBundle)
160 mFormat = "app " + mFormat;
161 mAppLike = isAppBundle && !appDisqualified;
162 return;
163 }
164
165 // widget
166 if (mainHTML) {
167 if (CFGetTypeID(mainHTML) != CFStringGetTypeID())
168 MacOSError::throwMe(errSecCSBadBundleFormat);
169 mMainExecutableURL.take(makeCFURL(cfString(CFStringRef(mainHTML)), false,
170 CFRef<CFURLRef>(CFBundleCopySupportFilesDirectoryURL(mBundle))));
171 if (!mMainExecutableURL)
172 MacOSError::throwMe(errSecCSBadBundleFormat);
173 mExecRep = new FileDiskRep(this->mainExecutablePath().c_str());
174 checkPlainFile(mExecRep->fd(), this->mainExecutablePath());
175 mFormat = "widget bundle";
176 mAppLike = true;
177 return;
178 }
179
180 // do we have a real Info.plist here?
181 if (CFRef<CFURLRef> infoURL = _CFBundleCopyInfoPlistURL(mBundle)) {
182 // focus on the Info.plist (which we know exists) as the nominal "main executable" file
183 mMainExecutableURL = infoURL;
184 mExecRep = new FileDiskRep(this->mainExecutablePath().c_str());
185 checkPlainFile(mExecRep->fd(), this->mainExecutablePath());
186 if (packageVersion) {
187 mInstallerPackage = true;
188 mFormat = "installer package bundle";
189 } else {
190 mFormat = "bundle";
191 }
192 return;
193 }
194
195 // we're getting desperate here. Perhaps an oldish-style installer package? Look for a *.dist file
196 std::string distFile = findDistFile(this->resourcesRootPath());
197 if (!distFile.empty()) {
198 mMainExecutableURL = makeCFURL(distFile);
199 mExecRep = new FileDiskRep(this->mainExecutablePath().c_str());
200 checkPlainFile(mExecRep->fd(), this->mainExecutablePath());
201 mInstallerPackage = true;
202 mFormat = "installer package bundle";
203 return;
204 }
205
206 // this bundle cannot be signed
207 MacOSError::throwMe(errSecCSBadBundleFormat);
208 }
209
210
211 //
212 // Return the full path to the one-and-only file named something.dist in a directory.
213 // Return empty string if none; throw an exception if multiple. Do not descend into subdirectories.
214 //
215 static std::string findDistFile(const std::string &directory)
216 {
217 std::string found;
218 char *paths[] = {(char *)directory.c_str(), NULL};
219 FTS *fts = fts_open(paths, FTS_PHYSICAL | FTS_NOCHDIR | FTS_NOSTAT, NULL);
220 bool root = true;
221 while (FTSENT *ent = fts_read(fts)) {
222 switch (ent->fts_info) {
223 case FTS_F:
224 case FTS_NSOK:
225 if (!strcmp(ent->fts_path + ent->fts_pathlen - 5, ".dist")) { // found plain file foo.dist
226 if (found.empty()) // first found
227 found = ent->fts_path;
228 else // multiple *.dist files (bad)
229 MacOSError::throwMe(errSecCSBadBundleFormat);
230 }
231 break;
232 case FTS_D:
233 if (!root)
234 fts_set(fts, ent, FTS_SKIP); // don't descend
235 root = false;
236 break;
237 default:
238 break;
239 }
240 }
241 fts_close(fts);
242 return found;
243 }
244
245
246 //
247 // Try to create the meta-file directory in our bundle.
248 // Does nothing if the directory already exists.
249 // Throws if an error occurs.
250 //
251 void BundleDiskRep::createMeta()
252 {
253 string meta = metaPath(NULL);
254 if (!mMetaExists) {
255 if (::mkdir(meta.c_str(), 0755) == 0) {
256 copyfile(cfStringRelease(copyCanonicalPath()).c_str(), meta.c_str(), NULL, COPYFILE_SECURITY);
257 mMetaPath = meta;
258 mMetaExists = true;
259 } else if (errno != EEXIST)
260 UnixError::throwMe();
261 }
262 }
263
264
265 //
266 // Create a path to a bundle signing resource, by name.
267 // This is in the BUNDLEDISKREP_DIRECTORY directory in the bundle's support directory.
268 //
269 string BundleDiskRep::metaPath(const char *name)
270 {
271 if (mMetaPath.empty()) {
272 string support = cfStringRelease(CFBundleCopySupportFilesDirectoryURL(mBundle));
273 mMetaPath = support + "/" BUNDLEDISKREP_DIRECTORY;
274 mMetaExists = ::access(mMetaPath.c_str(), F_OK) == 0;
275 }
276 if (name)
277 return mMetaPath + "/" + name;
278 else
279 return mMetaPath;
280 }
281
282 CFDataRef BundleDiskRep::metaData(const char *name)
283 {
284 if (CFRef<CFURLRef> url = makeCFURL(metaPath(name))) {
285 return cfLoadFile(url);
286 } else {
287 secnotice("bundlediskrep", "no metapath for %s", name);
288 return NULL;
289 }
290 }
291
292 CFDataRef BundleDiskRep::metaData(CodeDirectory::SpecialSlot slot)
293 {
294 if (const char *name = CodeDirectory::canonicalSlotName(slot))
295 return metaData(name);
296 else
297 return NULL;
298 }
299
300
301
302 //
303 // Load's a CFURL and makes sure that it is a regular file and not a symlink (or fifo, etc.)
304 //
305 CFDataRef BundleDiskRep::loadRegularFile(CFURLRef url)
306 {
307 assert(url);
308
309 CFDataRef data = NULL;
310
311 std::string path(cfString(url));
312
313 AutoFileDesc fd(path);
314
315 checkPlainFile(fd, path);
316
317 data = cfLoadFile(fd, fd.fileSize());
318
319 if (!data) {
320 secinfo("bundlediskrep", "failed to load %s", cfString(url).c_str());
321 MacOSError::throwMe(errSecCSInvalidSymlink);
322 }
323
324 return data;
325 }
326
327 //
328 // Load and return a component, by slot number.
329 // Info.plist components come from the bundle, always (we don't look
330 // for Mach-O embedded versions).
331 // ResourceDirectory always comes from bundle files.
332 // Everything else comes from the embedded blobs of a Mach-O image, or from
333 // files located in the Contents directory of the bundle; but we must be consistent
334 // (no half-and-half situations).
335 //
336 CFDataRef BundleDiskRep::component(CodeDirectory::SpecialSlot slot)
337 {
338 switch (slot) {
339 // the Info.plist comes from the magic CFBundle-indicated place and ONLY from there
340 case cdInfoSlot:
341 if (CFRef<CFURLRef> info = _CFBundleCopyInfoPlistURL(mBundle))
342 return loadRegularFile(info);
343 else
344 return NULL;
345 case cdResourceDirSlot:
346 mUsedComponents.insert(slot);
347 return metaData(slot);
348 // by default, we take components from the executable image or files (but not both)
349 default:
350 if (CFRef<CFDataRef> data = mExecRep->component(slot)) {
351 componentFromExec(true);
352 return data.yield();
353 }
354 if (CFRef<CFDataRef> data = metaData(slot)) {
355 componentFromExec(false);
356 mUsedComponents.insert(slot);
357 return data.yield();
358 }
359 return NULL;
360 }
361 }
362
363
364 // Check that all components of this BundleDiskRep come from either the main
365 // executable or the _CodeSignature directory (not mix-and-match).
366 void BundleDiskRep::componentFromExec(bool fromExec)
367 {
368 if (!mComponentsFromExecValid) {
369 // first use; set latch
370 mComponentsFromExecValid = true;
371 mComponentsFromExec = fromExec;
372 } else if (mComponentsFromExec != fromExec) {
373 // subsequent use: check latch
374 MacOSError::throwMe(errSecCSSignatureFailed);
375 }
376 }
377
378
379 //
380 // The binary identifier is taken directly from the main executable.
381 //
382 CFDataRef BundleDiskRep::identification()
383 {
384 return mExecRep->identification();
385 }
386
387
388 //
389 // Various aspects of our DiskRep personality.
390 //
391 CFURLRef BundleDiskRep::copyCanonicalPath()
392 {
393 if (CFURLRef url = CFBundleCopyBundleURL(mBundle))
394 return url;
395 CFError::throwMe();
396 }
397
398 string BundleDiskRep::mainExecutablePath()
399 {
400 return cfString(mMainExecutableURL);
401 }
402
403 string BundleDiskRep::resourcesRootPath()
404 {
405 return cfStringRelease(CFBundleCopySupportFilesDirectoryURL(mBundle));
406 }
407
408 void BundleDiskRep::adjustResources(ResourceBuilder &builder)
409 {
410 // exclude entire contents of meta directory
411 builder.addExclusion("^" BUNDLEDISKREP_DIRECTORY "$");
412 builder.addExclusion("^" CODERESOURCES_LINK "$"); // ancient-ish symlink into it
413
414 // exclude the store manifest directory
415 builder.addExclusion("^" STORE_RECEIPT_DIRECTORY "$");
416
417 // exclude the main executable file
418 string resources = resourcesRootPath();
419 if (resources.compare(resources.size() - 2, 2, "/.") == 0) // chop trailing /.
420 resources = resources.substr(0, resources.size()-2);
421 string executable = mainExecutablePath();
422 if (!executable.compare(0, resources.length(), resources, 0, resources.length())
423 && executable[resources.length()] == '/') // is proper directory prefix
424 builder.addExclusion(string("^")
425 + ResourceBuilder::escapeRE(executable.substr(resources.length()+1)) + "$", ResourceBuilder::softTarget);
426 }
427
428
429
430 Universal *BundleDiskRep::mainExecutableImage()
431 {
432 return mExecRep->mainExecutableImage();
433 }
434
435 void BundleDiskRep::prepareForSigning(SigningContext &context)
436 {
437 return mExecRep->prepareForSigning(context);
438 }
439
440 size_t BundleDiskRep::signingBase()
441 {
442 return mExecRep->signingBase();
443 }
444
445 size_t BundleDiskRep::signingLimit()
446 {
447 return mExecRep->signingLimit();
448 }
449
450 size_t BundleDiskRep::execSegBase(const Architecture *arch)
451 {
452 return mExecRep->execSegBase(arch);
453 }
454
455 size_t BundleDiskRep::execSegLimit(const Architecture *arch)
456 {
457 return mExecRep->execSegLimit(arch);
458 }
459
460 string BundleDiskRep::format()
461 {
462 return mFormat;
463 }
464
465 CFArrayRef BundleDiskRep::modifiedFiles()
466 {
467 CFRef<CFArrayRef> execFiles = mExecRep->modifiedFiles();
468 CFRef<CFMutableArrayRef> files = CFArrayCreateMutableCopy(NULL, 0, execFiles);
469 checkModifiedFile(files, cdCodeDirectorySlot);
470 checkModifiedFile(files, cdSignatureSlot);
471 checkModifiedFile(files, cdResourceDirSlot);
472 checkModifiedFile(files, cdTopDirectorySlot);
473 checkModifiedFile(files, cdEntitlementSlot);
474 checkModifiedFile(files, cdEntitlementDERSlot);
475 checkModifiedFile(files, cdRepSpecificSlot);
476 for (CodeDirectory::Slot slot = cdAlternateCodeDirectorySlots; slot < cdAlternateCodeDirectoryLimit; ++slot)
477 checkModifiedFile(files, slot);
478 return files.yield();
479 }
480
481 void BundleDiskRep::checkModifiedFile(CFMutableArrayRef files, CodeDirectory::SpecialSlot slot)
482 {
483 if (CFDataRef data = mExecRep->component(slot)) // provided by executable file
484 CFRelease(data);
485 else if (const char *resourceName = CodeDirectory::canonicalSlotName(slot)) {
486 string file = metaPath(resourceName);
487 if (::access(file.c_str(), F_OK) == 0)
488 CFArrayAppendValue(files, CFTempURL(file));
489 }
490 }
491
492 FileDesc &BundleDiskRep::fd()
493 {
494 return mExecRep->fd();
495 }
496
497 void BundleDiskRep::flush()
498 {
499 mExecRep->flush();
500 }
501
502 CFDictionaryRef BundleDiskRep::diskRepInformation()
503 {
504 return mExecRep->diskRepInformation();
505 }
506
507 //
508 // Defaults for signing operations
509 //
510 string BundleDiskRep::recommendedIdentifier(const SigningContext &)
511 {
512 if (CFStringRef identifier = CFBundleGetIdentifier(mBundle))
513 return cfString(identifier);
514 if (CFDictionaryRef infoDict = CFBundleGetInfoDictionary(mBundle))
515 if (CFStringRef identifier = CFStringRef(CFDictionaryGetValue(infoDict, kCFBundleNameKey)))
516 return cfString(identifier);
517
518 // fall back to using the canonical path
519 return canonicalIdentifier(cfStringRelease(this->copyCanonicalPath()));
520 }
521
522 string BundleDiskRep::resourcesRelativePath()
523 {
524 // figure out the resource directory base. Clean up some gunk inserted by CFBundle in frameworks
525 string rbase = this->resourcesRootPath();
526 size_t pos = rbase.find("/./"); // gratuitously inserted by CFBundle in some frameworks
527 while (pos != std::string::npos) {
528 rbase = rbase.replace(pos, 2, "", 0);
529 pos = rbase.find("/./");
530 }
531 if (rbase.substr(rbase.length()-2, 2) == "/.") // produced by versioned bundle implicit "Current" case
532 rbase = rbase.substr(0, rbase.length()-2); // ... so take it off for this
533
534 // find the resources directory relative to the resource base
535 string resources = cfStringRelease(CFBundleCopyResourcesDirectoryURL(mBundle));
536 if (resources == rbase)
537 resources = "";
538 else if (resources.compare(0, rbase.length(), rbase, 0, rbase.length()) != 0) // Resources not in resource root
539 MacOSError::throwMe(errSecCSBadBundleFormat);
540 else
541 resources = resources.substr(rbase.length() + 1) + "/"; // differential path segment
542
543 return resources;
544 }
545
546 CFDictionaryRef BundleDiskRep::defaultResourceRules(const SigningContext &ctx)
547 {
548 string resources = this->resourcesRelativePath();
549
550 // installer package rules
551 if (mInstallerPackage)
552 return cfmake<CFDictionaryRef>("{rules={"
553 "'^.*' = #T" // include everything, but...
554 "%s = {optional=#T, weight=1000}" // make localizations optional
555 "'^.*/.*\\.pkg/' = {omit=#T, weight=10000}" // and exclude all nested packages (by name)
556 "}}",
557 (string("^") + resources + ".*\\.lproj/").c_str()
558 );
559
560 // old (V1) executable bundle rules - compatible with before
561 if (ctx.signingFlags() & kSecCSSignV1) // *** must be exactly the same as before ***
562 return cfmake<CFDictionaryRef>("{rules={"
563 "'^version.plist$' = #T" // include version.plist
564 "%s = #T" // include Resources
565 "%s = {optional=#T, weight=1000}" // make localizations optional
566 "%s = {omit=#T, weight=1100}" // exclude all locversion.plist files
567 "}}",
568 (string("^") + resources).c_str(),
569 (string("^") + resources + ".*\\.lproj/").c_str(),
570 (string("^") + resources + ".*\\.lproj/locversion.plist$").c_str()
571 );
572
573 // FMJ (everything is a resource) rules
574 if (ctx.signingFlags() & kSecCSSignOpaque) // Full Metal Jacket - everything is a resource file
575 return cfmake<CFDictionaryRef>("{rules={"
576 "'^.*' = #T" // everything is a resource
577 "'^Info\\.plist$' = {omit=#T,weight=10}" // explicitly exclude this for backward compatibility
578 "}}");
579
580 // new (V2) executable bundle rules
581 return cfmake<CFDictionaryRef>("{" // *** the new (V2) world ***
582 "rules={" // old (V1; legacy) version
583 "'^version.plist$' = #T" // include version.plist
584 "%s = #T" // include Resources
585 "%s = {optional=#T, weight=1000}" // make localizations optional
586 "%s = {weight=1010}" // ... except for Base.lproj which really isn't optional at all
587 "%s = {omit=#T, weight=1100}" // exclude all locversion.plist files
588 "},rules2={"
589 "'^.*' = #T" // include everything as a resource, with the following exceptions
590 "'^[^/]+$' = {nested=#T, weight=10}" // files directly in Contents
591 "'^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/' = {nested=#T, weight=10}" // dynamic repositories
592 "'.*\\.dSYM($|/)' = {weight=11}" // but allow dSYM directories in code locations (parallel to their code)
593 "'^(.*/)?\\.DS_Store$' = {omit=#T,weight=2000}" // ignore .DS_Store files
594 "'^Info\\.plist$' = {omit=#T, weight=20}" // excluded automatically now, but old systems need to be told
595 "'^version\\.plist$' = {weight=20}" // include version.plist as resource
596 "'^embedded\\.provisionprofile$' = {weight=20}" // include embedded.provisionprofile as resource
597 "'^PkgInfo$' = {omit=#T, weight=20}" // traditionally not included
598 "%s = {weight=20}" // Resources override default nested (widgets)
599 "%s = {optional=#T, weight=1000}" // make localizations optional
600 "%s = {weight=1010}" // ... except for Base.lproj which really isn't optional at all
601 "%s = {omit=#T, weight=1100}" // exclude all locversion.plist files
602 "}}",
603
604 (string("^") + resources).c_str(),
605 (string("^") + resources + ".*\\.lproj/").c_str(),
606 (string("^") + resources + "Base\\.lproj/").c_str(),
607 (string("^") + resources + ".*\\.lproj/locversion.plist$").c_str(),
608
609 (string("^") + resources).c_str(),
610 (string("^") + resources + ".*\\.lproj/").c_str(),
611 (string("^") + resources + "Base\\.lproj/").c_str(),
612 (string("^") + resources + ".*\\.lproj/locversion.plist$").c_str()
613 );
614 }
615
616
617 CFArrayRef BundleDiskRep::allowedResourceOmissions()
618 {
619 return cfmake<CFArrayRef>("["
620 "'^(.*/)?\\.DS_Store$'"
621 "'^Info\\.plist$'"
622 "'^PkgInfo$'"
623 "%s"
624 "]",
625 (string("^") + this->resourcesRelativePath() + ".*\\.lproj/locversion.plist$").c_str()
626 );
627 }
628
629
630 const Requirements *BundleDiskRep::defaultRequirements(const Architecture *arch, const SigningContext &ctx)
631 {
632 return mExecRep->defaultRequirements(arch, ctx);
633 }
634
635 size_t BundleDiskRep::pageSize(const SigningContext &ctx)
636 {
637 return mExecRep->pageSize(ctx);
638 }
639
640
641 //
642 // Strict validation.
643 // Takes an array of CFNumbers of errors to tolerate.
644 //
645 void BundleDiskRep::strictValidate(const CodeDirectory* cd, const ToleratedErrors& tolerated, SecCSFlags flags)
646 {
647 // scan our metadirectory (_CodeSignature) for unwanted guests
648 if (!(flags & kSecCSQuickCheck))
649 validateMetaDirectory(cd);
650
651 // check accumulated strict errors and report them
652 if (!(flags & kSecCSRestrictSidebandData)) // tolerate resource forks etc.
653 mStrictErrors.erase(errSecCSInvalidAssociatedFileData);
654
655 std::vector<OSStatus> fatalErrors;
656 set_difference(mStrictErrors.begin(), mStrictErrors.end(), tolerated.begin(), tolerated.end(), back_inserter(fatalErrors));
657 if (!fatalErrors.empty())
658 MacOSError::throwMe(fatalErrors[0]);
659
660 // if app focus is requested and this doesn't look like an app, fail - but allow whitelist overrides
661 if (flags & kSecCSRestrictToAppLike)
662 if (!mAppLike)
663 if (tolerated.find(kSecCSRestrictToAppLike) == tolerated.end())
664 MacOSError::throwMe(errSecCSNotAppLike);
665
666 // now strict-check the main executable (which won't be an app-like object)
667 mExecRep->strictValidate(cd, tolerated, flags & ~kSecCSRestrictToAppLike);
668 }
669
670 void BundleDiskRep::recordStrictError(OSStatus error)
671 {
672 mStrictErrors.insert(error);
673 }
674
675
676 void BundleDiskRep::validateMetaDirectory(const CodeDirectory* cd)
677 {
678 // we know the resource directory will be checked after this call, so we'll give it a pass here
679 if (cd->slotIsPresent(-cdResourceDirSlot))
680 mUsedComponents.insert(cdResourceDirSlot);
681
682 // make a set of allowed (regular) filenames in this directory
683 std::set<std::string> allowedFiles;
684 for (auto it = mUsedComponents.begin(); it != mUsedComponents.end(); ++it) {
685 switch (*it) {
686 case cdInfoSlot:
687 break; // always from Info.plist, not from here
688 default:
689 if (const char *name = CodeDirectory::canonicalSlotName(*it)) {
690 allowedFiles.insert(name);
691 }
692 break;
693 }
694 }
695 DirScanner scan(mMetaPath);
696 if (scan.initialized()) {
697 while (struct dirent* ent = scan.getNext()) {
698 if (!scan.isRegularFile(ent))
699 MacOSError::throwMe(errSecCSUnsealedAppRoot); // only regular files allowed
700 if (allowedFiles.find(ent->d_name) == allowedFiles.end()) { // not in expected set of files
701 if (strcmp(ent->d_name, kSecCS_SIGNATUREFILE) == 0) {
702 // special case - might be empty and unused (adhoc signature)
703 AutoFileDesc fd(metaPath(kSecCS_SIGNATUREFILE));
704 if (fd.fileSize() == 0)
705 continue; // that's okay, then
706 }
707 // not on list of needed files; it's a freeloading rogue!
708 recordStrictError(errSecCSUnsealedAppRoot); // funnel through strict set so GKOpaque can override it
709 }
710 }
711 }
712 }
713
714
715 //
716 // Check framework root for unsafe symlinks and unsealed content.
717 //
718 void BundleDiskRep::validateFrameworkRoot(string root)
719 {
720 // build regex element that matches either the "Current" symlink, or the name of the current version
721 string current = "Current";
722 char currentVersion[PATH_MAX];
723 ssize_t len = ::readlink((root + "/Versions/Current").c_str(), currentVersion, sizeof(currentVersion)-1);
724 if (len > 0) {
725 currentVersion[len] = '\0';
726 current = string("(Current|") + ResourceBuilder::escapeRE(currentVersion) + ")";
727 }
728
729 DirValidator val;
730 val.require("^Versions$", DirValidator::directory | DirValidator::descend); // descend into Versions directory
731 val.require("^Versions/[^/]+$", DirValidator::directory); // require at least one version
732 val.require("^Versions/Current$", DirValidator::symlink, // require Current symlink...
733 "^(\\./)?(\\.\\.[^/]+|\\.?[^\\./][^/]*)$"); // ...must point to a version
734 val.allow("^(Versions/)?\\.DS_Store$", DirValidator::file | DirValidator::noexec); // allow .DS_Store files
735 val.allow("^[^/]+$", DirValidator::symlink, ^ string (const string &name, const string &target) {
736 // top-level symlinks must point to namesake in current version
737 return string("^(\\./)?Versions/") + current + "/" + ResourceBuilder::escapeRE(name) + "$";
738 });
739 // module.map must be regular non-executable file, or symlink to module.map in current version
740 val.allow("^module\\.map$", DirValidator::file | DirValidator::noexec | DirValidator::symlink,
741 string("^(\\./)?Versions/") + current + "/module\\.map$");
742
743 try {
744 val.validate(root, errSecCSUnsealedFrameworkRoot);
745 } catch (const MacOSError &err) {
746 recordStrictError(err.error);
747 }
748 }
749
750
751 //
752 // Check a file descriptor for harmlessness. This is a strict check (only).
753 //
754 void BundleDiskRep::checkPlainFile(FileDesc fd, const std::string& path)
755 {
756 if (!fd.isPlainFile(path))
757 recordStrictError(errSecCSRegularFile);
758 checkForks(fd);
759 }
760
761 void BundleDiskRep::checkForks(FileDesc fd)
762 {
763 if (fd.hasExtendedAttribute(XATTR_RESOURCEFORK_NAME) || fd.hasExtendedAttribute(XATTR_FINDERINFO_NAME))
764 recordStrictError(errSecCSInvalidAssociatedFileData);
765 }
766
767
768 //
769 // Writers
770 //
771 DiskRep::Writer *BundleDiskRep::writer()
772 {
773 return new Writer(this);
774 }
775
776 BundleDiskRep::Writer::Writer(BundleDiskRep *r)
777 : rep(r), mMadeMetaDirectory(false)
778 {
779 execWriter = rep->mExecRep->writer();
780 }
781
782
783 //
784 // Write a component.
785 // Note that this isn't concerned with Mach-O writing; this is handled at
786 // a much higher level. If we're called, we write to a file in the Bundle's meta directory.
787 //
788 void BundleDiskRep::Writer::component(CodeDirectory::SpecialSlot slot, CFDataRef data)
789 {
790 switch (slot) {
791 default:
792 if (!execWriter->attribute(writerLastResort)) // willing to take the data...
793 return execWriter->component(slot, data); // ... so hand it through
794 // execWriter doesn't want the data; store it as a resource file (below)
795 case cdResourceDirSlot:
796 // the resource directory always goes into a bundle file
797 if (const char *name = CodeDirectory::canonicalSlotName(slot)) {
798 rep->createMeta();
799 string path = rep->metaPath(name);
800 AutoFileDesc fd(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
801 fd.writeAll(CFDataGetBytePtr(data), CFDataGetLength(data));
802 mWrittenFiles.insert(name);
803 } else
804 MacOSError::throwMe(errSecCSBadBundleFormat);
805 }
806 }
807
808
809 //
810 // Remove all signature data
811 //
812 void BundleDiskRep::Writer::remove()
813 {
814 // remove signature from the executable
815 execWriter->remove();
816
817 // remove signature files from bundle
818 for (CodeDirectory::SpecialSlot slot = 0; slot < cdSlotCount; slot++)
819 remove(slot);
820 remove(cdSignatureSlot);
821 }
822
823 void BundleDiskRep::Writer::remove(CodeDirectory::SpecialSlot slot)
824 {
825 if (const char *name = CodeDirectory::canonicalSlotName(slot))
826 if (::unlink(rep->metaPath(name).c_str()))
827 switch (errno) {
828 case ENOENT: // not found - that's okay
829 break;
830 default:
831 UnixError::throwMe();
832 }
833 }
834
835
836 void BundleDiskRep::Writer::flush()
837 {
838 execWriter->flush();
839 purgeMetaDirectory();
840 }
841
842
843 // purge _CodeSignature of all left-over files from any previous signature
844 void BundleDiskRep::Writer::purgeMetaDirectory()
845 {
846 DirScanner scan(rep->mMetaPath);
847 if (scan.initialized()) {
848 while (struct dirent* ent = scan.getNext()) {
849 if (!scan.isRegularFile(ent))
850 MacOSError::throwMe(errSecCSUnsealedAppRoot); // only regular files allowed
851 if (mWrittenFiles.find(ent->d_name) == mWrittenFiles.end()) { // we didn't write this!
852 scan.unlink(ent, 0);
853 }
854 }
855 }
856
857 }
858
859
860 } // end namespace CodeSigning
861 } // end namespace Security