parsecommon.c 15 KB

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