2 * Copyright (c) 2006-2007 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 // Requirements Language Grammar
27 // This file describes two distinct (related) grammars:
28 // Requirement => single requirement (Requirement *)
29 // RequirementSet => set of labeled requirements (Requirements *)
30 // The grammar can "autosense" - i.e. recognize which one it's fed and
31 // return appropriate semantic data.
33 // The semantic data compiled is a malloc'ed BlobCore * - a Requirement
34 // object or a SuperBlob containing multiple Requirements.
36 // Errors are indicated to the caller by accumulating error message strings
37 // in the errors member variable. Any non-empty error value indicates failure.
38 // Presence of semantic data is not a reliable indication of success.
40 header "post_include_hpp" {
41 #include "requirement.h"
42 using namespace CodeSigning;
43 typedef Requirement::Maker Maker;
46 header "post_include_cpp" {
47 #include "requirement.h"
49 #include "csutilities.h"
50 #include <security_utilities/cfutilities.h>
51 #include <security_utilities/hashing.h>
52 #include <security_cdsa_utilities/cssmdata.h> // OID coding
53 using namespace CodeSigning;
54 typedef Requirement::Maker Maker;
59 namespace="Security_CodeSigning";
61 namespaceAntlr="antlr";
68 // Collect error messages.
69 // Note that the immediate caller takes the absence of collected error messages
70 // to indicate compilation success.
72 void RequirementParser::reportError(const antlr::RecognitionException &ex)
74 errors += ex.toString() + "\n";
77 void RequirementParser::reportError(const std::string &s)
84 // Parser helper functions
86 string RequirementParser::hexString(const string &s)
89 throw antlr::SemanticException("odd number of digits");
90 const char *p = s.data();
92 for (unsigned n = 0; n < s.length(); n += 2) {
94 sscanf(p+n, "%2hhx", &c);
100 void RequirementParser::hashString(const string &s, SHA1::Digest hash)
102 if (s.size() != 2 * SHA1::digestLength)
103 throw antlr::SemanticException("invalid hash length");
104 memcpy(hash, hexString(s).data(), SHA1::digestLength);
107 void RequirementParser::certMatchOperation(Maker &maker, int slot, string key)
109 if (!key.compare(0, 8, "subject.", 0, 8)) {
110 maker.put(opCertField);
113 } else if (!key.compare(0, 6, "field.", 0, 6)) {
114 maker.put(opCertGeneric);
116 CssmAutoData oid(Allocator::standard()); oid.fromOid(key.c_str() + 6);
117 maker.putData(oid.data(), oid.length());
119 throw antlr::SemanticException(key + ": unrecognized certificate field");
125 class RequirementParser extends Parser;
134 void reportError(const antlr::RecognitionException &ex);
135 void reportError(const std::string &s);
138 static string hexString(const string &s);
139 static void hashString(const string &s, SHA1::Digest hash);
140 void certMatchOperation(Maker &maker, int slot, string key);
145 // Compound target; compiles single requirements or requirement sets
146 // and returns them as a BlobCore.
148 autosense returns [BlobCore *result = NULL]
150 | result=requirementSet
155 // A Requirements Set.
157 requirementSet returns [Requirements *result = NULL]
158 { Requirements::Maker maker; }
159 : ( { uint32_t t; Requirement *req; }
160 t=requirementType ARROW req=requirementElement
161 { maker.add(t, req); }
163 { result = errors.empty() ? maker() : NULL; }
167 requirementType returns [uint32_t type = kSecInvalidRequirementType]
169 { type = kSecGuestRequirementType; }
171 { type = kSecHostRequirementType; }
173 { type = kSecDesignatedRequirementType; }
175 { type = kSecLibraryRequirementType; }
177 { type = atol(stype->getText().c_str()); }
182 // A single Requirement (untyped)
184 requirement returns [Requirement *result = NULL]
185 : result = requirementElement
189 requirementElement returns [Requirement *result = NULL]
190 { Requirement::Maker maker; }
192 { result = maker(); }
198 // Classic recursive expressions
201 { Maker::Label label(maker); }
202 : term[maker] ( "and" { maker.insert<ExprOp>(label) = opAnd; } term[maker] )*
206 { Maker::Label label(maker); }
207 : primary[maker] ( "or" { maker.insert<ExprOp>(label) = opOr; } primary[maker] )*
210 primary[Maker &maker]
211 : LPAREN expr[maker] RPAREN
212 | NOT { maker.put(opNot); } primary[maker]
213 | ( "always" | "true" )
214 { maker.put(opTrue); }
215 | ( "never" | "false" )
216 { maker.put(opFalse); }
219 | entitlementspec[maker]
220 | "identifier" { string code; } eql code=identifierString
221 { maker.ident(code); }
222 | "cdhash" { SHA1::Digest digest; } eql hash[digest]
223 { maker.cdhash(digest); }
228 // Certificate specifications restrict certificates in the signing chain
230 certspec[Maker &maker]
231 : "anchor" "apple" appleanchor[maker]
232 | "anchor" "generic" "apple" // alternate form
233 { maker.put(opAppleGenericAnchor); }
234 | ( "certificate" | "cert" | "anchor" ) "trusted"
235 { maker.trustedAnchor(); }
236 | ( "certificate" | "cert" ) { int slot; } slot=certSlot
237 ( certslotspec[maker, slot] | "trusted" { maker.trustedAnchor(slot); } )
238 | "anchor" certslotspec[maker, Requirement::anchorCert]
241 appleanchor[Maker &maker]
243 { maker.put(opAppleAnchor); }
245 { maker.put(opAppleGenericAnchor); }
248 certslotspec[Maker &maker, int slot] { string key; }
249 : eql { SHA1::Digest digest; } certificateDigest[digest]
250 { maker.anchor(slot, digest); }
252 { certMatchOperation(maker, slot, key); }
258 // Info specifications place conditions on entries in the Info.plist
260 infospec[Maker &maker] { string key; }
261 : "info" key=bracketKey
262 { maker.put(opInfoKeyField); maker.put(key); }
268 // Entitlement specifications place conditions on embedded entitlement entries
270 entitlementspec[Maker &maker] { string key; }
271 : "entitlement" key=bracketKey
272 { maker.put(opEntitlementField); maker.put(key); }
278 // Common match operations, written as a syntactic suffix (the operand precedes this)
280 match_suffix[Maker &maker]
281 : empty ( "exists" ) ?
282 { maker.put(matchExists); }
284 { MatchOperation mop = matchEqual; string value; }
285 ( STAR { mop = matchEndsWith; } ) ?
287 ( STAR { mop = (mop == matchEndsWith) ? matchContains : matchBeginsWith; } ) ?
288 { maker.put(mop); maker.put(value); }
289 | SUBS { string value; } value=datavalue
290 { maker.put(matchContains); maker.put(value); }
291 | LESS { string value; } value=datavalue
292 { maker.put(matchLessThan); maker.put(value); }
293 | GT { string value; } value=datavalue
294 { maker.put(matchGreaterThan); maker.put(value); }
295 | LE { string value; } value=datavalue
296 { maker.put(matchLessEqual); maker.put(value); }
297 | GE { string value; } value=datavalue
298 { maker.put(matchGreaterEqual); maker.put(value); }
301 bracketKey returns [string key]
302 : LBRACK key=stringvalue RBRACK
306 // A certSlot identifiers one certificate from the certificate chain
308 certSlot returns [int slot]
309 : s:INTEGER // counting from the anchor up
310 { slot = atol(s->getText().c_str()); }
311 | NEG ss:INTEGER // counting from the leaf down
312 { slot = -atol(ss->getText().c_str()); }
313 | "leaf" // the leaf ( == -1)
314 { slot = Requirement::leafCert; }
315 | "root" // the root ( == 0)
316 { slot = Requirement::anchorCert; }
319 // an arbitrary digest value
320 hash[SHA1::Digest digest]
322 { hashString(hash->getText(), digest); }
325 // various forms to specify a certificate hash
326 certificateDigest[SHA1::Digest digest]
328 | { string path; } path=pathstring
329 { if (CFRef<CFDataRef> certData = cfLoadFile(path))
330 hashOfCertificate(CFDataGetBytePtr(certData), CFDataGetLength(certData), digest);
332 throw antlr::SemanticException(path + ": not found");
336 // generic data - can be simple string, quoted string, or 0x-style hex
337 datavalue returns [string result]
339 | hex:HEXCONSTANT { result = hexString(hex->getText()); }
342 // strings can always be quoted, but DOTKEYs don't need to be
343 stringvalue returns [string result]
344 : dk:DOTKEY { result = dk->getText(); }
345 | s:STRING { result = s->getText(); }
348 // pathstrings are like strings, but PATHNAMEs don't need to be quoted either
349 pathstring returns [string result]
350 : dk:DOTKEY { result = dk->getText(); }
351 | s:STRING { result = s->getText(); }
352 | pn:PATHNAME { result = pn->getText(); }
355 // unique identifier value
356 identifierString returns [string result]
357 : dk:DOTKEY { result = dk->getText(); }
358 | s:STRING { result = s->getText(); }
361 // syntactic cavity generators
376 // The lexer for the Requirement language.
377 // Really straightforward and conventional.
378 // A subset of strings don't need to be quoted (DOTKEYs). Neither do some simple
379 // pathnames starting with "/".
380 // Hash values have a special syntax H"abcd" (abcd in straight hex).
381 // Hex constants of the form 0xabcd can have any length; they are carried
382 // around as strings (which are in turn stored as data in the language binary).
384 class RequirementLexer extends Lexer;
392 IDENT options { testLiterals=true; }
393 : ( 'A' .. 'Z' | 'a' .. 'z' ) ( 'A' .. 'Z' | 'a' .. 'z' | '0' .. '9' )*
396 DOTKEY options { testLiterals=true; }
397 : IDENT ( "." ( IDENT | INTEGER ) )*
401 : "/" IDENT ( "/" IDENT )+
405 : 'H'! '"'! ( HEX )+ '"'!
413 : '"'! ( ( '\\'! '"' ) | ( ~ ( '"' | '\\' ) ) )* '"'!
421 HEX : '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' ;
446 WS : ( ' ' | '\n' { newline(); } | '\t' )+
447 { $setType(antlr::Token::SKIP); }
452 { $setType(antlr::Token::SKIP); }
456 : "/*" ( (~'*')|('*'(~'/')) )* "*/"
457 { $setType(antlr::Token::SKIP); }
462 { $setType(antlr::Token::SKIP); }