2 * Copyright (c) 2006-2011 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
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
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.
21 * @APPLE_LICENSE_HEADER_END@
23 #include "bundlediskrep.h"
24 #include "filediskrep.h"
25 #include <CoreFoundation/CFURLAccess.h>
26 #include <CoreFoundation/CFBundlePriv.h>
27 #include <security_utilities/cfmunge.h>
32 namespace CodeSigning
{
34 using namespace UnixPlusPlus
;
38 // We make a CFBundleRef immediately, but everything else is lazy
40 BundleDiskRep::BundleDiskRep(const char *path
, const Context
*ctx
)
41 : mBundle(CFBundleCreate(NULL
, CFTempURL(path
)))
44 MacOSError::throwMe(errSecCSBadBundleFormat
);
46 CODESIGN_DISKREP_CREATE_BUNDLE_PATH(this, (char*)path
, (void*)ctx
, mExecRep
);
49 BundleDiskRep::BundleDiskRep(CFBundleRef ref
, const Context
*ctx
)
51 mBundle
= ref
; // retains
53 CODESIGN_DISKREP_CREATE_BUNDLE_REF(this, ref
, (void*)ctx
, mExecRep
);
56 // common construction code
57 void BundleDiskRep::setup(const Context
*ctx
)
59 // deal with versioned bundles (aka Frameworks)
60 string version
= resourcesRootPath()
62 + ((ctx
&& ctx
->version
) ? ctx
->version
: "Current")
64 if (::access(version
.c_str(), F_OK
) == 0) { // versioned bundle
65 if (CFBundleRef versionBundle
= CFBundleCreate(NULL
, CFTempURL(version
)))
66 mBundle
.take(versionBundle
); // replace top bundle ref
68 MacOSError::throwMe(errSecCSStaticCodeNotFound
);
70 if (ctx
&& ctx
->version
) // explicitly specified
71 MacOSError::throwMe(errSecCSStaticCodeNotFound
);
74 // conventional executable bundle: CFBundle identifies an executable for us
75 if (mMainExecutableURL
.take(CFBundleCopyExecutableURL(mBundle
))) {
76 // conventional executable bundle
77 mExecRep
= DiskRep::bestFileGuess(this->mainExecutablePath(), ctx
);
78 mFormat
= string("bundle with ") + mExecRep
->format();
82 CFDictionaryRef infoDict
= CFBundleGetInfoDictionary(mBundle
);
83 assert(infoDict
); // CFBundle will always make one up for us
85 if (CFTypeRef main
= CFDictionaryGetValue(infoDict
, CFSTR("MainHTML"))) {
87 if (CFGetTypeID(main
) != CFStringGetTypeID())
88 MacOSError::throwMe(errSecCSBadBundleFormat
);
89 mMainExecutableURL
= makeCFURL(cfString(CFStringRef(main
)), false, CFRef
<CFURLRef
>(CFBundleCopySupportFilesDirectoryURL(mBundle
)));
90 if (!mMainExecutableURL
)
91 MacOSError::throwMe(errSecCSBadBundleFormat
);
92 mExecRep
= new FileDiskRep(this->mainExecutablePath().c_str());
93 mFormat
= "widget bundle";
97 // generic bundle case - impose our own "minimal signable bundle" standard
99 // we MUST have an actual Info.plist in here
100 CFRef
<CFURLRef
> infoURL
= _CFBundleCopyInfoPlistURL(mBundle
);
102 MacOSError::throwMe(errSecCSBadBundleFormat
);
104 // focus on the Info.plist (which we know exists) as the nominal "main executable" file
105 if ((mMainExecutableURL
= _CFBundleCopyInfoPlistURL(mBundle
))) {
106 mExecRep
= new FileDiskRep(this->mainExecutablePath().c_str());
111 // this bundle cannot be signed
112 MacOSError::throwMe(errSecCSBadBundleFormat
);
117 // Create a path to a bundle signing resource, by name.
118 // If the BUNDLEDISKREP_DIRECTORY directory exists in the bundle's support directory, files
119 // will be read and written there. Otherwise, they go directly into the support directory.
121 string
BundleDiskRep::metaPath(const char *name
)
123 if (mMetaPath
.empty()) {
124 string support
= cfString(CFBundleCopySupportFilesDirectoryURL(mBundle
), true);
125 mMetaPath
= support
+ "/" BUNDLEDISKREP_DIRECTORY
;
126 if (::access(mMetaPath
.c_str(), F_OK
) == 0) {
133 return mMetaPath
+ "/" + name
;
138 // Try to create the meta-file directory in our bundle.
139 // Does nothing if the directory already exists.
140 // Throws if an error occurs.
142 void BundleDiskRep::createMeta()
144 string meta
= metaPath(BUNDLEDISKREP_DIRECTORY
);
146 if (::mkdir(meta
.c_str(), 0755) == 0) {
147 copyfile(cfString(canonicalPath(), true).c_str(), meta
.c_str(), NULL
, COPYFILE_SECURITY
);
150 } else if (errno
!= EEXIST
)
151 UnixError::throwMe();
157 // Load and return a component, by slot number.
158 // Info.plist components come from the bundle, always (we don't look
159 // for Mach-O embedded versions).
160 // Everything else comes from the embedded blobs of a Mach-O image, or from
161 // files located in the Contents directory of the bundle.
163 CFDataRef
BundleDiskRep::component(CodeDirectory::SpecialSlot slot
)
166 // the Info.plist comes from the magic CFBundle-indicated place and ONLY from there
168 if (CFRef
<CFURLRef
> info
= _CFBundleCopyInfoPlistURL(mBundle
))
169 return cfLoadFile(info
);
172 // by default, we take components from the executable image or files
174 if (CFDataRef data
= mExecRep
->component(slot
))
177 // but the following always come from files
178 case cdResourceDirSlot
:
179 if (const char *name
= CodeDirectory::canonicalSlotName(slot
))
180 return metaData(name
);
188 // The binary identifier is taken directly from the main executable.
190 CFDataRef
BundleDiskRep::identification()
192 return mExecRep
->identification();
197 // Various aspects of our DiskRep personality.
199 CFURLRef
BundleDiskRep::canonicalPath()
201 return CFBundleCopyBundleURL(mBundle
);
204 string
BundleDiskRep::mainExecutablePath()
206 return cfString(mMainExecutableURL
);
209 string
BundleDiskRep::resourcesRootPath()
211 return cfString(CFBundleCopySupportFilesDirectoryURL(mBundle
), true);
214 void BundleDiskRep::adjustResources(ResourceBuilder
&builder
)
216 // exclude entire contents of meta directory
217 builder
.addExclusion("^" BUNDLEDISKREP_DIRECTORY
"/");
219 // exclude the store manifest directory
220 builder
.addExclusion("^" STORE_RECEIPT_DIRECTORY
"/");
222 // exclude the main executable file
223 string resources
= resourcesRootPath();
224 string executable
= mainExecutablePath();
225 if (!executable
.compare(0, resources
.length(), resources
, 0, resources
.length())) // is prefix
226 builder
.addExclusion(string("^")
227 + ResourceBuilder::escapeRE(executable
.substr(resources
.length() + 1)) + "$");
232 Universal
*BundleDiskRep::mainExecutableImage()
234 return mExecRep
->mainExecutableImage();
237 size_t BundleDiskRep::signingBase()
239 return mExecRep
->signingBase();
242 size_t BundleDiskRep::signingLimit()
244 return mExecRep
->signingLimit();
247 string
BundleDiskRep::format()
252 CFArrayRef
BundleDiskRep::modifiedFiles()
254 CFMutableArrayRef files
= CFArrayCreateMutableCopy(NULL
, 0, mExecRep
->modifiedFiles());
255 checkModifiedFile(files
, cdCodeDirectorySlot
);
256 checkModifiedFile(files
, cdSignatureSlot
);
257 checkModifiedFile(files
, cdResourceDirSlot
);
258 checkModifiedFile(files
, cdEntitlementSlot
);
262 void BundleDiskRep::checkModifiedFile(CFMutableArrayRef files
, CodeDirectory::SpecialSlot slot
)
264 if (CFDataRef data
= mExecRep
->component(slot
)) // provided by executable file
266 else if (const char *resourceName
= CodeDirectory::canonicalSlotName(slot
)) {
267 string file
= metaPath(resourceName
);
268 if (::access(file
.c_str(), F_OK
) == 0)
269 CFArrayAppendValue(files
, CFTempURL(file
));
273 FileDesc
&BundleDiskRep::fd()
275 return mExecRep
->fd();
278 void BundleDiskRep::flush()
285 // Defaults for signing operations
287 string
BundleDiskRep::recommendedIdentifier(const SigningContext
&)
289 if (CFStringRef identifier
= CFBundleGetIdentifier(mBundle
))
290 return cfString(identifier
);
291 if (CFDictionaryRef infoDict
= CFBundleGetInfoDictionary(mBundle
))
292 if (CFStringRef identifier
= CFStringRef(CFDictionaryGetValue(infoDict
, kCFBundleNameKey
)))
293 return cfString(identifier
);
295 // fall back to using the canonical path
296 return canonicalIdentifier(cfString(this->canonicalPath()));
299 CFDictionaryRef
BundleDiskRep::defaultResourceRules(const SigningContext
&)
301 // consider the bundle's structure
302 string rbase
= this->resourcesRootPath();
303 if (rbase
.substr(rbase
.length()-2, 2) == "/.") // produced by versioned bundle implicit "Current" case
304 rbase
= rbase
.substr(0, rbase
.length()-2); // ... so take it off for this
305 string resources
= cfString(CFBundleCopyResourcesDirectoryURL(mBundle
), true);
306 if (resources
== rbase
)
308 else if (resources
.compare(0, rbase
.length(), rbase
, 0, rbase
.length()) != 0) // Resources not in resource root
309 MacOSError::throwMe(errSecCSBadBundleFormat
);
311 resources
= resources
.substr(rbase
.length() + 1) + "/"; // differential path segment
313 return cfmake
<CFDictionaryRef
>("{rules={"
314 "'^version.plist$' = #T"
316 "%s = {optional=#T, weight=1000}"
317 "%s = {omit=#T, weight=1100}"
319 (string("^") + resources
).c_str(),
320 (string("^") + resources
+ ".*\\.lproj/").c_str(),
321 (string("^") + resources
+ ".*\\.lproj/locversion.plist$").c_str()
325 const Requirements
*BundleDiskRep::defaultRequirements(const Architecture
*arch
, const SigningContext
&ctx
)
327 return mExecRep
->defaultRequirements(arch
, ctx
);
330 size_t BundleDiskRep::pageSize(const SigningContext
&ctx
)
332 return mExecRep
->pageSize(ctx
);
339 DiskRep::Writer
*BundleDiskRep::writer()
341 return new Writer(this);
344 BundleDiskRep::Writer::Writer(BundleDiskRep
*r
)
345 : rep(r
), mMadeMetaDirectory(false)
347 execWriter
= rep
->mExecRep
->writer();
352 // Write a component.
353 // Note that this isn't concerned with Mach-O writing; this is handled at
354 // a much higher level. If we're called, we write to a file in the Bundle's meta directory.
356 void BundleDiskRep::Writer::component(CodeDirectory::SpecialSlot slot
, CFDataRef data
)
360 if (!execWriter
->attribute(writerLastResort
)) // willing to take the data...
361 return execWriter
->component(slot
, data
); // ... so hand it through
362 // execWriter doesn't want the data; store it as a resource file (below)
363 case cdResourceDirSlot
:
364 // the resource directory always goes into a bundle file
365 if (const char *name
= CodeDirectory::canonicalSlotName(slot
)) {
367 string path
= rep
->metaPath(name
);
368 AutoFileDesc
fd(path
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0644);
369 fd
.writeAll(CFDataGetBytePtr(data
), CFDataGetLength(data
));
371 MacOSError::throwMe(errSecCSBadBundleFormat
);
377 // Remove all signature data
379 void BundleDiskRep::Writer::remove()
381 // remove signature from the executable
382 execWriter
->remove();
384 // remove signature files from bundle
385 for (CodeDirectory::SpecialSlot slot
= 0; slot
< cdSlotCount
; slot
++)
387 remove(cdSignatureSlot
);
390 void BundleDiskRep::Writer::remove(CodeDirectory::SpecialSlot slot
)
392 if (const char *name
= CodeDirectory::canonicalSlotName(slot
))
393 if (::unlink(rep
->metaPath(name
).c_str()))
395 case ENOENT
: // not found - that's okay
398 UnixError::throwMe();
403 void BundleDiskRep::Writer::flush()
409 } // end namespace CodeSigning
410 } // end namespace Security