]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_codesigning/lib/CodeSigner.cpp
Security-58286.70.7.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)
174 return true;
175 return mSigner;
176 }
177
178
179 //
180 // Sign code
181 //
182 void SecCodeSigner::sign(SecStaticCode *code, SecCSFlags flags)
183 {
184 code->setValidationFlags(flags);
185 if (code->isSigned() && (flags & kSecCSSignPreserveSignature))
186 return;
187 Signer operation(*this, code);
188 if ((flags | mOpFlags) & kSecCSRemoveSignature) {
189 secinfo("signer", "%p will remove signature from %p", this, code);
190 operation.remove(flags);
191 } else {
192 if (!valid())
193 MacOSError::throwMe(errSecCSInvalidObjectRef);
194 secinfo("signer", "%p will sign %p (flags 0x%x)", this, code, flags);
195 operation.sign(flags);
196 }
197 code->resetValidity();
198 }
199
200
201 //
202 // ReturnDetachedSignature is called by writers or editors that try to return
203 // detached signature data (rather than annotate the target).
204 //
205 void SecCodeSigner::returnDetachedSignature(BlobCore *blob, Signer &signer)
206 {
207 assert(mDetached);
208 if (CFGetTypeID(mDetached) == CFURLGetTypeID()) {
209 // URL to destination file
210 AutoFileDesc fd(cfString(CFURLRef(mDetached.get())), O_WRONLY | O_CREAT | O_TRUNC);
211 fd.writeAll(*blob);
212 } else if (CFGetTypeID(mDetached) == CFDataGetTypeID()) {
213 CFDataAppendBytes(CFMutableDataRef(mDetached.get()),
214 (const UInt8 *)blob, blob->length());
215 } else if (CFGetTypeID(mDetached) == CFNullGetTypeID()) {
216 SignatureDatabaseWriter db;
217 db.storeCode(blob, signer.path().c_str());
218 } else
219 assert(false);
220 }
221
222
223 //
224 // The actual parsing operation is done in the Parser class.
225 //
226 // Note that we need to copy or retain all incoming data. The caller has no requirement
227 // to keep the parameters dictionary around.
228 //
229 SecCodeSigner::Parser::Parser(SecCodeSigner &state, CFDictionaryRef parameters)
230 : CFDictionary(parameters, errSecCSBadDictionaryFormat)
231 {
232 // the signer may be an identity or null
233 state.mSigner = SecIdentityRef(get<CFTypeRef>(kSecCodeSignerIdentity));
234 if (state.mSigner)
235 if (CFGetTypeID(state.mSigner) != SecIdentityGetTypeID() && !CFEqual(state.mSigner, kCFNull))
236 MacOSError::throwMe(errSecCSInvalidObjectRef);
237
238 // the flags need some augmentation
239 if (CFNumberRef flags = get<CFNumberRef>(kSecCodeSignerFlags)) {
240 state.mCdFlagsGiven = true;
241 state.mCdFlags = cfNumber<uint32_t>(flags);
242 } else
243 state.mCdFlagsGiven = false;
244
245 // digest algorithms are specified as a numeric code
246 if (CFCopyRef<CFTypeRef> digestAlgorithms = get<CFTypeRef>(kSecCodeSignerDigestAlgorithm)) {
247 CFRef<CFArrayRef> array = cfArrayize(digestAlgorithms);
248 CFToVector<CodeDirectory::HashAlgorithm, CFNumberRef, cfNumber<CodeDirectory::HashAlgorithm> > digests(array);
249 std::copy(digests.begin(), digests.end(), std::inserter(state.mDigestAlgorithms, state.mDigestAlgorithms.begin()));
250 }
251
252 if (CFNumberRef cmsSize = get<CFNumberRef>(CFSTR("cmssize")))
253 state.mCMSSize = cfNumber<size_t>(cmsSize);
254 else
255 state.mCMSSize = 18000; // big enough for now, not forever.
256
257 // metadata preservation options
258 if (CFNumberRef preserve = get<CFNumberRef>(kSecCodeSignerPreserveMetadata)) {
259 state.mPreserveMetadata = cfNumber<uint32_t>(preserve);
260 } else
261 state.mPreserveMetadata = 0;
262
263 // signing time can be a CFDateRef or null
264 if (CFTypeRef time = get<CFTypeRef>(kSecCodeSignerSigningTime)) {
265 if (CFGetTypeID(time) == CFDateGetTypeID() || time == kCFNull)
266 state.mSigningTime = CFDateRef(time);
267 else
268 MacOSError::throwMe(errSecCSInvalidObjectRef);
269 }
270
271 if (CFStringRef ident = get<CFStringRef>(kSecCodeSignerIdentifier))
272 state.mIdentifier = cfString(ident);
273
274 if (CFStringRef teamid = get<CFStringRef>(kSecCodeSignerTeamIdentifier))
275 state.mTeamID = cfString(teamid);
276
277 if (CFNumberRef platform = get<CFNumberRef>(kSecCodeSignerPlatformIdentifier)) {
278 int64_t ident = cfNumber<int64_t>(platform);
279 if (ident < 0 || ident > maxPlatform) // overflow
280 MacOSError::throwMe(errSecCSInvalidPlatform);
281 state.mPlatform = ident;
282 }
283
284 if (CFStringRef prefix = get<CFStringRef>(kSecCodeSignerIdentifierPrefix))
285 state.mIdentifierPrefix = cfString(prefix);
286
287 // Requirements can be binary or string (to be compiled).
288 // We must pass them along to the signer for possible text substitution
289 if (CFTypeRef reqs = get<CFTypeRef>(kSecCodeSignerRequirements)) {
290 if (CFGetTypeID(reqs) == CFDataGetTypeID() || CFGetTypeID(reqs) == CFStringGetTypeID())
291 state.mRequirements = reqs;
292 else
293 MacOSError::throwMe(errSecCSInvalidObjectRef);
294 } else
295 state.mRequirements = NULL;
296
297 state.mNoMachO = getBool(CFSTR("no-macho"));
298
299 state.mPageSize = get<CFNumberRef>(kSecCodeSignerPageSize);
300
301 // detached can be (destination) file URL or (mutable) Data to be appended-to
302 if ((state.mDetached = get<CFTypeRef>(kSecCodeSignerDetached))) {
303 CFTypeID type = CFGetTypeID(state.mDetached);
304 if (type != CFURLGetTypeID() && type != CFDataGetTypeID() && type != CFNullGetTypeID())
305 MacOSError::throwMe(errSecCSInvalidObjectRef);
306 }
307
308 state.mDryRun = getBool(kSecCodeSignerDryRun);
309
310 state.mResourceRules = get<CFDictionaryRef>(kSecCodeSignerResourceRules);
311
312 state.mApplicationData = get<CFDataRef>(kSecCodeSignerApplicationData);
313 state.mEntitlementData = get<CFDataRef>(kSecCodeSignerEntitlements);
314
315 state.mSDKRoot = get<CFURLRef>(kSecCodeSignerSDKRoot);
316
317 if (CFBooleanRef timestampRequest = get<CFBooleanRef>(kSecCodeSignerRequireTimestamp)) {
318 state.mWantTimeStamp = timestampRequest == kCFBooleanTrue;
319 } else { // pick default
320 state.mWantTimeStamp = false;
321 if (state.mSigner && state.mSigner != SecIdentityRef(kCFNull)) {
322 CFRef<SecCertificateRef> signerCert;
323 MacOSError::check(SecIdentityCopyCertificate(state.mSigner, &signerCert.aref()));
324 if (certificateHasField(signerCert, devIdLeafMarkerOID))
325 state.mWantTimeStamp = true;
326 }
327 }
328 state.mTimestampAuthentication = get<SecIdentityRef>(kSecCodeSignerTimestampAuthentication);
329 state.mTimestampService = get<CFURLRef>(kSecCodeSignerTimestampServer);
330 state.mNoTimeStampCerts = getBool(kSecCodeSignerTimestampOmitCertificates);
331
332 if (CFStringRef runtimeVersionOverride = get<CFStringRef>(kSecCodeSignerRuntimeVersion)) {
333 std::string runtime = cfString(runtimeVersionOverride);
334 if (runtime.empty()) {
335 MacOSError::throwMe(errSecCSInvalidRuntimeVersion);
336 }
337 state.mRuntimeVersionOverride = parseRuntimeVersion(runtime);
338 }
339 }
340
341
342 } // end namespace CodeSigning
343 } // end namespace Security