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>
33 #include "csutilities.h"
36 namespace CodeSigning
{
40 // Fragment fetching, caching, and evaluation.
42 // Several language elements allow "calling" of separate requirement programs
43 // stored on disk as (binary) requirement blobs. The Fragments class takes care
44 // of finding, loading, caching, and evaluating them.
46 // This is a singleton for (process global) caching. It works fine as multiple instances,
47 // at a loss of caching effectiveness.
53 bool named(const std::string
&name
, const Requirement::Context
&ctx
)
54 { return evalNamed("subreq", name
, ctx
); }
55 bool namedAnchor(const std::string
&name
, const Requirement::Context
&ctx
)
56 { return evalNamed("anchorreq", name
, ctx
); }
59 bool evalNamed(const char *type
, const std::string
&name
, const Requirement::Context
&ctx
);
60 CFDataRef
fragment(const char *type
, const std::string
&name
);
62 typedef std::map
<std::string
, CFRef
<CFDataRef
> > FragMap
;
65 CFBundleRef mMyBundle
; // Security.framework bundle
66 Mutex mLock
; // lock for all of the below...
67 FragMap mFragments
; // cached fragments
70 static ModuleNexus
<Fragments
> fragments
;
74 // Magic certificate features
76 static CFStringRef appleIntermediateCN
= CFSTR("Apple Code Signing Certification Authority");
77 static CFStringRef appleIntermediateO
= CFSTR("Apple Inc.");
81 // Main interpreter function.
83 // ExprOp code is in Polish Notation (operator followed by operands),
84 // and this engine uses opportunistic evaluation.
86 bool Requirement::Interpreter::evaluate()
87 { return eval(stackLimit
); }
89 bool Requirement::Interpreter::eval(int depth
)
91 if (--depth
<= 0) // nested too deeply - protect the stack
92 MacOSError::throwMe(errSecCSReqInvalid
);
94 ExprOp op
= ExprOp(get
<uint32_t>());
95 CODESIGN_EVAL_REQINT_OP(op
, this->pc() - sizeof(uint32_t));
96 switch (op
& ~opFlagMask
) {
102 return mContext
->directory
&& getString() == mContext
->directory
->identifier();
104 return appleSigned();
105 case opAppleGenericAnchor
:
106 return appleAnchored();
109 SecCertificateRef cert
= mContext
->cert(get
<int32_t>());
110 return verifyAnchor(cert
, getSHA1());
112 case opInfoKeyValue
: // [legacy; use opInfoKeyField]
114 string key
= getString();
115 return infoKeyValue(key
, Match(CFTempString(getString()), matchEqual
));
118 return eval(depth
) & eval(depth
);
120 return eval(depth
) | eval(depth
);
122 if (mContext
->directory
) {
123 CFRef
<CFDataRef
> cdhash
= mContext
->directory
->cdhash();
124 CFRef
<CFDataRef
> required
= getHash();
125 return CFEqual(cdhash
, required
);
132 string key
= getString();
134 return infoKeyValue(key
, match
);
136 case opEntitlementField
:
138 string key
= getString();
140 return entitlementValue(key
, match
);
144 SecCertificateRef cert
= mContext
->cert(get
<int32_t>());
145 string key
= getString();
147 return certFieldValue(key
, match
, cert
);
151 SecCertificateRef cert
= mContext
->cert(get
<int32_t>());
152 string key
= getString();
154 return certFieldGeneric(key
, match
, cert
);
158 SecCertificateRef cert
= mContext
->cert(get
<int32_t>());
159 string key
= getString();
161 return certFieldPolicy(key
, match
, cert
);
164 return trustedCert(get
<int32_t>());
166 return trustedCerts();
168 return fragments().namedAnchor(getString(), *mContext
);
170 return fragments().named(getString(), *mContext
);
173 int32_t targetPlatform
= get
<int32_t>();
174 return mContext
->directory
&& mContext
->directory
->platform
== targetPlatform
;
177 // opcode not recognized - handle generically if possible, fail otherwise
178 if (op
& (opGenericFalse
| opGenericSkip
)) {
179 // unknown opcode, but it has a size field and can be safely bypassed
180 skip(get
<uint32_t>());
181 if (op
& opGenericFalse
) {
182 CODESIGN_EVAL_REQINT_UNKNOWN_FALSE(op
);
185 CODESIGN_EVAL_REQINT_UNKNOWN_SKIPPED(op
);
189 // unrecognized opcode and no way to interpret it
190 secdebug("csinterp", "opcode 0x%x cannot be handled; aborting", op
);
191 MacOSError::throwMe(errSecCSUnimplemented
);
197 // Evaluate an Info.plist key condition
199 bool Requirement::Interpreter::infoKeyValue(const string
&key
, const Match
&match
)
201 if (mContext
->info
) // we have an Info.plist
202 if (CFTypeRef value
= CFDictionaryGetValue(mContext
->info
, CFTempString(key
)))
209 // Evaluate an entitlement condition
211 bool Requirement::Interpreter::entitlementValue(const string
&key
, const Match
&match
)
213 if (mContext
->entitlements
) // we have an Info.plist
214 if (CFTypeRef value
= CFDictionaryGetValue(mContext
->entitlements
, CFTempString(key
)))
220 bool Requirement::Interpreter::certFieldValue(const string
&key
, const Match
&match
, SecCertificateRef cert
)
222 // no cert, no chance
226 // a table of recognized keys for the "certificate[foo]" syntax
227 static const struct CertField
{
231 { "subject.C", &CSSMOID_CountryName
},
232 { "subject.CN", &CSSMOID_CommonName
},
233 { "subject.D", &CSSMOID_Description
},
234 { "subject.L", &CSSMOID_LocalityName
},
235 // { "subject.C-L", &CSSMOID_CollectiveLocalityName }, // missing from Security.framework headers
236 { "subject.O", &CSSMOID_OrganizationName
},
237 { "subject.C-O", &CSSMOID_CollectiveOrganizationName
},
238 { "subject.OU", &CSSMOID_OrganizationalUnitName
},
239 { "subject.C-OU", &CSSMOID_CollectiveOrganizationalUnitName
},
240 { "subject.ST", &CSSMOID_StateProvinceName
},
241 { "subject.C-ST", &CSSMOID_CollectiveStateProvinceName
},
242 { "subject.STREET", &CSSMOID_StreetAddress
},
243 { "subject.C-STREET", &CSSMOID_CollectiveStreetAddress
},
244 { "subject.UID", &CSSMOID_UserID
},
248 // DN-component single-value match
249 for (const CertField
*cf
= certFields
; cf
->name
; cf
++)
250 if (cf
->name
== key
) {
251 CFRef
<CFStringRef
> value
;
252 if (OSStatus rc
= SecCertificateCopySubjectComponent(cert
, cf
->oid
, &value
.aref())) {
253 secdebug("csinterp", "cert %p lookup for DN.%s failed rc=%d", cert
, key
.c_str(), (int)rc
);
259 // email multi-valued match (any of...)
260 if (key
== "email") {
261 CFRef
<CFArrayRef
> value
;
262 if (OSStatus rc
= SecCertificateCopyEmailAddresses(cert
, &value
.aref())) {
263 secdebug("csinterp", "cert %p lookup for email failed rc=%d", cert
, (int)rc
);
269 // unrecognized key. Fail but do not abort to promote backward compatibility down the road
270 secdebug("csinterp", "cert field notation \"%s\" not understood", key
.c_str());
275 bool Requirement::Interpreter::certFieldGeneric(const string
&key
, const Match
&match
, SecCertificateRef cert
)
277 // the key is actually a (binary) OID value
278 CssmOid
oid((char *)key
.data(), key
.length());
279 return certFieldGeneric(oid
, match
, cert
);
282 bool Requirement::Interpreter::certFieldGeneric(const CssmOid
&oid
, const Match
&match
, SecCertificateRef cert
)
284 return cert
&& certificateHasField(cert
, oid
) && match(kCFBooleanTrue
);
287 bool Requirement::Interpreter::certFieldPolicy(const string
&key
, const Match
&match
, SecCertificateRef cert
)
289 // the key is actually a (binary) OID value
290 CssmOid
oid((char *)key
.data(), key
.length());
291 return certFieldPolicy(oid
, match
, cert
);
294 bool Requirement::Interpreter::certFieldPolicy(const CssmOid
&oid
, const Match
&match
, SecCertificateRef cert
)
296 return cert
&& certificateHasPolicy(cert
, oid
) && match(kCFBooleanTrue
);
301 // Check the Apple-signed condition
303 bool Requirement::Interpreter::appleAnchored()
305 if (SecCertificateRef cert
= mContext
->cert(anchorCert
))
307 #if defined(TEST_APPLE_ANCHOR)
308 || verifyAnchor(cert
, testAppleAnchorHash())
315 bool Requirement::Interpreter::appleSigned()
318 if (SecCertificateRef intermed
= mContext
->cert(-2)) // first intermediate
319 // first intermediate common name match (exact)
320 if (certFieldValue("subject.CN", Match(appleIntermediateCN
, matchEqual
), intermed
)
321 && certFieldValue("subject.O", Match(appleIntermediateO
, matchEqual
), intermed
))
328 // Verify an anchor requirement against the context
330 bool Requirement::Interpreter::verifyAnchor(SecCertificateRef cert
, const unsigned char *digest
)
332 // get certificate bytes
335 MacOSError::check(SecCertificateGetData(cert
, &certData
));
339 hasher(certData
.Data
, certData
.Length
);
340 return hasher
.verify(digest
);
347 // Check one or all certificate(s) in the cert chain against the Trust Settings database.
349 bool Requirement::Interpreter::trustedCerts()
351 int anchor
= mContext
->certCount() - 1;
352 for (int slot
= 0; slot
<= anchor
; slot
++)
353 if (SecCertificateRef cert
= mContext
->cert(slot
))
354 switch (trustSetting(cert
, slot
== anchor
)) {
355 case kSecTrustSettingsResultTrustRoot
:
356 case kSecTrustSettingsResultTrustAsRoot
:
358 case kSecTrustSettingsResultDeny
:
360 case kSecTrustSettingsResultUnspecified
:
371 bool Requirement::Interpreter::trustedCert(int slot
)
373 if (SecCertificateRef cert
= mContext
->cert(slot
)) {
374 int anchorSlot
= mContext
->certCount() - 1;
375 switch (trustSetting(cert
, slot
== anchorCert
|| slot
== anchorSlot
)) {
376 case kSecTrustSettingsResultTrustRoot
:
377 case kSecTrustSettingsResultTrustAsRoot
:
379 case kSecTrustSettingsResultDeny
:
380 case kSecTrustSettingsResultUnspecified
:
392 // Explicitly check one certificate against the Trust Settings database and report
393 // the findings. This is a helper for the various Trust Settings evaluators.
395 SecTrustSettingsResult
Requirement::Interpreter::trustSetting(SecCertificateRef cert
, bool isAnchor
)
397 // the SPI input is the uppercase hex form of the SHA-1 of the certificate...
400 hashOfCertificate(cert
, digest
);
401 string Certhex
= CssmData(digest
, sizeof(digest
)).toHex();
402 for (string::iterator it
= Certhex
.begin(); it
!= Certhex
.end(); ++it
)
406 // call Trust Settings and see what it finds
407 SecTrustSettingsDomain domain
;
408 SecTrustSettingsResult result
;
409 CSSM_RETURN
*errors
= NULL
;
410 uint32 errorCount
= 0;
411 bool foundMatch
, foundAny
;
412 switch (OSStatus rc
= SecTrustSettingsEvaluateCert(
413 CFTempString(Certhex
), // settings index
414 &CSSMOID_APPLE_TP_CODE_SIGNING
, // standard code signing policy
415 NULL
, 0, // policy string (unused)
416 kSecTrustSettingsKeyUseAny
, // no restriction on key usage @@@
417 isAnchor
, // consult system default anchor set
419 &domain
, // domain of found setting
420 &errors
, &errorCount
, // error set and maximum count
421 &result
, // the actual setting
422 &foundMatch
, &foundAny
// optimization hints (not used)
429 return kSecTrustSettingsResultUnspecified
;
432 MacOSError::throwMe(rc
);
438 // Create a Match object from the interpreter stream
440 Requirement::Interpreter::Match::Match(Interpreter
&interp
)
442 switch (mOp
= interp
.get
<MatchOperation
>()) {
447 case matchBeginsWith
:
450 case matchGreaterThan
:
452 case matchGreaterEqual
:
453 mValue
.take(makeCFString(interp
.getString()));
456 // Assume this (unknown) match type has a single data argument.
457 // This gives us a chance to keep the instruction stream aligned.
458 interp
.getString(); // discard
465 // Execute a match against a candidate value
467 bool Requirement::Interpreter::Match::operator () (CFTypeRef candidate
) const
469 // null candidates always fail
473 // interpret an array as matching alternatives (any one succeeds)
474 if (CFGetTypeID(candidate
) == CFArrayGetTypeID()) {
475 CFArrayRef array
= CFArrayRef(candidate
);
476 CFIndex count
= CFArrayGetCount(array
);
477 for (CFIndex n
= 0; n
< count
; n
++)
478 if ((*this)(CFArrayGetValueAtIndex(array
, n
))) // yes, it's recursive
483 case matchExists
: // anything but NULL and boolean false "exists"
484 return !CFEqual(candidate
, kCFBooleanFalse
);
485 case matchEqual
: // equality works for all CF types
486 return CFEqual(candidate
, mValue
);
488 if (CFGetTypeID(candidate
) == CFStringGetTypeID()) {
489 CFStringRef value
= CFStringRef(candidate
);
490 if (CFStringFindWithOptions(value
, mValue
, CFRangeMake(0, CFStringGetLength(value
)), 0, NULL
))
494 case matchBeginsWith
:
495 if (CFGetTypeID(candidate
) == CFStringGetTypeID()) {
496 CFStringRef value
= CFStringRef(candidate
);
497 if (CFStringFindWithOptions(value
, mValue
, CFRangeMake(0, CFStringGetLength(mValue
)), 0, NULL
))
502 if (CFGetTypeID(candidate
) == CFStringGetTypeID()) {
503 CFStringRef value
= CFStringRef(candidate
);
504 CFIndex matchLength
= CFStringGetLength(mValue
);
505 CFIndex start
= CFStringGetLength(value
) - matchLength
;
507 if (CFStringFindWithOptions(value
, mValue
, CFRangeMake(start
, matchLength
), 0, NULL
))
512 return inequality(candidate
, kCFCompareNumerically
, kCFCompareLessThan
, true);
513 case matchGreaterThan
:
514 return inequality(candidate
, kCFCompareNumerically
, kCFCompareGreaterThan
, true);
516 return inequality(candidate
, kCFCompareNumerically
, kCFCompareGreaterThan
, false);
517 case matchGreaterEqual
:
518 return inequality(candidate
, kCFCompareNumerically
, kCFCompareLessThan
, false);
520 // unrecognized match types can never match
526 bool Requirement::Interpreter::Match::inequality(CFTypeRef candidate
, CFStringCompareFlags flags
,
527 CFComparisonResult outcome
, bool negate
) const
529 if (CFGetTypeID(candidate
) == CFStringGetTypeID()) {
530 CFStringRef value
= CFStringRef(candidate
);
531 if ((CFStringCompare(value
, mValue
, flags
) == outcome
) == negate
)
539 // External fragments
541 Fragments::Fragments()
543 mMyBundle
= CFBundleGetBundleWithIdentifier(CFSTR("com.apple.security"));
547 bool Fragments::evalNamed(const char *type
, const std::string
&name
, const Requirement::Context
&ctx
)
549 if (CFDataRef fragData
= fragment(type
, name
)) {
550 const Requirement
*req
= (const Requirement
*)CFDataGetBytePtr(fragData
); // was prevalidated as Requirement
551 return req
->validates(ctx
);
557 CFDataRef
Fragments::fragment(const char *type
, const std::string
&name
)
559 string key
= name
+ "!!" + type
; // compound key
560 StLock
<Mutex
> _(mLock
); // lock for cache access
561 FragMap::const_iterator it
= mFragments
.find(key
);
562 if (it
== mFragments
.end()) {
563 CFRef
<CFDataRef
> fragData
; // will always be set (NULL on any errors)
564 if (CFRef
<CFURLRef
> fragURL
= CFBundleCopyResourceURL(mMyBundle
, CFTempString(name
), CFSTR("csreq"), CFTempString(type
)))
565 if (CFRef
<CFDataRef
> data
= cfLoadFile(fragURL
)) { // got data
566 const Requirement
*req
= (const Requirement
*)CFDataGetBytePtr(data
);
567 if (req
->validateBlob(CFDataGetLength(data
))) // looks like a Requirement...
568 fragData
= data
; // ... so accept it
570 Syslog::warning("Invalid sub-requirement at %s", cfString(fragURL
).c_str());
572 if (CODESIGN_EVAL_REQINT_FRAGMENT_LOAD_ENABLED())
573 CODESIGN_EVAL_REQINT_FRAGMENT_LOAD(type
, name
.c_str(), fragData
? CFDataGetBytePtr(fragData
) : NULL
);
574 mFragments
[key
] = fragData
; // cache it, success or failure
577 CODESIGN_EVAL_REQINT_FRAGMENT_HIT(type
, name
.c_str());