2 * Copyright (c) 2006 Apple Computer, 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 <Security/SecTrustSettingsPriv.h>
29 #include <Security/SecCertificatePriv.h>
30 #include <security_utilities/memutils.h>
31 #include <security_cdsa_utilities/cssmdata.h> // for hex encoding
32 #include "csutilities.h"
35 namespace CodeSigning
{
39 // Construct an interpreter given a Requirement and an evaluation context.
41 Requirement::Interpreter::Interpreter(const Requirement
*req
, const Context
*ctx
)
42 : Reader(req
), mContext(ctx
)
48 // Main interpreter function.
50 // ExprOp code is in Polish Notation (operator followed by operands),
51 // and this engine uses opportunistic evaluation.
53 bool Requirement::Interpreter::evaluate()
55 ExprOp op
= ExprOp(get
<uint32_t>());
56 switch (op
& ~opFlagMask
) {
62 return getString() == mContext
->directory
->identifier();
64 if (SecCertificateRef cert
= mContext
->cert(anchorCert
))
65 return verifyAnchor(cert
, appleAnchorHash())
66 #if defined(TEST_APPLE_ANCHOR)
67 || verifyAnchor(cert
, testAppleAnchorHash())
74 SecCertificateRef cert
= mContext
->cert(get
<int32_t>());
75 return verifyAnchor(cert
, getSHA1());
77 case opInfoKeyValue
: // [legacy; use opInfoKeyField]
79 string key
= getString();
80 return infoKeyValue(key
, Match(CFTempString(getString()), matchEqual
));
83 return evaluate() && evaluate();
85 return evaluate() || evaluate();
89 hash(mContext
->directory
, mContext
->directory
->length());
90 return hash
.verify(getHash());
96 string key
= getString();
98 return infoKeyValue(key
, match
);
102 SecCertificateRef cert
= mContext
->cert(get
<int32_t>());
103 string key
= getString();
105 return certFieldValue(key
, match
, cert
);
108 return trustedCert(get
<int32_t>());
110 return trustedCerts();
112 // opcode not recognized - handle generically if possible, fail otherwise
113 if (op
& (opGenericFalse
| opGenericSkip
)) {
114 // unknown opcode, but it has a size field and can be safely bypassed
115 skip(get
<uint32_t>());
116 if (op
& opGenericFalse
) {
117 secdebug("csinterp", "opcode 0x%x interpreted as false", op
);
120 secdebug("csinterp", "opcode 0x%x ignored; continuing", op
);
124 // unrecognized opcode and no way to interpret it
125 secdebug("csinterp", "opcode 0x%x cannot be handled; aborting", op
);
126 MacOSError::throwMe(errSecCSUnimplemented
);
132 // Evaluate an Info.plist key condition
134 bool Requirement::Interpreter::infoKeyValue(const string
&key
, const Match
&match
)
136 if (mContext
->info
) // we have an Info.plist
137 if (CFTypeRef value
= CFDictionaryGetValue(mContext
->info
, CFTempString(key
)))
143 bool Requirement::Interpreter::certFieldValue(const string
&key
, const Match
&match
, SecCertificateRef cert
)
145 // no cert, no chance
149 // a table of recognized keys for the "certificate[foo]" syntax
150 static const struct CertField
{
154 { "subject.C", &CSSMOID_CountryName
},
155 { "subject.CN", &CSSMOID_CommonName
},
156 { "subject.D", &CSSMOID_Description
},
157 { "subject.L", &CSSMOID_LocalityName
},
158 { "subject.O", &CSSMOID_OrganizationName
},
159 { "subject.OU", &CSSMOID_OrganizationalUnitName
},
160 { "subject.ST", &CSSMOID_StateProvinceName
},
161 { "subject.STREET", &CSSMOID_StreetAddress
},
165 // email multi-valued match (any of...)
166 if (key
== "email") {
167 CFRef
<CFArrayRef
> value
;
168 if (IFDEBUG(OSStatus rc
=) SecCertificateCopyEmailAddresses(cert
, &value
.aref())) {
169 secdebug("csinterp", "cert %p lookup for email failed rc=%ld", cert
, rc
);
175 // DN-component single-value match
176 for (const CertField
*cf
= certFields
; cf
->name
; cf
++)
177 if (cf
->name
== key
) {
178 CFRef
<CFStringRef
> value
;
179 if (IFDEBUG(OSStatus rc
=) SecCertificateCopySubjectComponent(cert
, cf
->oid
, &value
.aref())) {
180 secdebug("csinterp", "cert %p lookup for DN.%s failed rc=%ld", cert
, key
.c_str(), rc
);
186 // unrecognized key. Fail but do not abort to promote backward compatibility down the road
187 secdebug("csinterp", "cert field notation \"%s\" not understood", key
.c_str());
193 // Verify an anchor requirement against the context
195 bool Requirement::Interpreter::verifyAnchor(SecCertificateRef cert
, const unsigned char *digest
)
197 // get certificate bytes
200 MacOSError::check(SecCertificateGetData(cert
, &certData
));
203 //@@@ should get SHA1(cert(-1).data) precalculated during chain verification
205 hasher(certData
.Data
, certData
.Length
);
206 return hasher
.verify(digest
);
213 // Check one or all certificate(s) in the cert chain against the Trust Settings database.
215 bool Requirement::Interpreter::trustedCerts()
217 int anchor
= mContext
->certCount() - 1;
218 for (int slot
= 0; slot
<= anchor
; slot
++)
219 if (SecCertificateRef cert
= mContext
->cert(slot
))
220 switch (trustSetting(cert
, slot
== anchor
)) {
221 case kSecTrustSettingsResultTrustRoot
:
222 case kSecTrustSettingsResultTrustAsRoot
:
224 case kSecTrustSettingsResultDeny
:
226 case kSecTrustSettingsResultUnspecified
:
237 bool Requirement::Interpreter::trustedCert(int slot
)
239 if (SecCertificateRef cert
= mContext
->cert(slot
)) {
240 int anchorSlot
= mContext
->certCount() - 1;
241 switch (trustSetting(cert
, slot
== anchorCert
|| slot
== anchorSlot
)) {
242 case kSecTrustSettingsResultTrustRoot
:
243 case kSecTrustSettingsResultTrustAsRoot
:
245 case kSecTrustSettingsResultDeny
:
246 case kSecTrustSettingsResultUnspecified
:
258 // Explicitly check one certificate against the Trust Settings database and report
259 // the findings. This is a helper for the various Trust Settings evaluators.
261 SecTrustSettingsResult
Requirement::Interpreter::trustSetting(SecCertificateRef cert
, bool isAnchor
)
263 // the SPI input is the uppercase hex form of the SHA-1 of the certificate...
266 hashOfCertificate(cert
, digest
);
267 string Certhex
= CssmData(digest
, sizeof(digest
)).toHex();
268 for (string::iterator it
= Certhex
.begin(); it
!= Certhex
.end(); ++it
)
272 // call Trust Settings and see what it finds
273 SecTrustSettingsDomain domain
;
274 SecTrustSettingsResult result
;
275 CSSM_RETURN
*errors
= NULL
;
276 uint32 errorCount
= 0;
277 bool foundMatch
, foundAny
;
278 switch (OSStatus rc
= SecTrustSettingsEvaluateCert(
279 CFTempString(Certhex
), // settings index
280 &CSSMOID_APPLE_TP_CODE_SIGNING
, // standard code signing policy
281 NULL
, 0, // policy string (unused)
282 kSecTrustSettingsKeyUseAny
, // no restriction on key usage @@@
283 isAnchor
, // consult system default anchor set
285 &domain
, // domain of found setting
286 &errors
, &errorCount
, // error set and maximum count
287 &result
, // the actual setting
288 &foundMatch
, &foundAny
// optimization hints (not used)
295 return kSecTrustSettingsResultUnspecified
;
298 MacOSError::throwMe(rc
);
304 // Create a Match object from the interpreter stream
306 Requirement::Interpreter::Match::Match(Interpreter
&interp
)
308 switch (mOp
= interp
.get
<MatchOperation
>()) {
313 mValue
= makeCFString(interp
.getString());
323 // Execute a match against a candidate value
325 bool Requirement::Interpreter::Match::operator () (CFTypeRef candidate
) const
327 // null candidates always fail
331 // interpret an array as matching alternatives (any one succeeds)
332 if (CFGetTypeID(candidate
) == CFArrayGetTypeID()) {
333 CFArrayRef array
= CFArrayRef(candidate
);
334 CFIndex count
= CFArrayGetCount(array
);
335 for (CFIndex n
= 0; n
< count
; n
++)
336 if ((*this)(CFArrayGetValueAtIndex(array
, n
))) // yes, it's recursive
341 case matchExists
: // anything but NULL and boolean false "exists"
342 return !CFEqual(candidate
, kCFBooleanFalse
);
343 case matchEqual
: // equality works for all CF types
344 return CFEqual(candidate
, mValue
);
346 if (CFGetTypeID(candidate
) == CFStringGetTypeID()) {
347 CFStringRef value
= CFStringRef(candidate
);
348 if (CFStringFindWithOptions(value
, mValue
, CFRangeMake(0, CFStringGetLength(value
)), 0, NULL
))