2 * Copyright (c) 2006-2012,2014 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@
25 // cdbuilder - constructor for CodeDirectories
27 #include "cdbuilder.h"
28 #include <security_utilities/memutils.h>
31 using namespace UnixPlusPlus
;
32 using LowLevelMemoryUtilities::alignUp
;
36 namespace CodeSigning
{
40 // Create an (empty) builder
42 CodeDirectory::Builder::Builder(HashAlgorithm digestAlgorithm
)
44 mHashType(digestAlgorithm
),
53 mGeneratePreEncryptHashes(false),
57 mDigestLength
= (uint32_t)MakeHash
<Builder
>(this)->digestLength();
58 mSpecial
= (unsigned char *)calloc(cdSlotMax
, mDigestLength
);
61 CodeDirectory::Builder::~Builder()
69 // Set the source of the main executable (i.e. the code pages)
71 void CodeDirectory::Builder::executable(string path
,
72 size_t pagesize
, size_t offset
, size_t length
)
74 mExec
.close(); // any previously opened one
81 void CodeDirectory::Builder::reopen(string path
, size_t offset
, size_t length
)
83 assert(mExec
); // already called executable()
92 // Set the source for one special slot
94 void CodeDirectory::Builder::specialSlot(SpecialSlot slot
, CFDataRef data
)
96 assert(slot
<= cdSlotMax
);
97 MakeHash
<Builder
> hash(this);
98 hash
->update(CFDataGetBytePtr(data
), CFDataGetLength(data
));
99 hash
->finish(specialSlot(slot
));
100 mFilledSpecialSlots
.insert(slot
);
101 if (slot
>= mSpecialSlots
)
102 mSpecialSlots
= slot
;
107 // Allocate a Scatter vector
109 CodeDirectory::Scatter
*CodeDirectory::Builder::scatter(unsigned count
)
111 mScatterSize
= (count
+ 1) * sizeof(Scatter
);
112 if (!(mScatter
= (Scatter
*)::realloc(mScatter
, mScatterSize
)))
113 UnixError::throwMe(ENOMEM
);
114 ::memset(mScatter
, 0, mScatterSize
);
119 // Keep the allocated size of the (static) CodeDirectory consistent with
120 // the version chosen. We dynamically picked the least-needed version
121 // to provide stability of virtual signatures.
123 size_t CodeDirectory::Builder::fixedSize(const uint32_t version
)
125 size_t cdSize
= sizeof(CodeDirectory
);
126 if (version
< supportsPreEncrypt
)
127 cdSize
-= sizeof(mDir
->runtime
) + sizeof(mDir
->preEncryptOffset
);
128 if (version
< supportsExecSegment
)
129 cdSize
-= sizeof(mDir
->execSegBase
) + sizeof(mDir
->execSegLimit
) + sizeof(mDir
->execSegFlags
);
130 if (version
< supportsCodeLimit64
)
131 cdSize
-= sizeof(mDir
->spare3
) + sizeof(mDir
->codeLimit64
);
132 if (version
< supportsTeamID
)
133 cdSize
-= sizeof(mDir
->teamIDOffset
);
139 // Calculate the size we'll need for the CodeDirectory as described so far
141 size_t CodeDirectory::Builder::size(const uint32_t version
)
143 assert(mExec
); // must have called executable()
144 if (mExecLength
== 0)
145 mExecLength
= mExec
.fileSize() - mExecOffset
;
147 // how many code pages?
148 if (mExecLength
<= 0) { // no code, no slots
150 } else if (mPageSize
== 0) { // indefinite - one page
152 } else { // finite - calculate from file size
153 mCodeSlots
= (mExecLength
- 1) / mPageSize
+ 1;
156 size_t offset
= fixedSize(version
);
157 size_t offset0
= offset
;
159 offset
+= mScatterSize
; // scatter vector
160 offset
+= mIdentifier
.size() + 1; // size of identifier (with null byte)
162 offset
+= mTeamID
.size() + 1; // size of teamID (with null byte)
163 offset
+= (mCodeSlots
+ mSpecialSlots
) * mDigestLength
; // hash vector
165 if (mGeneratePreEncryptHashes
|| !mPreservedPreEncryptHashMap
.empty()) {
166 offset
+= mCodeSlots
* mDigestLength
;
169 if (offset
<= offset0
)
170 UnixError::throwMe(ENOEXEC
);
177 // Take everything added to date and wrap it up in a shiny new CodeDirectory.
179 // Note that this only constructs a CodeDirectory; it does not touch any subsidiary
180 // structures (resource tables, etc.), nor does it create any signature to secure
181 // the CodeDirectory.
182 // The returned CodeDirectory object is yours, and you may modify it as desired.
183 // But the memory layout is set here, so the various sizes and counts should be good
184 // when you call build().
185 // It's up to us to order the dynamic fields as we wish; but note that we currently
186 // don't pad them, and so they should be allocated in non-increasing order of required
187 // alignment. Make sure to keep the code here in sync with the size-calculating code above.
189 CodeDirectory
*CodeDirectory::Builder::build()
191 assert(mExec
); // must have (successfully) called executable()
195 size_t identLength
= mIdentifier
.size() + 1;
196 size_t teamIDLength
= mTeamID
.size() + 1;
198 // Determine the version
199 if (mGeneratePreEncryptHashes
|| !mPreservedPreEncryptHashMap
.empty() || mRuntimeVersion
) {
200 version
= currentVersion
;
201 } else if (mExecSegLimit
> 0) {
202 version
= supportsExecSegment
;
203 } else if (mExecLength
> UINT32_MAX
) {
204 version
= supportsCodeLimit64
;
205 } else if (mTeamID
.size()) {
206 version
= supportsTeamID
;
208 version
= supportsScatter
;
211 if (mCodeSlots
> UINT32_MAX
) // (still limited to 32 bits)
212 MacOSError::throwMe(errSecCSTooBig
);
214 size_t total
= size(version
);
215 if (!(mDir
= (CodeDirectory
*)calloc(1, total
))) // initialize to zero
216 UnixError::throwMe(ENOMEM
);
219 mDir
->initialize(total
);
220 mDir
->version
= version
;
221 mDir
->flags
= mFlags
;
222 mDir
->nSpecialSlots
= (uint32_t)mSpecialSlots
;
223 mDir
->nCodeSlots
= (uint32_t)mCodeSlots
;
224 if (mExecLength
> UINT32_MAX
) {
225 mDir
->codeLimit
= UINT32_MAX
;
226 mDir
->codeLimit64
= mExecLength
;
228 mDir
->codeLimit
= uint32_t(mExecLength
);
230 mDir
->hashType
= mHashType
;
231 mDir
->platform
= mPlatform
;
232 mDir
->hashSize
= mDigestLength
;
235 assert(frexp(mPageSize
, &pglog
) == 0.5); // must be power of 2
236 frexp(mPageSize
, &pglog
);
238 mDir
->pageSize
= pglog
- 1;
240 mDir
->pageSize
= 0; // means infinite page size
242 mDir
->execSegBase
= mExecSegOffset
;
243 mDir
->execSegLimit
= mExecSegLimit
;
244 mDir
->execSegFlags
= mExecSegFlags
;
245 mDir
->runtime
= mRuntimeVersion
;
247 // locate and fill flex fields
248 size_t offset
= fixedSize(mDir
->version
);
251 mDir
->scatterOffset
= (uint32_t)offset
;
252 memcpy(mDir
->scatterVector(), mScatter
, mScatterSize
);
253 offset
+= mScatterSize
;
256 mDir
->identOffset
= (uint32_t)offset
;
257 memcpy(mDir
->identifier(), mIdentifier
.c_str(), identLength
);
258 offset
+= identLength
;
260 if (mTeamID
.size()) {
261 mDir
->teamIDOffset
= (uint32_t)offset
;
262 memcpy(mDir
->teamID(), mTeamID
.c_str(), teamIDLength
);
263 offset
+= teamIDLength
;
266 // (add new flexibly-allocated fields here)
268 /* Pre-encrypt hashes come before normal hashes, so that the kernel can free
269 * the normal, potentially post-encrypt hashes away easily. */
270 if (mGeneratePreEncryptHashes
|| !mPreservedPreEncryptHashMap
.empty()) {
271 mDir
->preEncryptOffset
= (uint32_t)offset
;
272 offset
+= mCodeSlots
* mDigestLength
;
275 mDir
->hashOffset
= (uint32_t)(offset
+ mSpecialSlots
* mDigestLength
);
276 offset
+= (mSpecialSlots
+ mCodeSlots
) * mDigestLength
;
278 assert(offset
== total
); // matches allocated size
282 // fill special slots
283 memset(mDir
->getSlotMutable((int)-mSpecialSlots
, false), 0, mDigestLength
* mSpecialSlots
);
284 for (size_t slot
= 1; slot
<= mSpecialSlots
; ++slot
)
285 memcpy(mDir
->getSlotMutable((int)-slot
, false), specialSlot((SpecialSlot
)slot
), mDigestLength
);
288 mExec
.seek(mExecOffset
);
289 size_t remaining
= mExecLength
;
290 for (unsigned int slot
= 0; slot
< mCodeSlots
; ++slot
) {
291 size_t thisPage
= remaining
;
293 thisPage
= min(thisPage
, mPageSize
);
294 MakeHash
<Builder
> hasher(this);
295 generateHash(hasher
, mExec
, mDir
->getSlotMutable(slot
, false), thisPage
);
296 if (mGeneratePreEncryptHashes
&& mPreservedPreEncryptHashMap
.empty()) {
297 memcpy(mDir
->getSlotMutable(slot
, true), mDir
->getSlot(slot
, false),
300 remaining
-= thisPage
;
302 assert(remaining
== 0);
304 PreEncryptHashMap::iterator preEncrypt
=
305 mPreservedPreEncryptHashMap
.find(mHashType
);
306 if (preEncrypt
!= mPreservedPreEncryptHashMap
.end()) {
307 memcpy(mDir
->getSlotMutable(0, true),
308 CFDataGetBytePtr(preEncrypt
->second
),
309 mCodeSlots
* mDigestLength
);
310 mPreservedPreEncryptHashMap
.erase(preEncrypt
->first
); // Releases the CFData memory.
313 // all done. Pass ownership to caller