parsecommon.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. /* Copyright (c) 2016-2018, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file parsecommon.c
  5. * \brief Common code to parse and validate various type of descriptors.
  6. **/
  7. #include "or/parsecommon.h"
  8. #include "lib/log/torlog.h"
  9. #include "lib/log/util_bug.h"
  10. #include "lib/encoding/binascii.h"
  11. #include "lib/container/smartlist.h"
  12. #include "lib/string/util_string.h"
  13. #include "lib/string/printf.h"
  14. #include <string.h>
  15. #define MIN_ANNOTATION A_PURPOSE
  16. #define MAX_ANNOTATION A_UNKNOWN_
  17. #define ALLOC_ZERO(sz) memarea_alloc_zero(area,sz)
  18. #define ALLOC(sz) memarea_alloc(area,sz)
  19. #define STRDUP(str) memarea_strdup(area,str)
  20. #define STRNDUP(str,n) memarea_strndup(area,(str),(n))
  21. #define RET_ERR(msg) \
  22. STMT_BEGIN \
  23. if (tok) token_clear(tok); \
  24. tok = ALLOC_ZERO(sizeof(directory_token_t)); \
  25. tok->tp = ERR_; \
  26. tok->error = STRDUP(msg); \
  27. goto done_tokenizing; \
  28. STMT_END
  29. /** Free all resources allocated for <b>tok</b> */
  30. void
  31. token_clear(directory_token_t *tok)
  32. {
  33. if (tok->key)
  34. crypto_pk_free(tok->key);
  35. }
  36. /** Read all tokens from a string between <b>start</b> and <b>end</b>, and add
  37. * them to <b>out</b>. Parse according to the token rules in <b>table</b>.
  38. * Caller must free tokens in <b>out</b>. If <b>end</b> is NULL, use the
  39. * entire string.
  40. */
  41. int
  42. tokenize_string(memarea_t *area,
  43. const char *start, const char *end, smartlist_t *out,
  44. token_rule_t *table, int flags)
  45. {
  46. const char **s;
  47. directory_token_t *tok = NULL;
  48. int counts[NIL_];
  49. int i;
  50. int first_nonannotation;
  51. int prev_len = smartlist_len(out);
  52. tor_assert(area);
  53. s = &start;
  54. if (!end) {
  55. end = start+strlen(start);
  56. } else {
  57. /* it's only meaningful to check for nuls if we got an end-of-string ptr */
  58. if (memchr(start, '\0', end-start)) {
  59. log_warn(LD_DIR, "parse error: internal NUL character.");
  60. return -1;
  61. }
  62. }
  63. for (i = 0; i < NIL_; ++i)
  64. counts[i] = 0;
  65. SMARTLIST_FOREACH(out, const directory_token_t *, t, ++counts[t->tp]);
  66. while (*s < end && (!tok || tok->tp != EOF_)) {
  67. tok = get_next_token(area, s, end, table);
  68. if (tok->tp == ERR_) {
  69. log_warn(LD_DIR, "parse error: %s", tok->error);
  70. token_clear(tok);
  71. return -1;
  72. }
  73. ++counts[tok->tp];
  74. smartlist_add(out, tok);
  75. *s = eat_whitespace_eos(*s, end);
  76. }
  77. if (flags & TS_NOCHECK)
  78. return 0;
  79. if ((flags & TS_ANNOTATIONS_OK)) {
  80. first_nonannotation = -1;
  81. for (i = 0; i < smartlist_len(out); ++i) {
  82. tok = smartlist_get(out, i);
  83. if (tok->tp < MIN_ANNOTATION || tok->tp > MAX_ANNOTATION) {
  84. first_nonannotation = i;
  85. break;
  86. }
  87. }
  88. if (first_nonannotation < 0) {
  89. log_warn(LD_DIR, "parse error: item contains only annotations");
  90. return -1;
  91. }
  92. for (i=first_nonannotation; i < smartlist_len(out); ++i) {
  93. tok = smartlist_get(out, i);
  94. if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
  95. log_warn(LD_DIR, "parse error: Annotations mixed with keywords");
  96. return -1;
  97. }
  98. }
  99. if ((flags & TS_NO_NEW_ANNOTATIONS)) {
  100. if (first_nonannotation != prev_len) {
  101. log_warn(LD_DIR, "parse error: Unexpected annotations.");
  102. return -1;
  103. }
  104. }
  105. } else {
  106. for (i=0; i < smartlist_len(out); ++i) {
  107. tok = smartlist_get(out, i);
  108. if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
  109. log_warn(LD_DIR, "parse error: no annotations allowed.");
  110. return -1;
  111. }
  112. }
  113. first_nonannotation = 0;
  114. }
  115. for (i = 0; table[i].t; ++i) {
  116. if (counts[table[i].v] < table[i].min_cnt) {
  117. log_warn(LD_DIR, "Parse error: missing %s element.", table[i].t);
  118. return -1;
  119. }
  120. if (counts[table[i].v] > table[i].max_cnt) {
  121. log_warn(LD_DIR, "Parse error: too many %s elements.", table[i].t);
  122. return -1;
  123. }
  124. if (table[i].pos & AT_START) {
  125. if (smartlist_len(out) < 1 ||
  126. (tok = smartlist_get(out, first_nonannotation))->tp != table[i].v) {
  127. log_warn(LD_DIR, "Parse error: first item is not %s.", table[i].t);
  128. return -1;
  129. }
  130. }
  131. if (table[i].pos & AT_END) {
  132. if (smartlist_len(out) < 1 ||
  133. (tok = smartlist_get(out, smartlist_len(out)-1))->tp != table[i].v) {
  134. log_warn(LD_DIR, "Parse error: last item is not %s.", table[i].t);
  135. return -1;
  136. }
  137. }
  138. }
  139. return 0;
  140. }
  141. /** Helper: parse space-separated arguments from the string <b>s</b> ending at
  142. * <b>eol</b>, and store them in the args field of <b>tok</b>. Store the
  143. * number of parsed elements into the n_args field of <b>tok</b>. Allocate
  144. * all storage in <b>area</b>. Return the number of arguments parsed, or
  145. * return -1 if there was an insanely high number of arguments. */
  146. static inline int
  147. get_token_arguments(memarea_t *area, directory_token_t *tok,
  148. const char *s, const char *eol)
  149. {
  150. /** Largest number of arguments we'll accept to any token, ever. */
  151. #define MAX_ARGS 512
  152. char *mem = memarea_strndup(area, s, eol-s);
  153. char *cp = mem;
  154. int j = 0;
  155. char *args[MAX_ARGS];
  156. memset(args, 0, sizeof(args));
  157. while (*cp) {
  158. if (j == MAX_ARGS)
  159. return -1;
  160. args[j++] = cp;
  161. cp = (char*)find_whitespace(cp);
  162. if (!cp || !*cp)
  163. break; /* End of the line. */
  164. *cp++ = '\0';
  165. cp = (char*)eat_whitespace(cp);
  166. }
  167. tok->n_args = j;
  168. tok->args = memarea_memdup(area, args, j*sizeof(char*));
  169. return j;
  170. #undef MAX_ARGS
  171. }
  172. /** Helper: make sure that the token <b>tok</b> with keyword <b>kwd</b> obeys
  173. * the object syntax of <b>o_syn</b>. Allocate all storage in <b>area</b>.
  174. * Return <b>tok</b> on success, or a new ERR_ token if the token didn't
  175. * conform to the syntax we wanted.
  176. **/
  177. static inline directory_token_t *
  178. token_check_object(memarea_t *area, const char *kwd,
  179. directory_token_t *tok, obj_syntax o_syn)
  180. {
  181. char ebuf[128];
  182. switch (o_syn) {
  183. case NO_OBJ:
  184. /* No object is allowed for this token. */
  185. if (tok->object_body) {
  186. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected object for %s", kwd);
  187. RET_ERR(ebuf);
  188. }
  189. if (tok->key) {
  190. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected public key for %s", kwd);
  191. RET_ERR(ebuf);
  192. }
  193. break;
  194. case NEED_OBJ:
  195. /* There must be a (non-key) object. */
  196. if (!tok->object_body) {
  197. tor_snprintf(ebuf, sizeof(ebuf), "Missing object for %s", kwd);
  198. RET_ERR(ebuf);
  199. }
  200. break;
  201. case NEED_KEY_1024: /* There must be a 1024-bit public key. */
  202. case NEED_SKEY_1024: /* There must be a 1024-bit private key. */
  203. if (tok->key && crypto_pk_num_bits(tok->key) != PK_BYTES*8) {
  204. tor_snprintf(ebuf, sizeof(ebuf), "Wrong size on key for %s: %d bits",
  205. kwd, crypto_pk_num_bits(tok->key));
  206. RET_ERR(ebuf);
  207. }
  208. /* fall through */
  209. case NEED_KEY: /* There must be some kind of key. */
  210. if (!tok->key) {
  211. tor_snprintf(ebuf, sizeof(ebuf), "Missing public key for %s", kwd);
  212. RET_ERR(ebuf);
  213. }
  214. if (o_syn != NEED_SKEY_1024) {
  215. if (crypto_pk_key_is_private(tok->key)) {
  216. tor_snprintf(ebuf, sizeof(ebuf),
  217. "Private key given for %s, which wants a public key", kwd);
  218. RET_ERR(ebuf);
  219. }
  220. } else { /* o_syn == NEED_SKEY_1024 */
  221. if (!crypto_pk_key_is_private(tok->key)) {
  222. tor_snprintf(ebuf, sizeof(ebuf),
  223. "Public key given for %s, which wants a private key", kwd);
  224. RET_ERR(ebuf);
  225. }
  226. }
  227. break;
  228. case OBJ_OK:
  229. /* Anything goes with this token. */
  230. break;
  231. }
  232. done_tokenizing:
  233. return tok;
  234. }
  235. /** Helper function: read the next token from *s, advance *s to the end of the
  236. * token, and return the parsed token. Parse *<b>s</b> according to the list
  237. * of tokens in <b>table</b>.
  238. */
  239. directory_token_t *
  240. get_next_token(memarea_t *area,
  241. const char **s, const char *eos, token_rule_t *table)
  242. {
  243. /** Reject any object at least this big; it is probably an overflow, an
  244. * attack, a bug, or some other nonsense. */
  245. #define MAX_UNPARSED_OBJECT_SIZE (128*1024)
  246. /** Reject any line at least this big; it is probably an overflow, an
  247. * attack, a bug, or some other nonsense. */
  248. #define MAX_LINE_LENGTH (128*1024)
  249. const char *next, *eol, *obstart;
  250. size_t obname_len;
  251. int i;
  252. directory_token_t *tok;
  253. obj_syntax o_syn = NO_OBJ;
  254. char ebuf[128];
  255. const char *kwd = "";
  256. tor_assert(area);
  257. tok = ALLOC_ZERO(sizeof(directory_token_t));
  258. tok->tp = ERR_;
  259. /* Set *s to first token, eol to end-of-line, next to after first token */
  260. *s = eat_whitespace_eos(*s, eos); /* eat multi-line whitespace */
  261. tor_assert(eos >= *s);
  262. eol = memchr(*s, '\n', eos-*s);
  263. if (!eol)
  264. eol = eos;
  265. if (eol - *s > MAX_LINE_LENGTH) {
  266. RET_ERR("Line far too long");
  267. }
  268. next = find_whitespace_eos(*s, eol);
  269. if (!strcmp_len(*s, "opt", next-*s)) {
  270. /* Skip past an "opt" at the start of the line. */
  271. *s = eat_whitespace_eos_no_nl(next, eol);
  272. next = find_whitespace_eos(*s, eol);
  273. } else if (*s == eos) { /* If no "opt", and end-of-line, line is invalid */
  274. RET_ERR("Unexpected EOF");
  275. }
  276. /* Search the table for the appropriate entry. (I tried a binary search
  277. * instead, but it wasn't any faster.) */
  278. for (i = 0; table[i].t ; ++i) {
  279. if (!strcmp_len(*s, table[i].t, next-*s)) {
  280. /* We've found the keyword. */
  281. kwd = table[i].t;
  282. tok->tp = table[i].v;
  283. o_syn = table[i].os;
  284. *s = eat_whitespace_eos_no_nl(next, eol);
  285. /* We go ahead whether there are arguments or not, so that tok->args is
  286. * always set if we want arguments. */
  287. if (table[i].concat_args) {
  288. /* The keyword takes the line as a single argument */
  289. tok->args = ALLOC(sizeof(char*));
  290. tok->args[0] = STRNDUP(*s,eol-*s); /* Grab everything on line */
  291. tok->n_args = 1;
  292. } else {
  293. /* This keyword takes multiple arguments. */
  294. if (get_token_arguments(area, tok, *s, eol)<0) {
  295. tor_snprintf(ebuf, sizeof(ebuf),"Far too many arguments to %s", kwd);
  296. RET_ERR(ebuf);
  297. }
  298. *s = eol;
  299. }
  300. if (tok->n_args < table[i].min_args) {
  301. tor_snprintf(ebuf, sizeof(ebuf), "Too few arguments to %s", kwd);
  302. RET_ERR(ebuf);
  303. } else if (tok->n_args > table[i].max_args) {
  304. tor_snprintf(ebuf, sizeof(ebuf), "Too many arguments to %s", kwd);
  305. RET_ERR(ebuf);
  306. }
  307. break;
  308. }
  309. }
  310. if (tok->tp == ERR_) {
  311. /* No keyword matched; call it an "K_opt" or "A_unrecognized" */
  312. if (*s < eol && **s == '@')
  313. tok->tp = A_UNKNOWN_;
  314. else
  315. tok->tp = K_OPT;
  316. tok->args = ALLOC(sizeof(char*));
  317. tok->args[0] = STRNDUP(*s, eol-*s);
  318. tok->n_args = 1;
  319. o_syn = OBJ_OK;
  320. }
  321. /* Check whether there's an object present */
  322. *s = eat_whitespace_eos(eol, eos); /* Scan from end of first line */
  323. tor_assert(eos >= *s);
  324. eol = memchr(*s, '\n', eos-*s);
  325. if (!eol || eol-*s<11 || strcmpstart(*s, "-----BEGIN ")) /* No object. */
  326. goto check_object;
  327. obstart = *s; /* Set obstart to start of object spec */
  328. if (*s+16 >= eol || memchr(*s+11,'\0',eol-*s-16) || /* no short lines, */
  329. strcmp_len(eol-5, "-----", 5) || /* nuls or invalid endings */
  330. (eol-*s) > MAX_UNPARSED_OBJECT_SIZE) { /* name too long */
  331. RET_ERR("Malformed object: bad begin line");
  332. }
  333. tok->object_type = STRNDUP(*s+11, eol-*s-16);
  334. obname_len = eol-*s-16; /* store objname length here to avoid a strlen() */
  335. *s = eol+1; /* Set *s to possible start of object data (could be eos) */
  336. /* Go to the end of the object */
  337. next = tor_memstr(*s, eos-*s, "-----END ");
  338. if (!next) {
  339. RET_ERR("Malformed object: missing object end line");
  340. }
  341. tor_assert(eos >= next);
  342. eol = memchr(next, '\n', eos-next);
  343. if (!eol) /* end-of-line marker, or eos if there's no '\n' */
  344. eol = eos;
  345. /* Validate the ending tag, which should be 9 + NAME + 5 + eol */
  346. if ((size_t)(eol-next) != 9+obname_len+5 ||
  347. strcmp_len(next+9, tok->object_type, obname_len) ||
  348. strcmp_len(eol-5, "-----", 5)) {
  349. tor_snprintf(ebuf, sizeof(ebuf), "Malformed object: mismatched end tag %s",
  350. tok->object_type);
  351. ebuf[sizeof(ebuf)-1] = '\0';
  352. RET_ERR(ebuf);
  353. }
  354. if (next - *s > MAX_UNPARSED_OBJECT_SIZE)
  355. RET_ERR("Couldn't parse object: missing footer or object much too big.");
  356. if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) { /* If it's a public key */
  357. tok->key = crypto_pk_new();
  358. if (crypto_pk_read_public_key_from_string(tok->key, obstart, eol-obstart))
  359. RET_ERR("Couldn't parse public key.");
  360. } else if (!strcmp(tok->object_type, "RSA PRIVATE KEY")) { /* private key */
  361. tok->key = crypto_pk_new();
  362. if (crypto_pk_read_private_key_from_string(tok->key, obstart, eol-obstart))
  363. RET_ERR("Couldn't parse private key.");
  364. } else { /* If it's something else, try to base64-decode it */
  365. int r;
  366. tok->object_body = ALLOC(next-*s); /* really, this is too much RAM. */
  367. r = base64_decode(tok->object_body, next-*s, *s, next-*s);
  368. if (r<0)
  369. RET_ERR("Malformed object: bad base64-encoded data");
  370. tok->object_size = r;
  371. }
  372. *s = eol;
  373. check_object:
  374. tok = token_check_object(area, kwd, tok, o_syn);
  375. done_tokenizing:
  376. return tok;
  377. #undef RET_ERR
  378. #undef ALLOC
  379. #undef ALLOC_ZERO
  380. #undef STRDUP
  381. #undef STRNDUP
  382. }
  383. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; fail
  384. * with an assert if no such keyword is found.
  385. */
  386. directory_token_t *
  387. find_by_keyword_(smartlist_t *s, directory_keyword keyword,
  388. const char *keyword_as_string)
  389. {
  390. directory_token_t *tok = find_opt_by_keyword(s, keyword);
  391. if (PREDICT_UNLIKELY(!tok)) {
  392. log_err(LD_BUG, "Missing %s [%d] in directory object that should have "
  393. "been validated. Internal error.", keyword_as_string, (int)keyword);
  394. tor_assert(tok);
  395. }
  396. return tok;
  397. }
  398. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
  399. * NULL if no such keyword is found.
  400. */
  401. directory_token_t *
  402. find_opt_by_keyword(const smartlist_t *s, directory_keyword keyword)
  403. {
  404. SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
  405. return NULL;
  406. }
  407. /** If there are any directory_token_t entries in <b>s</b> whose keyword is
  408. * <b>k</b>, return a newly allocated smartlist_t containing all such entries,
  409. * in the same order in which they occur in <b>s</b>. Otherwise return
  410. * NULL. */
  411. smartlist_t *
  412. find_all_by_keyword(const smartlist_t *s, directory_keyword k)
  413. {
  414. smartlist_t *out = NULL;
  415. SMARTLIST_FOREACH(s, directory_token_t *, t,
  416. if (t->tp == k) {
  417. if (!out)
  418. out = smartlist_new();
  419. smartlist_add(out, t);
  420. });
  421. return out;
  422. }