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