parsecommon.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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. while (*cp) {
  152. if (j == MAX_ARGS)
  153. return -1;
  154. args[j++] = cp;
  155. cp = (char*)find_whitespace(cp);
  156. if (!cp || !*cp)
  157. break; /* End of the line. */
  158. *cp++ = '\0';
  159. cp = (char*)eat_whitespace(cp);
  160. }
  161. tok->n_args = j;
  162. tok->args = memarea_memdup(area, args, j*sizeof(char*));
  163. return j;
  164. #undef MAX_ARGS
  165. }
  166. /** Helper: make sure that the token <b>tok</b> with keyword <b>kwd</b> obeys
  167. * the object syntax of <b>o_syn</b>. Allocate all storage in <b>area</b>.
  168. * Return <b>tok</b> on success, or a new ERR_ token if the token didn't
  169. * conform to the syntax we wanted.
  170. **/
  171. static inline directory_token_t *
  172. token_check_object(memarea_t *area, const char *kwd,
  173. directory_token_t *tok, obj_syntax o_syn)
  174. {
  175. char ebuf[128];
  176. switch (o_syn) {
  177. case NO_OBJ:
  178. /* No object is allowed for this token. */
  179. if (tok->object_body) {
  180. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected object for %s", kwd);
  181. RET_ERR(ebuf);
  182. }
  183. if (tok->key) {
  184. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected public key for %s", kwd);
  185. RET_ERR(ebuf);
  186. }
  187. break;
  188. case NEED_OBJ:
  189. /* There must be a (non-key) object. */
  190. if (!tok->object_body) {
  191. tor_snprintf(ebuf, sizeof(ebuf), "Missing object for %s", kwd);
  192. RET_ERR(ebuf);
  193. }
  194. break;
  195. case NEED_KEY_1024: /* There must be a 1024-bit public key. */
  196. case NEED_SKEY_1024: /* There must be a 1024-bit private key. */
  197. if (tok->key && crypto_pk_num_bits(tok->key) != PK_BYTES*8) {
  198. tor_snprintf(ebuf, sizeof(ebuf), "Wrong size on key for %s: %d bits",
  199. kwd, crypto_pk_num_bits(tok->key));
  200. RET_ERR(ebuf);
  201. }
  202. /* fall through */
  203. case NEED_KEY: /* There must be some kind of key. */
  204. if (!tok->key) {
  205. tor_snprintf(ebuf, sizeof(ebuf), "Missing public key for %s", kwd);
  206. RET_ERR(ebuf);
  207. }
  208. if (o_syn != NEED_SKEY_1024) {
  209. if (crypto_pk_key_is_private(tok->key)) {
  210. tor_snprintf(ebuf, sizeof(ebuf),
  211. "Private key given for %s, which wants a public key", kwd);
  212. RET_ERR(ebuf);
  213. }
  214. } else { /* o_syn == NEED_SKEY_1024 */
  215. if (!crypto_pk_key_is_private(tok->key)) {
  216. tor_snprintf(ebuf, sizeof(ebuf),
  217. "Public key given for %s, which wants a private key", kwd);
  218. RET_ERR(ebuf);
  219. }
  220. }
  221. break;
  222. case OBJ_OK:
  223. /* Anything goes with this token. */
  224. break;
  225. }
  226. done_tokenizing:
  227. return tok;
  228. }
  229. /** Helper function: read the next token from *s, advance *s to the end of the
  230. * token, and return the parsed token. Parse *<b>s</b> according to the list
  231. * of tokens in <b>table</b>.
  232. */
  233. directory_token_t *
  234. get_next_token(memarea_t *area,
  235. const char **s, const char *eos, token_rule_t *table)
  236. {
  237. /** Reject any object at least this big; it is probably an overflow, an
  238. * attack, a bug, or some other nonsense. */
  239. #define MAX_UNPARSED_OBJECT_SIZE (128*1024)
  240. /** Reject any line at least this big; it is probably an overflow, an
  241. * attack, a bug, or some other nonsense. */
  242. #define MAX_LINE_LENGTH (128*1024)
  243. const char *next, *eol, *obstart;
  244. size_t obname_len;
  245. int i;
  246. directory_token_t *tok;
  247. obj_syntax o_syn = NO_OBJ;
  248. char ebuf[128];
  249. const char *kwd = "";
  250. tor_assert(area);
  251. tok = ALLOC_ZERO(sizeof(directory_token_t));
  252. tok->tp = ERR_;
  253. /* Set *s to first token, eol to end-of-line, next to after first token */
  254. *s = eat_whitespace_eos(*s, eos); /* eat multi-line whitespace */
  255. tor_assert(eos >= *s);
  256. eol = memchr(*s, '\n', eos-*s);
  257. if (!eol)
  258. eol = eos;
  259. if (eol - *s > MAX_LINE_LENGTH) {
  260. RET_ERR("Line far too long");
  261. }
  262. next = find_whitespace_eos(*s, eol);
  263. if (!strcmp_len(*s, "opt", next-*s)) {
  264. /* Skip past an "opt" at the start of the line. */
  265. *s = eat_whitespace_eos_no_nl(next, eol);
  266. next = find_whitespace_eos(*s, eol);
  267. } else if (*s == eos) { /* If no "opt", and end-of-line, line is invalid */
  268. RET_ERR("Unexpected EOF");
  269. }
  270. /* Search the table for the appropriate entry. (I tried a binary search
  271. * instead, but it wasn't any faster.) */
  272. for (i = 0; table[i].t ; ++i) {
  273. if (!strcmp_len(*s, table[i].t, next-*s)) {
  274. /* We've found the keyword. */
  275. kwd = table[i].t;
  276. tok->tp = table[i].v;
  277. o_syn = table[i].os;
  278. *s = eat_whitespace_eos_no_nl(next, eol);
  279. /* We go ahead whether there are arguments or not, so that tok->args is
  280. * always set if we want arguments. */
  281. if (table[i].concat_args) {
  282. /* The keyword takes the line as a single argument */
  283. tok->args = ALLOC(sizeof(char*));
  284. tok->args[0] = STRNDUP(*s,eol-*s); /* Grab everything on line */
  285. tok->n_args = 1;
  286. } else {
  287. /* This keyword takes multiple arguments. */
  288. if (get_token_arguments(area, tok, *s, eol)<0) {
  289. tor_snprintf(ebuf, sizeof(ebuf),"Far too many arguments to %s", kwd);
  290. RET_ERR(ebuf);
  291. }
  292. *s = eol;
  293. }
  294. if (tok->n_args < table[i].min_args) {
  295. tor_snprintf(ebuf, sizeof(ebuf), "Too few arguments to %s", kwd);
  296. RET_ERR(ebuf);
  297. } else if (tok->n_args > table[i].max_args) {
  298. tor_snprintf(ebuf, sizeof(ebuf), "Too many arguments to %s", kwd);
  299. RET_ERR(ebuf);
  300. }
  301. break;
  302. }
  303. }
  304. if (tok->tp == ERR_) {
  305. /* No keyword matched; call it an "K_opt" or "A_unrecognized" */
  306. if (*s < eol && **s == '@')
  307. tok->tp = A_UNKNOWN_;
  308. else
  309. tok->tp = K_OPT;
  310. tok->args = ALLOC(sizeof(char*));
  311. tok->args[0] = STRNDUP(*s, eol-*s);
  312. tok->n_args = 1;
  313. o_syn = OBJ_OK;
  314. }
  315. /* Check whether there's an object present */
  316. *s = eat_whitespace_eos(eol, eos); /* Scan from end of first line */
  317. tor_assert(eos >= *s);
  318. eol = memchr(*s, '\n', eos-*s);
  319. if (!eol || eol-*s<11 || strcmpstart(*s, "-----BEGIN ")) /* No object. */
  320. goto check_object;
  321. obstart = *s; /* Set obstart to start of object spec */
  322. if (*s+16 >= eol || memchr(*s+11,'\0',eol-*s-16) || /* no short lines, */
  323. strcmp_len(eol-5, "-----", 5) || /* nuls or invalid endings */
  324. (eol-*s) > MAX_UNPARSED_OBJECT_SIZE) { /* name too long */
  325. RET_ERR("Malformed object: bad begin line");
  326. }
  327. tok->object_type = STRNDUP(*s+11, eol-*s-16);
  328. obname_len = eol-*s-16; /* store objname length here to avoid a strlen() */
  329. *s = eol+1; /* Set *s to possible start of object data (could be eos) */
  330. /* Go to the end of the object */
  331. next = tor_memstr(*s, eos-*s, "-----END ");
  332. if (!next) {
  333. RET_ERR("Malformed object: missing object end line");
  334. }
  335. tor_assert(eos >= next);
  336. eol = memchr(next, '\n', eos-next);
  337. if (!eol) /* end-of-line marker, or eos if there's no '\n' */
  338. eol = eos;
  339. /* Validate the ending tag, which should be 9 + NAME + 5 + eol */
  340. if ((size_t)(eol-next) != 9+obname_len+5 ||
  341. strcmp_len(next+9, tok->object_type, obname_len) ||
  342. strcmp_len(eol-5, "-----", 5)) {
  343. tor_snprintf(ebuf, sizeof(ebuf), "Malformed object: mismatched end tag %s",
  344. tok->object_type);
  345. ebuf[sizeof(ebuf)-1] = '\0';
  346. RET_ERR(ebuf);
  347. }
  348. if (next - *s > MAX_UNPARSED_OBJECT_SIZE)
  349. RET_ERR("Couldn't parse object: missing footer or object much too big.");
  350. if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) { /* If it's a public key */
  351. tok->key = crypto_pk_new();
  352. if (crypto_pk_read_public_key_from_string(tok->key, obstart, eol-obstart))
  353. RET_ERR("Couldn't parse public key.");
  354. } else if (!strcmp(tok->object_type, "RSA PRIVATE KEY")) { /* private key */
  355. tok->key = crypto_pk_new();
  356. if (crypto_pk_read_private_key_from_string(tok->key, obstart, eol-obstart))
  357. RET_ERR("Couldn't parse private key.");
  358. } else { /* If it's something else, try to base64-decode it */
  359. int r;
  360. tok->object_body = ALLOC(next-*s); /* really, this is too much RAM. */
  361. r = base64_decode(tok->object_body, next-*s, *s, next-*s);
  362. if (r<0)
  363. RET_ERR("Malformed object: bad base64-encoded data");
  364. tok->object_size = r;
  365. }
  366. *s = eol;
  367. check_object:
  368. tok = token_check_object(area, kwd, tok, o_syn);
  369. done_tokenizing:
  370. return tok;
  371. #undef RET_ERR
  372. #undef ALLOC
  373. #undef ALLOC_ZERO
  374. #undef STRDUP
  375. #undef STRNDUP
  376. }
  377. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; fail
  378. * with an assert if no such keyword is found.
  379. */
  380. directory_token_t *
  381. find_by_keyword_(smartlist_t *s, directory_keyword keyword,
  382. const char *keyword_as_string)
  383. {
  384. directory_token_t *tok = find_opt_by_keyword(s, keyword);
  385. if (PREDICT_UNLIKELY(!tok)) {
  386. log_err(LD_BUG, "Missing %s [%d] in directory object that should have "
  387. "been validated. Internal error.", keyword_as_string, (int)keyword);
  388. tor_assert(tok);
  389. }
  390. return tok;
  391. }
  392. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
  393. * NULL if no such keyword is found.
  394. */
  395. directory_token_t *
  396. find_opt_by_keyword(smartlist_t *s, directory_keyword keyword)
  397. {
  398. SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
  399. return NULL;
  400. }
  401. /** If there are any directory_token_t entries in <b>s</b> whose keyword is
  402. * <b>k</b>, return a newly allocated smartlist_t containing all such entries,
  403. * in the same order in which they occur in <b>s</b>. Otherwise return
  404. * NULL. */
  405. smartlist_t *
  406. find_all_by_keyword(const smartlist_t *s, directory_keyword k)
  407. {
  408. smartlist_t *out = NULL;
  409. SMARTLIST_FOREACH(s, directory_token_t *, t,
  410. if (t->tp == k) {
  411. if (!out)
  412. out = smartlist_new();
  413. smartlist_add(out, t);
  414. });
  415. return out;
  416. }