]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_codesigning/lib/CodeSigner.cpp
Security-57740.51.3.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
38 namespace Security {
39
40 __SEC_CFTYPE(SecIdentity)
41
42 namespace CodeSigning {
43
44 using namespace UnixPlusPlus;
45
46
47 //
48 // A helper for parsing out a CFDictionary signing-data specification
49 //
50 class SecCodeSigner::Parser : CFDictionary {
51 public:
52 Parser(SecCodeSigner &signer, CFDictionaryRef parameters);
53
54 bool getBool(CFStringRef key) const
55 {
56 if (CFBooleanRef flag = get<CFBooleanRef>(key))
57 return flag == kCFBooleanTrue;
58 else
59 return false;
60 }
61 };
62
63
64 //
65 // Construct a SecCodeSigner
66 //
67 SecCodeSigner::SecCodeSigner(SecCSFlags flags)
68 : mOpFlags(flags), mLimitedAsync(NULL)
69 {
70 }
71
72
73 //
74 // Clean up a SecCodeSigner
75 //
76 SecCodeSigner::~SecCodeSigner() throw()
77 try {
78 delete mLimitedAsync;
79 } catch (...) {
80 return;
81 }
82
83
84 //
85 // Parse an input parameter dictionary and set ready-to-use parameters
86 //
87 void SecCodeSigner::parameters(CFDictionaryRef paramDict)
88 {
89 Parser(*this, paramDict);
90 if (!valid())
91 MacOSError::throwMe(errSecCSInvalidObjectRef);
92 }
93
94 //
95 // Retrieve the team ID from the signing certificate if and only if
96 // it is an apple developer signing cert
97 //
98 std::string SecCodeSigner::getTeamIDFromSigner(CFArrayRef certs)
99 {
100 if (mSigner && mSigner != SecIdentityRef(kCFNull)) {
101 CFRef<SecCertificateRef> signerCert;
102 MacOSError::check(SecIdentityCopyCertificate(mSigner, &signerCert.aref()));
103
104 /* Make sure the certificate looks like an Apple certificate, because we do not
105 extract the team ID from a non Apple certificate */
106 if (SecStaticCode::isAppleDeveloperCert(certs)) {
107 CFRef<CFStringRef> teamIDFromCert;
108
109 MacOSError::check(SecCertificateCopySubjectComponent(signerCert.get(), &CSSMOID_OrganizationalUnitName, &teamIDFromCert.aref()));
110
111 if (teamIDFromCert)
112 return cfString(teamIDFromCert);
113 }
114 }
115
116 return "";
117 }
118
119 //
120 // Roughly check for validity.
121 // This isn't thorough; it just sees if if looks like we've set up the object appropriately.
122 //
123 bool SecCodeSigner::valid() const
124 {
125 if (mOpFlags & kSecCSRemoveSignature)
126 return true;
127 return mSigner;
128 }
129
130
131 //
132 // Sign code
133 //
134 void SecCodeSigner::sign(SecStaticCode *code, SecCSFlags flags)
135 {
136 code->setValidationFlags(flags);
137 if (code->isSigned() && (flags & kSecCSSignPreserveSignature))
138 return;
139 Signer operation(*this, code);
140 if ((flags | mOpFlags) & kSecCSRemoveSignature) {
141 secinfo("signer", "%p will remove signature from %p", this, code);
142 operation.remove(flags);
143 } else {
144 if (!valid())
145 MacOSError::throwMe(errSecCSInvalidObjectRef);
146 secinfo("signer", "%p will sign %p (flags 0x%x)", this, code, flags);
147 operation.sign(flags);
148 }
149 code->resetValidity();
150 }
151
152
153 //
154 // ReturnDetachedSignature is called by writers or editors that try to return
155 // detached signature data (rather than annotate the target).
156 //
157 void SecCodeSigner::returnDetachedSignature(BlobCore *blob, Signer &signer)
158 {
159 assert(mDetached);
160 if (CFGetTypeID(mDetached) == CFURLGetTypeID()) {
161 // URL to destination file
162 AutoFileDesc fd(cfString(CFURLRef(mDetached.get())), O_WRONLY | O_CREAT | O_TRUNC);
163 fd.writeAll(*blob);
164 } else if (CFGetTypeID(mDetached) == CFDataGetTypeID()) {
165 CFDataAppendBytes(CFMutableDataRef(mDetached.get()),
166 (const UInt8 *)blob, blob->length());
167 } else if (CFGetTypeID(mDetached) == CFNullGetTypeID()) {
168 SignatureDatabaseWriter db;
169 db.storeCode(blob, signer.path().c_str());
170 } else
171 assert(false);
172 }
173
174
175 //
176 // The actual parsing operation is done in the Parser class.
177 //
178 // Note that we need to copy or retain all incoming data. The caller has no requirement
179 // to keep the parameters dictionary around.
180 //
181 SecCodeSigner::Parser::Parser(SecCodeSigner &state, CFDictionaryRef parameters)
182 : CFDictionary(parameters, errSecCSBadDictionaryFormat)
183 {
184 // the signer may be an identity or null
185 state.mSigner = SecIdentityRef(get<CFTypeRef>(kSecCodeSignerIdentity));
186 if (state.mSigner)
187 if (CFGetTypeID(state.mSigner) != SecIdentityGetTypeID() && !CFEqual(state.mSigner, kCFNull))
188 MacOSError::throwMe(errSecCSInvalidObjectRef);
189
190 // the flags need some augmentation
191 if (CFNumberRef flags = get<CFNumberRef>(kSecCodeSignerFlags)) {
192 state.mCdFlagsGiven = true;
193 state.mCdFlags = cfNumber<uint32_t>(flags);
194 } else
195 state.mCdFlagsGiven = false;
196
197 // digest algorithms are specified as a numeric code
198 if (CFCopyRef<CFTypeRef> digestAlgorithms = get<CFTypeRef>(kSecCodeSignerDigestAlgorithm)) {
199 CFRef<CFArrayRef> array = cfArrayize(digestAlgorithms);
200 CFToVector<CodeDirectory::HashAlgorithm, CFNumberRef, cfNumber<CodeDirectory::HashAlgorithm> > digests(array);
201 std::copy(digests.begin(), digests.end(), std::inserter(state.mDigestAlgorithms, state.mDigestAlgorithms.begin()));
202 }
203
204 if (CFNumberRef cmsSize = get<CFNumberRef>(CFSTR("cmssize")))
205 state.mCMSSize = cfNumber<size_t>(cmsSize);
206 else
207 state.mCMSSize = 9000; // likely big enough
208
209 // metadata preservation options
210 if (CFNumberRef preserve = get<CFNumberRef>(kSecCodeSignerPreserveMetadata)) {
211 state.mPreserveMetadata = cfNumber<uint32_t>(preserve);
212 } else
213 state.mPreserveMetadata = 0;
214
215 // signing time can be a CFDateRef or null
216 if (CFTypeRef time = get<CFTypeRef>(kSecCodeSignerSigningTime)) {
217 if (CFGetTypeID(time) == CFDateGetTypeID() || time == kCFNull)
218 state.mSigningTime = CFDateRef(time);
219 else
220 MacOSError::throwMe(errSecCSInvalidObjectRef);
221 }
222
223 if (CFStringRef ident = get<CFStringRef>(kSecCodeSignerIdentifier))
224 state.mIdentifier = cfString(ident);
225
226 if (CFStringRef teamid = get<CFStringRef>(kSecCodeSignerTeamIdentifier))
227 state.mTeamID = cfString(teamid);
228
229 if (CFNumberRef platform = get<CFNumberRef>(kSecCodeSignerPlatformIdentifier)) {
230 int64_t ident = cfNumber<int64_t>(platform);
231 if (ident < 0 || ident > maxPlatform) // overflow
232 MacOSError::throwMe(errSecCSInvalidPlatform);
233 state.mPlatform = ident;
234 }
235
236 if (CFStringRef prefix = get<CFStringRef>(kSecCodeSignerIdentifierPrefix))
237 state.mIdentifierPrefix = cfString(prefix);
238
239 // Requirements can be binary or string (to be compiled).
240 // We must pass them along to the signer for possible text substitution
241 if (CFTypeRef reqs = get<CFTypeRef>(kSecCodeSignerRequirements)) {
242 if (CFGetTypeID(reqs) == CFDataGetTypeID() || CFGetTypeID(reqs) == CFStringGetTypeID())
243 state.mRequirements = reqs;
244 else
245 MacOSError::throwMe(errSecCSInvalidObjectRef);
246 } else
247 state.mRequirements = NULL;
248
249 state.mNoMachO = getBool(CFSTR("no-macho"));
250
251 state.mPageSize = get<CFNumberRef>(kSecCodeSignerPageSize);
252
253 // detached can be (destination) file URL or (mutable) Data to be appended-to
254 if ((state.mDetached = get<CFTypeRef>(kSecCodeSignerDetached))) {
255 CFTypeID type = CFGetTypeID(state.mDetached);
256 if (type != CFURLGetTypeID() && type != CFDataGetTypeID() && type != CFNullGetTypeID())
257 MacOSError::throwMe(errSecCSInvalidObjectRef);
258 }
259
260 state.mDryRun = getBool(kSecCodeSignerDryRun);
261
262 state.mResourceRules = get<CFDictionaryRef>(kSecCodeSignerResourceRules);
263
264 state.mApplicationData = get<CFDataRef>(kSecCodeSignerApplicationData);
265 state.mEntitlementData = get<CFDataRef>(kSecCodeSignerEntitlements);
266
267 state.mSDKRoot = get<CFURLRef>(kSecCodeSignerSDKRoot);
268
269 if (CFBooleanRef timestampRequest = get<CFBooleanRef>(kSecCodeSignerRequireTimestamp)) {
270 state.mWantTimeStamp = timestampRequest == kCFBooleanTrue;
271 } else { // pick default
272 state.mWantTimeStamp = false;
273 if (state.mSigner && state.mSigner != SecIdentityRef(kCFNull)) {
274 CFRef<SecCertificateRef> signerCert;
275 MacOSError::check(SecIdentityCopyCertificate(state.mSigner, &signerCert.aref()));
276 if (certificateHasField(signerCert, devIdLeafMarkerOID))
277 state.mWantTimeStamp = true;
278 }
279 }
280 state.mTimestampAuthentication = get<SecIdentityRef>(kSecCodeSignerTimestampAuthentication);
281 state.mTimestampService = get<CFURLRef>(kSecCodeSignerTimestampServer);
282 state.mNoTimeStampCerts = getBool(kSecCodeSignerTimestampOmitCertificates);
283 }
284
285
286 } // end namespace CodeSigning
287 } // end namespace Security