2 * Copyright (c) 2006,2011-2014 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 // reqinterp - Requirement language (exprOp) interpreter
28 #include "reqinterp.h"
29 #include "codesigning_dtrace.h"
30 #include <Security/SecTrustSettingsPriv.h>
31 #include <Security/SecCertificatePriv.h>
32 #include <security_utilities/memutils.h>
33 #include <security_utilities/logging.h>
35 #include <IOKit/IOKitLib.h>
36 #include <IOKit/IOCFUnserialize.h>
37 #include "csutilities.h"
38 #include "notarization.h"
41 namespace CodeSigning
{
45 // Fragment fetching, caching, and evaluation.
47 // Several language elements allow "calling" of separate requirement programs
48 // stored on disk as (binary) requirement blobs. The Fragments class takes care
49 // of finding, loading, caching, and evaluating them.
51 // This is a singleton for (process global) caching. It works fine as multiple instances,
52 // at a loss of caching effectiveness.
58 bool named(const std::string
&name
, const Requirement::Context
&ctx
)
59 { return evalNamed("subreq", name
, ctx
); }
60 bool namedAnchor(const std::string
&name
, const Requirement::Context
&ctx
)
61 { return evalNamed("anchorreq", name
, ctx
); }
64 bool evalNamed(const char *type
, const std::string
&name
, const Requirement::Context
&ctx
);
65 CFDataRef
fragment(const char *type
, const std::string
&name
);
67 typedef std::map
<std::string
, CFRef
<CFDataRef
> > FragMap
;
70 CFBundleRef mMyBundle
; // Security.framework bundle
71 Mutex mLock
; // lock for all of the below...
72 FragMap mFragments
; // cached fragments
75 static ModuleNexus
<Fragments
> fragments
;
79 // Magic certificate features
81 static CFStringRef appleIntermediateCN
= CFSTR("Apple Code Signing Certification Authority");
82 static CFStringRef appleIntermediateO
= CFSTR("Apple Inc.");
86 // Main interpreter function.
88 // ExprOp code is in Polish Notation (operator followed by operands),
89 // and this engine uses opportunistic evaluation.
91 bool Requirement::Interpreter::evaluate()
92 { return eval(stackLimit
); }
94 bool Requirement::Interpreter::eval(int depth
)
96 if (--depth
<= 0) // nested too deeply - protect the stack
97 MacOSError::throwMe(errSecCSReqInvalid
);
99 ExprOp op
= ExprOp(get
<uint32_t>());
100 CODESIGN_EVAL_REQINT_OP(op
, this->pc() - sizeof(uint32_t));
101 switch (op
& ~opFlagMask
) {
107 return mContext
->directory
&& getString() == mContext
->directory
->identifier();
109 return appleSigned();
110 case opAppleGenericAnchor
:
111 return appleAnchored();
114 SecCertificateRef cert
= mContext
->cert(get
<int32_t>());
115 return verifyAnchor(cert
, getSHA1());
117 case opInfoKeyValue
: // [legacy; use opInfoKeyField]
119 string key
= getString();
120 return infoKeyValue(key
, Match(CFTempString(getString()), matchEqual
));
123 return eval(depth
) & eval(depth
);
125 return eval(depth
) | eval(depth
);
127 if (mContext
->directory
) {
128 CFRef
<CFDataRef
> cdhash
= mContext
->directory
->cdhash();
129 CFRef
<CFDataRef
> required
= getHash();
130 return CFEqual(cdhash
, required
);
137 string key
= getString();
139 return infoKeyValue(key
, match
);
141 case opEntitlementField
:
143 string key
= getString();
145 return entitlementValue(key
, match
);
149 SecCertificateRef cert
= mContext
->cert(get
<int32_t>());
150 string key
= getString();
152 return certFieldValue(key
, match
, cert
);
157 SecCertificateRef cert
= mContext
->cert(get
<int32_t>());
158 string key
= getString();
160 return certFieldGeneric(key
, match
, cert
);
162 case opCertFieldDate
:
164 SecCertificateRef cert
= mContext
->cert(get
<int32_t>());
165 string key
= getString();
167 return certFieldDate(key
, match
, cert
);
171 SecCertificateRef cert
= mContext
->cert(get
<int32_t>());
172 string key
= getString();
174 return certFieldPolicy(key
, match
, cert
);
178 return trustedCert(get
<int32_t>());
180 return trustedCerts();
182 return fragments().namedAnchor(getString(), *mContext
);
184 return fragments().named(getString(), *mContext
);
187 int32_t targetPlatform
= get
<int32_t>();
188 return mContext
->directory
&& mContext
->directory
->platform
== targetPlatform
;
192 return isNotarized(mContext
);
195 // opcode not recognized - handle generically if possible, fail otherwise
196 if (op
& (opGenericFalse
| opGenericSkip
)) {
197 // unknown opcode, but it has a size field and can be safely bypassed
198 skip(get
<uint32_t>());
199 if (op
& opGenericFalse
) {
200 CODESIGN_EVAL_REQINT_UNKNOWN_FALSE(op
);
203 CODESIGN_EVAL_REQINT_UNKNOWN_SKIPPED(op
);
207 // unrecognized opcode and no way to interpret it
208 secinfo("csinterp", "opcode 0x%x cannot be handled; aborting", op
);
209 MacOSError::throwMe(errSecCSUnimplemented
);
215 // Evaluate an Info.plist key condition
217 bool Requirement::Interpreter::infoKeyValue(const string
&key
, const Match
&match
)
219 if (mContext
->info
) // we have an Info.plist
220 if (CFTypeRef value
= CFDictionaryGetValue(mContext
->info
, CFTempString(key
)))
222 return match(kCFNull
);
227 // Evaluate an entitlement condition
229 bool Requirement::Interpreter::entitlementValue(const string
&key
, const Match
&match
)
231 if (mContext
->entitlements
) // we have an Info.plist
232 if (CFTypeRef value
= CFDictionaryGetValue(mContext
->entitlements
, CFTempString(key
)))
234 return match(kCFNull
);
238 bool Requirement::Interpreter::certFieldValue(const string
&key
, const Match
&match
, SecCertificateRef cert
)
240 // XXX: Not supported on embedded yet due to lack of supporting API
242 // no cert, no chance
246 // a table of recognized keys for the "certificate[foo]" syntax
247 static const struct CertField
{
251 { "subject.C", &CSSMOID_CountryName
},
252 { "subject.CN", &CSSMOID_CommonName
},
253 { "subject.D", &CSSMOID_Description
},
254 { "subject.L", &CSSMOID_LocalityName
},
255 // { "subject.C-L", &CSSMOID_CollectiveLocalityName }, // missing from Security.framework headers
256 { "subject.O", &CSSMOID_OrganizationName
},
257 { "subject.C-O", &CSSMOID_CollectiveOrganizationName
},
258 { "subject.OU", &CSSMOID_OrganizationalUnitName
},
259 { "subject.C-OU", &CSSMOID_CollectiveOrganizationalUnitName
},
260 { "subject.ST", &CSSMOID_StateProvinceName
},
261 { "subject.C-ST", &CSSMOID_CollectiveStateProvinceName
},
262 { "subject.STREET", &CSSMOID_StreetAddress
},
263 { "subject.C-STREET", &CSSMOID_CollectiveStreetAddress
},
264 { "subject.UID", &CSSMOID_UserID
},
268 // DN-component single-value match
269 for (const CertField
*cf
= certFields
; cf
->name
; cf
++)
270 if (cf
->name
== key
) {
271 CFRef
<CFStringRef
> value
;
272 OSStatus rc
= SecCertificateCopySubjectComponent(cert
, cf
->oid
, &value
.aref());
274 secinfo("csinterp", "cert %p lookup for DN.%s failed rc=%d", cert
, key
.c_str(), (int)rc
);
280 // email multi-valued match (any of...)
281 if (key
== "email") {
282 CFRef
<CFArrayRef
> value
;
283 OSStatus rc
= SecCertificateCopyEmailAddresses(cert
, &value
.aref());
285 secinfo("csinterp", "cert %p lookup for email failed rc=%d", cert
, (int)rc
);
291 // unrecognized key. Fail but do not abort to promote backward compatibility down the road
292 secinfo("csinterp", "cert field notation \"%s\" not understood", key
.c_str());
298 bool Requirement::Interpreter::certFieldGeneric(const string
&key
, const Match
&match
, SecCertificateRef cert
)
300 // the key is actually a (binary) OID value
301 CssmOid
oid((char *)key
.data(), key
.length());
302 return certFieldGeneric(oid
, match
, cert
);
305 bool Requirement::Interpreter::certFieldGeneric(const CssmOid
&oid
, const Match
&match
, SecCertificateRef cert
)
307 return cert
&& match(certificateHasField(cert
, oid
) ? (CFTypeRef
)kCFBooleanTrue
: (CFTypeRef
)kCFNull
);
310 bool Requirement::Interpreter::certFieldDate(const string
&key
, const Match
&match
, SecCertificateRef cert
)
312 // the key is actually a (binary) OID value
313 CssmOid
oid((char *)key
.data(), key
.length());
314 return certFieldDate(oid
, match
, cert
);
317 bool Requirement::Interpreter::certFieldDate(const CssmOid
&oid
, const Match
&match
, SecCertificateRef cert
)
319 CFTypeRef value
= cert
!= NULL
? certificateCopyFieldDate(cert
, oid
) : NULL
;
320 bool matching
= match(value
!= NULL
? value
: kCFNull
);
329 bool Requirement::Interpreter::certFieldPolicy(const string
&key
, const Match
&match
, SecCertificateRef cert
)
331 // the key is actually a (binary) OID value
332 CssmOid
oid((char *)key
.data(), key
.length());
333 return certFieldPolicy(oid
, match
, cert
);
336 bool Requirement::Interpreter::certFieldPolicy(const CssmOid
&oid
, const Match
&match
, SecCertificateRef cert
)
338 return cert
&& match(certificateHasPolicy(cert
, oid
) ? (CFTypeRef
)kCFBooleanTrue
: (CFTypeRef
)kCFNull
);
343 // Check the Apple-signed condition
345 bool Requirement::Interpreter::appleAnchored()
347 if (SecCertificateRef cert
= mContext
->cert(anchorCert
))
353 static CFStringRef kAMFINVRAMTrustedKeys
= CFSTR("AMFITrustedKeys");
355 CFArrayRef
Requirement::Interpreter::getAdditionalTrustedAnchors()
357 __block CFRef
<CFMutableArrayRef
> keys
= makeCFMutableArray(0);
360 io_registry_entry_t entry
= IORegistryEntryFromPath(kIOMasterPortDefault
, "IODeviceTree:/options");
361 if (entry
== IO_OBJECT_NULL
)
364 CFRef
<CFDataRef
> configData
= (CFDataRef
)IORegistryEntryCreateCFProperty(entry
, kAMFINVRAMTrustedKeys
, kCFAllocatorDefault
, 0);
365 IOObjectRelease(entry
);
369 CFRef
<CFDictionaryRef
> configDict
= CFDictionaryRef(IOCFUnserializeWithSize((const char *)CFDataGetBytePtr(configData
),
370 (size_t)CFDataGetLength(configData
),
371 kCFAllocatorDefault
, 0, NULL
));
375 CFArrayRef trustedKeys
= CFArrayRef(CFDictionaryGetValue(configDict
, CFSTR("trustedKeys")));
376 if (!trustedKeys
&& CFGetTypeID(trustedKeys
) != CFArrayGetTypeID())
379 cfArrayApplyBlock(trustedKeys
, ^(const void *value
) {
380 CFDictionaryRef key
= CFDictionaryRef(value
);
381 if (!key
&& CFGetTypeID(key
) != CFDictionaryGetTypeID())
384 CFDataRef hash
= CFDataRef(CFDictionaryGetValue(key
, CFSTR("certDigest")));
385 if (!hash
&& CFGetTypeID(hash
) != CFDataGetTypeID())
387 CFArrayAppendValue(keys
, hash
);
393 if (CFArrayGetCount(keys
) == 0)
399 bool Requirement::Interpreter::appleLocalAnchored()
401 static CFArrayRef additionalTrustedCertificates
= NULL
;
403 if (csr_check(CSR_ALLOW_APPLE_INTERNAL
))
406 if (mContext
->forcePlatform
) {
410 static dispatch_once_t onceToken
;
411 dispatch_once(&onceToken
, ^{
412 additionalTrustedCertificates
= getAdditionalTrustedAnchors();
415 if (additionalTrustedCertificates
== NULL
)
418 CFRef
<CFDataRef
> hash
= SecCertificateCopySHA256Digest(mContext
->cert(leafCert
));
422 if (CFArrayContainsValue(additionalTrustedCertificates
, CFRangeMake(0, CFArrayGetCount(additionalTrustedCertificates
)), hash
))
428 bool Requirement::Interpreter::appleSigned()
430 if (appleAnchored()) {
431 if (SecCertificateRef intermed
= mContext
->cert(-2)) // first intermediate
432 // first intermediate common name match (exact)
433 if (certFieldValue("subject.CN", Match(appleIntermediateCN
, matchEqual
), intermed
)
434 && certFieldValue("subject.O", Match(appleIntermediateO
, matchEqual
), intermed
))
436 } else if (appleLocalAnchored()) {
444 // Verify an anchor requirement against the context
446 bool Requirement::Interpreter::verifyAnchor(SecCertificateRef cert
, const unsigned char *digest
)
448 // get certificate bytes
453 MacOSError::check(SecCertificateGetData(cert
, &certData
));
456 hasher(certData
.Data
, certData
.Length
);
458 hasher(SecCertificateGetBytePtr(cert
), SecCertificateGetLength(cert
));
460 return hasher
.verify(digest
);
467 // Check one or all certificate(s) in the cert chain against the Trust Settings database.
469 bool Requirement::Interpreter::trustedCerts()
471 int anchor
= mContext
->certCount() - 1;
472 for (int slot
= 0; slot
<= anchor
; slot
++)
473 if (SecCertificateRef cert
= mContext
->cert(slot
))
474 switch (trustSetting(cert
, slot
== anchor
)) {
475 case kSecTrustSettingsResultTrustRoot
:
476 case kSecTrustSettingsResultTrustAsRoot
:
478 case kSecTrustSettingsResultDeny
:
480 case kSecTrustSettingsResultUnspecified
:
491 bool Requirement::Interpreter::trustedCert(int slot
)
493 if (SecCertificateRef cert
= mContext
->cert(slot
)) {
494 int anchorSlot
= mContext
->certCount() - 1;
495 switch (trustSetting(cert
, slot
== anchorCert
|| slot
== anchorSlot
)) {
496 case kSecTrustSettingsResultTrustRoot
:
497 case kSecTrustSettingsResultTrustAsRoot
:
499 case kSecTrustSettingsResultDeny
:
500 case kSecTrustSettingsResultUnspecified
:
512 // Explicitly check one certificate against the Trust Settings database and report
513 // the findings. This is a helper for the various Trust Settings evaluators.
515 SecTrustSettingsResult
Requirement::Interpreter::trustSetting(SecCertificateRef cert
, bool isAnchor
)
517 // XXX: Not supported on embedded yet due to lack of supporting API
519 // the SPI input is the uppercase hex form of the SHA-1 of the certificate...
522 hashOfCertificate(cert
, digest
);
523 string Certhex
= CssmData(digest
, sizeof(digest
)).toHex();
524 for (string::iterator it
= Certhex
.begin(); it
!= Certhex
.end(); ++it
)
528 // call Trust Settings and see what it finds
529 SecTrustSettingsDomain domain
;
530 SecTrustSettingsResult result
;
531 CSSM_RETURN
*errors
= NULL
;
532 uint32 errorCount
= 0;
533 bool foundMatch
, foundAny
;
534 switch (OSStatus rc
= SecTrustSettingsEvaluateCert(
535 CFTempString(Certhex
), // settings index
536 &CSSMOID_APPLE_TP_CODE_SIGNING
, // standard code signing policy
537 NULL
, 0, // policy string (unused)
538 kSecTrustSettingsKeyUseAny
, // no restriction on key usage @@@
539 isAnchor
, // consult system default anchor set
541 &domain
, // domain of found setting
542 &errors
, &errorCount
, // error set and maximum count
543 &result
, // the actual setting
544 &foundMatch
, &foundAny
// optimization hints (not used)
551 return kSecTrustSettingsResultUnspecified
;
554 MacOSError::throwMe(rc
);
557 return kSecTrustSettingsResultUnspecified
;
563 // Create a Match object from the interpreter stream
565 Requirement::Interpreter::Match::Match(Interpreter
&interp
)
567 switch (mOp
= interp
.get
<MatchOperation
>()) {
573 case matchBeginsWith
:
576 case matchGreaterThan
:
578 case matchGreaterEqual
:
579 mValue
.take(makeCFString(interp
.getString()));
584 case matchOnOrBefore
:
585 case matchOnOrAfter
: {
586 mValue
.take(CFDateCreate(NULL
, interp
.getAbsoluteTime()));
590 // Assume this (unknown) match type has a single data argument.
591 // This gives us a chance to keep the instruction stream aligned.
592 interp
.getString(); // discard
599 // Execute a match against a candidate value
601 bool Requirement::Interpreter::Match::operator () (CFTypeRef candidate
) const
603 // null candidates always fail
607 if (candidate
== kCFNull
) {
608 return mOp
== matchAbsent
; // only 'absent' matches
611 // interpret an array as matching alternatives (any one succeeds)
612 if (CFGetTypeID(candidate
) == CFArrayGetTypeID()) {
613 CFArrayRef array
= CFArrayRef(candidate
);
614 CFIndex count
= CFArrayGetCount(array
);
615 for (CFIndex n
= 0; n
< count
; n
++)
616 if ((*this)(CFArrayGetValueAtIndex(array
, n
))) // yes, it's recursive
622 return false; // it exists, so it cannot be absent
623 case matchExists
: // anything but NULL and boolean false "exists"
624 return !CFEqual(candidate
, kCFBooleanFalse
);
625 case matchEqual
: // equality works for all CF types
626 return CFEqual(candidate
, mValue
);
628 if (isStringValue() && CFGetTypeID(candidate
) == CFStringGetTypeID()) {
629 CFStringRef value
= CFStringRef(candidate
);
630 if (CFStringFindWithOptions(value
, cfStringValue(), CFRangeMake(0, CFStringGetLength(value
)), 0, NULL
))
634 case matchBeginsWith
:
635 if (isStringValue() && CFGetTypeID(candidate
) == CFStringGetTypeID()) {
636 CFStringRef value
= CFStringRef(candidate
);
637 if (CFStringFindWithOptions(value
, cfStringValue(), CFRangeMake(0, CFStringGetLength(cfStringValue())), 0, NULL
))
642 if (isStringValue() && CFGetTypeID(candidate
) == CFStringGetTypeID()) {
643 CFStringRef value
= CFStringRef(candidate
);
644 CFIndex matchLength
= CFStringGetLength(cfStringValue());
645 CFIndex start
= CFStringGetLength(value
) - matchLength
;
647 if (CFStringFindWithOptions(value
, cfStringValue(), CFRangeMake(start
, matchLength
), 0, NULL
))
652 return inequality(candidate
, kCFCompareNumerically
, kCFCompareLessThan
, true);
653 case matchGreaterThan
:
654 return inequality(candidate
, kCFCompareNumerically
, kCFCompareGreaterThan
, true);
656 return inequality(candidate
, kCFCompareNumerically
, kCFCompareGreaterThan
, false);
657 case matchGreaterEqual
:
658 return inequality(candidate
, kCFCompareNumerically
, kCFCompareLessThan
, false);
662 case matchOnOrBefore
:
663 case matchOnOrAfter
: {
664 if (!isDateValue() || CFGetTypeID(candidate
) != CFDateGetTypeID()) {
668 CFComparisonResult res
= CFDateCompare((CFDateRef
)candidate
, cfDateValue(), NULL
);
671 case matchOn
: return res
== 0;
672 case matchBefore
: return res
< 0;
673 case matchAfter
: return res
> 0;
674 case matchOnOrBefore
: return res
<= 0;
675 case matchOnOrAfter
: return res
>= 0;
680 // unrecognized match types can never match
686 bool Requirement::Interpreter::Match::inequality(CFTypeRef candidate
, CFStringCompareFlags flags
,
687 CFComparisonResult outcome
, bool negate
) const
689 if (isStringValue() && CFGetTypeID(candidate
) == CFStringGetTypeID()) {
690 CFStringRef value
= CFStringRef(candidate
);
691 if ((CFStringCompare(value
, cfStringValue(), flags
) == outcome
) == negate
)
699 // External fragments
701 Fragments::Fragments()
703 mMyBundle
= CFBundleGetBundleWithIdentifier(CFSTR("com.apple.security"));
707 bool Fragments::evalNamed(const char *type
, const std::string
&name
, const Requirement::Context
&ctx
)
709 if (CFDataRef fragData
= fragment(type
, name
)) {
710 const Requirement
*req
= (const Requirement
*)CFDataGetBytePtr(fragData
); // was prevalidated as Requirement
711 return req
->validates(ctx
);
717 CFDataRef
Fragments::fragment(const char *type
, const std::string
&name
)
719 string key
= name
+ "!!" + type
; // compound key
720 StLock
<Mutex
> _(mLock
); // lock for cache access
721 FragMap::const_iterator it
= mFragments
.find(key
);
722 if (it
== mFragments
.end()) {
723 CFRef
<CFDataRef
> fragData
; // will always be set (NULL on any errors)
724 if (CFRef
<CFURLRef
> fragURL
= CFBundleCopyResourceURL(mMyBundle
, CFTempString(name
), CFSTR("csreq"), CFTempString(type
)))
725 if (CFRef
<CFDataRef
> data
= cfLoadFile(fragURL
)) { // got data
726 const Requirement
*req
= (const Requirement
*)CFDataGetBytePtr(data
);
727 if (req
->validateBlob(CFDataGetLength(data
))) // looks like a Requirement...
728 fragData
= data
; // ... so accept it
730 Syslog::warning("Invalid sub-requirement at %s", cfString(fragURL
).c_str());
732 if (CODESIGN_EVAL_REQINT_FRAGMENT_LOAD_ENABLED())
733 CODESIGN_EVAL_REQINT_FRAGMENT_LOAD(type
, name
.c_str(), fragData
? CFDataGetBytePtr(fragData
) : NULL
);
734 mFragments
[key
] = fragData
; // cache it, success or failure
737 CODESIGN_EVAL_REQINT_FRAGMENT_HIT(type
, name
.c_str());