cert-expr.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  1. /*
  2. * Parser for the boolean expression language used to configure what
  3. * host names an OpenSSH certificate will be trusted to sign for.
  4. */
  5. /*
  6. Language specification
  7. ======================
  8. Outer lexical layer: the input expression is broken up into tokens,
  9. with any whitespace between them discarded and ignored. The following
  10. tokens are special:
  11. ( ) && || !
  12. and the remaining token type is an 'atom', which is any non-empty
  13. sequence of characters from the following set:
  14. ABCDEFGHIJKLMNOPQRSTUVWXYZ
  15. abcdefghijklmnopqrstuvwxyz
  16. 0123456789
  17. .-_*?[]/:
  18. Inner lexical layer: once the boundaries of an 'atom' token have been
  19. determined by the outer lex layer, each atom is further classified
  20. into one of the following subtypes:
  21. - If it contains no ':' or '/', it's taken to be a wildcard matching
  22. hostnames, e.g. "*.example.com".
  23. - If it begins with 'port:' followed by digits, it's taken to be a
  24. single port number specification, e.g. "port:22".
  25. - If it begins with 'port:' followed by two digit sequences separated
  26. by '-', it's taken to be a port number range, e.g. "port:0-1023".
  27. - Any other atom is reserved for future expansion. (See Rationale.)
  28. Syntax layer: all of those types of atom are interpreted as predicates
  29. applied to the (hostname, port) data configured for the SSH connection
  30. for which the certificate is being validated.
  31. Wildcards are handled using the syntax in wildcard.c. The dot-
  32. separated structure of hostnames is thus not special; the '*' in
  33. "*.example.com" will match any number of subdomains under example.com.
  34. More complex boolean expressions can be made by combining those
  35. predicates using the boolean operators and parentheses, in the obvious
  36. way: && and || are infix operators representing logical AND and OR, !
  37. is a prefix operator representing logical NOT, and parentheses
  38. indicate grouping.
  39. Each of && and || can associate freely with itself (that is, you can
  40. write "a && b && c" without having to parenthesise one or the other
  41. subexpression). But they are forbidden to associate with _each other_.
  42. That is, if you write "a && b || c" or "a || b && c", it's a syntax
  43. error, and you must add parentheses to indicate which operator was
  44. intended to have the higher priority.
  45. Rationale
  46. =========
  47. Atoms: restrictions
  48. -------------------
  49. The characters permitted in the 'atom' token don't include \, even
  50. though it's a special character defined by wildcard.c. That's because
  51. in this restricted context wildcards will never need it: no hostname
  52. contains a literal \, and neither does any hostname contain a literal
  53. instance of any of the wildcard characters that wildcard.c allows you
  54. to use \ to escape.
  55. Atoms: future extension
  56. -----------------------
  57. The specification of the 'atom' token is intended to leave space for
  58. more than one kind of future extension.
  59. Most obviously, additional special predicates similar to "port:", with
  60. different disambiguating prefixes. I don't know what things of that
  61. kind we might need, but space is left for them just in case.
  62. Also, the unused '/' in the permitted-characters spec is intended to
  63. leave open the possibility of allowing certificate acceptance to be
  64. based on IP address, because the usual CIDR syntax for specifying IP
  65. ranges (e.g. "192.168.1.0/24" or "2345:6789:abcd:ef01::/128") would be
  66. lexed as a single atom under these rules.
  67. For the moment, certificate acceptance rules based on IP address are
  68. not supported, because it's not clear what the semantics ought to be.
  69. There are two problems with using IP addresses for this purpose:
  70. 1. Sometimes they come from the DNS, which means you can't trust
  71. them. The whole idea of SSH is to end-to-end authenticate the host
  72. key against only the input given _by the user_ to the client. Any
  73. additional data provided by the network, such as the result of a
  74. DNS lookup, is suspect.
  75. On the other hand, sometimes the IP address *is* part of the user
  76. input, because the user can provide an IP address rather than a
  77. hostname as the intended connection destination. So there are two
  78. kinds of IP address, and they should very likely be treated
  79. differently.
  80. 2. Sometimes the server's IP address is not even *known* by the
  81. client, if you're connecting via a proxy and leaving DNS lookups
  82. to the proxy.
  83. So, what should a boolean expression do if it's asked to accept or
  84. reject based on an IP address, and the IP address is unknown or
  85. untrustworthy? I'm not sure, and therefore, in the initial version of
  86. this expression system, I haven't implemented them at all.
  87. But the syntax is still available for a future extension to use, if we
  88. come up with good answers to these questions.
  89. (One possibility would be to evaluate the whole expression in Kleene
  90. three-valued logic, so that every subexpression has the possible
  91. answers TRUE, FALSE and UNKNOWN. If a definite IP address is not
  92. available, IP address predicates evaluate to UNKNOWN. Then, once the
  93. expression as a whole is evaluated, fail closed, by interpreting
  94. UNKNOWN as 'reject'. The effect would be that a positive _or_ negative
  95. constraint on the IP address would cause rejection if the IP address
  96. is not reliably known, because once the predicate itself has returned
  97. UNKNOWN, negating it still gives UNKNOWN. The only way you could still
  98. accept a certificate in that situation would be if the overall
  99. structure of the expression meant that the test of the IP address
  100. couldn't affect the result anyway, e.g. if it was ANDed with another
  101. subexpression that definitely evaluated to FALSE, or ORed with one
  102. that evaluated to TRUE. This system seems conceptually elegant to me,
  103. but the argument against it is that it's complicated and
  104. counterintuitive, which is not a property you want in something a user
  105. is writing for security purposes!)
  106. Operator precedence
  107. -------------------
  108. Why did I choose to make && and || refuse to associate with each
  109. other, instead of applying the usual C precedence rule that && beats
  110. ||? Because I think the C precedence rule is essentially arbitrary, in
  111. the sense that when people are writing boolean expressions in practice
  112. based on predicates from the rest of their program, it's about equally
  113. common to want to nest an && within an || and vice versa. So the
  114. default precedence rule only gives the user what they actually wanted
  115. about 50% of the time, and leads to absent-minded errors about as
  116. often as it conveniently allows you to omit a pair of parens.
  117. With my mathematician hat on, it's not so arbitrary. I agree that if
  118. you're *going* to give || and && a relative priority then it makes
  119. more sense to make && the higher-priority one, because if you're
  120. thinking algebraically, && is more multiplicative and || is more
  121. additive. But the pure-maths contexts in which that's convenient have
  122. nothing to do with general boolean expressions in if statements.
  123. This boolean syntax is still close enough to that of C and its
  124. derivatives to allow easy enough expression interchange (not counting
  125. the fact that atoms would need rewriting). Any boolean expression
  126. structure accepted by this syntax is also legal C and means the same
  127. thing; any expression structure accepted by C is either legal and
  128. equivalent in this syntax, or will fail with an error. In no case is
  129. anything accepted but mapped to a different meaning.
  130. */
  131. #include "putty.h"
  132. typedef enum Token {
  133. TOK_LPAR, TOK_RPAR,
  134. TOK_AND, TOK_OR, TOK_NOT,
  135. TOK_ATOM,
  136. TOK_END, TOK_ERROR
  137. } Token;
  138. static inline bool is_space(char c)
  139. {
  140. return (c == ' ' || c == '\n' || c == '\r' || c == '\t' ||
  141. c == '\f' || c == '\v');
  142. }
  143. static inline bool is_operator_char(char c)
  144. {
  145. return (c == '(' || c == ')' || c == '&' || c == '|' || c == '!');
  146. }
  147. static inline bool is_atom_char(char c)
  148. {
  149. return (('A' <= c && c <= 'Z') ||
  150. ('a' <= c && c <= 'z') ||
  151. ('0' <= c && c <= '9') ||
  152. c == '.' || c == '-' || c == '_' || c == '*' || c == '?' ||
  153. c == '[' || c == ']' || c == '/' || c == ':');
  154. }
  155. static Token lex(ptrlen *text, ptrlen *token, char **err)
  156. {
  157. const char *p = text->ptr, *e = p + text->len;
  158. Token type = TOK_ERROR;
  159. /* Skip whitespace */
  160. while (p < e && is_space(*p))
  161. p++;
  162. const char *start = p;
  163. if (!(p < e)) {
  164. type = TOK_END;
  165. goto out;
  166. }
  167. if (is_operator_char(*p)) {
  168. /* Match boolean-expression tokens */
  169. static const struct operator {
  170. ptrlen text;
  171. Token type;
  172. } operators[] = {
  173. {PTRLEN_DECL_LITERAL("("), TOK_LPAR},
  174. {PTRLEN_DECL_LITERAL(")"), TOK_RPAR},
  175. {PTRLEN_DECL_LITERAL("&&"), TOK_AND},
  176. {PTRLEN_DECL_LITERAL("||"), TOK_OR},
  177. {PTRLEN_DECL_LITERAL("!"), TOK_NOT},
  178. };
  179. for (size_t i = 0; i < lenof(operators); i++) {
  180. const struct operator *op = &operators[i];
  181. if (e - p >= op->text.len &&
  182. ptrlen_eq_ptrlen(op->text, make_ptrlen(p, op->text.len))) {
  183. p += op->text.len;
  184. type = op->type;
  185. goto out;
  186. }
  187. }
  188. /*
  189. * Report an error if one of the operator characters is used
  190. * in a way that doesn't match something in that table (e.g. a
  191. * single &).
  192. */
  193. p++;
  194. type = TOK_ERROR;
  195. *err = dupstr("unrecognised boolean operator");
  196. goto out;
  197. } else if (is_atom_char(*p)) {
  198. /*
  199. * Match an 'atom' token, which is any non-empty sequence of
  200. * characters from the combined set that allows hostname
  201. * wildcards, IP address ranges and special predicates like
  202. * port numbers.
  203. */
  204. do {
  205. p++;
  206. } while (p < e && is_atom_char(*p));
  207. type = TOK_ATOM;
  208. goto out;
  209. } else {
  210. /*
  211. * Otherwise, report an error.
  212. */
  213. p++;
  214. type = TOK_ERROR;
  215. *err = dupstr("unexpected character in expression");
  216. goto out;
  217. }
  218. out:
  219. *token = make_ptrlen(start, p - start);
  220. text->ptr = p;
  221. text->len = e - p;
  222. return type;
  223. }
  224. typedef enum Operator {
  225. OP_AND, OP_OR, OP_NOT,
  226. OP_HOSTNAME_WC, OP_PORT_RANGE
  227. } Operator;
  228. typedef struct ExprNode ExprNode;
  229. struct ExprNode {
  230. Operator op;
  231. ptrlen text;
  232. union {
  233. struct {
  234. /* OP_AND, OP_OR */
  235. ExprNode **subexprs;
  236. size_t nsubexprs;
  237. };
  238. struct {
  239. /* OP_NOT */
  240. ExprNode *subexpr;
  241. };
  242. struct {
  243. /* OP_HOSTNAME_WC */
  244. char *wc;
  245. };
  246. struct {
  247. /* OP_PORT_RANGE */
  248. unsigned lo, hi; /* both inclusive */
  249. };
  250. };
  251. };
  252. static ExprNode *exprnode_new(Operator op, ptrlen text)
  253. {
  254. ExprNode *en = snew(ExprNode);
  255. memset(en, 0, sizeof(*en));
  256. en->op = op;
  257. en->text = text;
  258. return en;
  259. }
  260. static void exprnode_free(ExprNode *en)
  261. {
  262. switch (en->op) {
  263. case OP_AND:
  264. case OP_OR:
  265. for (size_t i = 0; i < en->nsubexprs; i++)
  266. exprnode_free(en->subexprs[i]);
  267. sfree(en->subexprs);
  268. break;
  269. case OP_NOT:
  270. exprnode_free(en->subexpr);
  271. break;
  272. case OP_HOSTNAME_WC:
  273. sfree(en->wc);
  274. break;
  275. case OP_PORT_RANGE:
  276. break;
  277. default:
  278. unreachable("unhandled node type in exprnode_free");
  279. }
  280. sfree(en);
  281. }
  282. static unsigned ptrlen_to_port_number(ptrlen input)
  283. {
  284. unsigned val = 0;
  285. for (const char *p = input.ptr, *end = p + input.len; p < end; p++) {
  286. assert('0' <= *p && *p <= '9'); /* expect parser to have checked */
  287. val = 10 * val + (*p - '0');
  288. if (val >= 65536)
  289. val = 65536; /* normalise 'too large' to avoid integer overflow */
  290. }
  291. return val;
  292. }
  293. typedef struct ParserState ParserState;
  294. struct ParserState {
  295. ptrlen currtext;
  296. Token tok;
  297. ptrlen toktext;
  298. char *err;
  299. ptrlen errloc;
  300. };
  301. static void error(ParserState *ps, char *errtext, ptrlen errloc)
  302. {
  303. if (!ps->err) {
  304. ps->err = errtext;
  305. ps->errloc = errloc;
  306. } else {
  307. sfree(errtext);
  308. }
  309. }
  310. static void advance(ParserState *ps)
  311. {
  312. char *err = NULL;
  313. ps->tok = lex(&ps->currtext, &ps->toktext, &err);
  314. if (ps->tok == TOK_ERROR)
  315. error(ps, err, ps->toktext);
  316. }
  317. static ExprNode *parse_atom(ParserState *ps);
  318. static ExprNode *parse_expr(ParserState *ps);
  319. static bool atom_is_hostname_wc(ptrlen toktext)
  320. {
  321. return !ptrlen_contains(toktext, ":/");
  322. }
  323. static ExprNode *parse_atom(ParserState *ps)
  324. {
  325. if (ps->tok == TOK_LPAR) {
  326. ptrlen openpar = ps->toktext;
  327. advance(ps); /* eat the ( */
  328. ExprNode *subexpr = parse_expr(ps);
  329. if (!subexpr)
  330. return NULL;
  331. if (ps->tok != TOK_RPAR) {
  332. error(ps, dupstr("expected ')' after parenthesised subexpression"),
  333. subexpr->text);
  334. exprnode_free(subexpr);
  335. return NULL;
  336. }
  337. ptrlen closepar = ps->toktext;
  338. advance(ps); /* eat the ) */
  339. /* We can reuse the existing AST node, but we need to extend
  340. * its bounds within the input expression to include the
  341. * parentheses */
  342. subexpr->text = make_ptrlen_startend(
  343. openpar.ptr, ptrlen_end(closepar));
  344. return subexpr;
  345. }
  346. if (ps->tok == TOK_NOT) {
  347. ptrlen notloc = ps->toktext;
  348. advance(ps); /* eat the ! */
  349. ExprNode *subexpr = parse_atom(ps);
  350. if (!subexpr)
  351. return NULL;
  352. ExprNode *en = exprnode_new(
  353. OP_NOT, make_ptrlen_startend(
  354. notloc.ptr, ptrlen_end(subexpr->text)));
  355. en->subexpr = subexpr;
  356. return en;
  357. }
  358. if (ps->tok == TOK_ATOM) {
  359. if (atom_is_hostname_wc(ps->toktext)) {
  360. /* Hostname wildcard. */
  361. ExprNode *en = exprnode_new(OP_HOSTNAME_WC, ps->toktext);
  362. en->wc = mkstr(ps->toktext);
  363. advance(ps);
  364. return en;
  365. }
  366. ptrlen tail;
  367. if (ptrlen_startswith(ps->toktext, PTRLEN_LITERAL("port:"), &tail)) {
  368. /* Port number (single or range). */
  369. unsigned lo, hi;
  370. char *minus;
  371. static const char DIGITS[] = "0123456789\0";
  372. bool parse_ok = false;
  373. if (tail.len > 0 && ptrlen_contains_only(tail, DIGITS)) {
  374. lo = ptrlen_to_port_number(tail);
  375. if (lo >= 65536) {
  376. error(ps, dupstr("port number too large"), tail);
  377. return NULL;
  378. }
  379. hi = lo;
  380. parse_ok = true;
  381. } else if ((minus = memchr(tail.ptr, '-', tail.len)) != NULL) {
  382. ptrlen pl_lo = make_ptrlen_startend(tail.ptr, minus);
  383. ptrlen pl_hi = make_ptrlen_startend(minus+1, ptrlen_end(tail));
  384. if (pl_lo.len > 0 && ptrlen_contains_only(pl_lo, DIGITS) &&
  385. pl_hi.len > 0 && ptrlen_contains_only(pl_hi, DIGITS)) {
  386. lo = ptrlen_to_port_number(pl_lo);
  387. if (lo >= 65536) {
  388. error(ps, dupstr("port number too large"), pl_lo);
  389. return NULL;
  390. }
  391. hi = ptrlen_to_port_number(pl_hi);
  392. if (hi >= 65536) {
  393. error(ps, dupstr("port number too large"), pl_hi);
  394. return NULL;
  395. }
  396. if (hi < lo) {
  397. error(ps, dupstr("port number range is backwards"),
  398. make_ptrlen_startend(pl_lo.ptr,
  399. ptrlen_end(pl_hi)));
  400. return NULL;
  401. }
  402. parse_ok = true;
  403. }
  404. }
  405. if (!parse_ok) {
  406. error(ps, dupstr("unable to parse port number specification"),
  407. ps->toktext);
  408. return NULL;
  409. }
  410. ExprNode *en = exprnode_new(OP_PORT_RANGE, ps->toktext);
  411. en->lo = lo;
  412. en->hi = hi;
  413. advance(ps);
  414. return en;
  415. }
  416. }
  417. error(ps, dupstr("expected a predicate or a parenthesised subexpression"),
  418. ps->toktext);
  419. return NULL;
  420. }
  421. static ExprNode *parse_expr(ParserState *ps)
  422. {
  423. ExprNode *subexpr = parse_atom(ps);
  424. if (!subexpr)
  425. return NULL;
  426. if (ps->tok != TOK_AND && ps->tok != TOK_OR)
  427. return subexpr;
  428. Token operator = ps->tok;
  429. ExprNode *en = exprnode_new(ps->tok == TOK_AND ? OP_AND : OP_OR,
  430. subexpr->text);
  431. size_t subexprs_size = 0;
  432. sgrowarray(en->subexprs, subexprs_size, en->nsubexprs);
  433. en->subexprs[en->nsubexprs++] = subexpr;
  434. while (true) {
  435. advance(ps); /* eat the operator */
  436. subexpr = parse_atom(ps);
  437. if (!subexpr) {
  438. exprnode_free(en);
  439. return NULL;
  440. }
  441. sgrowarray(en->subexprs, subexprs_size, en->nsubexprs);
  442. en->subexprs[en->nsubexprs++] = subexpr;
  443. en->text = make_ptrlen_startend(
  444. en->text.ptr, ptrlen_end(subexpr->text));
  445. if (ps->tok != TOK_AND && ps->tok != TOK_OR)
  446. return en;
  447. if (ps->tok != operator) {
  448. error(ps, dupstr("expected parentheses to disambiguate && and || "
  449. "on either side of expression"), subexpr->text);
  450. exprnode_free(en);
  451. return NULL;
  452. }
  453. }
  454. }
  455. static ExprNode *parse(ptrlen expr, char **error_msg, ptrlen *error_loc)
  456. {
  457. ParserState ps[1];
  458. ps->currtext = expr;
  459. ps->err = NULL;
  460. advance(ps);
  461. ExprNode *en = parse_expr(ps);
  462. if (en && ps->tok != TOK_END) {
  463. error(ps, dupstr("unexpected text at end of expression"),
  464. make_ptrlen_startend(ps->toktext.ptr, ptrlen_end(expr)));
  465. exprnode_free(en);
  466. en = NULL;
  467. }
  468. if (!en) {
  469. if (error_msg)
  470. *error_msg = ps->err;
  471. else
  472. sfree(ps->err);
  473. if (error_loc)
  474. *error_loc = ps->errloc;
  475. return NULL;
  476. }
  477. return en;
  478. }
  479. static bool eval(ExprNode *en, const char *hostname, unsigned port)
  480. {
  481. switch (en->op) {
  482. case OP_AND:
  483. for (size_t i = 0; i < en->nsubexprs; i++)
  484. if (!eval(en->subexprs[i], hostname, port))
  485. return false;
  486. return true;
  487. case OP_OR:
  488. for (size_t i = 0; i < en->nsubexprs; i++)
  489. if (eval(en->subexprs[i], hostname, port))
  490. return true;
  491. return false;
  492. case OP_NOT:
  493. return !eval(en->subexpr, hostname, port);
  494. case OP_HOSTNAME_WC:
  495. return wc_match(en->wc, hostname);
  496. case OP_PORT_RANGE:
  497. return en->lo <= port && port <= en->hi;
  498. default:
  499. unreachable("unhandled node type in eval");
  500. }
  501. }
  502. bool cert_expr_match_str(const char *expression,
  503. const char *hostname, unsigned port)
  504. {
  505. ExprNode *en = parse(ptrlen_from_asciz(expression), NULL, NULL);
  506. if (!en)
  507. return false;
  508. bool matched = eval(en, hostname, port);
  509. exprnode_free(en);
  510. return matched;
  511. }
  512. bool cert_expr_valid(const char *expression,
  513. char **error_msg, ptrlen *error_loc)
  514. {
  515. ExprNode *en = parse(ptrlen_from_asciz(expression), error_msg, error_loc);
  516. if (en) {
  517. exprnode_free(en);
  518. return true;
  519. } else {
  520. return false;
  521. }
  522. }
  523. struct CertExprBuilder {
  524. char **wcs;
  525. size_t nwcs, wcsize;
  526. };
  527. CertExprBuilder *cert_expr_builder_new(void)
  528. {
  529. CertExprBuilder *eb = snew(CertExprBuilder);
  530. eb->wcs = NULL;
  531. eb->nwcs = eb->wcsize = 0;
  532. return eb;
  533. }
  534. void cert_expr_builder_free(CertExprBuilder *eb)
  535. {
  536. for (size_t i = 0; i < eb->nwcs; i++)
  537. sfree(eb->wcs[i]);
  538. sfree(eb->wcs);
  539. sfree(eb);
  540. }
  541. void cert_expr_builder_add(CertExprBuilder *eb, const char *wildcard)
  542. {
  543. /* Check this wildcard is lexically valid as an atom */
  544. ptrlen orig = ptrlen_from_asciz(wildcard), pl = orig;
  545. ptrlen toktext;
  546. char *err;
  547. Token tok = lex(&pl, &toktext, &err);
  548. if (!(tok == TOK_ATOM &&
  549. toktext.ptr == orig.ptr &&
  550. toktext.len == orig.len &&
  551. atom_is_hostname_wc(toktext))) {
  552. if (tok == TOK_ERROR)
  553. sfree(err);
  554. return;
  555. }
  556. sgrowarray(eb->wcs, eb->wcsize, eb->nwcs);
  557. eb->wcs[eb->nwcs++] = mkstr(orig);
  558. }
  559. char *cert_expr_expression(CertExprBuilder *eb)
  560. {
  561. strbuf *sb = strbuf_new();
  562. for (size_t i = 0; i < eb->nwcs; i++) {
  563. if (i)
  564. put_dataz(sb, " || ");
  565. put_dataz(sb, eb->wcs[i]);
  566. }
  567. return strbuf_to_str(sb);
  568. }
  569. #ifdef TEST
  570. void out_of_memory(void) { fprintf(stderr, "out of memory\n"); abort(); }
  571. static void exprnode_dump(BinarySink *bs, ExprNode *en, const char *origtext)
  572. {
  573. put_fmt(bs, "(%zu:%zu ",
  574. (size_t)((const char *)en->text.ptr - origtext),
  575. (size_t)((const char *)ptrlen_end(en->text) - origtext));
  576. switch (en->op) {
  577. case OP_AND:
  578. case OP_OR:
  579. put_dataz(bs, en->op == OP_AND ? "and" : "or");
  580. for (size_t i = 0; i < en->nsubexprs; i++) {
  581. put_byte(bs, ' ');
  582. exprnode_dump(bs, en->subexprs[i], origtext);
  583. }
  584. break;
  585. case OP_NOT:
  586. put_dataz(bs, "not ");
  587. exprnode_dump(bs, en->subexpr, origtext);
  588. break;
  589. case OP_HOSTNAME_WC:
  590. put_dataz(bs, "host-wc '");
  591. put_dataz(bs, en->wc);
  592. put_byte(bs, '\'');
  593. break;
  594. case OP_PORT_RANGE:
  595. put_fmt(bs, "port-range %u %u", en->lo, en->hi);
  596. break;
  597. default:
  598. unreachable("unhandled node type in exprnode_dump");
  599. }
  600. put_byte(bs, ')');
  601. }
  602. static const struct ParseTest {
  603. const char *file;
  604. int line;
  605. const char *expr, *output;
  606. } parsetests[] = {
  607. #define T(expr_, output_) { \
  608. .file=__FILE__, .line=__LINE__, .expr=expr_, .output=output_}
  609. T("*.example.com", "(0:13 host-wc '*.example.com')"),
  610. T("port:0", "(0:6 port-range 0 0)"),
  611. T("port:22", "(0:7 port-range 22 22)"),
  612. T("port:22-22", "(0:10 port-range 22 22)"),
  613. T("port:65535", "(0:10 port-range 65535 65535)"),
  614. T("port:0-1023", "(0:11 port-range 0 1023)"),
  615. T("&", "ERR:0:1:unrecognised boolean operator"),
  616. T("|", "ERR:0:1:unrecognised boolean operator"),
  617. T(";", "ERR:0:1:unexpected character in expression"),
  618. T("port:", "ERR:0:5:unable to parse port number specification"),
  619. T("port:abc", "ERR:0:8:unable to parse port number specification"),
  620. T("port:65536", "ERR:5:10:port number too large"),
  621. T("port:65536-65537", "ERR:5:10:port number too large"),
  622. T("port:0-65536", "ERR:7:12:port number too large"),
  623. T("port:23-22", "ERR:5:10:port number range is backwards"),
  624. T("a", "(0:1 host-wc 'a')"),
  625. T("(a)", "(0:3 host-wc 'a')"),
  626. T("((a))", "(0:5 host-wc 'a')"),
  627. T(" (\n(\ra\t)\f)\v", "(1:10 host-wc 'a')"),
  628. T("a&&b", "(0:4 and (0:1 host-wc 'a') (3:4 host-wc 'b'))"),
  629. T("a||b", "(0:4 or (0:1 host-wc 'a') (3:4 host-wc 'b'))"),
  630. T("a&&b&&c", "(0:7 and (0:1 host-wc 'a') (3:4 host-wc 'b') (6:7 host-wc 'c'))"),
  631. T("a||b||c", "(0:7 or (0:1 host-wc 'a') (3:4 host-wc 'b') (6:7 host-wc 'c'))"),
  632. T("a&&(b||c)", "(0:9 and (0:1 host-wc 'a') (3:9 or (4:5 host-wc 'b') (7:8 host-wc 'c')))"),
  633. T("a||(b&&c)", "(0:9 or (0:1 host-wc 'a') (3:9 and (4:5 host-wc 'b') (7:8 host-wc 'c')))"),
  634. T("(a&&b)||c", "(0:9 or (0:6 and (1:2 host-wc 'a') (4:5 host-wc 'b')) (8:9 host-wc 'c'))"),
  635. T("(a||b)&&c", "(0:9 and (0:6 or (1:2 host-wc 'a') (4:5 host-wc 'b')) (8:9 host-wc 'c'))"),
  636. T("!a&&b", "(0:5 and (0:2 not (1:2 host-wc 'a')) (4:5 host-wc 'b'))"),
  637. T("a&&!b&&c", "(0:8 and (0:1 host-wc 'a') (3:5 not (4:5 host-wc 'b')) (7:8 host-wc 'c'))"),
  638. T("!a||b", "(0:5 or (0:2 not (1:2 host-wc 'a')) (4:5 host-wc 'b'))"),
  639. T("a||!b||c", "(0:8 or (0:1 host-wc 'a') (3:5 not (4:5 host-wc 'b')) (7:8 host-wc 'c'))"),
  640. T("", "ERR:0:0:expected a predicate or a parenthesised subexpression"),
  641. T("a &&", "ERR:4:4:expected a predicate or a parenthesised subexpression"),
  642. T("a ||", "ERR:4:4:expected a predicate or a parenthesised subexpression"),
  643. T("a b c d", "ERR:2:7:unexpected text at end of expression"),
  644. T("(", "ERR:1:1:expected a predicate or a parenthesised subexpression"),
  645. T("(a", "ERR:1:2:expected ')' after parenthesised subexpression"),
  646. T("(a b", "ERR:1:2:expected ')' after parenthesised subexpression"),
  647. T("a&&b&&c||d||e", "ERR:6:7:expected parentheses to disambiguate && and || on either side of expression"),
  648. T("a||b||c&&d&&e", "ERR:6:7:expected parentheses to disambiguate && and || on either side of expression"),
  649. T("!", "ERR:1:1:expected a predicate or a parenthesised subexpression"),
  650. T("!a", "(0:2 not (1:2 host-wc 'a'))"),
  651. #undef T
  652. };
  653. static const struct EvalTest {
  654. const char *file;
  655. int line;
  656. const char *expr;
  657. const char *host;
  658. unsigned port;
  659. bool output;
  660. } evaltests[] = {
  661. #define T(expr_, host_, port_, output_) { \
  662. .file=__FILE__, .line=__LINE__, \
  663. .expr=expr_, .host=host_, .port=port_, .output=output_}
  664. T("*.example.com", "hostname.example.com", 22, true),
  665. T("*.example.com", "hostname.example.org", 22, false),
  666. T("*.example.com", "hostname.dept.example.com", 22, true),
  667. T("*.example.com && port:22", "hostname.example.com", 21, false),
  668. T("*.example.com && port:22", "hostname.example.com", 22, true),
  669. T("*.example.com && port:22", "hostname.example.com", 23, false),
  670. T("*.example.com && port:22-24", "hostname.example.com", 21, false),
  671. T("*.example.com && port:22-24", "hostname.example.com", 22, true),
  672. T("*.example.com && port:22-24", "hostname.example.com", 23, true),
  673. T("*.example.com && port:22-24", "hostname.example.com", 24, true),
  674. T("*.example.com && port:22-24", "hostname.example.com", 25, false),
  675. T("*a* && *b* && *c*", "", 22, false),
  676. T("*a* && *b* && *c*", "a", 22, false),
  677. T("*a* && *b* && *c*", "b", 22, false),
  678. T("*a* && *b* && *c*", "c", 22, false),
  679. T("*a* && *b* && *c*", "ab", 22, false),
  680. T("*a* && *b* && *c*", "ac", 22, false),
  681. T("*a* && *b* && *c*", "bc", 22, false),
  682. T("*a* && *b* && *c*", "abc", 22, true),
  683. T("*a* || *b* || *c*", "", 22, false),
  684. T("*a* || *b* || *c*", "a", 22, true),
  685. T("*a* || *b* || *c*", "b", 22, true),
  686. T("*a* || *b* || *c*", "c", 22, true),
  687. T("*a* || *b* || *c*", "ab", 22, true),
  688. T("*a* || *b* || *c*", "ac", 22, true),
  689. T("*a* || *b* || *c*", "bc", 22, true),
  690. T("*a* || *b* || *c*", "abc", 22, true),
  691. T("*a* && !*b* && *c*", "", 22, false),
  692. T("*a* && !*b* && *c*", "a", 22, false),
  693. T("*a* && !*b* && *c*", "b", 22, false),
  694. T("*a* && !*b* && *c*", "c", 22, false),
  695. T("*a* && !*b* && *c*", "ab", 22, false),
  696. T("*a* && !*b* && *c*", "ac", 22, true),
  697. T("*a* && !*b* && *c*", "bc", 22, false),
  698. T("*a* && !*b* && *c*", "abc", 22, false),
  699. T("*a* || !*b* || *c*", "", 22, true),
  700. T("*a* || !*b* || *c*", "a", 22, true),
  701. T("*a* || !*b* || *c*", "b", 22, false),
  702. T("*a* || !*b* || *c*", "c", 22, true),
  703. T("*a* || !*b* || *c*", "ab", 22, true),
  704. T("*a* || !*b* || *c*", "ac", 22, true),
  705. T("*a* || !*b* || *c*", "bc", 22, true),
  706. T("*a* || !*b* || *c*", "abc", 22, true),
  707. #undef T
  708. };
  709. int main(int argc, char **argv)
  710. {
  711. if (argc > 1) {
  712. /*
  713. * Parse an expression from the command line.
  714. */
  715. ptrlen expr = ptrlen_from_asciz(argv[1]);
  716. char *error_msg;
  717. ptrlen error_loc;
  718. ExprNode *en = parse(expr, &error_msg, &error_loc);
  719. if (!en) {
  720. fprintf(stderr, "ERR:%zu:%zu:%s\n",
  721. (size_t)((const char *)error_loc.ptr - argv[1]),
  722. (size_t)((const char *)ptrlen_end(error_loc) - argv[1]),
  723. error_msg);
  724. fprintf(stderr, "%.*s\n", PTRLEN_PRINTF(expr));
  725. for (const char *p = expr.ptr, *e = error_loc.ptr; p<e; p++)
  726. fputc(' ', stderr);
  727. for (size_t i = 0; i < error_loc.len || i < 1; i++)
  728. fputc('^', stderr);
  729. fputc('\n', stderr);
  730. sfree(error_msg);
  731. return 1;
  732. }
  733. if (argc > 2) {
  734. /*
  735. * Test-evaluate against a host/port pair given on the
  736. * command line.
  737. */
  738. const char *host = argv[2];
  739. unsigned port = (argc > 3 ? strtoul(argv[3], NULL, 0) : 22);
  740. bool result = eval(en, host, port);
  741. printf("%s\n", result ? "accept" : "reject");
  742. } else {
  743. /*
  744. * Just dump the result of parsing the expression.
  745. */
  746. stdio_sink ss[1];
  747. stdio_sink_init(ss, stdout);
  748. exprnode_dump(BinarySink_UPCAST(ss), en, expr.ptr);
  749. put_byte(ss, '\n');
  750. }
  751. exprnode_free(en);
  752. return 0;
  753. } else {
  754. /*
  755. * Run our automated tests.
  756. */
  757. size_t pass = 0, fail = 0;
  758. for (size_t i = 0; i < lenof(parsetests); i++) {
  759. const struct ParseTest *test = &parsetests[i];
  760. ptrlen expr = ptrlen_from_asciz(test->expr);
  761. char *error_msg;
  762. ptrlen error_loc;
  763. ExprNode *en = parse(expr, &error_msg, &error_loc);
  764. strbuf *output = strbuf_new();
  765. if (!en) {
  766. put_fmt(output, "ERR:%zu:%zu:%s",
  767. (size_t)((const char *)error_loc.ptr - test->expr),
  768. (size_t)((const char *)ptrlen_end(error_loc) -
  769. test->expr),
  770. error_msg);
  771. sfree(error_msg);
  772. } else {
  773. exprnode_dump(BinarySink_UPCAST(output), en, expr.ptr);
  774. exprnode_free(en);
  775. }
  776. if (ptrlen_eq_ptrlen(ptrlen_from_strbuf(output),
  777. ptrlen_from_asciz(test->output))) {
  778. pass++;
  779. } else {
  780. fprintf(stderr, "FAIL: parsetests[%zu] @ %s:%d:\n"
  781. " expression: %s\n"
  782. " expected: %s\n"
  783. " actual: %s\n",
  784. i, test->file, test->line, test->expr,
  785. test->output, output->s);
  786. fail++;
  787. }
  788. strbuf_free(output);
  789. }
  790. for (size_t i = 0; i < lenof(evaltests); i++) {
  791. const struct EvalTest *test = &evaltests[i];
  792. ptrlen expr = ptrlen_from_asciz(test->expr);
  793. char *error_msg;
  794. ptrlen error_loc;
  795. ExprNode *en = parse(expr, &error_msg, &error_loc);
  796. if (!en) {
  797. fprintf(stderr, "FAIL: evaltests[%zu] @ %s:%d:\n"
  798. " expression: %s\n"
  799. " parse error: %zu:%zu:%s\n",
  800. i, test->file, test->line, test->expr,
  801. (size_t)((const char *)error_loc.ptr - test->expr),
  802. (size_t)((const char *)ptrlen_end(error_loc) -
  803. test->expr),
  804. error_msg);
  805. sfree(error_msg);
  806. } else {
  807. bool output = eval(en, test->host, test->port);
  808. if (output == test->output) {
  809. pass++;
  810. } else {
  811. fprintf(stderr, "FAIL: evaltests[%zu] @ %s:%d:\n"
  812. " expression: %s\n"
  813. " host: %s\n"
  814. " port: %u\n"
  815. " expected: %s\n"
  816. " actual: %s\n",
  817. i, test->file, test->line, test->expr,
  818. test->host, test->port,
  819. test->output ? "accept" : "reject",
  820. output ? "accept" : "reject");
  821. fail++;
  822. }
  823. exprnode_free(en);
  824. }
  825. }
  826. fprintf(stderr, "pass %zu fail %zu total %zu\n",
  827. pass, fail, pass+fail);
  828. return fail != 0;
  829. }
  830. }
  831. #endif // TEST