routerparse.c 65 KB

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