]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_codesigning/lib/csutilities.cpp
Security-59754.41.1.tar.gz
[apple/security.git] / OSX / libsecurity_codesigning / lib / csutilities.cpp
1 /*
2 * Copyright (c) 2006-2013 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 // csutilities - miscellaneous utilities for the code signing implementation
26 //
27
28 #include "csutilities.h"
29 #include <libDER/DER_Encode.h>
30 #include <libDER/DER_Keys.h>
31 #include <libDER/asn1Types.h>
32 #include <libDER/oids.h>
33 #include <security_asn1/SecAsn1Coder.h>
34 #include <security_asn1/SecAsn1Templates.h>
35 #include <Security/SecCertificatePriv.h>
36 #include <Security/SecCertificate.h>
37 #include <Security/SecPolicyPriv.h>
38 #include <utilities/SecAppleAnchorPriv.h>
39 #include <utilities/SecInternalReleasePriv.h>
40 #include "requirement.h"
41 #include <security_utilities/hashing.h>
42 #include <security_utilities/debugging.h>
43 #include <security_utilities/errors.h>
44 #include <sys/mount.h>
45 #include <sys/utsname.h>
46 #include "debugging.h"
47
48 extern "C" {
49
50 /* Decode a choice of UTCTime or GeneralizedTime to a CFAbsoluteTime. Return
51 an absoluteTime if the date was valid and properly decoded. Return
52 NULL_TIME otherwise. */
53 CFAbsoluteTime SecAbsoluteTimeFromDateContent(DERTag tag, const uint8_t *bytes,
54 size_t length);
55
56 }
57
58 namespace Security {
59 namespace CodeSigning {
60
61
62 //
63 // Test for the canonical Apple CA certificate
64 //
65 bool isAppleCA(SecCertificateRef cert)
66 {
67 SecAppleTrustAnchorFlags flags = 0;
68 if (SecIsInternalRelease())
69 flags |= kSecAppleTrustAnchorFlagsIncludeTestAnchors;
70 return SecIsAppleTrustAnchor(cert, flags);
71 }
72
73
74 //
75 // Calculate the canonical hash of a certificate, given its raw (DER) data.
76 //
77 void hashOfCertificate(const void *certData, size_t certLength, SHA1::Digest digest)
78 {
79 SHA1 hasher;
80 hasher(certData, certLength);
81 hasher.finish(digest);
82 }
83
84
85 //
86 // Ditto, given a SecCertificateRef
87 //
88 void hashOfCertificate(SecCertificateRef cert, SHA1::Digest digest)
89 {
90 assert(cert);
91 hashOfCertificate(SecCertificateGetBytePtr(cert), SecCertificateGetLength(cert), digest);
92 }
93
94
95 //
96 // One-stop hash-certificate-and-compare
97 //
98 bool verifyHash(SecCertificateRef cert, const Hashing::Byte *digest)
99 {
100 SHA1::Digest dig;
101 hashOfCertificate(cert, dig);
102 return !memcmp(dig, digest, SHA1::digestLength);
103 }
104
105 #if TARGET_OS_OSX
106 //
107 // Check to see if a certificate contains a particular field, by OID. This works for extensions,
108 // even ones not recognized by the local CL. It does not return any value, only presence.
109 //
110 bool certificateHasField(SecCertificateRef cert, const CSSM_OID &oid)
111 {
112 CFDataRef oidData = NULL;
113 CFDataRef data = NULL;
114 bool isCritical = false;
115 bool matched = false;
116
117 oidData = CFDataCreateWithBytesNoCopy(NULL, oid.Data, oid.Length,
118 kCFAllocatorNull);
119 if (!(cert && oidData)) {
120 goto out;
121 }
122 data = SecCertificateCopyExtensionValue(cert, oidData, &isCritical);
123 if (data == NULL) {
124 goto out;
125 }
126 matched = true;
127 out:
128 if (data) {
129 CFRelease(data);
130 }
131 if (oidData) {
132 CFRelease(oidData);
133 }
134 return matched;
135 }
136
137
138 //
139 // Retrieve X.509 policy extension OIDs, if any.
140 // This currently ignores policy qualifiers.
141 //
142 bool certificateHasPolicy(SecCertificateRef cert, const CSSM_OID &policyOid)
143 {
144 bool matched = false;
145 CFDataRef oidData = CFDataCreateWithBytesNoCopy(NULL, policyOid.Data, policyOid.Length,
146 kCFAllocatorNull);
147 if (!(cert && oidData)) {
148 goto out;
149 }
150 matched = SecPolicyCheckCertCertificatePolicy(cert, oidData);
151 out:
152 if (oidData) {
153 CFRelease(oidData);
154 }
155 return matched;
156 }
157
158
159 CFDateRef certificateCopyFieldDate(SecCertificateRef cert, const CSSM_OID &policyOid)
160 {
161 CFDataRef oidData = NULL;
162 CFDateRef value = NULL;
163 CFDataRef data = NULL;
164 SecAsn1CoderRef coder = NULL;
165 CSSM_DATA str = { 0 };
166 CFAbsoluteTime time = 0.0;
167 OSStatus status = 0;
168 bool isCritical;
169
170 oidData = CFDataCreateWithBytesNoCopy(NULL, policyOid.Data, policyOid.Length,
171 kCFAllocatorNull);
172
173 if (oidData == NULL) {
174 goto out;
175 }
176
177 data = SecCertificateCopyExtensionValue(cert, oidData, &isCritical);
178
179 if (data == NULL) {
180 goto out;
181 }
182
183 status = SecAsn1CoderCreate(&coder);
184 if (status != 0) {
185 goto out;
186 }
187
188 // We currently only support UTF8 strings.
189 status = SecAsn1Decode(coder, CFDataGetBytePtr(data), CFDataGetLength(data),
190 kSecAsn1UTF8StringTemplate, &str);
191 if (status != 0) {
192 goto out;
193 }
194
195 time = SecAbsoluteTimeFromDateContent(ASN1_GENERALIZED_TIME,
196 str.Data, str.Length);
197
198 if (time == 0.0) {
199 goto out;
200 }
201
202 value = CFDateCreate(NULL, time);
203 out:
204 if (coder) {
205 SecAsn1CoderRelease(coder);
206 }
207 if (data) {
208 CFRelease(data);
209 }
210 if (oidData) {
211 CFRelease(oidData);
212 }
213
214 return value;
215 }
216 #endif
217
218 //
219 // Copyfile
220 //
221 Copyfile::Copyfile()
222 {
223 if (!(mState = copyfile_state_alloc()))
224 UnixError::throwMe();
225 }
226
227 void Copyfile::set(uint32_t flag, const void *value)
228 {
229 check(::copyfile_state_set(mState, flag, value));
230 }
231
232 void Copyfile::get(uint32_t flag, void *value)
233 {
234 check(::copyfile_state_set(mState, flag, value));
235 }
236
237 void Copyfile::operator () (const char *src, const char *dst, copyfile_flags_t flags)
238 {
239 check(::copyfile(src, dst, mState, flags));
240 }
241
242 void Copyfile::check(int rc)
243 {
244 if (rc < 0)
245 UnixError::throwMe();
246 }
247
248
249 //
250 // MessageTracer support
251 //
252 MessageTrace::MessageTrace(const char *domain, const char *signature)
253 {
254 mAsl = asl_new(ASL_TYPE_MSG);
255 if (domain)
256 asl_set(mAsl, "com.apple.message.domain", domain);
257 if (signature)
258 asl_set(mAsl, "com.apple.message.signature", signature);
259 }
260
261 void MessageTrace::add(const char *key, const char *format, ...)
262 {
263 va_list args;
264 va_start(args, format);
265 char value[200];
266 vsnprintf(value, sizeof(value), format, args);
267 va_end(args);
268 asl_set(mAsl, (string("com.apple.message.") + key).c_str(), value);
269 }
270
271 void MessageTrace::send(const char *format, ...)
272 {
273 va_list args;
274 va_start(args, format);
275 asl_vlog(NULL, mAsl, ASL_LEVEL_NOTICE, format, args);
276 va_end(args);
277 }
278
279
280
281 // Resource limited async workers for doing work on nested bundles
282 LimitedAsync::LimitedAsync(bool async)
283 {
284 // validate multiple resources concurrently if bundle resides on solid-state media
285
286 // How many async workers to spin off. If zero, validating only happens synchronously.
287 long async_workers = 0;
288
289 long ncpu = sysconf(_SC_NPROCESSORS_ONLN);
290
291 if (async && ncpu > 0)
292 async_workers = ncpu - 1; // one less because this thread also validates
293
294 mResourceSemaphore = new Dispatch::Semaphore(async_workers);
295 }
296
297 LimitedAsync::LimitedAsync(LimitedAsync &limitedAsync)
298 {
299 mResourceSemaphore = new Dispatch::Semaphore(*limitedAsync.mResourceSemaphore);
300 }
301
302 LimitedAsync::~LimitedAsync()
303 {
304 delete mResourceSemaphore;
305 }
306
307 bool LimitedAsync::perform(Dispatch::Group &groupRef, void (^block)()) {
308 __block Dispatch::SemaphoreWait wait(*mResourceSemaphore, DISPATCH_TIME_NOW);
309
310 if (wait.acquired()) {
311 dispatch_queue_t defaultQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
312
313 groupRef.enqueue(defaultQueue, ^{
314 // Hold the semaphore count until the worker is done validating.
315 Dispatch::SemaphoreWait innerWait(wait);
316 block();
317 });
318 return true;
319 } else {
320 block();
321 return false;
322 }
323 }
324
325 bool isOnRootFilesystem(const char *path)
326 {
327 int rc = 0;
328 struct statfs sfb;
329
330 rc = statfs(path, &sfb);
331 if (rc != 0) {
332 secerror("Unable to check if path is on rootfs: %d, %s", errno, path);
333 return false;
334 }
335 return ((sfb.f_flags & MNT_ROOTFS) == MNT_ROOTFS);
336 }
337
338 } // end namespace CodeSigning
339 } // end namespace Security