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
27 #include "reqinterp.h"
28 #include "codesigning_dtrace.h"
29 #include <Security/SecTrustSettingsPriv.h>
30 #include <Security/SecCertificatePriv.h>
31 #include <security_utilities/memutils.h>
32 #include <security_utilities/logging.h>
34 #include <IOKit/IOKitLib.h>
35 #include <IOKit/IOCFUnserialize.h>
36 #include "csutilities.h"
39 namespace CodeSigning
{
43 // Fragment fetching, caching, and evaluation.
45 // Several language elements allow "calling" of separate requirement programs
46 // stored on disk as (binary) requirement blobs. The Fragments class takes care
47 // of finding, loading, caching, and evaluating them.
49 // This is a singleton for (process global) caching. It works fine as multiple instances,
50 // at a loss of caching effectiveness.
56 bool named(const std::string
&name
, const Requirement::Context
&ctx
)
57 { return evalNamed("subreq", name
, ctx
); }
58 bool namedAnchor(const std::string
&name
, const Requirement::Context
&ctx
)
59 { return evalNamed("anchorreq", name
, ctx
); }
62 bool evalNamed(const char *type
, const std::string
&name
, const Requirement::Context
&ctx
);
63 CFDataRef
fragment(const char *type
, const std::string
&name
);
65 typedef std::map
<std::string
, CFRef
<CFDataRef
> > FragMap
;
68 CFBundleRef mMyBundle
; // Security.framework bundle
69 Mutex mLock
; // lock for all of the below...
70 FragMap mFragments
; // cached fragments
73 static ModuleNexus
<Fragments
> fragments
;
77 // Magic certificate features
79 static CFStringRef appleIntermediateCN
= CFSTR("Apple Code Signing Certification Authority");
80 static CFStringRef appleIntermediateO
= CFSTR("Apple Inc.");
84 // Main interpreter function.
86 // ExprOp code is in Polish Notation (operator followed by operands),
87 // and this engine uses opportunistic evaluation.
89 bool Requirement::Interpreter::evaluate()
90 { return eval(stackLimit
); }
92 bool Requirement::Interpreter::eval(int depth
)
94 if (--depth
<= 0) // nested too deeply - protect the stack
95 MacOSError::throwMe(errSecCSReqInvalid
);
97 ExprOp op
= ExprOp(get
<uint32_t>());
98 CODESIGN_EVAL_REQINT_OP(op
, this->pc() - sizeof(uint32_t));
99 switch (op
& ~opFlagMask
) {
105 return mContext
->directory
&& getString() == mContext
->directory
->identifier();
107 return appleSigned();
108 case opAppleGenericAnchor
:
109 return appleAnchored();
112 SecCertificateRef cert
= mContext
->cert(get
<int32_t>());
113 return verifyAnchor(cert
, getSHA1());
115 case opInfoKeyValue
: // [legacy; use opInfoKeyField]
117 string key
= getString();
118 return infoKeyValue(key
, Match(CFTempString(getString()), matchEqual
));
121 return eval(depth
) & eval(depth
);
123 return eval(depth
) | eval(depth
);
125 if (mContext
->directory
) {
126 CFRef
<CFDataRef
> cdhash
= mContext
->directory
->cdhash();
127 CFRef
<CFDataRef
> required
= getHash();
128 return CFEqual(cdhash
, required
);
135 string key
= getString();
137 return infoKeyValue(key
, match
);
139 case opEntitlementField
:
141 string key
= getString();
143 return entitlementValue(key
, match
);
147 SecCertificateRef cert
= mContext
->cert(get
<int32_t>());
148 string key
= getString();
150 return certFieldValue(key
, match
, cert
);
154 SecCertificateRef cert
= mContext
->cert(get
<int32_t>());
155 string key
= getString();
157 return certFieldGeneric(key
, match
, cert
);
161 SecCertificateRef cert
= mContext
->cert(get
<int32_t>());
162 string key
= getString();
164 return certFieldPolicy(key
, match
, cert
);
167 return trustedCert(get
<int32_t>());
169 return trustedCerts();
171 return fragments().namedAnchor(getString(), *mContext
);
173 return fragments().named(getString(), *mContext
);
176 int32_t targetPlatform
= get
<int32_t>();
177 return mContext
->directory
&& mContext
->directory
->platform
== targetPlatform
;
180 // opcode not recognized - handle generically if possible, fail otherwise
181 if (op
& (opGenericFalse
| opGenericSkip
)) {
182 // unknown opcode, but it has a size field and can be safely bypassed
183 skip(get
<uint32_t>());
184 if (op
& opGenericFalse
) {
185 CODESIGN_EVAL_REQINT_UNKNOWN_FALSE(op
);
188 CODESIGN_EVAL_REQINT_UNKNOWN_SKIPPED(op
);
192 // unrecognized opcode and no way to interpret it
193 secinfo("csinterp", "opcode 0x%x cannot be handled; aborting", op
);
194 MacOSError::throwMe(errSecCSUnimplemented
);
200 // Evaluate an Info.plist key condition
202 bool Requirement::Interpreter::infoKeyValue(const string
&key
, const Match
&match
)
204 if (mContext
->info
) // we have an Info.plist
205 if (CFTypeRef value
= CFDictionaryGetValue(mContext
->info
, CFTempString(key
)))
212 // Evaluate an entitlement condition
214 bool Requirement::Interpreter::entitlementValue(const string
&key
, const Match
&match
)
216 if (mContext
->entitlements
) // we have an Info.plist
217 if (CFTypeRef value
= CFDictionaryGetValue(mContext
->entitlements
, CFTempString(key
)))
223 bool Requirement::Interpreter::certFieldValue(const string
&key
, const Match
&match
, SecCertificateRef cert
)
225 // no cert, no chance
229 // a table of recognized keys for the "certificate[foo]" syntax
230 static const struct CertField
{
234 { "subject.C", &CSSMOID_CountryName
},
235 { "subject.CN", &CSSMOID_CommonName
},
236 { "subject.D", &CSSMOID_Description
},
237 { "subject.L", &CSSMOID_LocalityName
},
238 // { "subject.C-L", &CSSMOID_CollectiveLocalityName }, // missing from Security.framework headers
239 { "subject.O", &CSSMOID_OrganizationName
},
240 { "subject.C-O", &CSSMOID_CollectiveOrganizationName
},
241 { "subject.OU", &CSSMOID_OrganizationalUnitName
},
242 { "subject.C-OU", &CSSMOID_CollectiveOrganizationalUnitName
},
243 { "subject.ST", &CSSMOID_StateProvinceName
},
244 { "subject.C-ST", &CSSMOID_CollectiveStateProvinceName
},
245 { "subject.STREET", &CSSMOID_StreetAddress
},
246 { "subject.C-STREET", &CSSMOID_CollectiveStreetAddress
},
247 { "subject.UID", &CSSMOID_UserID
},
251 // DN-component single-value match
252 for (const CertField
*cf
= certFields
; cf
->name
; cf
++)
253 if (cf
->name
== key
) {
254 CFRef
<CFStringRef
> value
;
255 OSStatus rc
= SecCertificateCopySubjectComponent(cert
, cf
->oid
, &value
.aref());
257 secinfo("csinterp", "cert %p lookup for DN.%s failed rc=%d", cert
, key
.c_str(), (int)rc
);
263 // email multi-valued match (any of...)
264 if (key
== "email") {
265 CFRef
<CFArrayRef
> value
;
266 OSStatus rc
= SecCertificateCopyEmailAddresses(cert
, &value
.aref());
268 secinfo("csinterp", "cert %p lookup for email failed rc=%d", cert
, (int)rc
);
274 // unrecognized key. Fail but do not abort to promote backward compatibility down the road
275 secinfo("csinterp", "cert field notation \"%s\" not understood", key
.c_str());
280 bool Requirement::Interpreter::certFieldGeneric(const string
&key
, const Match
&match
, SecCertificateRef cert
)
282 // the key is actually a (binary) OID value
283 CssmOid
oid((char *)key
.data(), key
.length());
284 return certFieldGeneric(oid
, match
, cert
);
287 bool Requirement::Interpreter::certFieldGeneric(const CssmOid
&oid
, const Match
&match
, SecCertificateRef cert
)
289 return cert
&& certificateHasField(cert
, oid
) && match(kCFBooleanTrue
);
292 bool Requirement::Interpreter::certFieldPolicy(const string
&key
, const Match
&match
, SecCertificateRef cert
)
294 // the key is actually a (binary) OID value
295 CssmOid
oid((char *)key
.data(), key
.length());
296 return certFieldPolicy(oid
, match
, cert
);
299 bool Requirement::Interpreter::certFieldPolicy(const CssmOid
&oid
, const Match
&match
, SecCertificateRef cert
)
301 return cert
&& certificateHasPolicy(cert
, oid
) && match(kCFBooleanTrue
);
306 // Check the Apple-signed condition
308 bool Requirement::Interpreter::appleAnchored()
310 if (SecCertificateRef cert
= mContext
->cert(anchorCert
))
316 static CFStringRef kAMFINVRAMTrustedKeys
= CFSTR("AMFITrustedKeys");
318 CFArrayRef
Requirement::Interpreter::getAdditionalTrustedAnchors()
320 __block CFRef
<CFMutableArrayRef
> keys
= makeCFMutableArray(0);
323 io_registry_entry_t entry
= IORegistryEntryFromPath(kIOMasterPortDefault
, "IODeviceTree:/options");
324 if (entry
== IO_OBJECT_NULL
)
327 CFRef
<CFDataRef
> configData
= (CFDataRef
)IORegistryEntryCreateCFProperty(entry
, kAMFINVRAMTrustedKeys
, kCFAllocatorDefault
, 0);
328 IOObjectRelease(entry
);
332 CFRef
<CFDictionaryRef
> configDict
= CFDictionaryRef(IOCFUnserializeWithSize((const char *)CFDataGetBytePtr(configData
),
333 (size_t)CFDataGetLength(configData
),
334 kCFAllocatorDefault
, 0, NULL
));
338 CFArrayRef trustedKeys
= CFArrayRef(CFDictionaryGetValue(configDict
, CFSTR("trustedKeys")));
339 if (!trustedKeys
&& CFGetTypeID(trustedKeys
) != CFArrayGetTypeID())
342 cfArrayApplyBlock(trustedKeys
, ^(const void *value
) {
343 CFDictionaryRef key
= CFDictionaryRef(value
);
344 if (!key
&& CFGetTypeID(key
) != CFDictionaryGetTypeID())
347 CFDataRef hash
= CFDataRef(CFDictionaryGetValue(key
, CFSTR("certDigest")));
348 if (!hash
&& CFGetTypeID(hash
) != CFDataGetTypeID())
350 CFArrayAppendValue(keys
, hash
);
356 if (CFArrayGetCount(keys
) == 0)
362 bool Requirement::Interpreter::appleLocalAnchored()
364 static CFArrayRef additionalTrustedCertificates
= NULL
;
366 if (csr_check(CSR_ALLOW_APPLE_INTERNAL
))
369 static dispatch_once_t onceToken
;
370 dispatch_once(&onceToken
, ^{
371 additionalTrustedCertificates
= getAdditionalTrustedAnchors();
374 if (additionalTrustedCertificates
== NULL
)
377 CFRef
<CFDataRef
> hash
= SecCertificateCopySHA256Digest(mContext
->cert(leafCert
));
381 if (CFArrayContainsValue(additionalTrustedCertificates
, CFRangeMake(0, CFArrayGetCount(additionalTrustedCertificates
)), hash
))
387 bool Requirement::Interpreter::appleSigned()
389 if (appleAnchored()) {
390 if (SecCertificateRef intermed
= mContext
->cert(-2)) // first intermediate
391 // first intermediate common name match (exact)
392 if (certFieldValue("subject.CN", Match(appleIntermediateCN
, matchEqual
), intermed
)
393 && certFieldValue("subject.O", Match(appleIntermediateO
, matchEqual
), intermed
))
395 } else if (appleLocalAnchored()) {
403 // Verify an anchor requirement against the context
405 bool Requirement::Interpreter::verifyAnchor(SecCertificateRef cert
, const unsigned char *digest
)
407 // get certificate bytes
410 MacOSError::check(SecCertificateGetData(cert
, &certData
));
414 hasher(certData
.Data
, certData
.Length
);
415 return hasher
.verify(digest
);
422 // Check one or all certificate(s) in the cert chain against the Trust Settings database.
424 bool Requirement::Interpreter::trustedCerts()
426 int anchor
= mContext
->certCount() - 1;
427 for (int slot
= 0; slot
<= anchor
; slot
++)
428 if (SecCertificateRef cert
= mContext
->cert(slot
))
429 switch (trustSetting(cert
, slot
== anchor
)) {
430 case kSecTrustSettingsResultTrustRoot
:
431 case kSecTrustSettingsResultTrustAsRoot
:
433 case kSecTrustSettingsResultDeny
:
435 case kSecTrustSettingsResultUnspecified
:
446 bool Requirement::Interpreter::trustedCert(int slot
)
448 if (SecCertificateRef cert
= mContext
->cert(slot
)) {
449 int anchorSlot
= mContext
->certCount() - 1;
450 switch (trustSetting(cert
, slot
== anchorCert
|| slot
== anchorSlot
)) {
451 case kSecTrustSettingsResultTrustRoot
:
452 case kSecTrustSettingsResultTrustAsRoot
:
454 case kSecTrustSettingsResultDeny
:
455 case kSecTrustSettingsResultUnspecified
:
467 // Explicitly check one certificate against the Trust Settings database and report
468 // the findings. This is a helper for the various Trust Settings evaluators.
470 SecTrustSettingsResult
Requirement::Interpreter::trustSetting(SecCertificateRef cert
, bool isAnchor
)
472 // the SPI input is the uppercase hex form of the SHA-1 of the certificate...
475 hashOfCertificate(cert
, digest
);
476 string Certhex
= CssmData(digest
, sizeof(digest
)).toHex();
477 for (string::iterator it
= Certhex
.begin(); it
!= Certhex
.end(); ++it
)
481 // call Trust Settings and see what it finds
482 SecTrustSettingsDomain domain
;
483 SecTrustSettingsResult result
;
484 CSSM_RETURN
*errors
= NULL
;
485 uint32 errorCount
= 0;
486 bool foundMatch
, foundAny
;
487 switch (OSStatus rc
= SecTrustSettingsEvaluateCert(
488 CFTempString(Certhex
), // settings index
489 &CSSMOID_APPLE_TP_CODE_SIGNING
, // standard code signing policy
490 NULL
, 0, // policy string (unused)
491 kSecTrustSettingsKeyUseAny
, // no restriction on key usage @@@
492 isAnchor
, // consult system default anchor set
494 &domain
, // domain of found setting
495 &errors
, &errorCount
, // error set and maximum count
496 &result
, // the actual setting
497 &foundMatch
, &foundAny
// optimization hints (not used)
504 return kSecTrustSettingsResultUnspecified
;
507 MacOSError::throwMe(rc
);
513 // Create a Match object from the interpreter stream
515 Requirement::Interpreter::Match::Match(Interpreter
&interp
)
517 switch (mOp
= interp
.get
<MatchOperation
>()) {
522 case matchBeginsWith
:
525 case matchGreaterThan
:
527 case matchGreaterEqual
:
528 mValue
.take(makeCFString(interp
.getString()));
531 // Assume this (unknown) match type has a single data argument.
532 // This gives us a chance to keep the instruction stream aligned.
533 interp
.getString(); // discard
540 // Execute a match against a candidate value
542 bool Requirement::Interpreter::Match::operator () (CFTypeRef candidate
) const
544 // null candidates always fail
548 // interpret an array as matching alternatives (any one succeeds)
549 if (CFGetTypeID(candidate
) == CFArrayGetTypeID()) {
550 CFArrayRef array
= CFArrayRef(candidate
);
551 CFIndex count
= CFArrayGetCount(array
);
552 for (CFIndex n
= 0; n
< count
; n
++)
553 if ((*this)(CFArrayGetValueAtIndex(array
, n
))) // yes, it's recursive
558 case matchExists
: // anything but NULL and boolean false "exists"
559 return !CFEqual(candidate
, kCFBooleanFalse
);
560 case matchEqual
: // equality works for all CF types
561 return CFEqual(candidate
, mValue
);
563 if (CFGetTypeID(candidate
) == CFStringGetTypeID()) {
564 CFStringRef value
= CFStringRef(candidate
);
565 if (CFStringFindWithOptions(value
, mValue
, CFRangeMake(0, CFStringGetLength(value
)), 0, NULL
))
569 case matchBeginsWith
:
570 if (CFGetTypeID(candidate
) == CFStringGetTypeID()) {
571 CFStringRef value
= CFStringRef(candidate
);
572 if (CFStringFindWithOptions(value
, mValue
, CFRangeMake(0, CFStringGetLength(mValue
)), 0, NULL
))
577 if (CFGetTypeID(candidate
) == CFStringGetTypeID()) {
578 CFStringRef value
= CFStringRef(candidate
);
579 CFIndex matchLength
= CFStringGetLength(mValue
);
580 CFIndex start
= CFStringGetLength(value
) - matchLength
;
582 if (CFStringFindWithOptions(value
, mValue
, CFRangeMake(start
, matchLength
), 0, NULL
))
587 return inequality(candidate
, kCFCompareNumerically
, kCFCompareLessThan
, true);
588 case matchGreaterThan
:
589 return inequality(candidate
, kCFCompareNumerically
, kCFCompareGreaterThan
, true);
591 return inequality(candidate
, kCFCompareNumerically
, kCFCompareGreaterThan
, false);
592 case matchGreaterEqual
:
593 return inequality(candidate
, kCFCompareNumerically
, kCFCompareLessThan
, false);
595 // unrecognized match types can never match
601 bool Requirement::Interpreter::Match::inequality(CFTypeRef candidate
, CFStringCompareFlags flags
,
602 CFComparisonResult outcome
, bool negate
) const
604 if (CFGetTypeID(candidate
) == CFStringGetTypeID()) {
605 CFStringRef value
= CFStringRef(candidate
);
606 if ((CFStringCompare(value
, mValue
, flags
) == outcome
) == negate
)
614 // External fragments
616 Fragments::Fragments()
618 mMyBundle
= CFBundleGetBundleWithIdentifier(CFSTR("com.apple.security"));
622 bool Fragments::evalNamed(const char *type
, const std::string
&name
, const Requirement::Context
&ctx
)
624 if (CFDataRef fragData
= fragment(type
, name
)) {
625 const Requirement
*req
= (const Requirement
*)CFDataGetBytePtr(fragData
); // was prevalidated as Requirement
626 return req
->validates(ctx
);
632 CFDataRef
Fragments::fragment(const char *type
, const std::string
&name
)
634 string key
= name
+ "!!" + type
; // compound key
635 StLock
<Mutex
> _(mLock
); // lock for cache access
636 FragMap::const_iterator it
= mFragments
.find(key
);
637 if (it
== mFragments
.end()) {
638 CFRef
<CFDataRef
> fragData
; // will always be set (NULL on any errors)
639 if (CFRef
<CFURLRef
> fragURL
= CFBundleCopyResourceURL(mMyBundle
, CFTempString(name
), CFSTR("csreq"), CFTempString(type
)))
640 if (CFRef
<CFDataRef
> data
= cfLoadFile(fragURL
)) { // got data
641 const Requirement
*req
= (const Requirement
*)CFDataGetBytePtr(data
);
642 if (req
->validateBlob(CFDataGetLength(data
))) // looks like a Requirement...
643 fragData
= data
; // ... so accept it
645 Syslog::warning("Invalid sub-requirement at %s", cfString(fragURL
).c_str());
647 if (CODESIGN_EVAL_REQINT_FRAGMENT_LOAD_ENABLED())
648 CODESIGN_EVAL_REQINT_FRAGMENT_LOAD(type
, name
.c_str(), fragData
? CFDataGetBytePtr(fragData
) : NULL
);
649 mFragments
[key
] = fragData
; // cache it, success or failure
652 CODESIGN_EVAL_REQINT_FRAGMENT_HIT(type
, name
.c_str());