]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_codesigning/lib/bundlediskrep.cpp
Security-58286.1.32.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, cdRepSpecificSlot);
475 for (CodeDirectory::Slot slot = cdAlternateCodeDirectorySlots; slot < cdAlternateCodeDirectoryLimit; ++slot)
476 checkModifiedFile(files, slot);
477 return files.yield();
478 }
479
480 void BundleDiskRep::checkModifiedFile(CFMutableArrayRef files, CodeDirectory::SpecialSlot slot)
481 {
482 if (CFDataRef data = mExecRep->component(slot)) // provided by executable file
483 CFRelease(data);
484 else if (const char *resourceName = CodeDirectory::canonicalSlotName(slot)) {
485 string file = metaPath(resourceName);
486 if (::access(file.c_str(), F_OK) == 0)
487 CFArrayAppendValue(files, CFTempURL(file));
488 }
489 }
490
491 FileDesc &BundleDiskRep::fd()
492 {
493 return mExecRep->fd();
494 }
495
496 void BundleDiskRep::flush()
497 {
498 mExecRep->flush();
499 }
500
501 CFDictionaryRef BundleDiskRep::diskRepInformation()
502 {
503 return mExecRep->diskRepInformation();
504 }
505
506 //
507 // Defaults for signing operations
508 //
509 string BundleDiskRep::recommendedIdentifier(const SigningContext &)
510 {
511 if (CFStringRef identifier = CFBundleGetIdentifier(mBundle))
512 return cfString(identifier);
513 if (CFDictionaryRef infoDict = CFBundleGetInfoDictionary(mBundle))
514 if (CFStringRef identifier = CFStringRef(CFDictionaryGetValue(infoDict, kCFBundleNameKey)))
515 return cfString(identifier);
516
517 // fall back to using the canonical path
518 return canonicalIdentifier(cfStringRelease(this->copyCanonicalPath()));
519 }
520
521 string BundleDiskRep::resourcesRelativePath()
522 {
523 // figure out the resource directory base. Clean up some gunk inserted by CFBundle in frameworks
524 string rbase = this->resourcesRootPath();
525 size_t pos = rbase.find("/./"); // gratuitously inserted by CFBundle in some frameworks
526 while (pos != std::string::npos) {
527 rbase = rbase.replace(pos, 2, "", 0);
528 pos = rbase.find("/./");
529 }
530 if (rbase.substr(rbase.length()-2, 2) == "/.") // produced by versioned bundle implicit "Current" case
531 rbase = rbase.substr(0, rbase.length()-2); // ... so take it off for this
532
533 // find the resources directory relative to the resource base
534 string resources = cfStringRelease(CFBundleCopyResourcesDirectoryURL(mBundle));
535 if (resources == rbase)
536 resources = "";
537 else if (resources.compare(0, rbase.length(), rbase, 0, rbase.length()) != 0) // Resources not in resource root
538 MacOSError::throwMe(errSecCSBadBundleFormat);
539 else
540 resources = resources.substr(rbase.length() + 1) + "/"; // differential path segment
541
542 return resources;
543 }
544
545 CFDictionaryRef BundleDiskRep::defaultResourceRules(const SigningContext &ctx)
546 {
547 string resources = this->resourcesRelativePath();
548
549 // installer package rules
550 if (mInstallerPackage)
551 return cfmake<CFDictionaryRef>("{rules={"
552 "'^.*' = #T" // include everything, but...
553 "%s = {optional=#T, weight=1000}" // make localizations optional
554 "'^.*/.*\\.pkg/' = {omit=#T, weight=10000}" // and exclude all nested packages (by name)
555 "}}",
556 (string("^") + resources + ".*\\.lproj/").c_str()
557 );
558
559 // old (V1) executable bundle rules - compatible with before
560 if (ctx.signingFlags() & kSecCSSignV1) // *** must be exactly the same as before ***
561 return cfmake<CFDictionaryRef>("{rules={"
562 "'^version.plist$' = #T" // include version.plist
563 "%s = #T" // include Resources
564 "%s = {optional=#T, weight=1000}" // make localizations optional
565 "%s = {omit=#T, weight=1100}" // exclude all locversion.plist files
566 "}}",
567 (string("^") + resources).c_str(),
568 (string("^") + resources + ".*\\.lproj/").c_str(),
569 (string("^") + resources + ".*\\.lproj/locversion.plist$").c_str()
570 );
571
572 // FMJ (everything is a resource) rules
573 if (ctx.signingFlags() & kSecCSSignOpaque) // Full Metal Jacket - everything is a resource file
574 return cfmake<CFDictionaryRef>("{rules={"
575 "'^.*' = #T" // everything is a resource
576 "'^Info\\.plist$' = {omit=#T,weight=10}" // explicitly exclude this for backward compatibility
577 "}}");
578
579 // new (V2) executable bundle rules
580 return cfmake<CFDictionaryRef>("{" // *** the new (V2) world ***
581 "rules={" // old (V1; legacy) version
582 "'^version.plist$' = #T" // include version.plist
583 "%s = #T" // include Resources
584 "%s = {optional=#T, weight=1000}" // make localizations optional
585 "%s = {weight=1010}" // ... except for Base.lproj which really isn't optional at all
586 "%s = {omit=#T, weight=1100}" // exclude all locversion.plist files
587 "},rules2={"
588 "'^.*' = #T" // include everything as a resource, with the following exceptions
589 "'^[^/]+$' = {nested=#T, weight=10}" // files directly in Contents
590 "'^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/' = {nested=#T, weight=10}" // dynamic repositories
591 "'.*\\.dSYM($|/)' = {weight=11}" // but allow dSYM directories in code locations (parallel to their code)
592 "'^(.*/)?\\.DS_Store$' = {omit=#T,weight=2000}" // ignore .DS_Store files
593 "'^Info\\.plist$' = {omit=#T, weight=20}" // excluded automatically now, but old systems need to be told
594 "'^version\\.plist$' = {weight=20}" // include version.plist as resource
595 "'^embedded\\.provisionprofile$' = {weight=20}" // include embedded.provisionprofile as resource
596 "'^PkgInfo$' = {omit=#T, weight=20}" // traditionally not included
597 "%s = {weight=20}" // Resources override default nested (widgets)
598 "%s = {optional=#T, weight=1000}" // make localizations optional
599 "%s = {weight=1010}" // ... except for Base.lproj which really isn't optional at all
600 "%s = {omit=#T, weight=1100}" // exclude all locversion.plist files
601 "}}",
602
603 (string("^") + resources).c_str(),
604 (string("^") + resources + ".*\\.lproj/").c_str(),
605 (string("^") + resources + "Base\\.lproj/").c_str(),
606 (string("^") + resources + ".*\\.lproj/locversion.plist$").c_str(),
607
608 (string("^") + resources).c_str(),
609 (string("^") + resources + ".*\\.lproj/").c_str(),
610 (string("^") + resources + "Base\\.lproj/").c_str(),
611 (string("^") + resources + ".*\\.lproj/locversion.plist$").c_str()
612 );
613 }
614
615
616 CFArrayRef BundleDiskRep::allowedResourceOmissions()
617 {
618 return cfmake<CFArrayRef>("["
619 "'^(.*/)?\\.DS_Store$'"
620 "'^Info\\.plist$'"
621 "'^PkgInfo$'"
622 "%s"
623 "]",
624 (string("^") + this->resourcesRelativePath() + ".*\\.lproj/locversion.plist$").c_str()
625 );
626 }
627
628
629 const Requirements *BundleDiskRep::defaultRequirements(const Architecture *arch, const SigningContext &ctx)
630 {
631 return mExecRep->defaultRequirements(arch, ctx);
632 }
633
634 size_t BundleDiskRep::pageSize(const SigningContext &ctx)
635 {
636 return mExecRep->pageSize(ctx);
637 }
638
639
640 //
641 // Strict validation.
642 // Takes an array of CFNumbers of errors to tolerate.
643 //
644 void BundleDiskRep::strictValidate(const CodeDirectory* cd, const ToleratedErrors& tolerated, SecCSFlags flags)
645 {
646 // scan our metadirectory (_CodeSignature) for unwanted guests
647 if (!(flags & kSecCSQuickCheck))
648 validateMetaDirectory(cd);
649
650 // check accumulated strict errors and report them
651 if (!(flags & kSecCSRestrictSidebandData)) // tolerate resource forks etc.
652 mStrictErrors.erase(errSecCSInvalidAssociatedFileData);
653
654 std::vector<OSStatus> fatalErrors;
655 set_difference(mStrictErrors.begin(), mStrictErrors.end(), tolerated.begin(), tolerated.end(), back_inserter(fatalErrors));
656 if (!fatalErrors.empty())
657 MacOSError::throwMe(fatalErrors[0]);
658
659 // if app focus is requested and this doesn't look like an app, fail - but allow whitelist overrides
660 if (flags & kSecCSRestrictToAppLike)
661 if (!mAppLike)
662 if (tolerated.find(kSecCSRestrictToAppLike) == tolerated.end())
663 MacOSError::throwMe(errSecCSNotAppLike);
664
665 // now strict-check the main executable (which won't be an app-like object)
666 mExecRep->strictValidate(cd, tolerated, flags & ~kSecCSRestrictToAppLike);
667 }
668
669 void BundleDiskRep::recordStrictError(OSStatus error)
670 {
671 mStrictErrors.insert(error);
672 }
673
674
675 void BundleDiskRep::validateMetaDirectory(const CodeDirectory* cd)
676 {
677 // we know the resource directory will be checked after this call, so we'll give it a pass here
678 if (cd->slotIsPresent(-cdResourceDirSlot))
679 mUsedComponents.insert(cdResourceDirSlot);
680
681 // make a set of allowed (regular) filenames in this directory
682 std::set<std::string> allowedFiles;
683 for (auto it = mUsedComponents.begin(); it != mUsedComponents.end(); ++it) {
684 switch (*it) {
685 case cdInfoSlot:
686 break; // always from Info.plist, not from here
687 default:
688 if (const char *name = CodeDirectory::canonicalSlotName(*it)) {
689 allowedFiles.insert(name);
690 }
691 break;
692 }
693 }
694 DirScanner scan(mMetaPath);
695 if (scan.initialized()) {
696 while (struct dirent* ent = scan.getNext()) {
697 if (!scan.isRegularFile(ent))
698 MacOSError::throwMe(errSecCSUnsealedAppRoot); // only regular files allowed
699 if (allowedFiles.find(ent->d_name) == allowedFiles.end()) { // not in expected set of files
700 if (strcmp(ent->d_name, kSecCS_SIGNATUREFILE) == 0) {
701 // special case - might be empty and unused (adhoc signature)
702 AutoFileDesc fd(metaPath(kSecCS_SIGNATUREFILE));
703 if (fd.fileSize() == 0)
704 continue; // that's okay, then
705 }
706 // not on list of needed files; it's a freeloading rogue!
707 recordStrictError(errSecCSUnsealedAppRoot); // funnel through strict set so GKOpaque can override it
708 }
709 }
710 }
711 }
712
713
714 //
715 // Check framework root for unsafe symlinks and unsealed content.
716 //
717 void BundleDiskRep::validateFrameworkRoot(string root)
718 {
719 // build regex element that matches either the "Current" symlink, or the name of the current version
720 string current = "Current";
721 char currentVersion[PATH_MAX];
722 ssize_t len = ::readlink((root + "/Versions/Current").c_str(), currentVersion, sizeof(currentVersion)-1);
723 if (len > 0) {
724 currentVersion[len] = '\0';
725 current = string("(Current|") + ResourceBuilder::escapeRE(currentVersion) + ")";
726 }
727
728 DirValidator val;
729 val.require("^Versions$", DirValidator::directory | DirValidator::descend); // descend into Versions directory
730 val.require("^Versions/[^/]+$", DirValidator::directory); // require at least one version
731 val.require("^Versions/Current$", DirValidator::symlink, // require Current symlink...
732 "^(\\./)?(\\.\\.[^/]+|\\.?[^\\./][^/]*)$"); // ...must point to a version
733 val.allow("^(Versions/)?\\.DS_Store$", DirValidator::file | DirValidator::noexec); // allow .DS_Store files
734 val.allow("^[^/]+$", DirValidator::symlink, ^ string (const string &name, const string &target) {
735 // top-level symlinks must point to namesake in current version
736 return string("^(\\./)?Versions/") + current + "/" + ResourceBuilder::escapeRE(name) + "$";
737 });
738 // module.map must be regular non-executable file, or symlink to module.map in current version
739 val.allow("^module\\.map$", DirValidator::file | DirValidator::noexec | DirValidator::symlink,
740 string("^(\\./)?Versions/") + current + "/module\\.map$");
741
742 try {
743 val.validate(root, errSecCSUnsealedFrameworkRoot);
744 } catch (const MacOSError &err) {
745 recordStrictError(err.error);
746 }
747 }
748
749
750 //
751 // Check a file descriptor for harmlessness. This is a strict check (only).
752 //
753 void BundleDiskRep::checkPlainFile(FileDesc fd, const std::string& path)
754 {
755 if (!fd.isPlainFile(path))
756 recordStrictError(errSecCSRegularFile);
757 checkForks(fd);
758 }
759
760 void BundleDiskRep::checkForks(FileDesc fd)
761 {
762 if (fd.hasExtendedAttribute(XATTR_RESOURCEFORK_NAME) || fd.hasExtendedAttribute(XATTR_FINDERINFO_NAME))
763 recordStrictError(errSecCSInvalidAssociatedFileData);
764 }
765
766
767 //
768 // Writers
769 //
770 DiskRep::Writer *BundleDiskRep::writer()
771 {
772 return new Writer(this);
773 }
774
775 BundleDiskRep::Writer::Writer(BundleDiskRep *r)
776 : rep(r), mMadeMetaDirectory(false)
777 {
778 execWriter = rep->mExecRep->writer();
779 }
780
781
782 //
783 // Write a component.
784 // Note that this isn't concerned with Mach-O writing; this is handled at
785 // a much higher level. If we're called, we write to a file in the Bundle's meta directory.
786 //
787 void BundleDiskRep::Writer::component(CodeDirectory::SpecialSlot slot, CFDataRef data)
788 {
789 switch (slot) {
790 default:
791 if (!execWriter->attribute(writerLastResort)) // willing to take the data...
792 return execWriter->component(slot, data); // ... so hand it through
793 // execWriter doesn't want the data; store it as a resource file (below)
794 case cdResourceDirSlot:
795 // the resource directory always goes into a bundle file
796 if (const char *name = CodeDirectory::canonicalSlotName(slot)) {
797 rep->createMeta();
798 string path = rep->metaPath(name);
799 AutoFileDesc fd(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
800 fd.writeAll(CFDataGetBytePtr(data), CFDataGetLength(data));
801 mWrittenFiles.insert(name);
802 } else
803 MacOSError::throwMe(errSecCSBadBundleFormat);
804 }
805 }
806
807
808 //
809 // Remove all signature data
810 //
811 void BundleDiskRep::Writer::remove()
812 {
813 // remove signature from the executable
814 execWriter->remove();
815
816 // remove signature files from bundle
817 for (CodeDirectory::SpecialSlot slot = 0; slot < cdSlotCount; slot++)
818 remove(slot);
819 remove(cdSignatureSlot);
820 }
821
822 void BundleDiskRep::Writer::remove(CodeDirectory::SpecialSlot slot)
823 {
824 if (const char *name = CodeDirectory::canonicalSlotName(slot))
825 if (::unlink(rep->metaPath(name).c_str()))
826 switch (errno) {
827 case ENOENT: // not found - that's okay
828 break;
829 default:
830 UnixError::throwMe();
831 }
832 }
833
834
835 void BundleDiskRep::Writer::flush()
836 {
837 execWriter->flush();
838 purgeMetaDirectory();
839 }
840
841
842 // purge _CodeSignature of all left-over files from any previous signature
843 void BundleDiskRep::Writer::purgeMetaDirectory()
844 {
845 DirScanner scan(rep->mMetaPath);
846 if (scan.initialized()) {
847 while (struct dirent* ent = scan.getNext()) {
848 if (!scan.isRegularFile(ent))
849 MacOSError::throwMe(errSecCSUnsealedAppRoot); // only regular files allowed
850 if (mWrittenFiles.find(ent->d_name) == mWrittenFiles.end()) { // we didn't write this!
851 scan.unlink(ent, 0);
852 }
853 }
854 }
855
856 }
857
858
859 } // end namespace CodeSigning
860 } // end namespace Security