]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_codesigning/lib/cdbuilder.cpp
Security-58286.70.7.tar.gz
[apple/security.git] / OSX / libsecurity_codesigning / lib / cdbuilder.cpp
1 /*
2 * Copyright (c) 2006-2012,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
24 //
25 // cdbuilder - constructor for CodeDirectories
26 //
27 #include "cdbuilder.h"
28 #include <security_utilities/memutils.h>
29 #include <cmath>
30
31 using namespace UnixPlusPlus;
32 using LowLevelMemoryUtilities::alignUp;
33
34
35 namespace Security {
36 namespace CodeSigning {
37
38
39 //
40 // Create an (empty) builder
41 //
42 CodeDirectory::Builder::Builder(HashAlgorithm digestAlgorithm)
43 : mFlags(0),
44 mHashType(digestAlgorithm),
45 mPlatform(0),
46 mSpecialSlots(0),
47 mCodeSlots(0),
48 mScatter(NULL),
49 mScatterSize(0),
50 mExecSegOffset(0),
51 mExecSegLimit(0),
52 mExecSegFlags(0),
53 mGeneratePreEncryptHashes(false),
54 mRuntimeVersion(0),
55 mDir(NULL)
56 {
57 mDigestLength = (uint32_t)MakeHash<Builder>(this)->digestLength();
58 mSpecial = (unsigned char *)calloc(cdSlotMax, mDigestLength);
59 }
60
61 CodeDirectory::Builder::~Builder()
62 {
63 ::free(mSpecial);
64 ::free(mScatter);
65 }
66
67
68 //
69 // Set the source of the main executable (i.e. the code pages)
70 //
71 void CodeDirectory::Builder::executable(string path,
72 size_t pagesize, size_t offset, size_t length)
73 {
74 mExec.close(); // any previously opened one
75 mExec.open(path);
76 mPageSize = pagesize;
77 mExecOffset = offset;
78 mExecLength = length;
79 }
80
81 void CodeDirectory::Builder::reopen(string path, size_t offset, size_t length)
82 {
83 assert(mExec); // already called executable()
84 mExec.close();
85 mExec.open(path);
86 mExecOffset = offset;
87 mExecLength = length;
88 }
89
90
91 //
92 // Set the source for one special slot
93 //
94 void CodeDirectory::Builder::specialSlot(SpecialSlot slot, CFDataRef data)
95 {
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;
103 }
104
105
106 //
107 // Allocate a Scatter vector
108 //
109 CodeDirectory::Scatter *CodeDirectory::Builder::scatter(unsigned count)
110 {
111 mScatterSize = (count + 1) * sizeof(Scatter);
112 if (!(mScatter = (Scatter *)::realloc(mScatter, mScatterSize)))
113 UnixError::throwMe(ENOMEM);
114 ::memset(mScatter, 0, mScatterSize);
115 return mScatter;
116 }
117
118 //
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.
122 //
123 size_t CodeDirectory::Builder::fixedSize(const uint32_t version)
124 {
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);
134
135 return cdSize;
136 }
137
138 //
139 // Calculate the size we'll need for the CodeDirectory as described so far
140 //
141 size_t CodeDirectory::Builder::size(const uint32_t version)
142 {
143 assert(mExec); // must have called executable()
144 if (mExecLength == 0)
145 mExecLength = mExec.fileSize() - mExecOffset;
146
147 // how many code pages?
148 if (mExecLength <= 0) { // no code, no slots
149 mCodeSlots = 0;
150 } else if (mPageSize == 0) { // indefinite - one page
151 mCodeSlots = 1;
152 } else { // finite - calculate from file size
153 mCodeSlots = (mExecLength - 1) / mPageSize + 1;
154 }
155
156 size_t offset = fixedSize(version);
157 size_t offset0 = offset;
158
159 offset += mScatterSize; // scatter vector
160 offset += mIdentifier.size() + 1; // size of identifier (with null byte)
161 if (mTeamID.size())
162 offset += mTeamID.size() + 1; // size of teamID (with null byte)
163 offset += (mCodeSlots + mSpecialSlots) * mDigestLength; // hash vector
164
165 if (mGeneratePreEncryptHashes || !mPreservedPreEncryptHashMap.empty()) {
166 offset += mCodeSlots * mDigestLength;
167 }
168
169 if (offset <= offset0)
170 UnixError::throwMe(ENOEXEC);
171
172 return offset;
173 }
174
175
176 //
177 // Take everything added to date and wrap it up in a shiny new CodeDirectory.
178 //
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.
188 //
189 CodeDirectory *CodeDirectory::Builder::build()
190 {
191 assert(mExec); // must have (successfully) called executable()
192 uint32_t version;
193
194 // size and allocate
195 size_t identLength = mIdentifier.size() + 1;
196 size_t teamIDLength = mTeamID.size() + 1;
197
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;
207 } else {
208 version = supportsScatter;
209 }
210
211 if (mCodeSlots > UINT32_MAX) // (still limited to 32 bits)
212 MacOSError::throwMe(errSecCSTooBig);
213
214 size_t total = size(version);
215 if (!(mDir = (CodeDirectory *)calloc(1, total))) // initialize to zero
216 UnixError::throwMe(ENOMEM);
217
218 // fill header
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;
227 } else {
228 mDir->codeLimit = uint32_t(mExecLength);
229 }
230 mDir->hashType = mHashType;
231 mDir->platform = mPlatform;
232 mDir->hashSize = mDigestLength;
233 if (mPageSize) {
234 int pglog;
235 assert(frexp(mPageSize, &pglog) == 0.5); // must be power of 2
236 frexp(mPageSize, &pglog);
237 assert(pglog < 256);
238 mDir->pageSize = pglog - 1;
239 } else
240 mDir->pageSize = 0; // means infinite page size
241
242 mDir->execSegBase = mExecSegOffset;
243 mDir->execSegLimit = mExecSegLimit;
244 mDir->execSegFlags = mExecSegFlags;
245 mDir->runtime = mRuntimeVersion;
246
247 // locate and fill flex fields
248 size_t offset = fixedSize(mDir->version);
249
250 if (mScatter) {
251 mDir->scatterOffset = (uint32_t)offset;
252 memcpy(mDir->scatterVector(), mScatter, mScatterSize);
253 offset += mScatterSize;
254 }
255
256 mDir->identOffset = (uint32_t)offset;
257 memcpy(mDir->identifier(), mIdentifier.c_str(), identLength);
258 offset += identLength;
259
260 if (mTeamID.size()) {
261 mDir->teamIDOffset = (uint32_t)offset;
262 memcpy(mDir->teamID(), mTeamID.c_str(), teamIDLength);
263 offset += teamIDLength;
264 }
265
266 // (add new flexibly-allocated fields here)
267
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;
273 }
274
275 mDir->hashOffset = (uint32_t)(offset + mSpecialSlots * mDigestLength);
276 offset += (mSpecialSlots + mCodeSlots) * mDigestLength;
277
278 assert(offset == total); // matches allocated size
279
280 (void)offset;
281
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);
286
287 // fill code slots
288 mExec.seek(mExecOffset);
289 size_t remaining = mExecLength;
290 for (unsigned int slot = 0; slot < mCodeSlots; ++slot) {
291 size_t thisPage = remaining;
292 if (mPageSize)
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),
298 mDir->hashSize);
299 }
300 remaining -= thisPage;
301 }
302 assert(remaining == 0);
303
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.
311 }
312
313 // all done. Pass ownership to caller
314 return mDir;
315 }
316
317
318 } // CodeSigning
319 } // Security