routerparse.c 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char routerparse_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file routerparse.c
  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_CONTACT,
  38. K_NETWORK_STATUS,
  39. K_UPTIME,
  40. K_DIR_SIGNING_KEY,
  41. K_FAMILY,
  42. K_FINGERPRINT,
  43. K_HIBERNATING,
  44. K_READ_HISTORY,
  45. K_WRITE_HISTORY,
  46. K_NETWORK_STATUS_VERSION,
  47. K_DIR_SOURCE,
  48. K_DIR_OPTIONS,
  49. K_CLIENT_VERSIONS,
  50. K_SERVER_VERSIONS,
  51. K_R,
  52. K_S,
  53. K_V,
  54. K_EVENTDNS,
  55. _UNRECOGNIZED,
  56. _ERR,
  57. _EOF,
  58. _NIL
  59. } directory_keyword;
  60. /** Structure to hold a single directory token.
  61. *
  62. * We parse a directory by breaking it into "tokens", each consisting
  63. * of a keyword, a line full of arguments, and a binary object. The
  64. * arguments and object are both optional, depending on the keyword
  65. * type.
  66. */
  67. typedef struct directory_token_t {
  68. directory_keyword tp; /**< Type of the token. */
  69. int n_args; /**< Number of elements in args */
  70. char **args; /**< Array of arguments from keyword line. */
  71. char *object_type; /**< -----BEGIN [object_type]-----*/
  72. size_t object_size; /**< Bytes in object_body */
  73. char *object_body; /**< Contents of object, base64-decoded. */
  74. crypto_pk_env_t *key; /**< For public keys only. */
  75. const char *error; /**< For _ERR tokens only. */
  76. } directory_token_t;
  77. /* ********************************************************************** */
  78. /** We use a table of rules to decide how to parse each token type. */
  79. /** Rules for how many arguments a keyword can take. */
  80. typedef enum {
  81. NO_ARGS, /**< No arguments, ever. */
  82. ARGS, /**< A list of arguments separated by spaces. */
  83. CONCAT_ARGS, /**< The rest of the line, treated as a single argument. */
  84. } arg_syntax;
  85. /** Rules for whether the keyword needs an object. */
  86. typedef enum {
  87. NO_OBJ, /**< No object, ever. */
  88. NEED_OBJ, /**< Object is required. */
  89. NEED_KEY, /**< Object is required, and must be a public key. */
  90. OBJ_OK, /**< Object is optional. */
  91. } obj_syntax;
  92. /** Rules for where a keyword can appear. */
  93. typedef enum {
  94. DIR = 1, /**< Appears only in directory. */
  95. RTR = 2, /**< Appears only in router descriptor or runningrouters. */
  96. NETSTATUS = 4, /**< v2 or later ("versioned") network status. */
  97. ANYSIGNED = 7, /**< Any "full" document (that is, not a router status.) */
  98. RTRSTATUS = 8, /**< Router-status portion of a versioned network status. */
  99. ANY = 15, /**< Appears in any document type. */
  100. } where_syntax;
  101. /** Table mapping keywords to token value and to argument rules. */
  102. static struct {
  103. const char *t; directory_keyword v; arg_syntax s; obj_syntax os; int ws;
  104. } token_table[] = {
  105. { "accept", K_ACCEPT, ARGS, NO_OBJ, RTR },
  106. { "directory-signature", K_DIRECTORY_SIGNATURE, ARGS, NEED_OBJ,
  107. DIR|NETSTATUS},
  108. { "r", K_R, ARGS, NO_OBJ, RTRSTATUS },
  109. { "s", K_S, ARGS, NO_OBJ, RTRSTATUS },
  110. { "v", K_V, CONCAT_ARGS, NO_OBJ, RTRSTATUS },
  111. { "reject", K_REJECT, ARGS, NO_OBJ, RTR },
  112. { "router", K_ROUTER, ARGS, NO_OBJ, RTR },
  113. { "recommended-software",K_RECOMMENDED_SOFTWARE,ARGS, NO_OBJ, DIR },
  114. { "signed-directory", K_SIGNED_DIRECTORY, NO_ARGS, NO_OBJ, DIR },
  115. { "signing-key", K_SIGNING_KEY, NO_ARGS, NEED_KEY,RTR },
  116. { "onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY,RTR },
  117. { "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ,RTR },
  118. { "running-routers", K_RUNNING_ROUTERS, ARGS, NO_OBJ, DIR },
  119. { "router-status", K_ROUTER_STATUS, ARGS, NO_OBJ, DIR },
  120. { "bandwidth", K_BANDWIDTH, ARGS, NO_OBJ, RTR },
  121. { "platform", K_PLATFORM, CONCAT_ARGS, NO_OBJ, RTR },
  122. { "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ, ANYSIGNED },
  123. { "opt", K_OPT, CONCAT_ARGS, OBJ_OK, ANY },
  124. { "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ, ANYSIGNED },
  125. { "network-status", K_NETWORK_STATUS, NO_ARGS, NO_OBJ, DIR },
  126. { "uptime", K_UPTIME, ARGS, NO_OBJ, RTR },
  127. { "dir-signing-key", K_DIR_SIGNING_KEY, ARGS, OBJ_OK,
  128. DIR|NETSTATUS},
  129. { "family", K_FAMILY, ARGS, NO_OBJ, RTR },
  130. { "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ, ANYSIGNED },
  131. { "hibernating", K_HIBERNATING, ARGS, NO_OBJ, RTR },
  132. { "read-history", K_READ_HISTORY, ARGS, NO_OBJ, RTR },
  133. { "write-history", K_WRITE_HISTORY, ARGS, NO_OBJ, RTR },
  134. { "network-status-version", K_NETWORK_STATUS_VERSION,
  135. ARGS, NO_OBJ, NETSTATUS },
  136. { "dir-source", K_DIR_SOURCE, ARGS, NO_OBJ, NETSTATUS },
  137. { "dir-options", K_DIR_OPTIONS, ARGS, NO_OBJ, NETSTATUS },
  138. { "client-versions", K_CLIENT_VERSIONS, ARGS, NO_OBJ, NETSTATUS },
  139. { "server-versions", K_SERVER_VERSIONS, ARGS, NO_OBJ, NETSTATUS },
  140. { "eventdns", K_EVENTDNS, ARGS, NO_OBJ, RTR },
  141. { NULL, _NIL, NO_ARGS, NO_OBJ, ANY }
  142. };
  143. /* static function prototypes */
  144. static int router_add_exit_policy(routerinfo_t *router,directory_token_t *tok);
  145. static addr_policy_t *router_parse_addr_policy(directory_token_t *tok);
  146. static addr_policy_t *router_parse_addr_policy_private(directory_token_t *tok);
  147. static int router_get_hash_impl(const char *s, char *digest,
  148. const char *start_str, const char *end_str);
  149. static void token_free(directory_token_t *tok);
  150. static smartlist_t *find_all_exitpolicy(smartlist_t *s);
  151. static directory_token_t *find_first_by_keyword(smartlist_t *s,
  152. directory_keyword keyword);
  153. static int tokenize_string(const char *start, const char *end,
  154. smartlist_t *out, where_syntax where);
  155. static directory_token_t *get_next_token(const char **s, where_syntax where);
  156. static int check_directory_signature(const char *digest,
  157. directory_token_t *tok,
  158. crypto_pk_env_t *pkey,
  159. crypto_pk_env_t *declared_key,
  160. int check_authority);
  161. static crypto_pk_env_t *find_dir_signing_key(const char *str);
  162. static int tor_version_same_series(tor_version_t *a, tor_version_t *b);
  163. /** Set <b>digest</b> to the SHA-1 digest of the hash of the directory in
  164. * <b>s</b>. Return 0 on success, -1 on failure.
  165. */
  166. int
  167. router_get_dir_hash(const char *s, char *digest)
  168. {
  169. return router_get_hash_impl(s,digest,
  170. "signed-directory","\ndirectory-signature");
  171. }
  172. /** Set <b>digest</b> to the SHA-1 digest of the hash of the first router in
  173. * <b>s</b>. Return 0 on success, -1 on failure.
  174. */
  175. int
  176. router_get_router_hash(const char *s, char *digest)
  177. {
  178. return router_get_hash_impl(s,digest,
  179. "router ","\nrouter-signature");
  180. }
  181. /** Set <b>digest</b> to the SHA-1 digest of the hash of the running-routers
  182. * string in <b>s</b>. Return 0 on success, -1 on failure.
  183. */
  184. int
  185. router_get_runningrouters_hash(const char *s, char *digest)
  186. {
  187. return router_get_hash_impl(s,digest,
  188. "network-status","\ndirectory-signature");
  189. }
  190. /** Set <b>digest</b> to the SHA-1 digest of the hash of the network-status
  191. * string in <b>s</b>. Return 0 on success, -1 on failure. */
  192. int
  193. router_get_networkstatus_v2_hash(const char *s, char *digest)
  194. {
  195. return router_get_hash_impl(s,digest,
  196. "network-status-version","\ndirectory-signature");
  197. }
  198. /** Helper: used to generate signatures for routers, directories and
  199. * network-status objects. Given a digest in <b>digest</b> and a secret
  200. * <b>private_key</b>, generate an PKCS1-padded signature, BASE64-encode it,
  201. * surround it with -----BEGIN/END----- pairs, and write it to the
  202. * <b>buf_len</b>-byte buffer at <b>buf</b>. Return 0 on success, -1 on
  203. * failure.
  204. */
  205. int
  206. router_append_dirobj_signature(char *buf, size_t buf_len, const char *digest,
  207. crypto_pk_env_t *private_key)
  208. {
  209. char signature[PK_BYTES];
  210. int i;
  211. if (crypto_pk_private_sign(private_key, signature, digest, DIGEST_LEN) < 0) {
  212. log_warn(LD_BUG,"Couldn't sign digest.");
  213. return -1;
  214. }
  215. if (strlcat(buf, "-----BEGIN SIGNATURE-----\n", buf_len) >= buf_len)
  216. goto truncated;
  217. i = strlen(buf);
  218. if (base64_encode(buf+i, buf_len-i, signature, 128) < 0) {
  219. log_warn(LD_BUG,"couldn't base64-encode signature");
  220. tor_free(buf);
  221. return -1;
  222. }
  223. if (strlcat(buf, "-----END SIGNATURE-----\n", buf_len) >= buf_len)
  224. goto truncated;
  225. return 0;
  226. truncated:
  227. log_warn(LD_BUG,"tried to exceed string length.");
  228. return -1;
  229. }
  230. /** Return VS_RECOMMENDED if <b>myversion</b> is contained in
  231. * <b>versionlist</b>. Else, return VS_OLD if every member of
  232. * <b>versionlist</b> is newer than <b>myversion</b>. Else, return
  233. * VS_NEW_IN_SERIES if there is at least one member of <b>versionlist</b> in
  234. * the same series (major.minor.micro) as <b>myversion</b>, but no such member
  235. * is newer than <b>myversion.</b>. Else, return VS_NEW if every memeber of
  236. * <b>versionlist</b> is older than <b>myversion</b>. Else, return
  237. * VS_UNRECOMMENDED.
  238. *
  239. * (versionlist is a comma-separated list of version strings,
  240. * optionally prefixed with "Tor". Versions that can't be parsed are
  241. * ignored.)
  242. */
  243. version_status_t
  244. tor_version_is_obsolete(const char *myversion, const char *versionlist)
  245. {
  246. tor_version_t mine, other;
  247. int found_newer = 0, found_older = 0, found_newer_in_series = 0,
  248. found_any_in_series = 0, r, same;
  249. version_status_t ret = VS_UNRECOMMENDED;
  250. smartlist_t *version_sl;
  251. log_debug(LD_CONFIG,"Checking whether version '%s' is in '%s'",
  252. myversion, versionlist);
  253. if (tor_version_parse(myversion, &mine)) {
  254. log_err(LD_BUG,"I couldn't parse my own version (%s)", myversion);
  255. tor_assert(0);
  256. }
  257. version_sl = smartlist_create();
  258. smartlist_split_string(version_sl, versionlist, ",", SPLIT_SKIP_SPACE, 0);
  259. SMARTLIST_FOREACH(version_sl, const char *, cp, {
  260. if (!strcmpstart(cp, "Tor "))
  261. cp += 4;
  262. if (tor_version_parse(cp, &other)) {
  263. /* Couldn't parse other; it can't be a match. */
  264. } else {
  265. same = tor_version_same_series(&mine, &other);
  266. if (same)
  267. found_any_in_series = 1;
  268. r = tor_version_compare(&mine, &other);
  269. if (r==0) {
  270. ret = VS_RECOMMENDED;
  271. goto done;
  272. } else if (r<0) {
  273. found_newer = 1;
  274. if (same)
  275. found_newer_in_series = 1;
  276. } else if (r>0) {
  277. found_older = 1;
  278. }
  279. }
  280. });
  281. /* We didn't find the listed version. Is it new or old? */
  282. if (found_any_in_series && !found_newer_in_series && found_newer) {
  283. ret = VS_NEW_IN_SERIES;
  284. } else if (found_newer && !found_older) {
  285. ret = VS_OLD;
  286. } else if (found_older && !found_newer) {
  287. ret = VS_NEW;
  288. } else {
  289. ret = VS_UNRECOMMENDED;
  290. }
  291. done:
  292. SMARTLIST_FOREACH(version_sl, char *, version, tor_free(version));
  293. smartlist_free(version_sl);
  294. return ret;
  295. }
  296. /** Return the combined status of the current version, given that we know of
  297. * one set of networkstatuses that give us status <b>a</b>, and another that
  298. * gives us status <b>b</b>.
  299. *
  300. * For example, if one authority thinks that we're NEW, and another thinks
  301. * we're OLD, we're simply UNRECOMMENDED.
  302. *
  303. * This function does not handle calculating whether we're RECOMMENDED; that
  304. * follows a simple majority rule. This function simply calculates *why*
  305. * we're not recommended (if we're not).
  306. */
  307. version_status_t
  308. version_status_join(version_status_t a, version_status_t b)
  309. {
  310. if (a == b)
  311. return a;
  312. else if (a == VS_UNRECOMMENDED || b == VS_UNRECOMMENDED)
  313. return VS_UNRECOMMENDED;
  314. else if (a == VS_RECOMMENDED)
  315. return b;
  316. else if (b == VS_RECOMMENDED)
  317. return a;
  318. /* Okay. Neither is 'recommended' or 'unrecommended', and they differ. */
  319. else if (a == VS_OLD || b == VS_OLD)
  320. return VS_UNRECOMMENDED;
  321. /* One is VS_NEW, the other is VS_NEW_IN_SERIES */
  322. else
  323. return VS_NEW_IN_SERIES;
  324. }
  325. /** Read a signed directory from <b>str</b>. If it's well-formed, return 0.
  326. * Otherwise, return -1. If we're a directory cache, cache it.
  327. */
  328. int
  329. router_parse_directory(const char *str)
  330. {
  331. directory_token_t *tok;
  332. char digest[DIGEST_LEN];
  333. time_t published_on;
  334. int r;
  335. const char *end, *cp;
  336. smartlist_t *tokens = NULL;
  337. crypto_pk_env_t *declared_key = NULL;
  338. /* XXXX This could be simplified a lot, but it will all go away
  339. * once pre-0.1.1.8 is obsolete, and for now it's better not to
  340. * touch it. */
  341. if (router_get_dir_hash(str, digest)) {
  342. log_warn(LD_DIR, "Unable to compute digest of directory");
  343. goto err;
  344. }
  345. log_debug(LD_DIR,"Received directory hashes to %s",hex_str(digest,4));
  346. /* Check signature first, before we try to tokenize. */
  347. cp = str;
  348. while (cp && (end = strstr(cp+1, "\ndirectory-signature")))
  349. cp = end;
  350. if (cp == str || !cp) {
  351. log_warn(LD_DIR, "No signature found on directory."); goto err;
  352. }
  353. ++cp;
  354. tokens = smartlist_create();
  355. if (tokenize_string(cp,strchr(cp,'\0'),tokens,DIR)) {
  356. log_warn(LD_DIR, "Error tokenizing directory signature"); goto err;
  357. }
  358. if (smartlist_len(tokens) != 1) {
  359. log_warn(LD_DIR, "Unexpected number of tokens in signature"); goto err;
  360. }
  361. tok=smartlist_get(tokens,0);
  362. if (tok->tp != K_DIRECTORY_SIGNATURE) {
  363. log_warn(LD_DIR,"Expected a single directory signature"); goto err;
  364. }
  365. declared_key = find_dir_signing_key(str);
  366. note_crypto_pk_op(VERIFY_DIR);
  367. if (check_directory_signature(digest, tok, NULL, declared_key, 1)<0)
  368. goto err;
  369. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  370. smartlist_free(tokens);
  371. tokens = NULL;
  372. /* Now try to parse the first part of the directory. */
  373. if ((end = strstr(str,"\nrouter "))) {
  374. ++end;
  375. } else if ((end = strstr(str, "\ndirectory-signature"))) {
  376. ++end;
  377. } else {
  378. end = str + strlen(str);
  379. }
  380. tokens = smartlist_create();
  381. if (tokenize_string(str,end,tokens,DIR)) {
  382. log_warn(LD_DIR, "Error tokenizing directory"); goto err;
  383. }
  384. if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
  385. log_warn(LD_DIR, "Missing published time on directory.");
  386. goto err;
  387. }
  388. tor_assert(tok->n_args == 1);
  389. if (parse_iso_time(tok->args[0], &published_on) < 0) {
  390. goto err;
  391. }
  392. /* Now that we know the signature is okay, and we have a
  393. * publication time, cache the directory. */
  394. if (get_options()->DirPort && !get_options()->V1AuthoritativeDir)
  395. dirserv_set_cached_directory(str, published_on, 0);
  396. r = 0;
  397. goto done;
  398. err:
  399. r = -1;
  400. done:
  401. if (declared_key) crypto_free_pk_env(declared_key);
  402. if (tokens) {
  403. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  404. smartlist_free(tokens);
  405. }
  406. return r;
  407. }
  408. /** Read a signed router status statement from <b>str</b>. If it's
  409. * well-formed, return 0. Otherwise, return -1. If we're a directory cache,
  410. * cache it.*/
  411. int
  412. router_parse_runningrouters(const char *str)
  413. {
  414. char digest[DIGEST_LEN];
  415. directory_token_t *tok;
  416. time_t published_on;
  417. int r = -1;
  418. crypto_pk_env_t *declared_key = NULL;
  419. smartlist_t *tokens = NULL;
  420. if (router_get_runningrouters_hash(str, digest)) {
  421. log_warn(LD_DIR, "Unable to compute digest of running-routers");
  422. goto err;
  423. }
  424. tokens = smartlist_create();
  425. if (tokenize_string(str,str+strlen(str),tokens,DIR)) {
  426. log_warn(LD_DIR, "Error tokenizing running-routers"); goto err;
  427. }
  428. tok = smartlist_get(tokens,0);
  429. if (tok->tp != K_NETWORK_STATUS) {
  430. log_warn(LD_DIR, "Network-status starts with wrong token");
  431. goto err;
  432. }
  433. if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
  434. log_warn(LD_DIR, "Missing published time on running-routers.");
  435. goto err;
  436. }
  437. tor_assert(tok->n_args == 1);
  438. if (parse_iso_time(tok->args[0], &published_on) < 0) {
  439. goto err;
  440. }
  441. if (!(tok = find_first_by_keyword(tokens, K_DIRECTORY_SIGNATURE))) {
  442. log_warn(LD_DIR, "Missing signature on running-routers");
  443. goto err;
  444. }
  445. declared_key = find_dir_signing_key(str);
  446. note_crypto_pk_op(VERIFY_DIR);
  447. if (check_directory_signature(digest, tok, NULL, declared_key, 1) < 0)
  448. goto err;
  449. /* Now that we know the signature is okay, and we have a
  450. * publication time, cache the list. */
  451. if (get_options()->DirPort && !get_options()->V1AuthoritativeDir)
  452. dirserv_set_cached_directory(str, published_on, 1);
  453. r = 0;
  454. err:
  455. if (declared_key) crypto_free_pk_env(declared_key);
  456. if (tokens) {
  457. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  458. smartlist_free(tokens);
  459. }
  460. return r;
  461. }
  462. /** Given a directory or running-routers string in <b>str</b>, try to
  463. * find the its dir-signing-key token (if any). If this token is
  464. * present, extract and return the key. Return NULL on failure. */
  465. static crypto_pk_env_t *
  466. find_dir_signing_key(const char *str)
  467. {
  468. const char *cp;
  469. directory_token_t *tok;
  470. crypto_pk_env_t *key = NULL;
  471. /* Is there a dir-signing-key in the directory? */
  472. cp = strstr(str, "\nopt dir-signing-key");
  473. if (!cp)
  474. cp = strstr(str, "\ndir-signing-key");
  475. if (!cp)
  476. return NULL;
  477. ++cp; /* Now cp points to the start of the token. */
  478. tok = get_next_token(&cp, DIR);
  479. if (!tok) {
  480. log_warn(LD_DIR, "Unparseable dir-signing-key token");
  481. return NULL;
  482. }
  483. if (tok->tp != K_DIR_SIGNING_KEY) {
  484. log_warn(LD_DIR, "Dir-signing-key token did not parse as expected");
  485. return NULL;
  486. }
  487. if (tok->key) {
  488. key = tok->key;
  489. tok->key = NULL; /* steal reference. */
  490. } else {
  491. log_warn(LD_DIR, "Dir-signing-key token contained no key");
  492. return NULL;
  493. }
  494. token_free(tok);
  495. return key;
  496. }
  497. /** Return true iff <b>key</b> is allowed to sign directories.
  498. */
  499. static int
  500. dir_signing_key_is_trusted(crypto_pk_env_t *key)
  501. {
  502. char digest[DIGEST_LEN];
  503. if (!key) return 0;
  504. if (crypto_pk_get_digest(key, digest) < 0) {
  505. log_warn(LD_DIR, "Error computing dir-signing-key digest");
  506. return 0;
  507. }
  508. if (!router_digest_is_trusted_dir(digest)) {
  509. log_warn(LD_DIR, "Listed dir-signing-key is not trusted");
  510. return 0;
  511. }
  512. return 1;
  513. }
  514. /** Check whether the K_DIRECTORY_SIGNATURE token in <b>tok</b> has a
  515. * good signature for <b>digest</b>.
  516. *
  517. * If <b>declared_key</b> is set, the directory has declared what key
  518. * was used to sign it, so we will use that key only if it is an
  519. * authoritative directory signing key or if check_authority is 0.
  520. *
  521. * Otherwise, if pkey is provided, try to use it.
  522. *
  523. * (New callers should always use <b>declared_key</b> when possible;
  524. * <b>pkey</b> is only for debugging.)
  525. */
  526. static int
  527. check_directory_signature(const char *digest,
  528. directory_token_t *tok,
  529. crypto_pk_env_t *pkey,
  530. crypto_pk_env_t *declared_key,
  531. int check_authority)
  532. {
  533. char signed_digest[PK_BYTES];
  534. crypto_pk_env_t *_pkey = NULL;
  535. if (tok->n_args != 1) {
  536. log_warn(LD_DIR, "Too many or too few arguments to directory-signature");
  537. return -1;
  538. }
  539. if (declared_key) {
  540. if (!check_authority || dir_signing_key_is_trusted(declared_key))
  541. _pkey = declared_key;
  542. }
  543. if (!_pkey && pkey) {
  544. /* pkey provided for debugging purposes */
  545. _pkey = pkey;
  546. }
  547. if (!_pkey) {
  548. log_warn(LD_DIR,
  549. "Obsolete directory format (dir signing key not present) or "
  550. "signing key not trusted--rejecting.");
  551. return -1;
  552. }
  553. if (strcmp(tok->object_type, "SIGNATURE") || tok->object_size != 128) {
  554. log_warn(LD_DIR, "Bad object type or length on directory signature");
  555. return -1;
  556. }
  557. tor_assert(_pkey);
  558. if (crypto_pk_public_checksig(_pkey, signed_digest, tok->object_body, 128)
  559. != 20) {
  560. log_warn(LD_DIR, "Error reading directory: invalid signature.");
  561. return -1;
  562. }
  563. log_debug(LD_DIR,"Signed directory hash starts %s",
  564. hex_str(signed_digest,4));
  565. if (memcmp(digest, signed_digest, DIGEST_LEN)) {
  566. log_warn(LD_DIR, "Error reading directory: signature does not match.");
  567. return -1;
  568. }
  569. return 0;
  570. }
  571. /** Given a string *<b>s</b> containing a concatenated sequence of router
  572. * descriptors, parses them and stores the result in <b>dest</b>. All routers
  573. * are marked running and valid. Advances *s to a point immediately
  574. * following the last router entry. Ignore any trailing router entries that
  575. * are not complete.
  576. *
  577. * If <b>saved_location</b> isn't SAVED_IN_CACHE, make a local copy of each
  578. * descriptor in the signed_descriptor_body field of each routerinfo_t. If it
  579. * isn't SAVED_NOWHERE, remember the offset of each descriptor.
  580. *
  581. * Returns 0 on success and -1 on failure.
  582. */
  583. int
  584. router_parse_list_from_string(const char **s, smartlist_t *dest,
  585. saved_location_t saved_location)
  586. {
  587. routerinfo_t *router;
  588. const char *end, *cp, *start;
  589. tor_assert(s);
  590. tor_assert(*s);
  591. tor_assert(dest);
  592. start = *s;
  593. while (1) {
  594. *s = eat_whitespace(*s);
  595. /* Don't start parsing the rest of *s unless it contains a router. */
  596. if (strcmpstart(*s, "router ")!=0)
  597. break;
  598. if ((end = strstr(*s+1, "\nrouter "))) {
  599. cp = end;
  600. end++;
  601. } else if ((end = strstr(*s+1, "\ndirectory-signature"))) {
  602. cp = end;
  603. end++;
  604. } else {
  605. cp = end = *s+strlen(*s);
  606. }
  607. while (cp > *s && (!*cp || TOR_ISSPACE(*cp)))
  608. --cp;
  609. /* cp now points to the last non-space character in this descriptor. */
  610. while (cp > *s && *cp != '\n')
  611. --cp;
  612. /* cp now points to the first \n before the last non-blank line in this
  613. * descriptor */
  614. if (strcmpstart(cp, "\n-----END SIGNATURE-----\n")) {
  615. log_info(LD_DIR, "Ignoring truncated router descriptor.");
  616. *s = end;
  617. continue;
  618. }
  619. router = router_parse_entry_from_string(*s, end,
  620. saved_location != SAVED_IN_CACHE);
  621. if (!router) {
  622. log_warn(LD_DIR, "Error reading router; skipping");
  623. *s = end;
  624. continue;
  625. }
  626. if (saved_location != SAVED_NOWHERE) {
  627. router->cache_info.saved_location = saved_location;
  628. router->cache_info.saved_offset = *s - start;
  629. }
  630. *s = end;
  631. smartlist_add(dest, router);
  632. }
  633. return 0;
  634. }
  635. /* For debugging: define to count every descriptor digest we've seen so we
  636. * know if we need to try harder to avoid duplicate verifies. */
  637. #undef COUNT_DISTINCT_DIGESTS
  638. #ifdef COUNT_DISTINCT_DIGESTS
  639. static digestmap_t *verified_digests = NULL;
  640. #endif
  641. /** Log the total count of the number of distinct router digests we've ever
  642. * verified. When compared to the number of times we've verified routerdesc
  643. * signatures <i>in toto</i>, this will tell us if we're doing too much
  644. * multiple-verification. */
  645. void
  646. dump_distinct_digest_count(int severity)
  647. {
  648. #ifdef COUNT_DISTINCT_DIGESTS
  649. if (!verified_digests)
  650. verified_digests = digestmap_new();
  651. log(severity, LD_GENERAL, "%d *distinct* router digests verified",
  652. digestmap_size(verified_digests));
  653. #else
  654. (void)severity; /* suppress "unused parameter" warning */
  655. #endif
  656. }
  657. /** Helper function: reads a single router entry from *<b>s</b> ...
  658. * *<b>end</b>. Mallocs a new router and returns it if all goes well, else
  659. * returns NULL. If <b>cache_copy</b> is true, duplicate the contents of
  660. * s through end into the signed_descriptor_body of the resulting
  661. * routerinfo_t.
  662. */
  663. routerinfo_t *
  664. router_parse_entry_from_string(const char *s, const char *end,
  665. int cache_copy)
  666. {
  667. routerinfo_t *router = NULL;
  668. char signed_digest[128];
  669. char digest[128];
  670. smartlist_t *tokens = NULL, *exit_policy_tokens = NULL;
  671. directory_token_t *tok;
  672. int t;
  673. struct in_addr in;
  674. if (!end) {
  675. end = s + strlen(s);
  676. }
  677. /* point 'end' to a point immediately after the final newline. */
  678. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  679. --end;
  680. if (router_get_router_hash(s, digest) < 0) {
  681. log_warn(LD_DIR, "Couldn't compute router hash.");
  682. return NULL;
  683. }
  684. tokens = smartlist_create();
  685. if (tokenize_string(s,end,tokens,RTR)) {
  686. log_warn(LD_DIR, "Error tokeninzing router descriptor.");
  687. goto err;
  688. }
  689. if (smartlist_len(tokens) < 2) {
  690. log_warn(LD_DIR, "Impossibly short router descriptor.");
  691. goto err;
  692. }
  693. tok = smartlist_get(tokens,0);
  694. if (tok->tp != K_ROUTER) {
  695. log_warn(LD_DIR,"Entry does not start with \"router\"");
  696. goto err;
  697. }
  698. router = tor_malloc_zero(sizeof(routerinfo_t));
  699. router->routerlist_index = -1;
  700. if (cache_copy)
  701. router->cache_info.signed_descriptor_body = tor_strndup(s, end-s);
  702. router->cache_info.signed_descriptor_len = end-s;
  703. memcpy(router->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  704. if (tok->n_args >= 5) {
  705. router->nickname = tor_strdup(tok->args[0]);
  706. if (!is_legal_nickname(router->nickname)) {
  707. log_warn(LD_DIR,"Router nickname is invalid");
  708. goto err;
  709. }
  710. router->address = tor_strdup(tok->args[1]);
  711. if (!tor_inet_aton(router->address, &in)) {
  712. log_warn(LD_DIR,"Router address is not an IP.");
  713. goto err;
  714. }
  715. router->addr = ntohl(in.s_addr);
  716. router->or_port =
  717. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
  718. router->dir_port =
  719. (uint16_t) tor_parse_long(tok->args[4],10,0,65535,NULL,NULL);
  720. } else {
  721. log_warn(LD_DIR,"Wrong # of arguments to \"router\" (%d)",tok->n_args);
  722. goto err;
  723. }
  724. tok = find_first_by_keyword(tokens, K_BANDWIDTH);
  725. if (!tok) {
  726. log_warn(LD_DIR,"No bandwidth declared; failing.");
  727. goto err;
  728. } else {
  729. if (tok->n_args < 3) {
  730. log_warn(LD_DIR,
  731. "Not enough arguments to \"bandwidth\" in server descriptor.");
  732. goto err;
  733. }
  734. router->bandwidthrate =
  735. tor_parse_long(tok->args[0],10,0,INT_MAX,NULL,NULL);
  736. if (!router->bandwidthrate) {
  737. log_warn(LD_DIR, "bandwidthrate %s unreadable or 0. Failing.",
  738. escaped(tok->args[0]));
  739. goto err;
  740. }
  741. router->bandwidthburst =
  742. tor_parse_long(tok->args[1],10,0,INT_MAX,NULL,NULL);
  743. router->bandwidthcapacity =
  744. tor_parse_long(tok->args[2],10,0,INT_MAX,NULL,NULL);
  745. /* XXX we don't error-check these values? -RD */
  746. }
  747. if ((tok = find_first_by_keyword(tokens, K_UPTIME))) {
  748. if (tok->n_args != 1) {
  749. log_warn(LD_DIR, "Unrecognized number of args on K_UPTIME; skipping.");
  750. } else {
  751. router->uptime = tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL);
  752. }
  753. }
  754. if ((tok = find_first_by_keyword(tokens, K_HIBERNATING))) {
  755. if (tok->n_args < 1) {
  756. log_warn(LD_DIR, "Too few args on 'hibernating' keyword. Skipping.");
  757. } else {
  758. router->is_hibernating
  759. = (tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL) != 0);
  760. }
  761. }
  762. if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
  763. log_warn(LD_DIR, "Missing published time on router descriptor"); goto err;
  764. }
  765. tor_assert(tok->n_args == 1);
  766. if (parse_iso_time(tok->args[0], &router->cache_info.published_on) < 0)
  767. goto err;
  768. if (!(tok = find_first_by_keyword(tokens, K_ONION_KEY))) {
  769. log_warn(LD_DIR, "Missing onion key"); goto err;
  770. }
  771. if (crypto_pk_keysize(tok->key) != PK_BYTES) {
  772. log_warn(LD_DIR, "Wrong size on onion key: %d bits!",
  773. (int)crypto_pk_keysize(tok->key)*8);
  774. goto err;
  775. }
  776. router->onion_pkey = tok->key;
  777. tok->key = NULL; /* Prevent free */
  778. if (!(tok = find_first_by_keyword(tokens, K_SIGNING_KEY))) {
  779. log_warn(LD_DIR, "Missing identity key"); goto err;
  780. }
  781. if (crypto_pk_keysize(tok->key) != PK_BYTES) {
  782. log_warn(LD_DIR, "Wrong size on identity key: %d bits!",
  783. (int)crypto_pk_keysize(tok->key)*8);
  784. goto err;
  785. }
  786. router->identity_pkey = tok->key;
  787. tok->key = NULL; /* Prevent free */
  788. if (crypto_pk_get_digest(router->identity_pkey,
  789. router->cache_info.identity_digest)) {
  790. log_warn(LD_DIR, "Couldn't calculate key digest"); goto err;
  791. }
  792. if ((tok = find_first_by_keyword(tokens, K_FINGERPRINT))) {
  793. /* If there's a fingerprint line, it must match the identity digest. */
  794. char d[DIGEST_LEN];
  795. if (tok->n_args < 1) {
  796. log_warn(LD_DIR, "Too few arguments to router fingerprint");
  797. goto err;
  798. }
  799. tor_strstrip(tok->args[0], " ");
  800. if (base16_decode(d, DIGEST_LEN, tok->args[0], strlen(tok->args[0]))) {
  801. log_warn(LD_DIR, "Couldn't decode router fingerprint %s",
  802. escaped(tok->args[0]));
  803. goto err;
  804. }
  805. if (memcmp(d,router->cache_info.identity_digest, DIGEST_LEN)!=0) {
  806. log_warn(LD_DIR, "Fingerprint '%s' does not match identity digest.",
  807. tok->args[0]);
  808. goto err;
  809. }
  810. }
  811. if ((tok = find_first_by_keyword(tokens, K_PLATFORM))) {
  812. router->platform = tor_strdup(tok->args[0]);
  813. }
  814. if ((tok = find_first_by_keyword(tokens, K_CONTACT))) {
  815. router->contact_info = tor_strdup(tok->args[0]);
  816. }
  817. if ((tok = find_first_by_keyword(tokens, K_EVENTDNS))) {
  818. router->has_old_dnsworkers = tok->n_args && !strcmp(tok->args[0], "0");
  819. } else if (router->platform) {
  820. if (! tor_version_as_new_as(router->platform, "0.1.2.2-alpha"))
  821. router->has_old_dnsworkers = 1;
  822. }
  823. exit_policy_tokens = find_all_exitpolicy(tokens);
  824. SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
  825. if (router_add_exit_policy(router,t)<0) {
  826. log_warn(LD_DIR,"Error in exit policy");
  827. goto err;
  828. });
  829. if ((tok = find_first_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
  830. int i;
  831. router->declared_family = smartlist_create();
  832. for (i=0;i<tok->n_args;++i) {
  833. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  834. log_warn(LD_DIR, "Illegal nickname %s in family line",
  835. escaped(tok->args[i]));
  836. goto err;
  837. }
  838. smartlist_add(router->declared_family, tor_strdup(tok->args[i]));
  839. }
  840. }
  841. if (!(tok = find_first_by_keyword(tokens, K_ROUTER_SIGNATURE))) {
  842. log_warn(LD_DIR, "Missing router signature");
  843. goto err;
  844. }
  845. if (strcmp(tok->object_type, "SIGNATURE") || tok->object_size != 128) {
  846. log_warn(LD_DIR, "Bad object type or length on router signature");
  847. goto err;
  848. }
  849. note_crypto_pk_op(VERIFY_RTR);
  850. #ifdef COUNT_DISTINCT_DIGESTS
  851. if (!verified_digests)
  852. verified_digests = digestmap_new();
  853. digestmap_set(verified_digests, signed_digest, (void*)(uintptr_t)1);
  854. #endif
  855. if ((t=crypto_pk_public_checksig(router->identity_pkey, signed_digest,
  856. tok->object_body, 128)) != 20) {
  857. log_warn(LD_DIR, "Invalid signature %d",t);
  858. goto err;
  859. }
  860. if (memcmp(digest, signed_digest, DIGEST_LEN)) {
  861. log_warn(LD_DIR, "Mismatched signature");
  862. goto err;
  863. }
  864. if (!router->or_port) {
  865. log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
  866. goto err;
  867. }
  868. if (!router->platform) {
  869. router->platform = tor_strdup("<unknown>");
  870. }
  871. goto done;
  872. err:
  873. routerinfo_free(router);
  874. router = NULL;
  875. done:
  876. if (tokens) {
  877. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  878. smartlist_free(tokens);
  879. }
  880. if (exit_policy_tokens) {
  881. smartlist_free(exit_policy_tokens);
  882. }
  883. return router;
  884. }
  885. /** Helper: given a string <b>s</b>, return the start of the next router-status
  886. * object (starting with "r " at the start of a line). If none is found,
  887. * return the start of the next directory signature. If none is found, return
  888. * the end of the string. */
  889. static INLINE const char *
  890. find_start_of_next_routerstatus(const char *s)
  891. {
  892. const char *eos = strstr(s, "\nr ");
  893. if (!eos)
  894. eos = strstr(s, "\ndirectory-signature");
  895. if (eos)
  896. return eos+1;
  897. else
  898. return s + strlen(s);
  899. }
  900. /** Given a string at *<b>s</b>, containing a routerstatus object, and an
  901. * empty smartlist at <b>tokens</b>, parse and return the first router status
  902. * object in the string, and advance *<b>s</b> to just after the end of the
  903. * router status. Return NULL and advance *<b>s</b> on error. */
  904. static routerstatus_t *
  905. routerstatus_parse_entry_from_string(const char **s, smartlist_t *tokens)
  906. {
  907. const char *eos;
  908. routerstatus_t *rs = NULL;
  909. directory_token_t *tok;
  910. char timebuf[ISO_TIME_LEN+1];
  911. struct in_addr in;
  912. tor_assert(tokens);
  913. eos = find_start_of_next_routerstatus(*s);
  914. if (tokenize_string(*s, eos, tokens, RTRSTATUS)) {
  915. log_warn(LD_DIR, "Error tokenizing router status");
  916. goto err;
  917. }
  918. if (smartlist_len(tokens) < 1) {
  919. log_warn(LD_DIR, "Impossibly short router status");
  920. goto err;
  921. }
  922. if (!(tok = find_first_by_keyword(tokens, K_R))) {
  923. log_warn(LD_DIR, "Missing 'r' keywork in router status; skipping.");
  924. goto err;
  925. }
  926. if (tok->n_args < 8) {
  927. log_warn(LD_DIR,
  928. "Too few arguments to 'r' keywork in router status; skipping.");
  929. }
  930. rs = tor_malloc_zero(sizeof(routerstatus_t));
  931. if (!is_legal_nickname(tok->args[0])) {
  932. log_warn(LD_DIR,
  933. "Invalid nickname %s in router status; skipping.",
  934. escaped(tok->args[0]));
  935. goto err;
  936. }
  937. strlcpy(rs->nickname, tok->args[0], sizeof(rs->nickname));
  938. if (digest_from_base64(rs->identity_digest, tok->args[1])) {
  939. log_warn(LD_DIR, "Error decoding identity digest %s",
  940. escaped(tok->args[1]));
  941. goto err;
  942. }
  943. if (digest_from_base64(rs->descriptor_digest, tok->args[2])) {
  944. log_warn(LD_DIR, "Error decoding descriptor digest %s",
  945. escaped(tok->args[2]));
  946. goto err;
  947. }
  948. if (tor_snprintf(timebuf, sizeof(timebuf), "%s %s",
  949. tok->args[3], tok->args[4]) < 0 ||
  950. parse_iso_time(timebuf, &rs->published_on)<0) {
  951. log_warn(LD_DIR, "Error parsing time '%s %s'",
  952. tok->args[3], tok->args[4]);
  953. goto err;
  954. }
  955. if (tor_inet_aton(tok->args[5], &in) == 0) {
  956. log_warn(LD_DIR, "Error parsing router address in network-status %s",
  957. escaped(tok->args[5]));
  958. goto err;
  959. }
  960. rs->addr = ntohl(in.s_addr);
  961. rs->or_port =(uint16_t) tor_parse_long(tok->args[6],10,0,65535,NULL,NULL);
  962. rs->dir_port = (uint16_t) tor_parse_long(tok->args[7],10,0,65535,NULL,NULL);
  963. if ((tok = find_first_by_keyword(tokens, K_S))) {
  964. int i;
  965. for (i=0; i < tok->n_args; ++i) {
  966. if (!strcmp(tok->args[i], "Exit"))
  967. rs->is_exit = 1;
  968. else if (!strcmp(tok->args[i], "Stable"))
  969. rs->is_stable = 1;
  970. else if (!strcmp(tok->args[i], "Fast"))
  971. rs->is_fast = 1;
  972. else if (!strcmp(tok->args[i], "Running"))
  973. rs->is_running = 1;
  974. else if (!strcmp(tok->args[i], "Named"))
  975. rs->is_named = 1;
  976. else if (!strcmp(tok->args[i], "Valid"))
  977. rs->is_valid = 1;
  978. else if (!strcmp(tok->args[i], "V2Dir"))
  979. rs->is_v2_dir = 1;
  980. else if (!strcmp(tok->args[i], "Guard"))
  981. rs->is_possible_guard = 1;
  982. else if (!strcmp(tok->args[i], "BadExit"))
  983. rs->is_bad_exit = 1;
  984. else if (!strcmp(tok->args[i], "BadDirectory"))
  985. rs->is_bad_directory = 1;
  986. }
  987. }
  988. if ((tok = find_first_by_keyword(tokens, K_V)) && tok->n_args) {
  989. rs->version_known = 1;
  990. if (strcmpstart(tok->args[0], "Tor ")) {
  991. rs->version_supports_begindir = 1;
  992. } else {
  993. rs->version_supports_begindir =
  994. tor_version_as_new_as(tok->args[0], "0.1.2.2-alpha");
  995. }
  996. }
  997. if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME))
  998. rs->is_named = 0;
  999. goto done;
  1000. err:
  1001. if (rs)
  1002. routerstatus_free(rs);
  1003. rs = NULL;
  1004. done:
  1005. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1006. smartlist_clear(tokens);
  1007. *s = eos;
  1008. return rs;
  1009. }
  1010. /** Helper to sort a smartlist of pointers to routerstatus_t */
  1011. static int
  1012. _compare_routerstatus_entries(const void **_a, const void **_b)
  1013. {
  1014. const routerstatus_t *a = *_a, *b = *_b;
  1015. return memcmp(a->identity_digest, b->identity_digest, DIGEST_LEN);
  1016. }
  1017. /** Helper: used in call to _smartlist_uniq to clear out duplicate entries. */
  1018. static void
  1019. _free_duplicate_routerstatus_entry(void *e)
  1020. {
  1021. log_warn(LD_DIR,
  1022. "Network-status has two entries for the same router. "
  1023. "Dropping one.");
  1024. routerstatus_free(e);
  1025. }
  1026. /** Given a versioned (v2 or later) network-status object in <b>s</b>, try to
  1027. * parse it and return the result. Return NULL on failure. Check the
  1028. * signature of the network status, but do not (yet) check the signing key for
  1029. * authority.
  1030. */
  1031. networkstatus_t *
  1032. networkstatus_parse_from_string(const char *s)
  1033. {
  1034. const char *eos;
  1035. smartlist_t *tokens = smartlist_create();
  1036. networkstatus_t *ns = NULL;
  1037. char ns_digest[DIGEST_LEN];
  1038. char tmp_digest[DIGEST_LEN];
  1039. struct in_addr in;
  1040. directory_token_t *tok;
  1041. int i;
  1042. if (router_get_networkstatus_v2_hash(s, ns_digest)) {
  1043. log_warn(LD_DIR, "Unable to compute digest of network-status");
  1044. goto err;
  1045. }
  1046. eos = find_start_of_next_routerstatus(s);
  1047. if (tokenize_string(s, eos, tokens, NETSTATUS)) {
  1048. log_warn(LD_DIR, "Error tokenizing network-status header.");
  1049. goto err;
  1050. }
  1051. ns = tor_malloc_zero(sizeof(networkstatus_t));
  1052. memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN);
  1053. if (!(tok = find_first_by_keyword(tokens, K_NETWORK_STATUS_VERSION))) {
  1054. log_warn(LD_DIR, "Couldn't find network-status-version keyword");
  1055. goto err;
  1056. }
  1057. if (!(tok = find_first_by_keyword(tokens, K_DIR_SOURCE))) {
  1058. log_warn(LD_DIR, "Couldn't find dir-source keyword");
  1059. goto err;
  1060. }
  1061. if (tok->n_args < 3) {
  1062. log_warn(LD_DIR, "Too few arguments to dir-source keyword");
  1063. goto err;
  1064. }
  1065. ns->source_address = tok->args[0]; tok->args[0] = NULL;
  1066. if (tor_inet_aton(tok->args[1], &in) == 0) {
  1067. log_warn(LD_DIR, "Error parsing network-status source address %s",
  1068. escaped(tok->args[1]));
  1069. goto err;
  1070. }
  1071. ns->source_addr = ntohl(in.s_addr);
  1072. ns->source_dirport =
  1073. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
  1074. if (ns->source_dirport == 0) {
  1075. log_warn(LD_DIR, "Directory source without dirport; skipping.");
  1076. goto err;
  1077. }
  1078. if (!(tok = find_first_by_keyword(tokens, K_FINGERPRINT))) {
  1079. log_warn(LD_DIR, "Couldn't find fingerprint keyword");
  1080. goto err;
  1081. }
  1082. if (tok->n_args < 1) {
  1083. log_warn(LD_DIR, "Too few arguments to networkstatus fingerprint");
  1084. goto err;
  1085. }
  1086. if (base16_decode(ns->identity_digest, DIGEST_LEN, tok->args[0],
  1087. strlen(tok->args[0]))) {
  1088. log_warn(LD_DIR, "Couldn't decode networkstatus fingerprint %s",
  1089. escaped(tok->args[0]));
  1090. goto err;
  1091. }
  1092. if ((tok = find_first_by_keyword(tokens, K_CONTACT)) && tok->n_args) {
  1093. ns->contact = tok->args[0];
  1094. tok->args[0] = NULL;
  1095. }
  1096. if (!(tok = find_first_by_keyword(tokens, K_DIR_SIGNING_KEY)) || !tok->key) {
  1097. log_warn(LD_DIR, "Missing dir-signing-key");
  1098. goto err;
  1099. }
  1100. ns->signing_key = tok->key;
  1101. tok->key = NULL;
  1102. if (crypto_pk_get_digest(ns->signing_key, tmp_digest)<0) {
  1103. log_warn(LD_DIR, "Couldn't compute signing key digest");
  1104. goto err;
  1105. }
  1106. if (memcmp(tmp_digest, ns->identity_digest, DIGEST_LEN)) {
  1107. log_warn(LD_DIR,
  1108. "network-status fingerprint did not match dir-signing-key");
  1109. goto err;
  1110. }
  1111. if ((tok = find_first_by_keyword(tokens, K_DIR_OPTIONS))) {
  1112. for (i=0; i < tok->n_args; ++i) {
  1113. if (!strcmp(tok->args[i], "Names"))
  1114. ns->binds_names = 1;
  1115. if (!strcmp(tok->args[i], "Versions"))
  1116. ns->recommends_versions = 1;
  1117. if (!strcmp(tok->args[i], "BadExits"))
  1118. ns->lists_bad_exits = 1;
  1119. if (!strcmp(tok->args[i], "BadDirectories"))
  1120. ns->lists_bad_directories = 1;
  1121. }
  1122. }
  1123. if (ns->recommends_versions) {
  1124. if (!(tok = find_first_by_keyword(tokens, K_CLIENT_VERSIONS)) ||
  1125. tok->n_args<1) {
  1126. log_warn(LD_DIR, "Missing client-versions");
  1127. }
  1128. ns->client_versions = tok->args[0];
  1129. tok->args[0] = NULL;
  1130. if (!(tok = find_first_by_keyword(tokens, K_SERVER_VERSIONS)) ||
  1131. tok->n_args<1) {
  1132. log_warn(LD_DIR, "Missing server-versions on versioning directory");
  1133. goto err;
  1134. }
  1135. ns->server_versions = tok->args[0];
  1136. tok->args[0] = NULL;
  1137. }
  1138. if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
  1139. log_warn(LD_DIR, "Missing published time on network-status.");
  1140. goto err;
  1141. }
  1142. tor_assert(tok->n_args == 1);
  1143. if (parse_iso_time(tok->args[0], &ns->published_on) < 0) {
  1144. goto err;
  1145. }
  1146. ns->entries = smartlist_create();
  1147. s = eos;
  1148. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1149. smartlist_clear(tokens);
  1150. while (!strcmpstart(s, "r ")) {
  1151. routerstatus_t *rs;
  1152. if ((rs = routerstatus_parse_entry_from_string(&s, tokens)))
  1153. smartlist_add(ns->entries, rs);
  1154. }
  1155. smartlist_sort(ns->entries, _compare_routerstatus_entries);
  1156. smartlist_uniq(ns->entries, _compare_routerstatus_entries,
  1157. _free_duplicate_routerstatus_entry);
  1158. if (tokenize_string(s, NULL, tokens, NETSTATUS)) {
  1159. log_warn(LD_DIR, "Error tokenizing network-status footer.");
  1160. goto err;
  1161. }
  1162. if (smartlist_len(tokens) < 1) {
  1163. log_warn(LD_DIR, "Too few items in network-status footer.");
  1164. goto err;
  1165. }
  1166. tok = smartlist_get(tokens, smartlist_len(tokens)-1);
  1167. if (tok->tp != K_DIRECTORY_SIGNATURE) {
  1168. log_warn(LD_DIR,
  1169. "Expected network-status footer to end with a signature.");
  1170. goto err;
  1171. }
  1172. note_crypto_pk_op(VERIFY_DIR);
  1173. if (check_directory_signature(ns_digest, tok, NULL, ns->signing_key, 0))
  1174. goto err;
  1175. goto done;
  1176. err:
  1177. if (ns)
  1178. networkstatus_free(ns);
  1179. ns = NULL;
  1180. done:
  1181. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1182. smartlist_free(tokens);
  1183. return ns;
  1184. }
  1185. /** Parse the addr policy in the string <b>s</b> and return it. If
  1186. * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
  1187. * ADDR_POLICY_REJECT) for items that specify no action.
  1188. */
  1189. addr_policy_t *
  1190. router_parse_addr_policy_from_string(const char *s, int assume_action)
  1191. {
  1192. directory_token_t *tok = NULL;
  1193. const char *cp;
  1194. char *tmp;
  1195. addr_policy_t *r;
  1196. size_t len, idx;
  1197. /* *s might not end with \n, so we need to extend it with one. */
  1198. len = strlen(s);
  1199. cp = tmp = tor_malloc(len+2);
  1200. for (idx = 0; idx < len; ++idx) {
  1201. tmp[idx] = TOR_TOLOWER(s[idx]);
  1202. }
  1203. tmp[len]='\n';
  1204. tmp[len+1]='\0';
  1205. while (TOR_ISSPACE(*cp))
  1206. ++cp;
  1207. if ((*cp == '*' || TOR_ISDIGIT(*cp)) && assume_action >= 0) {
  1208. char *new_str = tor_malloc(len+10);
  1209. tor_snprintf(new_str, len+10, "%s %s\n",
  1210. assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", cp);
  1211. tor_free(tmp);
  1212. cp = tmp = new_str;
  1213. }
  1214. tok = get_next_token(&cp, RTR);
  1215. if (tok->tp == _ERR) {
  1216. log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
  1217. goto err;
  1218. }
  1219. if (tok->tp != K_ACCEPT && tok->tp != K_REJECT) {
  1220. log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
  1221. goto err;
  1222. }
  1223. /* Now that we've gotten an addr policy, add it to the router. */
  1224. r = router_parse_addr_policy(tok);
  1225. goto done;
  1226. err:
  1227. r = NULL;
  1228. done:
  1229. tor_free(tmp);
  1230. token_free(tok);
  1231. return r;
  1232. }
  1233. /** Add an exit policy stored in the token <b>tok</b> to the router info in
  1234. * <b>router</b>. Return 0 on success, -1 on failure. */
  1235. static int
  1236. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
  1237. {
  1238. addr_policy_t *newe, **tmpe;
  1239. newe = router_parse_addr_policy(tok);
  1240. if (!newe)
  1241. return -1;
  1242. for (tmpe = &router->exit_policy; *tmpe; tmpe=&((*tmpe)->next))
  1243. ;
  1244. *tmpe = newe;
  1245. return 0;
  1246. }
  1247. /** Given a K_ACCEPT or K_REJECT token and a router, create and return
  1248. * a new exit_policy_t corresponding to the token. */
  1249. static addr_policy_t *
  1250. router_parse_addr_policy(directory_token_t *tok)
  1251. {
  1252. addr_policy_t *newe;
  1253. char *arg;
  1254. char buf[POLICY_BUF_LEN];
  1255. tor_assert(tok->tp == K_REJECT || tok->tp == K_ACCEPT);
  1256. if (tok->n_args != 1)
  1257. return NULL;
  1258. arg = tok->args[0];
  1259. if (!strcmpstart(arg,"private"))
  1260. return router_parse_addr_policy_private(tok);
  1261. newe = tor_malloc_zero(sizeof(addr_policy_t));
  1262. newe->policy_type = (tok->tp == K_REJECT) ? ADDR_POLICY_REJECT
  1263. : ADDR_POLICY_ACCEPT;
  1264. if (parse_addr_and_port_range(arg, &newe->addr, &newe->msk,
  1265. &newe->prt_min, &newe->prt_max))
  1266. goto policy_read_failed;
  1267. if (policy_write_item(buf, sizeof(buf), newe) < 0)
  1268. goto policy_read_failed;
  1269. newe->string = tor_strdup(buf);
  1270. return newe;
  1271. policy_read_failed:
  1272. log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
  1273. tor_free(newe);
  1274. return NULL;
  1275. }
  1276. /** Parse an exit policy line of the format "accept/reject private:...".
  1277. * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
  1278. * router descriptors until earlier versions are obsolete.
  1279. */
  1280. static addr_policy_t *
  1281. router_parse_addr_policy_private(directory_token_t *tok)
  1282. {
  1283. static const char *private_nets[] = {
  1284. "0.0.0.0/8", "169.254.0.0/16",
  1285. "127.0.0.0/8", "192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12",NULL };
  1286. char *arg;
  1287. addr_policy_t *result, **nextp;
  1288. int net;
  1289. uint16_t port_min, port_max;
  1290. arg = tok->args[0];
  1291. if (strcmpstart(arg, "private"))
  1292. return NULL;
  1293. arg += strlen("private");
  1294. arg = (char*) eat_whitespace(arg);
  1295. if (!arg || *arg != ':')
  1296. return NULL;
  1297. if (parse_port_range(arg+1, &port_min, &port_max)<0)
  1298. return NULL;
  1299. nextp = &result;
  1300. for (net = 0; private_nets[net]; ++net) {
  1301. size_t len;
  1302. *nextp = tor_malloc_zero(sizeof(addr_policy_t));
  1303. (*nextp)->policy_type = (tok->tp == K_REJECT) ? ADDR_POLICY_REJECT
  1304. : ADDR_POLICY_ACCEPT;
  1305. len = strlen(arg)+strlen(private_nets[net])+16;
  1306. (*nextp)->string = tor_malloc(len+1);
  1307. tor_snprintf((*nextp)->string, len, "%s %s%s",
  1308. tok->tp == K_REJECT ? "reject" : "accept",
  1309. private_nets[net], arg);
  1310. if (parse_addr_and_port_range((*nextp)->string + 7,
  1311. &(*nextp)->addr, &(*nextp)->msk,
  1312. &(*nextp)->prt_min, &(*nextp)->prt_max)) {
  1313. log_warn(LD_BUG, "Couldn't parse an address range we generated!");
  1314. return NULL;
  1315. }
  1316. nextp = &(*nextp)->next;
  1317. }
  1318. return result;
  1319. }
  1320. /** Log and exit if <b>t</b> is malformed */
  1321. void
  1322. assert_addr_policy_ok(addr_policy_t *t)
  1323. {
  1324. addr_policy_t *t2;
  1325. while (t) {
  1326. tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
  1327. t->policy_type == ADDR_POLICY_ACCEPT);
  1328. tor_assert(t->prt_min <= t->prt_max);
  1329. t2 = router_parse_addr_policy_from_string(t->string, -1);
  1330. tor_assert(t2);
  1331. tor_assert(t2->policy_type == t->policy_type);
  1332. tor_assert(t2->addr == t->addr);
  1333. tor_assert(t2->msk == t->msk);
  1334. tor_assert(t2->prt_min == t->prt_min);
  1335. tor_assert(t2->prt_max == t->prt_max);
  1336. tor_assert(!strcmp(t2->string, t->string));
  1337. tor_assert(t2->next == NULL);
  1338. addr_policy_free(t2);
  1339. t = t->next;
  1340. }
  1341. }
  1342. /*
  1343. * Low-level tokenizer for router descriptors and directories.
  1344. */
  1345. /** Free all resources allocated for <b>tok</b> */
  1346. static void
  1347. token_free(directory_token_t *tok)
  1348. {
  1349. int i;
  1350. tor_assert(tok);
  1351. if (tok->args) {
  1352. for (i = 0; i < tok->n_args; ++i) {
  1353. tor_free(tok->args[i]);
  1354. }
  1355. tor_free(tok->args);
  1356. }
  1357. tor_free(tok->object_type);
  1358. tor_free(tok->object_body);
  1359. if (tok->key)
  1360. crypto_free_pk_env(tok->key);
  1361. tor_free(tok);
  1362. }
  1363. /** Helper function: read the next token from *s, advance *s to the end
  1364. * of the token, and return the parsed token. If 'where' is DIR
  1365. * or RTR, reject all tokens of the wrong type.
  1366. */
  1367. static directory_token_t *
  1368. get_next_token(const char **s, where_syntax where)
  1369. {
  1370. const char *next, *obstart;
  1371. int i, done, allocated, is_opt;
  1372. directory_token_t *tok;
  1373. arg_syntax a_syn;
  1374. obj_syntax o_syn = NO_OBJ;
  1375. #define RET_ERR(msg) \
  1376. do { if (tok) token_free(tok); \
  1377. tok = tor_malloc_zero(sizeof(directory_token_t));\
  1378. tok->tp = _ERR; \
  1379. tok->error = msg; \
  1380. goto done_tokenizing; } while (0)
  1381. tok = tor_malloc_zero(sizeof(directory_token_t));
  1382. tok->tp = _ERR;
  1383. *s = eat_whitespace(*s);
  1384. if (!**s) {
  1385. tok->tp = _EOF;
  1386. return tok;
  1387. }
  1388. next = find_whitespace(*s);
  1389. if (!next) {
  1390. tok->error = "Unexpected EOF"; return tok;
  1391. }
  1392. /* It's a keyword... but which one? */
  1393. is_opt = !strncmp("opt", *s, next-*s);
  1394. if (is_opt) {
  1395. *s = eat_whitespace(next);
  1396. next = NULL;
  1397. if (**s)
  1398. next = find_whitespace(*s);
  1399. if (!**s || !next) {
  1400. RET_ERR("opt without keyword");
  1401. }
  1402. }
  1403. for (i = 0; token_table[i].t ; ++i) {
  1404. if (!strncmp(token_table[i].t, *s, next-*s)) {
  1405. /* We've found the keyword. */
  1406. tok->tp = token_table[i].v;
  1407. a_syn = token_table[i].s;
  1408. o_syn = token_table[i].os;
  1409. if (!(token_table[i].ws & where)) {
  1410. if (where == DIR) {
  1411. RET_ERR("Found an out-of-place token in a directory section");
  1412. } else if (where == RTR) {
  1413. RET_ERR("Found an out-of-place token in a router descriptor");
  1414. } else if (where == NETSTATUS) {
  1415. RET_ERR("Found an out-of-place token in a network-status header");
  1416. } else {
  1417. RET_ERR("Found an out-of-place token in a router status body");
  1418. }
  1419. }
  1420. if (a_syn == ARGS) {
  1421. /* This keyword takes multiple arguments. */
  1422. i = 0;
  1423. done = (*next == '\n');
  1424. allocated = 32;
  1425. tok->args = tor_malloc(sizeof(char*)*32);
  1426. *s = eat_whitespace_no_nl(next);
  1427. while (**s != '\n' && !done) {
  1428. next = find_whitespace(*s);
  1429. if (*next == '\n')
  1430. done = 1;
  1431. if (i == allocated) {
  1432. allocated *= 2;
  1433. tok->args = tor_realloc(tok->args,sizeof(char*)*allocated);
  1434. }
  1435. tok->args[i++] = tor_strndup(*s,next-*s);
  1436. *s = eat_whitespace_no_nl(next+1);
  1437. }
  1438. tok->n_args = i;
  1439. } else if (a_syn == CONCAT_ARGS) {
  1440. /* The keyword takes the line as a single argument */
  1441. *s = eat_whitespace_no_nl(next);
  1442. next = strchr(*s, '\n');
  1443. if (!next)
  1444. RET_ERR("Unexpected EOF");
  1445. tok->args = tor_malloc(sizeof(char*));
  1446. tok->args[0] = tor_strndup(*s,next-*s);
  1447. tok->n_args = 1;
  1448. *s = eat_whitespace_no_nl(next+1);
  1449. } else {
  1450. /* The keyword takes no arguments. */
  1451. tor_assert(a_syn == NO_ARGS);
  1452. *s = eat_whitespace_no_nl(next);
  1453. if (**s != '\n') {
  1454. RET_ERR("Unexpected arguments");
  1455. }
  1456. tok->n_args = 0;
  1457. *s = eat_whitespace_no_nl(*s+1);
  1458. }
  1459. break;
  1460. }
  1461. }
  1462. if (tok->tp == _ERR) {
  1463. tok->tp = K_OPT;
  1464. *s = eat_whitespace_no_nl(next);
  1465. next = strchr(*s,'\n');
  1466. if (!next)
  1467. RET_ERR("Unexpected EOF");
  1468. tok->args = tor_malloc(sizeof(char*));
  1469. tok->args[0] = tor_strndup(*s,next-*s);
  1470. tok->n_args = 1;
  1471. *s = eat_whitespace_no_nl(next+1);
  1472. o_syn = OBJ_OK;
  1473. }
  1474. *s = eat_whitespace(*s);
  1475. if (strcmpstart(*s, "-----BEGIN ")) {
  1476. goto done_tokenizing;
  1477. }
  1478. obstart = *s;
  1479. *s += 11; /* length of "-----BEGIN ". */
  1480. next = strchr(*s, '\n');
  1481. if (next-*s < 6 || strcmpstart(next-5, "-----\n")) {
  1482. RET_ERR("Malformed object: bad begin line");
  1483. }
  1484. tok->object_type = tor_strndup(*s, next-*s-5);
  1485. *s = next+1;
  1486. next = strstr(*s, "-----END ");
  1487. if (!next) {
  1488. RET_ERR("Malformed object: missing end line");
  1489. }
  1490. if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) {
  1491. if (strcmpstart(next, "-----END RSA PUBLIC KEY-----\n"))
  1492. RET_ERR("Malformed object: mismatched end line");
  1493. next = strchr(next,'\n')+1;
  1494. tok->key = crypto_new_pk_env();
  1495. if (crypto_pk_read_public_key_from_string(tok->key, obstart, next-obstart))
  1496. RET_ERR("Couldn't parse public key.");
  1497. *s = next;
  1498. } else {
  1499. tok->object_body = tor_malloc(next-*s); /* really, this is too much RAM. */
  1500. i = base64_decode(tok->object_body, 256, *s, next-*s);
  1501. if (i<0) {
  1502. RET_ERR("Malformed object: bad base64-encoded data");
  1503. }
  1504. tok->object_size = i;
  1505. *s = next + 9; /* length of "-----END ". */
  1506. i = strlen(tok->object_type);
  1507. if (strncmp(*s, tok->object_type, i) || strcmpstart(*s+i, "-----\n")) {
  1508. RET_ERR("Malformed object: mismatched end tag");
  1509. }
  1510. *s += i+6;
  1511. }
  1512. switch (o_syn)
  1513. {
  1514. case NO_OBJ:
  1515. if (tok->object_body)
  1516. RET_ERR("Unexpected object for keyword");
  1517. if (tok->key)
  1518. RET_ERR("Unexpected public key for keyword");
  1519. break;
  1520. case NEED_OBJ:
  1521. if (!tok->object_body)
  1522. RET_ERR("Missing object for keyword");
  1523. break;
  1524. case NEED_KEY:
  1525. if (!tok->key)
  1526. RET_ERR("Missing public key for keyword");
  1527. break;
  1528. case OBJ_OK:
  1529. break;
  1530. }
  1531. done_tokenizing:
  1532. return tok;
  1533. #undef RET_ERR
  1534. }
  1535. /** Read all tokens from a string between <b>start</b> and <b>end</b>, and add
  1536. * them to <b>out</b>. If <b>is_dir</b> is true, reject all non-directory
  1537. * tokens; else reject all non-routerdescriptor tokens.
  1538. */
  1539. static int
  1540. tokenize_string(const char *start, const char *end, smartlist_t *out,
  1541. where_syntax where)
  1542. {
  1543. const char **s;
  1544. directory_token_t *tok = NULL;
  1545. s = &start;
  1546. if (!end)
  1547. end = start+strlen(start);
  1548. while (*s < end && (!tok || tok->tp != _EOF)) {
  1549. tok = get_next_token(s, where);
  1550. if (tok->tp == _ERR) {
  1551. log_warn(LD_DIR, "parse error: %s", tok->error);
  1552. return -1;
  1553. }
  1554. smartlist_add(out, tok);
  1555. *s = eat_whitespace(*s);
  1556. }
  1557. return 0;
  1558. }
  1559. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
  1560. * NULL if no such keyword is found.
  1561. */
  1562. static directory_token_t *
  1563. find_first_by_keyword(smartlist_t *s, directory_keyword keyword)
  1564. {
  1565. SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
  1566. return NULL;
  1567. }
  1568. /** Return a newly allocated smartlist of all accept or reject tokens in
  1569. * <b>s</b>.
  1570. */
  1571. static smartlist_t *
  1572. find_all_exitpolicy(smartlist_t *s)
  1573. {
  1574. smartlist_t *out = smartlist_create();
  1575. SMARTLIST_FOREACH(s, directory_token_t *, t,
  1576. if (t->tp == K_ACCEPT || t->tp == K_REJECT)
  1577. smartlist_add(out,t));
  1578. return out;
  1579. }
  1580. /** Compute the SHA-1 digest of the substring of <b>s</b> taken from the first
  1581. * occurrence of <b>start_str</b> through the first newline after the first
  1582. * subsequent occurrence of <b>end_str</b>; store the 20-byte result in
  1583. * <b>digest</b>; return 0 on success.
  1584. *
  1585. * If no such substring exists, return -1.
  1586. */
  1587. static int
  1588. router_get_hash_impl(const char *s, char *digest,
  1589. const char *start_str,
  1590. const char *end_str)
  1591. {
  1592. char *start, *end;
  1593. start = strstr(s, start_str);
  1594. if (!start) {
  1595. log_warn(LD_DIR,"couldn't find start of hashed material \"%s\"",start_str);
  1596. return -1;
  1597. }
  1598. if (start != s && *(start-1) != '\n') {
  1599. log_warn(LD_DIR,
  1600. "first occurrence of \"%s\" is not at the start of a line",
  1601. start_str);
  1602. return -1;
  1603. }
  1604. end = strstr(start+strlen(start_str), end_str);
  1605. if (!end) {
  1606. log_warn(LD_DIR,"couldn't find end of hashed material \"%s\"",end_str);
  1607. return -1;
  1608. }
  1609. end = strchr(end+strlen(end_str), '\n');
  1610. if (!end) {
  1611. log_warn(LD_DIR,"couldn't find EOL");
  1612. return -1;
  1613. }
  1614. ++end;
  1615. if (crypto_digest(digest, start, end-start)) {
  1616. log_warn(LD_BUG,"couldn't compute digest");
  1617. return -1;
  1618. }
  1619. return 0;
  1620. }
  1621. /** Parse the Tor version of the platform string <b>platform</b>,
  1622. * and compare it to the version in <b>cutoff</b>. Return 1 if
  1623. * the router is at least as new as the cutoff, else return 0.
  1624. */
  1625. int
  1626. tor_version_as_new_as(const char *platform, const char *cutoff)
  1627. {
  1628. tor_version_t cutoff_version, router_version;
  1629. char *s, *start;
  1630. char tmp[128];
  1631. tor_assert(platform);
  1632. if (tor_version_parse(cutoff, &cutoff_version)<0) {
  1633. log_warn(LD_BUG,"cutoff version '%s' unparseable.",cutoff);
  1634. return 0;
  1635. }
  1636. if (strcmpstart(platform,"Tor ")) /* nonstandard Tor; be safe and say yes */
  1637. return 1;
  1638. start = (char *)eat_whitespace(platform+3);
  1639. if (!*start) return 0;
  1640. s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
  1641. if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
  1642. return 0;
  1643. strlcpy(tmp, start, s-start+1);
  1644. if (tor_version_parse(tmp, &router_version)<0) {
  1645. log_info(LD_DIR,"Router version '%s' unparseable.",tmp);
  1646. return 1; /* be safe and say yes */
  1647. }
  1648. return tor_version_compare(&router_version, &cutoff_version) >= 0;
  1649. }
  1650. /** Parse a tor version from <b>s</b>, and store the result in <b>out</b>.
  1651. * Return 0 on success, -1 on failure. */
  1652. int
  1653. tor_version_parse(const char *s, tor_version_t *out)
  1654. {
  1655. char *eos=NULL, *cp=NULL;
  1656. /* Format is:
  1657. * "Tor " ? NUM dot NUM dot NUM [ ( pre | rc | dot ) NUM [ - tag ] ]
  1658. */
  1659. tor_assert(s);
  1660. tor_assert(out);
  1661. memset(out, 0, sizeof(tor_version_t));
  1662. if (!strcasecmpstart(s, "Tor "))
  1663. s += 4;
  1664. /* Get major. */
  1665. out->major = strtol(s,&eos,10);
  1666. if (!eos || eos==s || *eos != '.') return -1;
  1667. cp = eos+1;
  1668. /* Get minor */
  1669. out->minor = strtol(cp,&eos,10);
  1670. if (!eos || eos==cp || *eos != '.') return -1;
  1671. cp = eos+1;
  1672. /* Get micro */
  1673. out->micro = strtol(cp,&eos,10);
  1674. if (!eos || eos==cp) return -1;
  1675. if (!*eos) {
  1676. out->status = VER_RELEASE;
  1677. out->patchlevel = 0;
  1678. return 0;
  1679. }
  1680. cp = eos;
  1681. /* Get status */
  1682. if (*cp == '.') {
  1683. out->status = VER_RELEASE;
  1684. ++cp;
  1685. } else if (0==strncmp(cp, "pre", 3)) {
  1686. out->status = VER_PRE;
  1687. cp += 3;
  1688. } else if (0==strncmp(cp, "rc", 2)) {
  1689. out->status = VER_RC;
  1690. cp += 2;
  1691. } else {
  1692. return -1;
  1693. }
  1694. /* Get patchlevel */
  1695. out->patchlevel = strtol(cp,&eos,10);
  1696. if (!eos || eos==cp) return -1;
  1697. cp = eos;
  1698. /* Get status tag. */
  1699. if (*cp == '-' || *cp == '.')
  1700. ++cp;
  1701. strlcpy(out->status_tag, cp, sizeof(out->status_tag));
  1702. return 0;
  1703. }
  1704. /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
  1705. * b. */
  1706. int
  1707. tor_version_compare(tor_version_t *a, tor_version_t *b)
  1708. {
  1709. int i;
  1710. tor_assert(a);
  1711. tor_assert(b);
  1712. if ((i = a->major - b->major))
  1713. return i;
  1714. else if ((i = a->minor - b->minor))
  1715. return i;
  1716. else if ((i = a->micro - b->micro))
  1717. return i;
  1718. else if ((i = a->status - b->status))
  1719. return i;
  1720. else if ((i = a->patchlevel - b->patchlevel))
  1721. return i;
  1722. return strcmp(a->status_tag, b->status_tag);
  1723. }
  1724. /** Return true iff versions <b>a</b> and <b>b</b> belong to the same series.
  1725. */
  1726. static int
  1727. tor_version_same_series(tor_version_t *a, tor_version_t *b)
  1728. {
  1729. tor_assert(a);
  1730. tor_assert(b);
  1731. return ((a->major == b->major) &&
  1732. (a->minor == b->minor) &&
  1733. (a->micro == b->micro));
  1734. }
  1735. /** Helper: Given pointers to two strings describing tor versions, return -1
  1736. * if _a precedes _b, 1 if _b preceeds _a, and 0 if they are equivalent.
  1737. * Used to sort a list of versions. */
  1738. static int
  1739. _compare_tor_version_str_ptr(const void **_a, const void **_b)
  1740. {
  1741. const char *a = *_a, *b = *_b;
  1742. int ca, cb;
  1743. tor_version_t va, vb;
  1744. ca = tor_version_parse(a, &va);
  1745. cb = tor_version_parse(b, &vb);
  1746. /* If they both parse, compare them. */
  1747. if (!ca && !cb)
  1748. return tor_version_compare(&va,&vb);
  1749. /* If one parses, it comes first. */
  1750. if (!ca && cb)
  1751. return -1;
  1752. if (ca && !cb)
  1753. return 1;
  1754. /* If neither parses, compare strings. Also, the directory server admin
  1755. ** needs to be smacked upside the head. But Tor is tolerant and gentle. */
  1756. return strcmp(a,b);
  1757. }
  1758. /** Sort a list of string-representations of versions in ascending order. */
  1759. void
  1760. sort_version_list(smartlist_t *versions, int remove_duplicates)
  1761. {
  1762. smartlist_sort(versions, _compare_tor_version_str_ptr);
  1763. if (remove_duplicates)
  1764. smartlist_uniq(versions, _compare_tor_version_str_ptr, NULL);
  1765. }