2 * Copyright (c) 2006-2013 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
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
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.
21 * @APPLE_LICENSE_HEADER_END@
25 // csutilities - miscellaneous utilities for the code signing implementation
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 <utilities/SecAppleAnchorPriv.h>
38 #include <utilities/SecInternalReleasePriv.h>
39 #include "requirement.h"
40 #include <security_utilities/hashing.h>
41 #include <security_utilities/debugging.h>
42 #include <security_utilities/errors.h>
43 #include <sys/utsname.h>
47 /* Decode a choice of UTCTime or GeneralizedTime to a CFAbsoluteTime. Return
48 an absoluteTime if the date was valid and properly decoded. Return
49 NULL_TIME otherwise. */
50 CFAbsoluteTime
SecAbsoluteTimeFromDateContent(DERTag tag
, const uint8_t *bytes
,
56 namespace CodeSigning
{
60 // Test for the canonical Apple CA certificate
62 bool isAppleCA(SecCertificateRef cert
)
64 SecAppleTrustAnchorFlags flags
= 0;
65 if (SecIsInternalRelease())
66 flags
|= kSecAppleTrustAnchorFlagsIncludeTestAnchors
;
67 return SecIsAppleTrustAnchor(cert
, flags
);
72 // Calculate the canonical hash of a certificate, given its raw (DER) data.
74 void hashOfCertificate(const void *certData
, size_t certLength
, SHA1::Digest digest
)
77 hasher(certData
, certLength
);
78 hasher
.finish(digest
);
83 // Ditto, given a SecCertificateRef
85 void hashOfCertificate(SecCertificateRef cert
, SHA1::Digest digest
)
90 MacOSError::check(SecCertificateGetData(cert
, &certData
));
91 hashOfCertificate(certData
.Data
, certData
.Length
, digest
);
93 hashOfCertificate(SecCertificateGetBytePtr(cert
), SecCertificateGetLength(cert
), digest
);
99 // One-stop hash-certificate-and-compare
101 bool verifyHash(SecCertificateRef cert
, const Hashing::Byte
*digest
)
104 hashOfCertificate(cert
, dig
);
105 return !memcmp(dig
, digest
, SHA1::digestLength
);
110 // Check to see if a certificate contains a particular field, by OID. This works for extensions,
111 // even ones not recognized by the local CL. It does not return any value, only presence.
113 bool certificateHasField(SecCertificateRef cert
, const CSSM_OID
&oid
)
117 switch (OSStatus rc
= SecCertificateCopyFirstFieldValue(cert
, &oid
, &value
)) {
119 MacOSError::check(SecCertificateReleaseFirstFieldValue(cert
, &oid
, value
));
120 return true; // extension found by oid
121 case errSecUnknownTag
:
122 break; // oid not recognized by CL - continue below
124 MacOSError::throwMe(rc
); // error: fail
127 // check the CL's bag of unrecognized extensions
130 if (SecCertificateCopyFieldValues(cert
, &CSSMOID_X509V3CertificateExtensionCStruct
, &values
))
131 return false; // no unrecognized extensions - no match
133 for (CSSM_DATA
**p
= values
; *p
; p
++) {
134 const CSSM_X509_EXTENSION
*ext
= (const CSSM_X509_EXTENSION
*)(*p
)->Data
;
135 if (oid
== ext
->extnId
) {
140 MacOSError::check(SecCertificateReleaseFieldValues(cert
, &CSSMOID_X509V3CertificateExtensionCStruct
, values
));
146 // Retrieve X.509 policy extension OIDs, if any.
147 // This currently ignores policy qualifiers.
149 bool certificateHasPolicy(SecCertificateRef cert
, const CSSM_OID
&policyOid
)
151 bool matched
= false;
154 if (OSStatus rc
= SecCertificateCopyFirstFieldValue(cert
, &CSSMOID_CertificatePolicies
, &data
))
155 MacOSError::throwMe(rc
);
156 if (data
&& data
->Data
&& data
->Length
== sizeof(CSSM_X509_EXTENSION
)) {
157 const CSSM_X509_EXTENSION
*ext
= (const CSSM_X509_EXTENSION
*)data
->Data
;
158 assert(ext
->format
== CSSM_X509_DATAFORMAT_PARSED
);
159 const CE_CertPolicies
*policies
= (const CE_CertPolicies
*)ext
->value
.parsedValue
;
161 for (unsigned int n
= 0; n
< policies
->numPolicies
; n
++) {
162 const CE_PolicyInformation
&cp
= policies
->policies
[n
];
163 if (cp
.certPolicyId
== policyOid
) {
169 SecCertificateReleaseFirstFieldValue(cert
, &CSSMOID_PolicyConstraints
, data
);
174 CFDateRef
certificateCopyFieldDate(SecCertificateRef cert
, const CSSM_OID
&policyOid
)
176 CFDataRef oidData
= NULL
;
177 CFDateRef value
= NULL
;
178 CFDataRef data
= NULL
;
179 SecAsn1CoderRef coder
= NULL
;
180 CSSM_DATA str
= { 0 };
181 CFAbsoluteTime time
= 0.0;
185 oidData
= CFDataCreateWithBytesNoCopy(NULL
, policyOid
.Data
, policyOid
.Length
,
188 if (oidData
== NULL
) {
192 data
= SecCertificateCopyExtensionValue(cert
, oidData
, &isCritical
);
198 status
= SecAsn1CoderCreate(&coder
);
203 // We currently only support UTF8 strings.
204 status
= SecAsn1Decode(coder
, CFDataGetBytePtr(data
), CFDataGetLength(data
),
205 kSecAsn1UTF8StringTemplate
, &str
);
210 time
= SecAbsoluteTimeFromDateContent(ASN1_GENERALIZED_TIME
,
211 str
.Data
, str
.Length
);
217 value
= CFDateCreate(NULL
, time
);
220 SecAsn1CoderRelease(coder
);
238 if (!(mState
= copyfile_state_alloc()))
239 UnixError::throwMe();
242 void Copyfile::set(uint32_t flag
, const void *value
)
244 check(::copyfile_state_set(mState
, flag
, value
));
247 void Copyfile::get(uint32_t flag
, void *value
)
249 check(::copyfile_state_set(mState
, flag
, value
));
252 void Copyfile::operator () (const char *src
, const char *dst
, copyfile_flags_t flags
)
254 check(::copyfile(src
, dst
, mState
, flags
));
257 void Copyfile::check(int rc
)
260 UnixError::throwMe();
265 // MessageTracer support
267 MessageTrace::MessageTrace(const char *domain
, const char *signature
)
269 mAsl
= asl_new(ASL_TYPE_MSG
);
271 asl_set(mAsl
, "com.apple.message.domain", domain
);
273 asl_set(mAsl
, "com.apple.message.signature", signature
);
276 void MessageTrace::add(const char *key
, const char *format
, ...)
279 va_start(args
, format
);
281 vsnprintf(value
, sizeof(value
), format
, args
);
283 asl_set(mAsl
, (string("com.apple.message.") + key
).c_str(), value
);
286 void MessageTrace::send(const char *format
, ...)
289 va_start(args
, format
);
290 asl_vlog(NULL
, mAsl
, ASL_LEVEL_NOTICE
, format
, args
);
296 // Resource limited async workers for doing work on nested bundles
297 LimitedAsync::LimitedAsync(bool async
)
299 // validate multiple resources concurrently if bundle resides on solid-state media
301 // How many async workers to spin off. If zero, validating only happens synchronously.
302 long async_workers
= 0;
304 long ncpu
= sysconf(_SC_NPROCESSORS_ONLN
);
306 if (async
&& ncpu
> 0)
307 async_workers
= ncpu
- 1; // one less because this thread also validates
309 mResourceSemaphore
= new Dispatch::Semaphore(async_workers
);
312 LimitedAsync::LimitedAsync(LimitedAsync
&limitedAsync
)
314 mResourceSemaphore
= new Dispatch::Semaphore(*limitedAsync
.mResourceSemaphore
);
317 LimitedAsync::~LimitedAsync()
319 delete mResourceSemaphore
;
322 bool LimitedAsync::perform(Dispatch::Group
&groupRef
, void (^block
)()) {
323 __block
Dispatch::SemaphoreWait
wait(*mResourceSemaphore
, DISPATCH_TIME_NOW
);
325 if (wait
.acquired()) {
326 dispatch_queue_t defaultQueue
= dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT
, 0);
328 groupRef
.enqueue(defaultQueue
, ^{
329 // Hold the semaphore count until the worker is done validating.
330 Dispatch::SemaphoreWait
innerWait(wait
);
340 } // end namespace CodeSigning
341 } // end namespace Security