parsecommon.c 15 KB

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