routerparse.c 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char routerparse_c_id[] = "$Id$";
  7. /**
  8. * \file routerparse.c
  9. *
  10. * \brief Code to parse and validate router descriptors and directories.
  11. **/
  12. #include "or.h"
  13. /****************************************************************************/
  14. /** Enumeration of possible token types. The ones starting with K_
  15. * correspond to directory 'keywords'. _UNRECOGNIZED is for an
  16. * unrecognized keyword; _ERR is an error in the tokenizing process,
  17. * _EOF is an end-of-file marker, and _NIL is used to encode
  18. * not-a-token.
  19. */
  20. typedef enum {
  21. K_ACCEPT,
  22. K_DIRECTORY_SIGNATURE,
  23. K_RECOMMENDED_SOFTWARE,
  24. K_REJECT,
  25. K_ROUTER,
  26. K_SIGNED_DIRECTORY,
  27. K_SIGNING_KEY,
  28. K_ONION_KEY,
  29. K_ROUTER_SIGNATURE,
  30. K_PUBLISHED,
  31. K_RUNNING_ROUTERS,
  32. K_ROUTER_STATUS,
  33. K_PLATFORM,
  34. K_OPT,
  35. K_BANDWIDTH,
  36. K_PORTS,
  37. K_DIRCACHEPORT,
  38. K_CONTACT,
  39. K_NETWORK_STATUS,
  40. K_UPTIME,
  41. K_DIR_SIGNING_KEY,
  42. K_FAMILY,
  43. _UNRECOGNIZED,
  44. _ERR,
  45. _EOF,
  46. _NIL
  47. } directory_keyword;
  48. /** Structure to hold a single directory token.
  49. *
  50. * We parse a directory by breaking it into "tokens", each consisting
  51. * of a keyword, a line full of arguments, and a binary object. The
  52. * arguments and object are both optional, depending on the keyword
  53. * type.
  54. */
  55. typedef struct directory_token_t {
  56. directory_keyword tp; /**< Type of the token. */
  57. int n_args; /**< Number of elements in args */
  58. char **args; /**< Array of arguments from keyword line. */
  59. char *object_type; /**< -----BEGIN [object_type]-----*/
  60. size_t object_size; /**< Bytes in object_body */
  61. char *object_body; /**< Contents of object, base64-decoded. */
  62. crypto_pk_env_t *key; /**< For public keys only. */
  63. const char *error; /**< For _ERR tokens only. */
  64. } directory_token_t;
  65. /* ********************************************************************** */
  66. /** We use a table of rules to decide how to parse each token type. */
  67. /** Rules for how many arguments a keyword can take. */
  68. typedef enum {
  69. NO_ARGS, /**< (1) no arguments, ever */
  70. ARGS, /**< (2) a list of arguments separated by spaces */
  71. CONCAT_ARGS, /**< or (3) the rest of the line, treated as a single argument. */
  72. } arg_syntax;
  73. /** Rules for whether the keyword needs an object. */
  74. typedef enum {
  75. NO_OBJ, /**< (1) no object, ever */
  76. NEED_OBJ, /**< (2) object is required */
  77. NEED_KEY, /**< (3) object is required, and must be a public key. */
  78. OBJ_OK, /**< or (4) object is optional. */
  79. } obj_syntax;
  80. /** Rules for where a keyword can appear. */
  81. typedef enum {
  82. ANY = 0, /**< Appears in router descriptor or in directory sections. */
  83. DIR_ONLY, /**< Appears only in directory. */
  84. RTR_ONLY, /**< Appears only in router descriptor or runningrouters */
  85. } where_syntax;
  86. /** Table mapping keywords to token value and to argument rules. */
  87. static struct {
  88. const char *t; int v; arg_syntax s; obj_syntax os; where_syntax ws;
  89. } token_table[] = {
  90. { "accept", K_ACCEPT, ARGS, NO_OBJ, RTR_ONLY },
  91. { "directory-signature", K_DIRECTORY_SIGNATURE, ARGS, NEED_OBJ,DIR_ONLY},
  92. { "reject", K_REJECT, ARGS, NO_OBJ, RTR_ONLY },
  93. { "router", K_ROUTER, ARGS, NO_OBJ, RTR_ONLY },
  94. { "recommended-software",K_RECOMMENDED_SOFTWARE,ARGS, NO_OBJ, DIR_ONLY },
  95. { "signed-directory", K_SIGNED_DIRECTORY, NO_ARGS, NO_OBJ, DIR_ONLY },
  96. { "signing-key", K_SIGNING_KEY, NO_ARGS, NEED_KEY,RTR_ONLY },
  97. { "onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY,RTR_ONLY },
  98. { "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ,RTR_ONLY },
  99. { "running-routers", K_RUNNING_ROUTERS, ARGS, NO_OBJ, DIR_ONLY },
  100. { "router-status", K_ROUTER_STATUS, ARGS, NO_OBJ, DIR_ONLY },
  101. { "ports", K_PORTS, ARGS, NO_OBJ, RTR_ONLY },
  102. { "bandwidth", K_BANDWIDTH, ARGS, NO_OBJ, RTR_ONLY },
  103. { "platform", K_PLATFORM, CONCAT_ARGS, NO_OBJ, RTR_ONLY },
  104. { "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ, ANY },
  105. { "opt", K_OPT, CONCAT_ARGS, OBJ_OK, ANY },
  106. { "dircacheport", K_DIRCACHEPORT, ARGS, NO_OBJ, RTR_ONLY },
  107. { "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ, ANY },
  108. { "network-status", K_NETWORK_STATUS, NO_ARGS, NO_OBJ, DIR_ONLY },
  109. { "uptime", K_UPTIME, ARGS, NO_OBJ, RTR_ONLY },
  110. { "dir-signing-key", K_DIR_SIGNING_KEY, ARGS, OBJ_OK, DIR_ONLY },
  111. { "family", K_FAMILY, ARGS, NO_OBJ, RTR_ONLY },
  112. { NULL, -1, NO_ARGS, NO_OBJ, ANY }
  113. };
  114. /* static function prototypes */
  115. static int router_add_exit_policy(routerinfo_t *router,directory_token_t *tok);
  116. static addr_policy_t *router_parse_addr_policy(directory_token_t *tok);
  117. static int router_get_hash_impl(const char *s, char *digest,
  118. const char *start_str, const char *end_str);
  119. static void token_free(directory_token_t *tok);
  120. static smartlist_t *find_all_exitpolicy(smartlist_t *s);
  121. static directory_token_t *find_first_by_keyword(smartlist_t *s,
  122. directory_keyword keyword);
  123. static int tokenize_string(const char *start, const char *end,
  124. smartlist_t *out, int is_dir);
  125. static directory_token_t *get_next_token(const char **s, where_syntax where);
  126. static int check_directory_signature(const char *digest,
  127. directory_token_t *tok,
  128. crypto_pk_env_t *pkey,
  129. crypto_pk_env_t *declared_key);
  130. static crypto_pk_env_t *find_dir_signing_key(const char *str);
  131. /* static */ int is_obsolete_version(const char *myversion,
  132. const char *versionlist);
  133. static int tor_version_same_series(tor_version_t *a, tor_version_t *b);
  134. /** Set <b>digest</b> to the SHA-1 digest of the hash of the directory in
  135. * <b>s</b>. Return 0 on success, nonzero on failure.
  136. */
  137. int router_get_dir_hash(const char *s, char *digest)
  138. {
  139. return router_get_hash_impl(s,digest,
  140. "signed-directory","\ndirectory-signature");
  141. }
  142. /** Set <b>digest</b> to the SHA-1 digest of the hash of the first router in
  143. * <b>s</b>. Return 0 on success, nonzero on failure.
  144. */
  145. int router_get_router_hash(const char *s, char *digest)
  146. {
  147. return router_get_hash_impl(s,digest,
  148. "router ","\nrouter-signature");
  149. }
  150. /** Set <b>digest</b> to the SHA-1 digest of the hash of the running-routers
  151. * string in <b>s</b>. Return 0 on success, nonzero on failure.
  152. */
  153. int router_get_runningrouters_hash(const char *s, char *digest)
  154. {
  155. return router_get_hash_impl(s,digest,
  156. "network-status","\ndirectory-signature");
  157. }
  158. /**
  159. * Find the first instance of "recommended-software ...\n" at the start of
  160. * a line; return a newly allocated string containing the "..." portion.
  161. * Return NULL if no such instance was found.
  162. */
  163. static char *
  164. get_recommended_software_from_directory(const char *str)
  165. {
  166. #define REC "recommended-software "
  167. const char *cp = str, *eol;
  168. size_t len = strlen(REC);
  169. cp = str;
  170. if (strcmpstart(str, REC)==0) {
  171. cp += len;
  172. } else {
  173. cp = strstr(str, "\n"REC);
  174. if (!cp)
  175. return NULL;
  176. cp += len+1;
  177. }
  178. eol = strchr(cp, '\n');
  179. if (!eol)
  180. return NULL;
  181. return tor_strndup(cp, eol-cp);
  182. #undef REC
  183. }
  184. /** Return 1 if <b>myversion</b> is not in <b>versionlist</b>, and if at least
  185. * one version of Tor on <b>versionlist</b> is newer than <b>myversion</b>.
  186. * Return 1 if no version from the same series as <b>myversion</b> is
  187. * in <b>versionlist</b> (and <b>myversion</b> is not the newest
  188. * version), or if a newer version from the same series is in
  189. * <b>versionlist</b>.
  190. *
  191. * Otherwise return 0.
  192. * (versionlist is a comma-separated list of version strings,
  193. * optionally prefixed with "Tor". Versions that can't be parsed are
  194. * ignored.) */
  195. /* static */ int is_obsolete_version(const char *myversion,
  196. const char *versionlist) {
  197. const char *vl;
  198. tor_version_t mine, other;
  199. int found_newer = 0, found_newer_in_series = 0, found_any_in_series = 0,
  200. r, ret, same;
  201. static int warned_too_new=0;
  202. smartlist_t *version_sl;
  203. int XXXpath;
  204. vl = versionlist;
  205. log_fn(LOG_DEBUG,"Checking whether version '%s' is in '%s'", myversion, versionlist);
  206. if (tor_version_parse(myversion, &mine)) {
  207. log_fn(LOG_ERR, "I couldn't parse my own version (%s)", myversion);
  208. tor_assert(0);
  209. }
  210. version_sl = smartlist_create();
  211. smartlist_split_string(version_sl, versionlist, ",", SPLIT_SKIP_SPACE, 0);
  212. SMARTLIST_FOREACH(version_sl, const char *, cp, {
  213. if (!strcmpstart(cp, "Tor "))
  214. cp += 4;
  215. if (tor_version_parse(cp, &other)) {
  216. /* Couldn't parse other; it can't be a match. */
  217. } else {
  218. same = tor_version_same_series(&mine, &other);
  219. if (same)
  220. found_any_in_series = 1;
  221. r = tor_version_compare(&mine, &other);
  222. if (r==0) {
  223. ret = 0;
  224. goto done;
  225. } else if (r<0) {
  226. found_newer = 1;
  227. if (same)
  228. found_newer_in_series = 1;
  229. }
  230. }
  231. });
  232. /* We didn't find the listed version. Is it new or old? */
  233. if (found_any_in_series) {
  234. if (!found_newer_in_series) {
  235. /* We belong to a series with recommended members, and we are newer than
  236. * any recommended member. We're probably okay. */
  237. if (!warned_too_new) {
  238. log(LOG_WARN, "This version of Tor (%s) is newer than any in the same series on the recommended list (%s)",
  239. myversion, versionlist);
  240. warned_too_new = 1;
  241. }
  242. ret = 0;
  243. XXXpath = 1;
  244. } else {
  245. /* We found a newer one in the same series; we're obsolete. */
  246. ret = 1;
  247. XXXpath = 2;
  248. }
  249. } else {
  250. if (found_newer) {
  251. /* We belong to a series with no recommended members, and
  252. * a newer series is recommended. We're obsolete. */
  253. ret = 1;
  254. XXXpath = 3;
  255. } else {
  256. /* We belong to a series with no recommended members, and it's
  257. * newer than any recommended series. We're probably okay. */
  258. if (!warned_too_new) {
  259. log(LOG_WARN, "This version of Tor (%s) is newer than any on the recommended list (%s)",
  260. myversion, versionlist);
  261. warned_too_new = 1;
  262. }
  263. ret = 0;
  264. XXXpath = 4;
  265. }
  266. }
  267. /*
  268. log_fn(LOG_DEBUG,
  269. "Decided that %s is %sobsolete relative to %s: %d, %d, %d\n",
  270. myversion, ret?"":"not ", versionlist, found_newer,
  271. found_any_in_series, found_newer_in_series);
  272. */
  273. done:
  274. SMARTLIST_FOREACH(version_sl, char *, version, tor_free(version));
  275. smartlist_free(version_sl);
  276. return ret;
  277. }
  278. /* Return 0 if myversion is supported; else log a message and return
  279. * -1 (or exit if ignoreversions is false) */
  280. int check_software_version_against_directory(const char *directory,
  281. int ignoreversion)
  282. {
  283. char *v;
  284. v = get_recommended_software_from_directory(directory);
  285. if (!v) {
  286. log_fn(LOG_WARN, "No recommended-versions string found in directory");
  287. return -1;
  288. }
  289. if (!is_obsolete_version(VERSION, v)) {
  290. tor_free(v);
  291. return 0;
  292. }
  293. log(ignoreversion ? LOG_WARN : LOG_ERR,
  294. "You are running Tor version %s, which will not work with this network.\n"
  295. "Please use %s%s.",
  296. VERSION, strchr(v,',') ? "one of " : "", v);
  297. tor_free(v);
  298. if (ignoreversion) {
  299. log(LOG_WARN, "IgnoreVersion is set. If it breaks, we told you so.");
  300. return -1;
  301. } else {
  302. fflush(0);
  303. tor_cleanup();
  304. exit(0);
  305. return -1; /* never reached */
  306. }
  307. }
  308. /** Parse a directory from <b>str</b> and, when done, store the
  309. * resulting routerlist in *<b>dest</b>, freeing the old value if
  310. * necessary.
  311. *
  312. * If <b>pkey</b> is provided, we check the directory signature with pkey.
  313. *
  314. * If <b>check_version</b> is non-zero, then examine the
  315. * Recommended-versions * line in the directory, and warn or quit
  316. * as needed.
  317. *
  318. * If <b>write_to_cache</b> is non-zero, then store this directory in
  319. * memory and/or disk as well.
  320. */
  321. int /* Should be static; exposed for unit tests */
  322. router_parse_routerlist_from_directory(const char *str,
  323. routerlist_t **dest,
  324. crypto_pk_env_t *pkey,
  325. int check_version,
  326. int write_to_cache)
  327. {
  328. directory_token_t *tok;
  329. char digest[DIGEST_LEN];
  330. routerlist_t *new_dir = NULL;
  331. char *versions = NULL;
  332. int nickname_list_is_running_routers;
  333. smartlist_t *good_nickname_list = NULL;
  334. time_t published_on;
  335. int i, r;
  336. const char *end, *cp;
  337. smartlist_t *tokens = NULL;
  338. char dirnickname[MAX_NICKNAME_LEN+1];
  339. crypto_pk_env_t *declared_key = NULL;
  340. if (router_get_dir_hash(str, digest)) {
  341. log_fn(LOG_WARN, "Unable to compute digest of directory");
  342. goto err;
  343. }
  344. log_fn(LOG_DEBUG,"Received directory hashes to %s",hex_str(digest,4));
  345. /* Check signature first, before we try to tokenize. */
  346. cp = str;
  347. while (cp && (end = strstr(cp+1, "\ndirectory-signature")))
  348. cp = end;
  349. if (cp == str || !cp) {
  350. log_fn(LOG_WARN, "No signature found on directory."); goto err;
  351. }
  352. ++cp;
  353. tokens = smartlist_create();
  354. if (tokenize_string(cp,strchr(cp,'\0'),tokens,1)) {
  355. log_fn(LOG_WARN, "Error tokenizing directory signature"); goto err;
  356. }
  357. if (smartlist_len(tokens) != 1) {
  358. log_fn(LOG_WARN, "Unexpected number of tokens in signature"); goto err;
  359. }
  360. tok=smartlist_get(tokens,0);
  361. if (tok->tp != K_DIRECTORY_SIGNATURE) {
  362. log_fn(LOG_WARN,"Expected a single directory signature"); goto err;
  363. }
  364. declared_key = find_dir_signing_key(str);
  365. if (check_directory_signature(digest, tok, pkey, declared_key)<0)
  366. goto err;
  367. /* now we know tok->n_args == 1, so it's safe to access tok->args[0] */
  368. if (!is_legal_nickname(tok->args[0])) {
  369. log_fn(LOG_WARN, "Directory nickname '%s' is misformed", tok->args[0]);
  370. goto err;
  371. }
  372. strlcpy(dirnickname, tok->args[0], sizeof(dirnickname));
  373. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  374. smartlist_free(tokens);
  375. tokens = NULL;
  376. /* Now that we know the signature is okay, check the version. */
  377. if (check_version)
  378. check_software_version_against_directory(str, get_options()->IgnoreVersion);
  379. /* Now try to parse the first part of the directory. */
  380. if ((end = strstr(str,"\nrouter "))) {
  381. ++end;
  382. } else if ((end = strstr(str, "\ndirectory-signature"))) {
  383. ++end;
  384. } else {
  385. end = str + strlen(str);
  386. }
  387. tokens = smartlist_create();
  388. if (tokenize_string(str,end,tokens,1)) {
  389. log_fn(LOG_WARN, "Error tokenizing directory"); goto err;
  390. }
  391. if (smartlist_len(tokens) < 1) {
  392. log_fn(LOG_WARN, "Impossibly short directory header"); goto err;
  393. }
  394. if ((tok = find_first_by_keyword(tokens, _UNRECOGNIZED))) {
  395. log_fn(LOG_WARN, "Unrecognized keyword \"%s\" in directory header; can't parse directory.",
  396. tok->args[0]);
  397. goto err;
  398. }
  399. tok = smartlist_get(tokens,0);
  400. if (tok->tp != K_SIGNED_DIRECTORY) {
  401. log_fn(LOG_WARN, "Directory doesn't start with signed-directory.");
  402. goto err;
  403. }
  404. if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
  405. log_fn(LOG_WARN, "Missing published time on directory.");
  406. goto err;
  407. }
  408. tor_assert(tok->n_args == 1);
  409. if (parse_iso_time(tok->args[0], &published_on) < 0) {
  410. goto err;
  411. }
  412. /* Now that we know the signature is okay, and we have a
  413. * publication time, cache the directory. */
  414. if (!get_options()->AuthoritativeDir && write_to_cache)
  415. dirserv_set_cached_directory(str, published_on, 0);
  416. if (!(tok = find_first_by_keyword(tokens, K_RECOMMENDED_SOFTWARE))) {
  417. log_fn(LOG_WARN, "Missing recommended-software line from directory.");
  418. goto err;
  419. }
  420. if (tok->n_args > 1) {
  421. log_fn(LOG_WARN, "Invalid recommended-software line");
  422. goto err;
  423. }
  424. versions = tok->n_args ? tor_strdup(tok->args[0]) : tor_strdup("");
  425. /* Prefer router-status, then running-routers. */
  426. if (!(tok = find_first_by_keyword(tokens, K_ROUTER_STATUS))) {
  427. if (!(tok = find_first_by_keyword(tokens, K_RUNNING_ROUTERS))) {
  428. log_fn(LOG_WARN,
  429. "Missing running-routers/router-status line from directory.");
  430. goto err;
  431. }
  432. }
  433. nickname_list_is_running_routers = (tok->tp == K_RUNNING_ROUTERS);
  434. good_nickname_list = smartlist_create();
  435. for (i=0; i<tok->n_args; ++i) {
  436. smartlist_add(good_nickname_list, tok->args[i]);
  437. }
  438. tok->n_args = 0; /* Don't free the strings in good_nickname_list yet. */
  439. /* Read the router list from s, advancing s up past the end of the last
  440. * router. */
  441. str = end;
  442. if (router_parse_list_from_string(&str, &new_dir,
  443. good_nickname_list,
  444. tok->tp==K_RUNNING_ROUTERS,
  445. published_on)) {
  446. log_fn(LOG_WARN, "Error reading routers from directory");
  447. goto err;
  448. }
  449. /* Determine if my routerinfo is considered verified. */
  450. {
  451. static int have_warned_about_unverified_status = 0;
  452. routerinfo_t *me = router_get_my_routerinfo();
  453. if (me) {
  454. if (router_update_status_from_smartlist(me,
  455. published_on, good_nickname_list, tok->tp==K_RUNNING_ROUTERS)==1 &&
  456. me->is_verified == 0 && !have_warned_about_unverified_status) {
  457. log_fn(LOG_WARN,"Dirserver '%s' lists your server as unverified. Please consider sending your identity fingerprint to the tor-ops.", dirnickname);
  458. have_warned_about_unverified_status = 1;
  459. }
  460. }
  461. }
  462. new_dir->software_versions = versions; versions = NULL;
  463. new_dir->published_on = published_on;
  464. new_dir->running_routers = tor_malloc_zero(sizeof(running_routers_t));
  465. new_dir->running_routers->published_on = published_on;
  466. new_dir->running_routers->running_routers = good_nickname_list;
  467. new_dir->running_routers->is_running_routers_format =
  468. nickname_list_is_running_routers;
  469. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  470. smartlist_free(tokens);
  471. tokens = NULL;
  472. if (*dest)
  473. routerlist_free(*dest);
  474. *dest = new_dir;
  475. r = 0;
  476. goto done;
  477. err:
  478. r = -1;
  479. if (new_dir)
  480. routerlist_free(new_dir);
  481. tor_free(versions);
  482. if (good_nickname_list) {
  483. SMARTLIST_FOREACH(good_nickname_list, char *, n, tor_free(n));
  484. smartlist_free(good_nickname_list);
  485. }
  486. done:
  487. if (declared_key) crypto_free_pk_env(declared_key);
  488. if (tokens) {
  489. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  490. smartlist_free(tokens);
  491. }
  492. return r;
  493. }
  494. /** Read a signed router status statement from <b>str</b>. On
  495. * success, return it, and cache the original string if
  496. * <b>write_to_cache</b> is set. Otherwise, return NULL. */
  497. running_routers_t *
  498. router_parse_runningrouters(const char *str, int write_to_cache)
  499. {
  500. char digest[DIGEST_LEN];
  501. running_routers_t *new_list = NULL;
  502. directory_token_t *tok;
  503. time_t published_on;
  504. int i;
  505. crypto_pk_env_t *declared_key = NULL;
  506. smartlist_t *tokens = NULL;
  507. if (router_get_runningrouters_hash(str, digest)) {
  508. log_fn(LOG_WARN, "Unable to compute digest of directory");
  509. goto err;
  510. }
  511. tokens = smartlist_create();
  512. if (tokenize_string(str,str+strlen(str),tokens,1)) {
  513. log_fn(LOG_WARN, "Error tokenizing directory"); goto err;
  514. }
  515. if ((tok = find_first_by_keyword(tokens, _UNRECOGNIZED))) {
  516. log_fn(LOG_WARN, "Unrecognized keyword '%s'; can't parse running-routers",
  517. tok->args[0]);
  518. goto err;
  519. }
  520. tok = smartlist_get(tokens,0);
  521. if (tok->tp != K_NETWORK_STATUS) {
  522. log_fn(LOG_WARN, "Network-status starts with wrong token");
  523. goto err;
  524. }
  525. if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
  526. log_fn(LOG_WARN, "Missing published time on directory.");
  527. goto err;
  528. }
  529. tor_assert(tok->n_args == 1);
  530. if (parse_iso_time(tok->args[0], &published_on) < 0) {
  531. goto err;
  532. }
  533. /* Now that we know the signature is okay, and we have a
  534. * publication time, cache the list. */
  535. if (!get_options()->AuthoritativeDir && write_to_cache)
  536. dirserv_set_cached_directory(str, published_on, 1);
  537. if (!(tok = find_first_by_keyword(tokens, K_ROUTER_STATUS))) {
  538. if (!(tok = find_first_by_keyword(tokens, K_RUNNING_ROUTERS))) {
  539. log_fn(LOG_WARN,
  540. "Missing running-routers/router-status line from directory.");
  541. goto err;
  542. }
  543. }
  544. new_list = tor_malloc_zero(sizeof(running_routers_t));
  545. new_list->published_on = published_on;
  546. new_list->running_routers = smartlist_create();
  547. new_list->is_running_routers_format = (tok->tp == K_RUNNING_ROUTERS);
  548. for (i=0;i<tok->n_args;++i) {
  549. smartlist_add(new_list->running_routers, tok->args[i]);
  550. }
  551. tok->n_args = 0; /* Don't free the elements of tok->args. */
  552. if (!(tok = find_first_by_keyword(tokens, K_DIRECTORY_SIGNATURE))) {
  553. log_fn(LOG_WARN, "Missing signature on running-routers");
  554. goto err;
  555. }
  556. declared_key = find_dir_signing_key(str);
  557. if (check_directory_signature(digest, tok, NULL, declared_key) < 0)
  558. goto err;
  559. goto done;
  560. err:
  561. if (new_list) {
  562. running_routers_free(new_list);
  563. new_list = NULL;
  564. }
  565. done:
  566. if (declared_key) crypto_free_pk_env(declared_key);
  567. if (tokens) {
  568. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  569. smartlist_free(tokens);
  570. }
  571. return new_list;
  572. }
  573. /** Given a directory or running-routers string in <b>str</b>, try to
  574. * find the its dir-signing-key token (if any). If this token is
  575. * present, extract and return the key. Return NULL on failure. */
  576. static crypto_pk_env_t *find_dir_signing_key(const char *str)
  577. {
  578. const char *cp;
  579. directory_token_t *tok;
  580. crypto_pk_env_t *key = NULL;
  581. /* Is there a dir-signing-key in the directory? */
  582. cp = strstr(str, "\nopt dir-signing-key");
  583. if (!cp)
  584. cp = strstr(str, "\ndir-signing-key");
  585. if (!cp)
  586. return NULL;
  587. ++cp; /* Now cp points to the start of the token. */
  588. tok = get_next_token(&cp, DIR_ONLY);
  589. if (!tok) {
  590. log_fn(LOG_WARN, "Unparseable dir-signing-key token");
  591. return NULL;
  592. }
  593. if (tok->tp != K_DIR_SIGNING_KEY) {
  594. log_fn(LOG_WARN, "Dir-signing-key token did not parse as expected");
  595. return NULL;
  596. }
  597. if (tok->key) {
  598. key = tok->key;
  599. tok->key = NULL; /* steal reference. */
  600. } else if (tok->n_args >= 1) {
  601. key = crypto_pk_DER64_decode_public_key(tok->args[0]);
  602. if (!key) {
  603. log_fn(LOG_WARN, "Unparseable dir-signing-key argument");
  604. return NULL;
  605. }
  606. } else {
  607. log_fn(LOG_WARN, "Dir-signing-key token contained no key");
  608. return NULL;
  609. }
  610. token_free(tok);
  611. return key;
  612. }
  613. /** Return true iff <b>key</b> is allowed to sign directories.
  614. */
  615. static int dir_signing_key_is_trusted(crypto_pk_env_t *key)
  616. {
  617. char digest[DIGEST_LEN];
  618. if (!key) return 0;
  619. if (crypto_pk_get_digest(key, digest) < 0) {
  620. log_fn(LOG_WARN, "Error computing dir-signing-key digest");
  621. return 0;
  622. }
  623. if (!router_digest_is_trusted_dir(digest)) {
  624. log_fn(LOG_WARN, "Listed dir-signing-key is not trusted");
  625. return 0;
  626. }
  627. return 1;
  628. }
  629. /** Check whether the K_DIRECTORY_SIGNATURE token in <b>tok</b> has a
  630. * good signature for <b>digest</b>.
  631. *
  632. * If <b>declared_key</b> is set, the directory has declared what key
  633. * was used to sign it, so we will use that key only if it is an
  634. * authoritative directory signing key.
  635. *
  636. * Otherwise, if pkey is provided, try to use it.
  637. *
  638. * (New callers should always use <b>declared_key</b> when possible;
  639. * <b>pkey is only for debugging.)
  640. */
  641. static int check_directory_signature(const char *digest,
  642. directory_token_t *tok,
  643. crypto_pk_env_t *pkey,
  644. crypto_pk_env_t *declared_key)
  645. {
  646. char signed_digest[PK_BYTES];
  647. crypto_pk_env_t *_pkey = NULL;
  648. if (tok->n_args != 1) {
  649. log_fn(LOG_WARN, "Too many or too few arguments to directory-signature");
  650. return -1;
  651. }
  652. if (declared_key) {
  653. if (dir_signing_key_is_trusted(declared_key))
  654. _pkey = declared_key;
  655. }
  656. if (!_pkey && pkey) {
  657. /* pkey provided for debugging purposes */
  658. _pkey = pkey;
  659. }
  660. if (!_pkey) {
  661. log_fn(LOG_WARN, "Found directory in old (before 0.0.9pre3) format--rejecting.");
  662. return -1;
  663. }
  664. if (strcmp(tok->object_type, "SIGNATURE") || tok->object_size != 128) {
  665. log_fn(LOG_WARN, "Bad object type or length on directory signature");
  666. return -1;
  667. }
  668. tor_assert(_pkey);
  669. if (crypto_pk_public_checksig(_pkey, signed_digest, tok->object_body, 128)
  670. != 20) {
  671. log_fn(LOG_WARN, "Error reading directory: invalid signature.");
  672. return -1;
  673. }
  674. log_fn(LOG_DEBUG,"Signed directory hash starts %s", hex_str(signed_digest,4));
  675. if (memcmp(digest, signed_digest, 20)) {
  676. log_fn(LOG_WARN, "Error reading directory: signature does not match.");
  677. return -1;
  678. }
  679. return 0;
  680. }
  681. /** Given a string *<b>s</b> containing a concatenated sequence of router
  682. * descriptors, parses them and stores the result in *<b>dest</b>. If
  683. * good_nickname_list is provided, then routers are marked as
  684. * running/nonrunning and verified/unverified based on their status in the
  685. * list. Otherwise, all routers are marked running and verified. Advances
  686. * *s to a point immediately following the last router entry. Returns 0 on
  687. * success and -1 on failure.
  688. */
  689. int
  690. router_parse_list_from_string(const char **s, routerlist_t **dest,
  691. smartlist_t *good_nickname_list,
  692. int rr_format, time_t published_on)
  693. {
  694. routerinfo_t *router;
  695. smartlist_t *routers;
  696. const char *end;
  697. tor_assert(s);
  698. tor_assert(*s);
  699. routers = smartlist_create();
  700. while (1) {
  701. *s = eat_whitespace(*s);
  702. /* Don't start parsing the rest of *s unless it contains a router. */
  703. if (strcmpstart(*s, "router ")!=0)
  704. break;
  705. if ((end = strstr(*s+1, "\nrouter "))) {
  706. end++;
  707. } else if ((end = strstr(*s+1, "\ndirectory-signature"))) {
  708. end++;
  709. } else {
  710. end = *s+strlen(*s);
  711. }
  712. router = router_parse_entry_from_string(*s, end);
  713. *s = end;
  714. if (!router) {
  715. log_fn(LOG_WARN, "Error reading router; skipping");
  716. continue;
  717. }
  718. if (!good_nickname_list) {
  719. router->is_running = 1; /* start out assuming all dirservers are up */
  720. router->is_verified = 1;
  721. router->status_set_at = time(NULL);
  722. }
  723. smartlist_add(routers, router);
  724. // log_fn(LOG_DEBUG,"just added router #%d.",smartlist_len(routers));
  725. }
  726. if (good_nickname_list) {
  727. SMARTLIST_FOREACH(good_nickname_list, const char *, cp,
  728. routers_update_status_from_entry(routers, published_on,
  729. cp, rr_format));
  730. }
  731. if (*dest)
  732. routerlist_free(*dest);
  733. *dest = tor_malloc_zero(sizeof(routerlist_t));
  734. (*dest)->routers = routers;
  735. return 0;
  736. }
  737. /** Helper function: reads a single router entry from *<b>s</b> ...
  738. * *<b>end</b>. Mallocs a new router and returns it if all goes well, else
  739. * returns NULL.
  740. */
  741. routerinfo_t *router_parse_entry_from_string(const char *s,
  742. const char *end) {
  743. routerinfo_t *router = NULL;
  744. char signed_digest[128];
  745. char digest[128];
  746. smartlist_t *tokens = NULL, *exit_policy_tokens = NULL;
  747. directory_token_t *tok;
  748. int t;
  749. int ports_set, bw_set;
  750. if (!end) {
  751. end = s + strlen(s);
  752. }
  753. if (router_get_router_hash(s, digest) < 0) {
  754. log_fn(LOG_WARN, "Couldn't compute router hash.");
  755. return NULL;
  756. }
  757. tokens = smartlist_create();
  758. if (tokenize_string(s,end,tokens,0)) {
  759. log_fn(LOG_WARN, "Error tokeninzing router descriptor."); goto err;
  760. }
  761. if (smartlist_len(tokens) < 2) {
  762. log_fn(LOG_WARN, "Impossibly short router descriptor.");
  763. goto err;
  764. }
  765. if ((tok = find_first_by_keyword(tokens, _UNRECOGNIZED))) {
  766. log_fn(LOG_WARN, "Unrecognized keyword '%s'; skipping descriptor.",
  767. tok->args[0]);
  768. goto err;
  769. }
  770. tok = smartlist_get(tokens,0);
  771. if (tok->tp != K_ROUTER) {
  772. log_fn(LOG_WARN,"Entry does not start with \"router\"");
  773. goto err;
  774. }
  775. router = tor_malloc_zero(sizeof(routerinfo_t));
  776. router->signed_descriptor = tor_strndup(s, end-s);
  777. ports_set = bw_set = 0;
  778. if (tok->n_args == 2 || tok->n_args == 5 || tok->n_args == 6) {
  779. router->nickname = tor_strdup(tok->args[0]);
  780. if (!is_legal_nickname(router->nickname)) {
  781. log_fn(LOG_WARN,"Router nickname is invalid");
  782. goto err;
  783. }
  784. router->address = tor_strdup(tok->args[1]);
  785. router->addr = 0;
  786. if (tok->n_args >= 5) {
  787. router->or_port = (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
  788. router->dir_port = (uint16_t) tor_parse_long(tok->args[4],10,0,65535,NULL,NULL);
  789. ports_set = 1;
  790. }
  791. } else {
  792. log_fn(LOG_WARN,"Wrong # of arguments to \"router\" (%d)",tok->n_args);
  793. goto err;
  794. }
  795. tok = find_first_by_keyword(tokens, K_PORTS);
  796. if (tok && ports_set) {
  797. log_fn(LOG_WARN,"Redundant ports line");
  798. goto err;
  799. } else if (tok) {
  800. if (tok->n_args != 3) {
  801. log_fn(LOG_WARN,"Wrong # of arguments to \"ports\"");
  802. goto err;
  803. }
  804. router->or_port = (uint16_t) tor_parse_long(tok->args[0],10,0,65535,NULL,NULL);
  805. router->dir_port = (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
  806. ports_set = 1;
  807. }
  808. tok = find_first_by_keyword(tokens, K_DIRCACHEPORT);
  809. if (tok) {
  810. if (router->dir_port)
  811. log_fn(LOG_WARN,"Redundant dircacheport line");
  812. if (tok->n_args != 1) {
  813. log_fn(LOG_WARN,"Wrong # of arguments to \"dircacheport\"");
  814. goto err;
  815. }
  816. router->dir_port = (uint16_t) tor_parse_long(tok->args[0],10,1,65535,NULL,NULL);
  817. }
  818. tok = find_first_by_keyword(tokens, K_BANDWIDTH);
  819. if (tok && bw_set) {
  820. log_fn(LOG_WARN,"Redundant bandwidth line");
  821. goto err;
  822. } else if (tok) {
  823. if (tok->n_args < 3) {
  824. /* XXXX Once 0.0.7 is *really* dead, restore this warning to its old form*/
  825. log_fn(LOG_WARN,"Not enough arguments to \"bandwidth\": must be an obsolete server. Rejecting one server (nickname '%s').", router->nickname);
  826. goto err;
  827. }
  828. router->bandwidthrate = tor_parse_long(tok->args[0],10,0,INT_MAX,NULL,NULL);
  829. router->bandwidthburst = tor_parse_long(tok->args[1],10,0,INT_MAX,NULL,NULL);
  830. router->bandwidthcapacity = tor_parse_long(tok->args[2],10,0,INT_MAX,NULL,NULL);
  831. bw_set = 1;
  832. }
  833. if ((tok = find_first_by_keyword(tokens, K_UPTIME))) {
  834. if (tok->n_args != 1) {
  835. log_fn(LOG_WARN, "Unrecognized number of args on K_UPTIME; skipping.");
  836. } else {
  837. router->uptime = tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL);
  838. }
  839. }
  840. if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
  841. log_fn(LOG_WARN, "Missing published time"); goto err;
  842. }
  843. tor_assert(tok->n_args == 1);
  844. if (parse_iso_time(tok->args[0], &router->published_on) < 0)
  845. goto err;
  846. if (!(tok = find_first_by_keyword(tokens, K_ONION_KEY))) {
  847. log_fn(LOG_WARN, "Missing onion key"); goto err;
  848. }
  849. if (crypto_pk_keysize(tok->key) != PK_BYTES) {
  850. log_fn(LOG_WARN, "Wrong size on onion key: %d bits!",
  851. crypto_pk_keysize(tok->key)*8);
  852. goto err;
  853. }
  854. router->onion_pkey = tok->key;
  855. tok->key = NULL; /* Prevent free */
  856. if (!(tok = find_first_by_keyword(tokens, K_SIGNING_KEY))) {
  857. log_fn(LOG_WARN, "Missing identity key"); goto err;
  858. }
  859. if (crypto_pk_keysize(tok->key) != PK_BYTES) {
  860. log_fn(LOG_WARN, "Wrong size on identity key: %d bits!",
  861. crypto_pk_keysize(tok->key)*8);
  862. goto err;
  863. }
  864. router->identity_pkey = tok->key;
  865. tok->key = NULL; /* Prevent free */
  866. if (crypto_pk_get_digest(router->identity_pkey,router->identity_digest)) {
  867. log_fn(LOG_WARN, "Couldn't calculate key digest"); goto err;
  868. }
  869. if ((tok = find_first_by_keyword(tokens, K_PLATFORM))) {
  870. router->platform = tor_strdup(tok->args[0]);
  871. }
  872. exit_policy_tokens = find_all_exitpolicy(tokens);
  873. SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
  874. if (router_add_exit_policy(router,t)<0) {
  875. log_fn(LOG_WARN,"Error in exit policy"); goto err;}
  876. );
  877. if ((tok = find_first_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
  878. int i;
  879. router->declared_family = smartlist_create();
  880. for (i=0;i<tok->n_args;++i) {
  881. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  882. log_fn(LOG_WARN, "Illegal nickname '%s' in family line", tok->args[i]);
  883. goto err;
  884. }
  885. smartlist_add(router->declared_family, tor_strdup(tok->args[i]));
  886. }
  887. }
  888. if (!(tok = find_first_by_keyword(tokens, K_ROUTER_SIGNATURE))) {
  889. log_fn(LOG_WARN, "Missing router signature"); goto err;
  890. }
  891. if (strcmp(tok->object_type, "SIGNATURE") || tok->object_size != 128) {
  892. log_fn(LOG_WARN, "Bad object type or length on router signature");
  893. goto err;
  894. }
  895. if ((t=crypto_pk_public_checksig(router->identity_pkey, signed_digest,
  896. tok->object_body, 128)) != 20) {
  897. log_fn(LOG_WARN, "Invalid signature %d",t); goto err;
  898. }
  899. if (memcmp(digest, signed_digest, 20)) {
  900. log_fn(LOG_WARN, "Mismatched signature"); goto err;
  901. }
  902. if (!ports_set) {
  903. log_fn(LOG_WARN,"No ports declared; failing."); goto err;
  904. }
  905. if (!bw_set) {
  906. log_fn(LOG_WARN,"No bandwidth declared; failing."); goto err;
  907. }
  908. if (!router->or_port) {
  909. log_fn(LOG_WARN,"or_port unreadable or 0. Failing.");
  910. goto err;
  911. }
  912. if (!router->bandwidthrate) {
  913. log_fn(LOG_WARN,"bandwidthrate unreadable or 0. Failing.");
  914. goto err;
  915. }
  916. if (!router->platform) {
  917. router->platform = tor_strdup("<unknown>");
  918. }
  919. // log_fn(LOG_DEBUG,"or_port %d, dir_port %d, bandwidthrate %u, bandwidthburst %u.",
  920. // router->or_port, router->dir_port,
  921. // (unsigned) router->bandwidthrate, (unsigned) router->bandwidthburst);
  922. goto done;
  923. return router;
  924. err:
  925. routerinfo_free(router);
  926. router = NULL;
  927. done:
  928. if (tokens) {
  929. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  930. smartlist_free(tokens);
  931. }
  932. if (exit_policy_tokens) {
  933. smartlist_free(exit_policy_tokens);
  934. }
  935. return router;
  936. }
  937. /** Parse the exit policy in the string <b>s</b> and return it.
  938. */
  939. addr_policy_t *
  940. router_parse_addr_policy_from_string(const char *s)
  941. {
  942. directory_token_t *tok = NULL;
  943. const char *cp;
  944. char *tmp;
  945. addr_policy_t *r;
  946. size_t len, idx;
  947. /* *s might not end with \n, so we need to extend it with one. */
  948. len = strlen(s);
  949. cp = tmp = tor_malloc(len+2);
  950. for (idx = 0; idx < len; ++idx) {
  951. tmp[idx] = tolower(s[idx]);
  952. }
  953. tmp[len]='\n';
  954. tmp[len+1]='\0';
  955. tok = get_next_token(&cp, RTR_ONLY);
  956. if (tok->tp == _ERR) {
  957. log_fn(LOG_WARN, "Error reading exit policy: %s", tok->error);
  958. goto err;
  959. }
  960. if (tok->tp != K_ACCEPT && tok->tp != K_REJECT) {
  961. log_fn(LOG_WARN, "Expected 'accept' or 'reject'.");
  962. goto err;
  963. }
  964. /* Now that we've gotten an exit policy, add it to the router. */
  965. r = router_parse_addr_policy(tok);
  966. goto done;
  967. err:
  968. r = NULL;
  969. done:
  970. tor_free(tmp);
  971. token_free(tok);
  972. return r;
  973. }
  974. int
  975. router_add_exit_policy_from_string(routerinfo_t *router, const char *s)
  976. {
  977. addr_policy_t *newe, *tmpe;
  978. newe = router_parse_addr_policy_from_string(s);
  979. if (!newe)
  980. return -1;
  981. for (tmpe = router->exit_policy; tmpe; tmpe=tmpe->next)
  982. ;
  983. tmpe->next = newe;
  984. return 0;
  985. }
  986. static int
  987. router_add_exit_policy(routerinfo_t *router,directory_token_t *tok)
  988. {
  989. addr_policy_t *newe, **tmpe;
  990. newe = router_parse_addr_policy(tok);
  991. if (!newe)
  992. return -1;
  993. for (tmpe = &router->exit_policy; *tmpe; tmpe=&((*tmpe)->next))
  994. ;
  995. *tmpe = newe;
  996. return 0;
  997. }
  998. /** Given a K_ACCEPT or K_REJECT token and a router, create and return
  999. * a new exit_policy_t corresponding to the token. */
  1000. static addr_policy_t *
  1001. router_parse_addr_policy(directory_token_t *tok) {
  1002. addr_policy_t *newe;
  1003. // struct in_addr in;
  1004. char *arg;
  1005. // char *address;
  1006. // char buf[INET_NTOA_BUF_LEN];
  1007. tor_assert(tok->tp == K_REJECT || tok->tp == K_ACCEPT);
  1008. if (tok->n_args != 1)
  1009. return NULL;
  1010. arg = tok->args[0];
  1011. newe = tor_malloc_zero(sizeof(addr_policy_t));
  1012. newe->string = tor_malloc(8+strlen(arg));
  1013. /* XXX eventually, use the code from router.c:727 to generate this */
  1014. tor_snprintf(newe->string, 8+strlen(arg), "%s %s",
  1015. (tok->tp == K_REJECT) ? "reject" : "accept", arg);
  1016. newe->policy_type = (tok->tp == K_REJECT) ? ADDR_POLICY_REJECT
  1017. : ADDR_POLICY_ACCEPT;
  1018. if (parse_addr_and_port_range(arg, &newe->addr, &newe->msk,
  1019. &newe->prt_min, &newe->prt_max))
  1020. goto policy_read_failed;
  1021. // in.s_addr = htonl(newe->addr);
  1022. // tor_inet_ntoa(&in, buf, sizeof(buf));
  1023. // address = tor_strdup(buf);
  1024. // in.s_addr = htonl(newe->msk);
  1025. // log_fn(LOG_DEBUG,"%s %s/%s:%d-%d",
  1026. // newe->policy_type == ADDR_POLICY_REJECT ? "reject" : "accept",
  1027. // address, inet_ntoa(in), newe->prt_min, newe->prt_max);
  1028. // tor_free(address);
  1029. return newe;
  1030. policy_read_failed:
  1031. tor_assert(newe->string);
  1032. log_fn(LOG_WARN,"Couldn't parse line '%s'. Dropping", newe->string);
  1033. tor_free(newe->string);
  1034. tor_free(newe);
  1035. return NULL;
  1036. }
  1037. void
  1038. assert_addr_policy_ok(addr_policy_t *t)
  1039. {
  1040. addr_policy_t *t2;
  1041. while (t) {
  1042. tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
  1043. t->policy_type == ADDR_POLICY_ACCEPT);
  1044. tor_assert(t->prt_min <= t->prt_max);
  1045. t2 = router_parse_addr_policy_from_string(t->string);
  1046. tor_assert(t2);
  1047. tor_assert(t2->policy_type == t->policy_type);
  1048. tor_assert(t2->addr == t->addr);
  1049. tor_assert(t2->msk == t->msk);
  1050. tor_assert(t2->prt_min == t->prt_min);
  1051. tor_assert(t2->prt_max == t->prt_max);
  1052. tor_assert(!strcmp(t2->string, t->string));
  1053. tor_assert(t2->next == NULL);
  1054. addr_policy_free(t2);
  1055. t = t->next;
  1056. }
  1057. }
  1058. /*
  1059. * Low-level tokenizer for router descriptors and directories.
  1060. */
  1061. /** Free all resources allocated for <b>tok</b> */
  1062. static void
  1063. token_free(directory_token_t *tok)
  1064. {
  1065. int i;
  1066. tor_assert(tok);
  1067. if (tok->args) {
  1068. for (i = 0; i < tok->n_args; ++i) {
  1069. tor_free(tok->args[i]);
  1070. }
  1071. tor_free(tok->args);
  1072. }
  1073. tor_free(tok->object_type);
  1074. tor_free(tok->object_body);
  1075. if (tok->key)
  1076. crypto_free_pk_env(tok->key);
  1077. tor_free(tok);
  1078. }
  1079. /** Helper function: read the next token from *s, advance *s to the end
  1080. * of the token, and return the parsed token. If 'where' is DIR_ONLY
  1081. * or RTR_ONLY, reject all tokens of the wrong type.
  1082. */
  1083. static directory_token_t *
  1084. get_next_token(const char **s, where_syntax where) {
  1085. const char *next, *obstart;
  1086. int i, done, allocated, is_opt;
  1087. directory_token_t *tok;
  1088. arg_syntax a_syn;
  1089. obj_syntax o_syn = NO_OBJ;
  1090. #define RET_ERR(msg) \
  1091. do { if (tok) token_free(tok); \
  1092. tok = tor_malloc_zero(sizeof(directory_token_t));\
  1093. tok->tp = _ERR; \
  1094. tok->error = msg; \
  1095. goto done_tokenizing; } while (0)
  1096. tok = tor_malloc_zero(sizeof(directory_token_t));
  1097. tok->tp = _ERR;
  1098. *s = eat_whitespace(*s);
  1099. if (!**s) {
  1100. tok->tp = _EOF;
  1101. return tok;
  1102. }
  1103. next = find_whitespace(*s);
  1104. if (!next) {
  1105. tok->error = "Unexpected EOF"; return tok;
  1106. }
  1107. /* It's a keyword... but which one? */
  1108. is_opt = !strncmp("opt", *s, next-*s);
  1109. if (is_opt) {
  1110. *s = eat_whitespace(next);
  1111. next = NULL;
  1112. if (**s)
  1113. next = find_whitespace(*s);
  1114. if (!**s || !next) {
  1115. RET_ERR("opt without keyword");
  1116. }
  1117. }
  1118. for (i = 0; token_table[i].t ; ++i) {
  1119. if (!strncmp(token_table[i].t, *s, next-*s)) {
  1120. /* We've found the keyword. */
  1121. tok->tp = token_table[i].v;
  1122. a_syn = token_table[i].s;
  1123. o_syn = token_table[i].os;
  1124. if (token_table[i].ws != ANY && token_table[i].ws != where) {
  1125. if (where == DIR_ONLY) {
  1126. RET_ERR("Found a router-only token in a directory section");
  1127. } else {
  1128. RET_ERR("Found a directory-only token in a router descriptor");
  1129. }
  1130. }
  1131. if (a_syn == ARGS) {
  1132. /* This keyword takes multiple arguments. */
  1133. i = 0;
  1134. done = (*next == '\n');
  1135. allocated = 32;
  1136. tok->args = tor_malloc(sizeof(char*)*32);
  1137. *s = eat_whitespace_no_nl(next);
  1138. while (**s != '\n' && !done) {
  1139. next = find_whitespace(*s);
  1140. if (*next == '\n')
  1141. done = 1;
  1142. if (i == allocated) {
  1143. allocated *= 2;
  1144. tok->args = tor_realloc(tok->args,sizeof(char*)*allocated);
  1145. }
  1146. tok->args[i++] = tor_strndup(*s,next-*s);
  1147. *s = eat_whitespace_no_nl(next+1);
  1148. }
  1149. tok->n_args = i;
  1150. } else if (a_syn == CONCAT_ARGS) {
  1151. /* The keyword takes the line as a single argument */
  1152. *s = eat_whitespace_no_nl(next);
  1153. next = strchr(*s, '\n');
  1154. if (!next)
  1155. RET_ERR("Unexpected EOF");
  1156. tok->args = tor_malloc(sizeof(char*));
  1157. tok->args[0] = tor_strndup(*s,next-*s);
  1158. tok->n_args = 1;
  1159. *s = eat_whitespace_no_nl(next+1);
  1160. } else {
  1161. /* The keyword takes no arguments. */
  1162. tor_assert(a_syn == NO_ARGS);
  1163. *s = eat_whitespace_no_nl(next);
  1164. if (**s != '\n') {
  1165. RET_ERR("Unexpected arguments");
  1166. }
  1167. tok->n_args = 0;
  1168. *s = eat_whitespace_no_nl(*s+1);
  1169. }
  1170. break;
  1171. }
  1172. }
  1173. if (tok->tp == _ERR) {
  1174. if (is_opt) {
  1175. tok->tp = K_OPT;
  1176. *s = eat_whitespace_no_nl(next);
  1177. next = strchr(*s,'\n');
  1178. if (!next)
  1179. RET_ERR("Unexpected EOF");
  1180. tok->args = tor_malloc(sizeof(char*));
  1181. tok->args[0] = tor_strndup(*s,next-*s);
  1182. tok->n_args = 1;
  1183. *s = eat_whitespace_no_nl(next+1);
  1184. o_syn = OBJ_OK;
  1185. } else {
  1186. tok->tp = _UNRECOGNIZED;
  1187. next = strchr(*s, '\n');
  1188. if (!next) {
  1189. RET_ERR("Unexpected EOF");
  1190. }
  1191. tok->args = tor_malloc(sizeof(char*));
  1192. tok->args[0] = tor_strndup(*s,next-*s);
  1193. tok->n_args = 1;
  1194. *s = next+1;
  1195. o_syn = OBJ_OK;
  1196. }
  1197. }
  1198. *s = eat_whitespace(*s);
  1199. if (strcmpstart(*s, "-----BEGIN ")) {
  1200. goto done_tokenizing;
  1201. }
  1202. obstart = *s;
  1203. *s += 11; /* length of "-----BEGIN ". */
  1204. next = strchr(*s, '\n');
  1205. if (next-*s < 6 || strcmpstart(next-5, "-----\n")) {
  1206. RET_ERR("Malformed object: bad begin line");
  1207. }
  1208. tok->object_type = tor_strndup(*s, next-*s-5);
  1209. *s = next+1;
  1210. next = strstr(*s, "-----END ");
  1211. if (!next) {
  1212. RET_ERR("Malformed object: missing end line");
  1213. }
  1214. if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) {
  1215. if (strcmpstart(next, "-----END RSA PUBLIC KEY-----\n"))
  1216. RET_ERR("Malformed object: mismatched end line");
  1217. next = strchr(next,'\n')+1;
  1218. tok->key = crypto_new_pk_env();
  1219. if (crypto_pk_read_public_key_from_string(tok->key, obstart, next-obstart))
  1220. RET_ERR("Couldn't parse public key.");
  1221. *s = next;
  1222. } else {
  1223. tok->object_body = tor_malloc(next-*s); /* really, this is too much RAM. */
  1224. i = base64_decode(tok->object_body, 256, *s, next-*s);
  1225. if (i<0) {
  1226. RET_ERR("Malformed object: bad base64-encoded data");
  1227. }
  1228. tok->object_size = i;
  1229. *s = next + 9; /* length of "-----END ". */
  1230. i = strlen(tok->object_type);
  1231. if (strncmp(*s, tok->object_type, i) || strcmpstart(*s+i, "-----\n")) {
  1232. RET_ERR("Malformed object: mismatched end tag");
  1233. }
  1234. *s += i+6;
  1235. }
  1236. switch (o_syn)
  1237. {
  1238. case NO_OBJ:
  1239. if (tok->object_body)
  1240. RET_ERR("Unexpected object for keyword");
  1241. if (tok->key)
  1242. RET_ERR("Unexpected public key for keyword");
  1243. break;
  1244. case NEED_OBJ:
  1245. if (!tok->object_body)
  1246. RET_ERR("Missing object for keyword");
  1247. break;
  1248. case NEED_KEY:
  1249. if (!tok->key)
  1250. RET_ERR("Missing public key for keyword");
  1251. break;
  1252. case OBJ_OK:
  1253. break;
  1254. }
  1255. done_tokenizing:
  1256. #if 0
  1257. for (i = 0; token_table[i].t ; ++i) {
  1258. if (token_table[i].v == tok->tp) {
  1259. fputs(token_table[i].t, stdout);
  1260. break;
  1261. i = -1;
  1262. }
  1263. }
  1264. if (i) {
  1265. if (tok->tp == _UNRECOGNIZED) fputs("UNRECOGNIZED", stdout);
  1266. if (tok->tp == _ERR) fputs("ERR",stdout);
  1267. if (tok->tp == _EOF) fputs("EOF",stdout);
  1268. if (tok->tp == _NIL) fputs("_NIL",stdout);
  1269. }
  1270. for (i = 0; i < tok->n_args; ++i) {
  1271. fprintf(stdout," \"%s\"", tok->args[i]);
  1272. }
  1273. if (tok->error) { fprintf(stdout," *%s*", tok->error); }
  1274. fputs("\n",stdout);
  1275. #endif
  1276. return tok;
  1277. #undef RET_ERR
  1278. }
  1279. /** Read all tokens from a string between <b>start</b> and <b>end</b>, and add
  1280. * them to <b>out</b>. If <b>is_dir</b> is true, reject all non-directory
  1281. * tokens; else reject all non-routerdescriptor tokens.
  1282. */
  1283. static int
  1284. tokenize_string(const char *start, const char *end, smartlist_t *out,
  1285. int is_dir)
  1286. {
  1287. const char **s;
  1288. directory_token_t *tok = NULL;
  1289. where_syntax where = is_dir ? DIR_ONLY : RTR_ONLY;
  1290. s = &start;
  1291. while (*s < end && (!tok || tok->tp != _EOF)) {
  1292. tok = get_next_token(s, where);
  1293. if (tok->tp == _ERR) {
  1294. log_fn(LOG_WARN, "parse error: %s", tok->error);
  1295. return -1;
  1296. }
  1297. smartlist_add(out, tok);
  1298. *s = eat_whitespace(*s);
  1299. }
  1300. return 0;
  1301. }
  1302. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
  1303. * NULL if no such keyword is found.
  1304. */
  1305. static directory_token_t *
  1306. find_first_by_keyword(smartlist_t *s, directory_keyword keyword)
  1307. {
  1308. SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
  1309. return NULL;
  1310. }
  1311. /** Return a newly allocated smartlist of all accept or reject tokens in
  1312. * <b>s</b>.
  1313. */
  1314. static smartlist_t *
  1315. find_all_exitpolicy(smartlist_t *s)
  1316. {
  1317. smartlist_t *out = smartlist_create();
  1318. SMARTLIST_FOREACH(s, directory_token_t *, t,
  1319. if (t->tp == K_ACCEPT || t->tp == K_REJECT)
  1320. smartlist_add(out,t));
  1321. return out;
  1322. }
  1323. /** Compute the SHA digest of the substring of <b>s</b> taken from the first
  1324. * occurrence of <b>start_str</b> through the first newline after the first
  1325. * subsequent occurrence of <b>end_str</b>; store the 20-byte result in
  1326. * <b>digest</b>; return 0 on success.
  1327. *
  1328. * If no such substring exists, return -1.
  1329. */
  1330. static int router_get_hash_impl(const char *s, char *digest,
  1331. const char *start_str,
  1332. const char *end_str)
  1333. {
  1334. char *start, *end;
  1335. start = strstr(s, start_str);
  1336. if (!start) {
  1337. log_fn(LOG_WARN,"couldn't find \"%s\"",start_str);
  1338. return -1;
  1339. }
  1340. if (start != s && *(start-1) != '\n') {
  1341. log_fn(LOG_WARN, "first occurrence of \"%s\" is not at the start of a line",
  1342. start_str);
  1343. return -1;
  1344. }
  1345. end = strstr(start+strlen(start_str), end_str);
  1346. if (!end) {
  1347. log_fn(LOG_WARN,"couldn't find \"%s\"",end_str);
  1348. return -1;
  1349. }
  1350. end = strchr(end+strlen(end_str), '\n');
  1351. if (!end) {
  1352. log_fn(LOG_WARN,"couldn't find EOL");
  1353. return -1;
  1354. }
  1355. ++end;
  1356. if (crypto_digest(digest, start, end-start)) {
  1357. log_fn(LOG_WARN,"couldn't compute digest");
  1358. return -1;
  1359. }
  1360. return 0;
  1361. }
  1362. /** Parse the Tor version of the platform string <b>platform</b>,
  1363. * and compare it to the version in <b>cutoff</b>. Return 1 if
  1364. * the router is at least as new as the cutoff, else return 0.
  1365. */
  1366. int tor_version_as_new_as(const char *platform, const char *cutoff) {
  1367. tor_version_t cutoff_version, router_version;
  1368. char *s, *start;
  1369. char tmp[128];
  1370. if (tor_version_parse(cutoff, &cutoff_version)<0) {
  1371. log_fn(LOG_WARN,"Bug: cutoff version '%s' unparseable.",cutoff);
  1372. return 0;
  1373. }
  1374. if (strcmpstart(platform,"Tor ")) /* nonstandard Tor; be safe and say yes */
  1375. return 1;
  1376. start = (char *)eat_whitespace(platform+3);
  1377. if (!*start) return 0;
  1378. s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
  1379. if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
  1380. return 0;
  1381. strlcpy(tmp, start, s-start+1);
  1382. if (tor_version_parse(tmp, &router_version)<0) {
  1383. log_fn(LOG_INFO,"Router version '%s' unparseable.",tmp);
  1384. return 1; /* be safe and say yes */
  1385. }
  1386. return tor_version_compare(&router_version, &cutoff_version) >= 0;
  1387. }
  1388. /** Parse a tor version from <b>s</b>, and store the result in <b>out</b>.
  1389. * Return 0 on success, -1 on failure. */
  1390. int tor_version_parse(const char *s, tor_version_t *out)
  1391. {
  1392. char *eos=NULL, *cp=NULL;
  1393. /* Format is:
  1394. * "Tor " ? NUM dot NUM dot NUM [ ( pre | rc | dot ) NUM [ -cvs ] ]
  1395. */
  1396. tor_assert(s);
  1397. tor_assert(out);
  1398. memset(out, 0, sizeof(tor_version_t));
  1399. if (!strcasecmpstart(s, "Tor "))
  1400. cp += 4;
  1401. /* Get major. */
  1402. out->major = strtol(s,&eos,10);
  1403. if (!eos || eos==s || *eos != '.') return -1;
  1404. cp = eos+1;
  1405. /* Get minor */
  1406. out->minor = strtol(cp,&eos,10);
  1407. if (!eos || eos==cp || *eos != '.') return -1;
  1408. cp = eos+1;
  1409. /* Get micro */
  1410. out->micro = strtol(cp,&eos,10);
  1411. if (!eos || eos==cp) return -1;
  1412. if (!*eos) {
  1413. out->status = VER_RELEASE;
  1414. out->patchlevel = 0;
  1415. out->cvs = IS_NOT_CVS;
  1416. return 0;
  1417. }
  1418. cp = eos;
  1419. /* Get status */
  1420. if (*cp == '.') {
  1421. out->status = VER_RELEASE;
  1422. ++cp;
  1423. } else if (0==strncmp(cp, "pre", 3)) {
  1424. out->status = VER_PRE;
  1425. cp += 3;
  1426. } else if (0==strncmp(cp, "rc", 2)) {
  1427. out->status = VER_RC;
  1428. cp += 2;
  1429. } else {
  1430. return -1;
  1431. }
  1432. /* Get patchlevel */
  1433. out->patchlevel = strtol(cp,&eos,10);
  1434. if (!eos || eos==cp) return -1;
  1435. cp = eos;
  1436. /* Get cvs status and status tag. */
  1437. if (*cp == '-' || *cp == '.')
  1438. ++cp;
  1439. strlcpy(out->status_tag, cp, sizeof(out->status_tag));
  1440. if (0==strcmp(cp, "cvs")) {
  1441. out->cvs = IS_CVS;
  1442. } else {
  1443. out->cvs = IS_NOT_CVS;
  1444. }
  1445. return 0;
  1446. }
  1447. /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
  1448. * b. */
  1449. int tor_version_compare(tor_version_t *a, tor_version_t *b)
  1450. {
  1451. int i;
  1452. tor_assert(a);
  1453. tor_assert(b);
  1454. if ((i = a->major - b->major))
  1455. return i;
  1456. else if ((i = a->minor - b->minor))
  1457. return i;
  1458. else if ((i = a->micro - b->micro))
  1459. return i;
  1460. else if ((i = a->status - b->status))
  1461. return i;
  1462. else if ((i = a->patchlevel - b->patchlevel))
  1463. return i;
  1464. if (a->major > 0 || a->minor > 0) {
  1465. return strcmp(a->status_tag, b->status_tag);
  1466. } else {
  1467. return (a->cvs - b->cvs);
  1468. }
  1469. }
  1470. static int
  1471. tor_version_same_series(tor_version_t *a, tor_version_t *b)
  1472. {
  1473. tor_assert(a);
  1474. tor_assert(b);
  1475. return ((a->major == b->major) &&
  1476. (a->minor == b->minor) &&
  1477. (a->micro == b->micro));
  1478. }