]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_codesigning/lib/CodeSigner.cpp
Security-58286.251.4.tar.gz
[apple/security.git] / OSX / libsecurity_codesigning / lib / CodeSigner.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
24 //
25 // CodeSigner - SecCodeSigner API objects
26 //
27 #include "CodeSigner.h"
28 #include "signer.h"
29 #include "csdatabase.h"
30 #include "drmaker.h"
31 #include "csutilities.h"
32 #include <security_utilities/unix++.h>
33 #include <security_utilities/unixchild.h>
34 #include <Security/SecCertificate.h>
35 #include <Security/SecCertificatePriv.h>
36 #include <vector>
37 #include <errno.h>
38
39 namespace Security {
40
41 __SEC_CFTYPE(SecIdentity)
42
43 namespace CodeSigning {
44
45 using namespace UnixPlusPlus;
46
47
48 //
49 // A helper for parsing out a CFDictionary signing-data specification
50 //
51 class SecCodeSigner::Parser : CFDictionary {
52 public:
53 Parser(SecCodeSigner &signer, CFDictionaryRef parameters);
54
55 bool getBool(CFStringRef key) const
56 {
57 if (CFBooleanRef flag = get<CFBooleanRef>(key))
58 return flag == kCFBooleanTrue;
59 else
60 return false;
61 }
62
63 uint32_t parseRuntimeVersion(std::string& runtime)
64 {
65 uint32_t version = 0;
66 char* cursor = const_cast<char*>(runtime.c_str());
67 char* end = cursor + runtime.length();
68 char* nxt = NULL;
69 long component = 0;
70 int component_shift = 16;
71
72 // x should convert to 0x00XX0000
73 // x.y should convert to 0x00XXYY00
74 // x.y.z should covert to 0x00XXYYZZ
75 // 0, 0.0, and 0.0.0 are rejected
76 // anything else should be rejected
77 while (cursor < end) {
78 nxt = NULL;
79 errno = 0;
80 component = strtol(cursor, &nxt, 10);
81 if (cursor == nxt ||
82 (errno != 0) ||
83 (component < 0 || component > UINT8_MAX)) {
84 secdebug("signer", "Runtime version: %s is invalid", runtime.c_str());
85 MacOSError::throwMe(errSecCSInvalidRuntimeVersion);
86 }
87 version |= (component & 0xff) << component_shift;
88 component_shift -= 8;
89
90 if (*nxt == '\0') {
91 break;
92 }
93
94 if (*nxt != '.' || component_shift < 0 || (nxt + 1) == end) {
95 // Catch a trailing "."
96 secdebug("signer", "Runtime version: %s is invalid", runtime.c_str());
97 MacOSError::throwMe(errSecCSInvalidRuntimeVersion);
98 }
99 cursor = nxt + 1;
100 }
101
102 if (version == 0) {
103 secdebug("signer","Runtime version: %s is a version of zero", runtime.c_str());
104 MacOSError::throwMe(errSecCSInvalidRuntimeVersion);
105 }
106
107 return version;
108 }
109 };
110
111
112 //
113 // Construct a SecCodeSigner
114 //
115 SecCodeSigner::SecCodeSigner(SecCSFlags flags)
116 : mOpFlags(flags), mLimitedAsync(NULL), mRuntimeVersionOverride(0)
117 {
118 }
119
120
121 //
122 // Clean up a SecCodeSigner
123 //
124 SecCodeSigner::~SecCodeSigner() throw()
125 try {
126 delete mLimitedAsync;
127 } catch (...) {
128 return;
129 }
130
131
132 //
133 // Parse an input parameter dictionary and set ready-to-use parameters
134 //
135 void SecCodeSigner::parameters(CFDictionaryRef paramDict)
136 {
137 Parser(*this, paramDict);
138 if (!valid())
139 MacOSError::throwMe(errSecCSInvalidObjectRef);
140 }
141
142 //
143 // Retrieve the team ID from the signing certificate if and only if
144 // it is an apple developer signing cert
145 //
146 std::string SecCodeSigner::getTeamIDFromSigner(CFArrayRef certs)
147 {
148 if (mSigner && mSigner != SecIdentityRef(kCFNull)) {
149 CFRef<SecCertificateRef> signerCert;
150 MacOSError::check(SecIdentityCopyCertificate(mSigner, &signerCert.aref()));
151
152 /* Make sure the certificate looks like an Apple certificate, because we do not
153 extract the team ID from a non Apple certificate */
154 if (SecStaticCode::isAppleDeveloperCert(certs)) {
155 CFRef<CFStringRef> teamIDFromCert;
156
157 MacOSError::check(SecCertificateCopySubjectComponent(signerCert.get(), &CSSMOID_OrganizationalUnitName, &teamIDFromCert.aref()));
158
159 if (teamIDFromCert)
160 return cfString(teamIDFromCert);
161 }
162 }
163
164 return "";
165 }
166
167 //
168 // Roughly check for validity.
169 // This isn't thorough; it just sees if if looks like we've set up the object appropriately.
170 //
171 bool SecCodeSigner::valid() const
172 {
173 if (mOpFlags & (kSecCSRemoveSignature | kSecCSEditSignature)) {
174 return true;
175 }
176 return mSigner;
177 }
178
179
180 //
181 // Sign code
182 //
183 void SecCodeSigner::sign(SecStaticCode *code, SecCSFlags flags)
184 {
185 code->setValidationFlags(flags);
186 if (code->isSigned() && (flags & kSecCSSignPreserveSignature))
187 return;
188 Signer operation(*this, code);
189 if ((flags | mOpFlags) & kSecCSRemoveSignature) {
190 secinfo("signer", "%p will remove signature from %p", this, code);
191 operation.remove(flags);
192 } else if ((flags | mOpFlags) & kSecCSEditSignature) {
193 secinfo("signer", "%p will edit signature of %p", this, code);
194 operation.edit(flags);
195 } else {
196 if (!valid())
197 MacOSError::throwMe(errSecCSInvalidObjectRef);
198 secinfo("signer", "%p will sign %p (flags 0x%x)", this, code, flags);
199 operation.sign(flags);
200 }
201 code->resetValidity();
202 }
203
204
205 //
206 // ReturnDetachedSignature is called by writers or editors that try to return
207 // detached signature data (rather than annotate the target).
208 //
209 void SecCodeSigner::returnDetachedSignature(BlobCore *blob, Signer &signer)
210 {
211 assert(mDetached);
212 if (CFGetTypeID(mDetached) == CFURLGetTypeID()) {
213 // URL to destination file
214 AutoFileDesc fd(cfString(CFURLRef(mDetached.get())), O_WRONLY | O_CREAT | O_TRUNC);
215 fd.writeAll(*blob);
216 } else if (CFGetTypeID(mDetached) == CFDataGetTypeID()) {
217 CFDataAppendBytes(CFMutableDataRef(mDetached.get()),
218 (const UInt8 *)blob, blob->length());
219 } else if (CFGetTypeID(mDetached) == CFNullGetTypeID()) {
220 SignatureDatabaseWriter db;
221 db.storeCode(blob, signer.path().c_str());
222 } else
223 assert(false);
224 }
225
226
227 //
228 // The actual parsing operation is done in the Parser class.
229 //
230 // Note that we need to copy or retain all incoming data. The caller has no requirement
231 // to keep the parameters dictionary around.
232 //
233 SecCodeSigner::Parser::Parser(SecCodeSigner &state, CFDictionaryRef parameters)
234 : CFDictionary(parameters, errSecCSBadDictionaryFormat)
235 {
236 CFNumberRef editCpuType = get<CFNumberRef>(kSecCodeSignerEditCpuType);
237 CFNumberRef editCpuSubtype = get<CFNumberRef>(kSecCodeSignerEditCpuSubtype);
238 if (editCpuType != NULL && editCpuSubtype != NULL) {
239 state.mEditArch = Architecture(cfNumber<uint32_t>(editCpuType),
240 cfNumber<uint32_t>(editCpuSubtype));
241 }
242
243 state.mEditCMS = get<CFDataRef>(kSecCodeSignerEditCMS);
244
245 state.mDryRun = getBool(kSecCodeSignerDryRun);
246
247 state.mSDKRoot = get<CFURLRef>(kSecCodeSignerSDKRoot);
248
249 state.mPreserveAFSC = getBool(kSecCodeSignerPreserveAFSC);
250
251 if (state.mOpFlags & kSecCSEditSignature) {
252 return;
253 /* Everything below this point is irrelevant for
254 * Signature Editing, which does not create any
255 * parts of the signature, only replaces them.
256 */
257 }
258
259 // the signer may be an identity or null
260 state.mSigner = SecIdentityRef(get<CFTypeRef>(kSecCodeSignerIdentity));
261 if (state.mSigner)
262 if (CFGetTypeID(state.mSigner) != SecIdentityGetTypeID() && !CFEqual(state.mSigner, kCFNull))
263 MacOSError::throwMe(errSecCSInvalidObjectRef);
264
265 // the flags need some augmentation
266 if (CFNumberRef flags = get<CFNumberRef>(kSecCodeSignerFlags)) {
267 state.mCdFlagsGiven = true;
268 state.mCdFlags = cfNumber<uint32_t>(flags);
269 } else
270 state.mCdFlagsGiven = false;
271
272 // digest algorithms are specified as a numeric code
273 if (CFCopyRef<CFTypeRef> digestAlgorithms = get<CFTypeRef>(kSecCodeSignerDigestAlgorithm)) {
274 CFRef<CFArrayRef> array = cfArrayize(digestAlgorithms);
275 CFToVector<CodeDirectory::HashAlgorithm, CFNumberRef, cfNumber<CodeDirectory::HashAlgorithm> > digests(array);
276 std::copy(digests.begin(), digests.end(), std::inserter(state.mDigestAlgorithms, state.mDigestAlgorithms.begin()));
277 }
278
279 if (CFNumberRef cmsSize = get<CFNumberRef>(CFSTR("cmssize")))
280 state.mCMSSize = cfNumber<size_t>(cmsSize);
281 else
282 state.mCMSSize = 18000; // big enough for now, not forever.
283
284 // metadata preservation options
285 if (CFNumberRef preserve = get<CFNumberRef>(kSecCodeSignerPreserveMetadata)) {
286 state.mPreserveMetadata = cfNumber<uint32_t>(preserve);
287 } else
288 state.mPreserveMetadata = 0;
289
290 // signing time can be a CFDateRef or null
291 if (CFTypeRef time = get<CFTypeRef>(kSecCodeSignerSigningTime)) {
292 if (CFGetTypeID(time) == CFDateGetTypeID() || time == kCFNull)
293 state.mSigningTime = CFDateRef(time);
294 else
295 MacOSError::throwMe(errSecCSInvalidObjectRef);
296 }
297
298 if (CFStringRef ident = get<CFStringRef>(kSecCodeSignerIdentifier))
299 state.mIdentifier = cfString(ident);
300
301 if (CFStringRef teamid = get<CFStringRef>(kSecCodeSignerTeamIdentifier))
302 state.mTeamID = cfString(teamid);
303
304 if (CFNumberRef platform = get<CFNumberRef>(kSecCodeSignerPlatformIdentifier)) {
305 int64_t ident = cfNumber<int64_t>(platform);
306 if (ident < 0 || ident > maxPlatform) // overflow
307 MacOSError::throwMe(errSecCSInvalidPlatform);
308 state.mPlatform = ident;
309 }
310
311 if (CFStringRef prefix = get<CFStringRef>(kSecCodeSignerIdentifierPrefix))
312 state.mIdentifierPrefix = cfString(prefix);
313
314 // Requirements can be binary or string (to be compiled).
315 // We must pass them along to the signer for possible text substitution
316 if (CFTypeRef reqs = get<CFTypeRef>(kSecCodeSignerRequirements)) {
317 if (CFGetTypeID(reqs) == CFDataGetTypeID() || CFGetTypeID(reqs) == CFStringGetTypeID())
318 state.mRequirements = reqs;
319 else
320 MacOSError::throwMe(errSecCSInvalidObjectRef);
321 } else
322 state.mRequirements = NULL;
323
324 state.mNoMachO = getBool(CFSTR("no-macho"));
325
326 state.mPageSize = get<CFNumberRef>(kSecCodeSignerPageSize);
327
328 // detached can be (destination) file URL or (mutable) Data to be appended-to
329 if ((state.mDetached = get<CFTypeRef>(kSecCodeSignerDetached))) {
330 CFTypeID type = CFGetTypeID(state.mDetached);
331 if (type != CFURLGetTypeID() && type != CFDataGetTypeID() && type != CFNullGetTypeID())
332 MacOSError::throwMe(errSecCSInvalidObjectRef);
333 }
334
335 state.mResourceRules = get<CFDictionaryRef>(kSecCodeSignerResourceRules);
336
337 state.mApplicationData = get<CFDataRef>(kSecCodeSignerApplicationData);
338 state.mEntitlementData = get<CFDataRef>(kSecCodeSignerEntitlements);
339
340 if (CFBooleanRef timestampRequest = get<CFBooleanRef>(kSecCodeSignerRequireTimestamp)) {
341 state.mWantTimeStamp = timestampRequest == kCFBooleanTrue;
342 } else { // pick default
343 state.mWantTimeStamp = false;
344 if (state.mSigner && state.mSigner != SecIdentityRef(kCFNull)) {
345 CFRef<SecCertificateRef> signerCert;
346 MacOSError::check(SecIdentityCopyCertificate(state.mSigner, &signerCert.aref()));
347 if (certificateHasField(signerCert, devIdLeafMarkerOID))
348 state.mWantTimeStamp = true;
349 }
350 }
351 state.mTimestampAuthentication = get<SecIdentityRef>(kSecCodeSignerTimestampAuthentication);
352 state.mTimestampService = get<CFURLRef>(kSecCodeSignerTimestampServer);
353 state.mNoTimeStampCerts = getBool(kSecCodeSignerTimestampOmitCertificates);
354
355 if (CFStringRef runtimeVersionOverride = get<CFStringRef>(kSecCodeSignerRuntimeVersion)) {
356 std::string runtime = cfString(runtimeVersionOverride);
357 if (runtime.empty()) {
358 MacOSError::throwMe(errSecCSInvalidRuntimeVersion);
359 }
360 state.mRuntimeVersionOverride = parseRuntimeVersion(runtime);
361 }
362
363 // Don't add the adhoc flag, even if no signer identity was specified.
364 // Useful for editing in the CMS at a later point.
365 state.mOmitAdhocFlag = getBool(kSecCodeSignerOmitAdhocFlag);
366 }
367
368
369 } // end namespace CodeSigning
370 } // end namespace Security