routers.c 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279
  1. /* Copyright 2001,2002 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. #define OR_PUBLICKEY_BEGIN_TAG "-----BEGIN RSA PUBLIC KEY-----\n"
  5. #define OR_PUBLICKEY_END_TAG "-----END RSA PUBLIC KEY-----\n"
  6. #define OR_SIGNATURE_BEGIN_TAG "-----BEGIN SIGNATURE-----\n"
  7. #define OR_SIGNATURE_END_TAG "-----END SIGNATURE-----\n"
  8. #define _GNU_SOURCE
  9. /* XXX this is required on rh7 to make strptime not complain. how bad
  10. * is this for portability?
  11. */
  12. #include "or.h"
  13. #ifdef HAVE_UNAME
  14. #include <sys/utsname.h>
  15. #endif
  16. /****************************************************************************/
  17. /* router array */
  18. static directory_t *directory = NULL;
  19. extern or_options_t options; /* command-line and config-file options */
  20. static routerinfo_t *my_routerinfo;
  21. /****************************************************************************/
  22. struct directory_token;
  23. typedef struct directory_token directory_token_t;
  24. /* static function prototypes */
  25. void routerlist_free(routerinfo_t *list);
  26. static char *eat_whitespace(char *s);
  27. static char *eat_whitespace_no_nl(char *s);
  28. static char *find_whitespace(char *s);
  29. static void router_free_exit_policy(routerinfo_t *router);
  30. static int router_add_exit_policy(routerinfo_t *router,
  31. directory_token_t *tok);
  32. static int router_resolve_directory(directory_t *dir);
  33. static int init_descriptor(void);
  34. /****************************************************************************/
  35. int learn_my_address(struct sockaddr_in *me) {
  36. /* local host information */
  37. char localhostname[256];
  38. struct hostent *localhost;
  39. static struct sockaddr_in answer;
  40. static int already_learned=0;
  41. if(!already_learned) {
  42. /* obtain local host information */
  43. if(gethostname(localhostname,sizeof(localhostname)) < 0) {
  44. log_fn(LOG_WARNING,"Error obtaining local hostname");
  45. return -1;
  46. }
  47. log_fn(LOG_DEBUG,"localhostname is '%s'.",localhostname);
  48. localhost = gethostbyname(localhostname);
  49. if (!localhost) {
  50. log_fn(LOG_WARNING,"Error obtaining local host info.");
  51. /* XXX maybe this is worse than warning? bad things happen when we don't know ourselves */
  52. return -1;
  53. }
  54. memset(&answer,0,sizeof(struct sockaddr_in));
  55. answer.sin_family = AF_INET;
  56. memcpy((void *)&answer.sin_addr,(void *)localhost->h_addr,sizeof(struct in_addr));
  57. answer.sin_port = htons((uint16_t) options.ORPort);
  58. log_fn(LOG_DEBUG,"chose address as '%s'.",inet_ntoa(answer.sin_addr));
  59. if (!strncmp("127.",inet_ntoa(answer.sin_addr), 4) &&
  60. strcasecmp(localhostname, "localhost")) {
  61. /* We're a loopback IP but we're not called localhost. Uh oh! */
  62. log_fn(LOG_WARNING, "Got a loopback address: /etc/hosts may be wrong");
  63. }
  64. already_learned = 1;
  65. }
  66. memcpy(me,&answer,sizeof(struct sockaddr_in));
  67. return 0;
  68. }
  69. void router_retry_connections(void) {
  70. int i;
  71. routerinfo_t *router;
  72. for (i=0;i<directory->n_routers;i++) {
  73. router = directory->routers[i];
  74. if(!connection_exact_get_by_addr_port(router->addr,router->or_port)) { /* not in the list */
  75. log_fn(LOG_DEBUG,"connecting to OR %s:%u.",router->address,router->or_port);
  76. connection_or_connect(router);
  77. }
  78. }
  79. }
  80. routerinfo_t *router_pick_directory_server(void) {
  81. /* pick the first running router with a positive dir_port */
  82. int i;
  83. routerinfo_t *router;
  84. if(!directory)
  85. return NULL;
  86. for(i=0;i<directory->n_routers;i++) {
  87. router = directory->routers[i];
  88. if(router->dir_port > 0 && router->is_running)
  89. return router;
  90. }
  91. return NULL;
  92. }
  93. void router_upload_desc_to_dirservers(void) {
  94. int i;
  95. routerinfo_t *router;
  96. if(!directory)
  97. return;
  98. if (!router_get_my_descriptor()) {
  99. log_fn(LOG_WARNING, "No descriptor; skipping upload");
  100. return;
  101. }
  102. for(i=0;i<directory->n_routers;i++) {
  103. router = directory->routers[i];
  104. if(router->dir_port > 0)
  105. directory_initiate_command(router, DIR_CONN_STATE_CONNECTING_UPLOAD);
  106. }
  107. }
  108. routerinfo_t *router_get_by_addr_port(uint32_t addr, uint16_t port) {
  109. int i;
  110. routerinfo_t *router;
  111. assert(directory);
  112. for(i=0;i<directory->n_routers;i++) {
  113. router = directory->routers[i];
  114. if ((router->addr == addr) && (router->or_port == port))
  115. return router;
  116. }
  117. return NULL;
  118. }
  119. routerinfo_t *router_get_by_link_pk(crypto_pk_env_t *pk)
  120. {
  121. int i;
  122. routerinfo_t *router;
  123. assert(directory);
  124. for(i=0;i<directory->n_routers;i++) {
  125. router = directory->routers[i];
  126. if (0 == crypto_pk_cmp_keys(router->link_pkey, pk))
  127. return router;
  128. }
  129. return NULL;
  130. }
  131. routerinfo_t *router_get_by_nickname(char *nickname)
  132. {
  133. int i;
  134. routerinfo_t *router;
  135. assert(directory);
  136. for(i=0;i<directory->n_routers;i++) {
  137. router = directory->routers[i];
  138. if (0 == strcmp(router->nickname, nickname))
  139. return router;
  140. }
  141. return NULL;
  142. }
  143. void router_get_directory(directory_t **pdirectory) {
  144. *pdirectory = directory;
  145. }
  146. /* return 1 if addr and port corresponds to my addr and my or_listenport. else 0,
  147. * or -1 for failure.
  148. */
  149. int router_is_me(uint32_t addr, uint16_t port)
  150. {
  151. /* XXXX Should this check the key too? */
  152. struct sockaddr_in me; /* my router identity */
  153. if(!options.OnionRouter) {
  154. /* we're not an OR. This obviously isn't us. */
  155. return 0;
  156. }
  157. if(learn_my_address(&me) < 0)
  158. return -1;
  159. /* XXX people call this function like a boolean. that's bad news: -1 is true. */
  160. if(ntohl(me.sin_addr.s_addr) == addr && ntohs(me.sin_port) == port)
  161. return 1;
  162. return 0;
  163. }
  164. /* delete a list of routers from memory */
  165. void routerinfo_free(routerinfo_t *router)
  166. {
  167. struct exit_policy_t *e = NULL, *etmp = NULL;
  168. if (!router)
  169. return;
  170. if (router->address)
  171. free(router->address);
  172. if (router->onion_pkey)
  173. crypto_free_pk_env(router->onion_pkey);
  174. if (router->link_pkey)
  175. crypto_free_pk_env(router->link_pkey);
  176. if (router->identity_pkey)
  177. crypto_free_pk_env(router->identity_pkey);
  178. e = router->exit_policy;
  179. while (e) {
  180. etmp = e->next;
  181. if (e->string) free(e->string);
  182. if (e->address) free(e->address);
  183. if (e->port) free(e->port);
  184. free(e);
  185. e = etmp;
  186. }
  187. free(router);
  188. }
  189. void directory_free(directory_t *directory)
  190. {
  191. int i;
  192. for (i = 0; i < directory->n_routers; ++i)
  193. routerinfo_free(directory->routers[i]);
  194. if (directory->routers)
  195. free(directory->routers);
  196. if(directory->software_versions)
  197. free(directory->software_versions);
  198. free(directory);
  199. }
  200. void router_mark_as_down(char *nickname) {
  201. routerinfo_t *router = router_get_by_nickname(nickname);
  202. if(!router) /* we don't seem to know about him in the first place */
  203. return;
  204. log_fn(LOG_DEBUG,"Marking %s as down.",router->nickname);
  205. router->is_running = 0;
  206. }
  207. /* load the router list */
  208. int router_get_list_from_file(char *routerfile)
  209. {
  210. char *string;
  211. string = read_file_to_str(routerfile);
  212. if(!string) {
  213. log_fn(LOG_WARNING,"Failed to load routerfile %s.",routerfile);
  214. return -1;
  215. }
  216. if(router_get_list_from_string(string) < 0) {
  217. log_fn(LOG_WARNING,"The routerfile itself was corrupt.");
  218. free(string);
  219. return -1;
  220. }
  221. free(string);
  222. return 0;
  223. }
  224. typedef enum {
  225. K_ACCEPT,
  226. K_DIRECTORY_SIGNATURE,
  227. K_RECOMMENDED_SOFTWARE,
  228. K_REJECT,
  229. K_ROUTER,
  230. K_SIGNED_DIRECTORY,
  231. K_SIGNING_KEY,
  232. K_ONION_KEY,
  233. K_LINK_KEY,
  234. K_ROUTER_SIGNATURE,
  235. K_PUBLISHED,
  236. K_RUNNING_ROUTERS,
  237. K_PLATFORM,
  238. _SIGNATURE,
  239. _PUBLIC_KEY,
  240. _ERR,
  241. _EOF
  242. } directory_keyword;
  243. struct token_table_ent { char *t; int v; };
  244. static struct token_table_ent token_table[] = {
  245. { "accept", K_ACCEPT },
  246. { "directory-signature", K_DIRECTORY_SIGNATURE },
  247. { "reject", K_REJECT },
  248. { "router", K_ROUTER },
  249. { "recommended-software", K_RECOMMENDED_SOFTWARE },
  250. { "signed-directory", K_SIGNED_DIRECTORY },
  251. { "signing-key", K_SIGNING_KEY },
  252. { "onion-key", K_ONION_KEY },
  253. { "link-key", K_LINK_KEY },
  254. { "router-signature", K_ROUTER_SIGNATURE },
  255. { "published", K_PUBLISHED },
  256. { "running-routers", K_RUNNING_ROUTERS },
  257. { "platform", K_PLATFORM },
  258. { NULL, -1 }
  259. };
  260. #define MAX_ARGS 1024
  261. struct directory_token {
  262. directory_keyword tp;
  263. union {
  264. struct {
  265. char *args[MAX_ARGS+1];
  266. int n_args;
  267. } cmd;
  268. char *signature;
  269. char *error;
  270. crypto_pk_env_t *public_key;
  271. } val;
  272. };
  273. /* Free any malloced resources allocated for a token. Don't call this if
  274. you inherit the reference to those resources.
  275. */
  276. static void
  277. router_release_token(directory_token_t *tok)
  278. {
  279. switch (tok->tp)
  280. {
  281. case _SIGNATURE:
  282. free(tok->val.signature);
  283. break;
  284. case _PUBLIC_KEY:
  285. crypto_free_pk_env(tok->val.public_key);
  286. break;
  287. default:
  288. break;
  289. }
  290. }
  291. static int
  292. _router_get_next_token(char **s, directory_token_t *tok) {
  293. char *next;
  294. crypto_pk_env_t *pkey = NULL;
  295. char *signature = NULL;
  296. int i, done;
  297. tok->tp = _ERR;
  298. tok->val.error = "";
  299. *s = eat_whitespace(*s);
  300. if (!**s) {
  301. tok->tp = _EOF;
  302. return 0;
  303. } else if (**s == '-') {
  304. next = strchr(*s, '\n');
  305. if (! next) { tok->val.error = "No newline at EOF"; return -1; }
  306. ++next;
  307. if (! strncmp(*s, OR_PUBLICKEY_BEGIN_TAG, next-*s)) {
  308. next = strstr(*s, OR_PUBLICKEY_END_TAG);
  309. if (!next) { tok->val.error = "No public key end tag found"; return -1; }
  310. next = strchr(next, '\n'); /* Part of OR_PUBLICKEY_END_TAG; can't fail.*/
  311. ++next;
  312. if (!(pkey = crypto_new_pk_env(CRYPTO_PK_RSA)))
  313. return -1;
  314. if (crypto_pk_read_public_key_from_string(pkey, *s, next-*s)) {
  315. crypto_free_pk_env(pkey);
  316. tok->val.error = "Couldn't parse public key.";
  317. return -1;
  318. }
  319. tok->tp = _PUBLIC_KEY;
  320. tok->val.public_key = pkey;
  321. *s = next;
  322. return 0;
  323. } else if (! strncmp(*s, OR_SIGNATURE_BEGIN_TAG, next-*s)) {
  324. /* Advance past newline; can't fail. */
  325. *s = strchr(*s, '\n');
  326. ++*s;
  327. /* Find end of base64'd data */
  328. next = strstr(*s, OR_SIGNATURE_END_TAG);
  329. if (!next) { tok->val.error = "No signature end tag found"; return -1; }
  330. signature = tor_malloc(256);
  331. i = base64_decode(signature, 256, *s, next-*s);
  332. if (i<0) {
  333. free(signature);
  334. tok->val.error = "Error decoding signature."; return -1;
  335. } else if (i != 128) {
  336. free(signature);
  337. tok->val.error = "Bad length on decoded signature."; return -1;
  338. }
  339. tok->tp = _SIGNATURE;
  340. tok->val.signature = signature;
  341. next = strchr(next, '\n'); /* Part of OR_SIGNATURE_END_TAG; can't fail.*/
  342. *s = next+1;
  343. return 0;
  344. } else {
  345. tok->val.error = "Unrecognized begin line"; return -1;
  346. }
  347. } else {
  348. next = find_whitespace(*s);
  349. if (!next) {
  350. tok->val.error = "Unexpected EOF"; return -1;
  351. }
  352. for (i = 0 ; token_table[i].t ; ++i) {
  353. if (!strncmp(token_table[i].t, *s, next-*s)) {
  354. tok->tp = token_table[i].v;
  355. i = 0;
  356. done = (*next == '\n');
  357. *s = eat_whitespace_no_nl(next);
  358. while (**s != '\n' && i <= MAX_ARGS && !done) {
  359. next = find_whitespace(*s);
  360. if (*next == '\n')
  361. done = 1;
  362. *next = 0;
  363. tok->val.cmd.args[i++] = *s;
  364. *s = eat_whitespace_no_nl(next+1);
  365. };
  366. tok->val.cmd.n_args = i;
  367. if (i > MAX_ARGS) {
  368. tok->tp = _ERR;
  369. tok->val.error = "Too many arguments"; return -1;
  370. }
  371. return 0;
  372. }
  373. }
  374. tok->val.error = "Unrecognized command"; return -1;
  375. }
  376. }
  377. #ifdef DEBUG_ROUTER_TOKENS
  378. static void
  379. router_dump_token(directory_token_t *tok) {
  380. int i;
  381. switch(tok->tp)
  382. {
  383. case _SIGNATURE:
  384. puts("(signature)");
  385. return;
  386. case _PUBLIC_KEY:
  387. puts("(public key)");
  388. return;
  389. case _ERR:
  390. printf("(Error: %s\n)", tok->val.error);
  391. return;
  392. case _EOF:
  393. puts("EOF");
  394. return;
  395. case K_ACCEPT: printf("Accept"); break;
  396. case K_DIRECTORY_SIGNATURE: printf("Directory-Signature"); break;
  397. case K_REJECT: printf("Reject"); break;
  398. case K_RECOMMENDED_SOFTWARE: printf("Server-Software"); break;
  399. case K_ROUTER: printf("Router"); break;
  400. case K_SIGNED_DIRECTORY: printf("Signed-Directory"); break;
  401. case K_SIGNING_KEY: printf("Signing-Key"); break;
  402. case K_ONION_KEY: printf("Onion-key"); break;
  403. case K_LINK_KEY: printf("Link-key"); break;
  404. case K_ROUTER_SIGNATURE: printf("Router-signature"); break;
  405. case K_PUBLISHED: printf("Published"); break;
  406. case K_RUNNING_ROUTERS: printf("Running-routers"); break;
  407. case K_PLATFORM: printf("Platform"); break;
  408. default:
  409. printf("?????? %d\n", tok->tp); return;
  410. }
  411. for (i = 0; i < tok->val.cmd.n_args; ++i) {
  412. printf(" \"%s\"", tok->val.cmd.args[i]);
  413. }
  414. printf("\n");
  415. return;
  416. }
  417. static int
  418. router_get_next_token(char **s, directory_token_t *tok) {
  419. int i;
  420. i = _router_get_next_token(s, tok);
  421. router_dump_token(tok);
  422. return i;
  423. }
  424. #else
  425. #define router_get_next_token _router_get_next_token
  426. #endif
  427. /* return the first char of s that is not whitespace and not a comment */
  428. static char *eat_whitespace(char *s) {
  429. assert(s);
  430. while(isspace(*s) || *s == '#') {
  431. while(isspace(*s))
  432. s++;
  433. if(*s == '#') { /* read to a \n or \0 */
  434. while(*s && *s != '\n')
  435. s++;
  436. if(!*s)
  437. return s;
  438. }
  439. }
  440. return s;
  441. }
  442. static char *eat_whitespace_no_nl(char *s) {
  443. while(*s == ' ' || *s == '\t')
  444. ++s;
  445. return s;
  446. }
  447. /* return the first char of s that is whitespace or '#' or '\0 */
  448. static char *find_whitespace(char *s) {
  449. assert(s);
  450. while(*s && !isspace(*s) && *s != '#')
  451. s++;
  452. return s;
  453. }
  454. int router_get_list_from_string(char *s)
  455. {
  456. if (router_get_list_from_string_impl(&s, &directory, -1, NULL)) {
  457. log(LOG_WARNING, "Error parsing router file");
  458. return -1;
  459. }
  460. if (router_resolve_directory(directory)) {
  461. log(LOG_WARNING, "Error resolving directory");
  462. return -1;
  463. }
  464. return 0;
  465. }
  466. static int router_get_hash_impl(char *s, char *digest, const char *start_str,
  467. const char *end_str)
  468. {
  469. char *start, *end;
  470. start = strstr(s, start_str);
  471. if (!start) {
  472. log_fn(LOG_WARNING,"couldn't find \"%s\"",start_str);
  473. return -1;
  474. }
  475. end = strstr(start+strlen(start_str), end_str);
  476. if (!end) {
  477. log_fn(LOG_WARNING,"couldn't find \"%s\"",end_str);
  478. return -1;
  479. }
  480. end = strchr(end, '\n');
  481. if (!end) {
  482. log_fn(LOG_WARNING,"couldn't find EOL");
  483. return -1;
  484. }
  485. ++end;
  486. if (crypto_SHA_digest(start, end-start, digest)) {
  487. log_fn(LOG_WARNING,"couldn't compute digest");
  488. return -1;
  489. }
  490. return 0;
  491. }
  492. int router_get_dir_hash(char *s, char *digest)
  493. {
  494. return router_get_hash_impl(s,digest,
  495. "signed-directory","directory-signature");
  496. }
  497. int router_get_router_hash(char *s, char *digest)
  498. {
  499. return router_get_hash_impl(s,digest,
  500. "router ","router-signature");
  501. }
  502. /* return 0 if myversion is in start. Else return -1. */
  503. int compare_recommended_versions(char *myversion, char *start) {
  504. int len_myversion = strlen(myversion);
  505. char *comma;
  506. char *end = start + strlen(start);
  507. log_fn(LOG_DEBUG,"checking '%s' in '%s'.", myversion, start);
  508. for(;;) {
  509. comma = strchr(start, ',');
  510. if( ((comma ? comma : end) - start == len_myversion) &&
  511. !strncmp(start, myversion, len_myversion)) /* only do strncmp if the length matches */
  512. return 0; /* success, it's there */
  513. if(!comma)
  514. return -1; /* nope */
  515. start = comma+1;
  516. }
  517. }
  518. int router_get_dir_from_string(char *s, crypto_pk_env_t *pkey)
  519. {
  520. if (router_get_dir_from_string_impl(s, &directory, pkey)) {
  521. log_fn(LOG_WARNING, "Couldn't parse directory.");
  522. return -1;
  523. }
  524. if (router_resolve_directory(directory)) {
  525. log_fn(LOG_WARNING, "Error resolving directory");
  526. return -1;
  527. }
  528. if (compare_recommended_versions(VERSION, directory->software_versions) < 0) {
  529. log(LOG_WARNING, "You are running tor version %s, which is no longer supported.\nPlease upgrade to one of %s.", VERSION, RECOMMENDED_SOFTWARE_VERSIONS);
  530. if(options.IgnoreVersion) {
  531. log(LOG_WARNING, "IgnoreVersion is set. If it breaks, we told you so.");
  532. } else {
  533. log(LOG_ERR,"Set IgnoreVersion config variable if you want to proceed.");
  534. fflush(0);
  535. exit(0);
  536. }
  537. }
  538. return 0;
  539. }
  540. int router_get_dir_from_string_impl(char *s, directory_t **dest,
  541. crypto_pk_env_t *pkey)
  542. {
  543. directory_token_t tok;
  544. char digest[20];
  545. char signed_digest[128];
  546. directory_t *new_dir = NULL;
  547. char *versions;
  548. struct tm published;
  549. time_t published_on;
  550. const char *good_nickname_lst[1024];
  551. int n_good_nicknames;
  552. #define NEXT_TOK() \
  553. do { \
  554. if (router_get_next_token(&s, &tok)) { \
  555. log_fn(LOG_WARNING, "Error reading directory: %s", tok.val.error);\
  556. return -1; \
  557. } } while (0)
  558. #define TOK_IS(type,name) \
  559. do { \
  560. if (tok.tp != type) { \
  561. router_release_token(&tok); \
  562. log_fn(LOG_WARNING, "Error reading directory: expected %s", name);\
  563. return -1; \
  564. } } while(0)
  565. if (router_get_dir_hash(s, digest)) {
  566. log_fn(LOG_WARNING, "Unable to compute digest of directory");
  567. goto err;
  568. }
  569. log(LOG_DEBUG,"Received directory hashes to %02x:%02x:%02x:%02x",
  570. ((int)digest[0])&0xff,((int)digest[1])&0xff,
  571. ((int)digest[2])&0xff,((int)digest[3])&0xff);
  572. NEXT_TOK();
  573. TOK_IS(K_SIGNED_DIRECTORY, "signed-directory");
  574. NEXT_TOK();
  575. TOK_IS(K_PUBLISHED, "published");
  576. if (tok.val.cmd.n_args != 2) {
  577. log_fn(LOG_WARNING, "Invalid published line");
  578. goto err;
  579. }
  580. tok.val.cmd.args[1][-1] = ' ';
  581. if (!strptime(tok.val.cmd.args[0], "%Y-%m-%d %H:%M:%S", &published)) {
  582. log_fn(LOG_WARNING, "Published time was unparseable"); goto err;
  583. }
  584. published_on = timegm(&published);
  585. NEXT_TOK();
  586. TOK_IS(K_RECOMMENDED_SOFTWARE, "recommended-software");
  587. if (tok.val.cmd.n_args != 1) {
  588. log_fn(LOG_WARNING, "Invalid recommended-software line");
  589. goto err;
  590. }
  591. versions = strdup(tok.val.cmd.args[0]);
  592. NEXT_TOK();
  593. TOK_IS(K_RUNNING_ROUTERS, "running-routers");
  594. n_good_nicknames = tok.val.cmd.n_args;
  595. memcpy(good_nickname_lst, tok.val.cmd.args, n_good_nicknames*sizeof(char *));
  596. if (router_get_list_from_string_impl(&s, &new_dir,
  597. n_good_nicknames, good_nickname_lst)) {
  598. log_fn(LOG_WARNING, "Error reading routers from directory");
  599. goto err;
  600. }
  601. new_dir->software_versions = versions;
  602. new_dir->published_on = published_on;
  603. NEXT_TOK();
  604. TOK_IS(K_DIRECTORY_SIGNATURE, "directory-signature");
  605. NEXT_TOK();
  606. TOK_IS(_SIGNATURE, "signature");
  607. if (pkey) {
  608. if (crypto_pk_public_checksig(pkey, tok.val.signature, 128, signed_digest)
  609. != 20) {
  610. log_fn(LOG_WARNING, "Error reading directory: invalid signature.");
  611. free(tok.val.signature);
  612. goto err;
  613. }
  614. log(LOG_DEBUG,"Signed directory hash starts %02x:%02x:%02x:%02x",
  615. ((int)signed_digest[0])&0xff,((int)signed_digest[1])&0xff,
  616. ((int)signed_digest[2])&0xff,((int)signed_digest[3])&0xff);
  617. if (memcmp(digest, signed_digest, 20)) {
  618. log_fn(LOG_WARNING, "Error reading directory: signature does not match.");
  619. free(tok.val.signature);
  620. goto err;
  621. }
  622. }
  623. free(tok.val.signature);
  624. NEXT_TOK();
  625. TOK_IS(_EOF, "end of directory");
  626. if (*dest)
  627. directory_free(*dest);
  628. *dest = new_dir;
  629. return 0;
  630. err:
  631. if (new_dir)
  632. directory_free(new_dir);
  633. return -1;
  634. #undef NEXT_TOK
  635. #undef TOK_IS
  636. }
  637. int router_get_list_from_string_impl(char **s, directory_t **dest,
  638. int n_good_nicknames,
  639. const char **good_nickname_lst)
  640. {
  641. routerinfo_t *router;
  642. routerinfo_t **rarray;
  643. int rarray_len = 0;
  644. int i;
  645. assert(s && *s);
  646. rarray = (routerinfo_t **)tor_malloc((sizeof(routerinfo_t *))*MAX_ROUTERS_IN_DIR);
  647. while (1) {
  648. *s = eat_whitespace(*s);
  649. if (strncmp(*s, "router ", 7)!=0)
  650. break;
  651. router = router_get_entry_from_string(s);
  652. if (!router) {
  653. log_fn(LOG_WARNING, "Error reading router");
  654. return -1;
  655. }
  656. if (rarray_len >= MAX_ROUTERS_IN_DIR) {
  657. log_fn(LOG_WARNING, "too many routers");
  658. routerinfo_free(router);
  659. continue;
  660. }
  661. if (n_good_nicknames>=0) {
  662. router->is_running = 0;
  663. for (i = 0; i < n_good_nicknames; ++i) {
  664. if (0==strcasecmp(good_nickname_lst[i], router->nickname)) {
  665. router->is_running = 1;
  666. break;
  667. }
  668. }
  669. } else {
  670. router->is_running = 1; /* start out assuming all dirservers are up */
  671. }
  672. rarray[rarray_len++] = router;
  673. log_fn(LOG_DEBUG,"just added router #%d.",rarray_len);
  674. }
  675. if (*dest)
  676. directory_free(*dest);
  677. *dest = (directory_t *)tor_malloc(sizeof(directory_t));
  678. (*dest)->routers = rarray;
  679. (*dest)->n_routers = rarray_len;
  680. (*dest)->software_versions = NULL;
  681. return 0;
  682. }
  683. static int
  684. router_resolve(routerinfo_t *router)
  685. {
  686. struct hostent *rent;
  687. rent = (struct hostent *)gethostbyname(router->address);
  688. if (!rent) {
  689. log_fn(LOG_WARNING,"Could not get address for router %s.",router->address);
  690. return -1;
  691. }
  692. assert(rent->h_length == 4);
  693. memcpy(&router->addr, rent->h_addr,rent->h_length);
  694. router->addr = ntohl(router->addr); /* get it back into host order */
  695. return 0;
  696. }
  697. static int
  698. router_resolve_directory(directory_t *dir)
  699. {
  700. int i, max, remove;
  701. if (!dir)
  702. dir = directory;
  703. max = dir->n_routers;
  704. for (i = 0; i < max; ++i) {
  705. remove = 0;
  706. if (router_resolve(dir->routers[i])) {
  707. log_fn(LOG_WARNING, "Couldn't resolve router %s; removing",
  708. dir->routers[i]->address);
  709. remove = 1;
  710. routerinfo_free(dir->routers[i]);
  711. } else if (router_is_me(dir->routers[i]->addr, dir->routers[i]->or_port)) {
  712. my_routerinfo = dir->routers[i];
  713. remove = 1;
  714. }
  715. if (remove) {
  716. dir->routers[i] = dir->routers[--max];
  717. --dir->n_routers;
  718. --i;
  719. }
  720. }
  721. return 0;
  722. }
  723. /* reads a single router entry from s.
  724. * updates s so it points to after the router it just read.
  725. * mallocs a new router, returns it if all goes well, else returns NULL.
  726. */
  727. routerinfo_t *router_get_entry_from_string(char**s) {
  728. routerinfo_t *router = NULL;
  729. char signed_digest[128];
  730. char digest[128];
  731. directory_token_t _tok;
  732. directory_token_t *tok = &_tok;
  733. struct tm published;
  734. #define NEXT_TOKEN() \
  735. do { if (router_get_next_token(s, tok)) { \
  736. log_fn(LOG_WARNING, "Error reading directory: %s", tok->val.error);\
  737. goto err; \
  738. } } while(0)
  739. #define ARGS tok->val.cmd.args
  740. if (router_get_router_hash(*s, digest) < 0)
  741. return NULL;
  742. NEXT_TOKEN();
  743. if (tok->tp != K_ROUTER) {
  744. router_release_token(tok);
  745. log_fn(LOG_WARNING,"Entry does not start with \"router\"");
  746. return NULL;
  747. }
  748. router = tor_malloc(sizeof(routerinfo_t));
  749. memset(router,0,sizeof(routerinfo_t)); /* zero it out first */
  750. /* C doesn't guarantee that NULL is represented by 0 bytes. You'll
  751. thank me for this someday. */
  752. router->onion_pkey = router->identity_pkey = router->link_pkey = NULL;
  753. if (tok->val.cmd.n_args != 6) {
  754. log_fn(LOG_WARNING,"Wrong # of arguments to \"router\"");
  755. goto err;
  756. }
  757. if (!(router->nickname = strdup(ARGS[0])))
  758. goto err;
  759. if (strlen(router->nickname) > MAX_NICKNAME_LEN)
  760. goto err;
  761. if (strspn(router->nickname, LEGAL_NICKNAME_CHARACTERS) !=
  762. strlen(router->nickname))
  763. goto err;
  764. /* read router.address */
  765. if (!(router->address = strdup(ARGS[1])))
  766. goto err;
  767. router->addr = 0;
  768. /* Read router->or_port */
  769. router->or_port = atoi(ARGS[2]);
  770. if(!router->or_port) {
  771. log_fn(LOG_WARNING,"or_port unreadable or 0. Failing.");
  772. goto err;
  773. }
  774. /* Router->ap_port */
  775. router->ap_port = atoi(ARGS[3]);
  776. /* Router->dir_port */
  777. router->dir_port = atoi(ARGS[4]);
  778. /* Router->bandwidth */
  779. router->bandwidth = atoi(ARGS[5]);
  780. if (!router->bandwidth) {
  781. log_fn(LOG_WARNING,"bandwidth unreadable or 0. Failing.");
  782. }
  783. log_fn(LOG_DEBUG,"or_port %d, ap_port %d, dir_port %d, bandwidth %d.",
  784. router->or_port, router->ap_port, router->dir_port, router->bandwidth);
  785. /* XXX Later, require platform before published. */
  786. NEXT_TOKEN();
  787. if (tok->tp == K_PLATFORM) {
  788. NEXT_TOKEN();
  789. }
  790. if (tok->tp != K_PUBLISHED) {
  791. log_fn(LOG_WARNING, "Missing published time"); goto err;
  792. }
  793. if (tok->val.cmd.n_args != 2) {
  794. log_fn(LOG_WARNING, "Wrong number of arguments to published"); goto err;
  795. }
  796. ARGS[1][-1] = ' '; /* Re-insert space. */
  797. if (!strptime(ARGS[0], "%Y-%m-%d %H:%M:%S", &published)) {
  798. log_fn(LOG_WARNING, "Published time was unparseable"); goto err;
  799. }
  800. router->published_on = timegm(&published);
  801. NEXT_TOKEN();
  802. if (tok->tp != K_ONION_KEY) {
  803. log_fn(LOG_WARNING, "Missing onion-key"); goto err;
  804. }
  805. NEXT_TOKEN();
  806. if (tok->tp != _PUBLIC_KEY) {
  807. log_fn(LOG_WARNING, "Missing onion key"); goto err;
  808. } /* XXX Check key length */
  809. router->onion_pkey = tok->val.public_key;
  810. NEXT_TOKEN();
  811. if (tok->tp != K_LINK_KEY) {
  812. log_fn(LOG_WARNING, "Missing link-key"); goto err;
  813. }
  814. NEXT_TOKEN();
  815. if (tok->tp != _PUBLIC_KEY) {
  816. log_fn(LOG_WARNING, "Missing link key"); goto err;
  817. } /* XXX Check key length */
  818. router->link_pkey = tok->val.public_key;
  819. NEXT_TOKEN();
  820. if (tok->tp != K_SIGNING_KEY) {
  821. log_fn(LOG_WARNING, "Missing signing-key"); goto err;
  822. }
  823. NEXT_TOKEN();
  824. if (tok->tp != _PUBLIC_KEY) {
  825. log_fn(LOG_WARNING, "Missing signing key"); goto err;
  826. }
  827. router->identity_pkey = tok->val.public_key;
  828. NEXT_TOKEN();
  829. while (tok->tp == K_ACCEPT || tok->tp == K_REJECT) {
  830. router_add_exit_policy(router, tok);
  831. NEXT_TOKEN();
  832. }
  833. if (tok->tp != K_ROUTER_SIGNATURE) {
  834. log_fn(LOG_WARNING,"Missing router signature");
  835. goto err;
  836. }
  837. NEXT_TOKEN();
  838. if (tok->tp != _SIGNATURE) {
  839. log_fn(LOG_WARNING,"Missing router signature");
  840. goto err;
  841. }
  842. assert (router->identity_pkey);
  843. if (crypto_pk_public_checksig(router->identity_pkey, tok->val.signature,
  844. 128, signed_digest) != 20) {
  845. log_fn(LOG_WARNING, "Invalid signature");
  846. goto err;
  847. }
  848. if (memcmp(digest, signed_digest, 20)) {
  849. log_fn(LOG_WARNING, "Mismatched signature");
  850. goto err;
  851. }
  852. return router;
  853. err:
  854. router_release_token(tok);
  855. if(router->address)
  856. free(router->address);
  857. if(router->link_pkey)
  858. crypto_free_pk_env(router->link_pkey);
  859. if(router->onion_pkey)
  860. crypto_free_pk_env(router->onion_pkey);
  861. if(router->identity_pkey)
  862. crypto_free_pk_env(router->identity_pkey);
  863. router_free_exit_policy(router);
  864. free(router);
  865. return NULL;
  866. #undef ARGS
  867. #undef NEXT_TOKEN
  868. }
  869. static void router_free_exit_policy(routerinfo_t *router) {
  870. struct exit_policy_t *tmpe;
  871. while(router->exit_policy) {
  872. tmpe = router->exit_policy;
  873. router->exit_policy = tmpe->next;
  874. free(tmpe->string);
  875. free(tmpe->address);
  876. free(tmpe->port);
  877. free(tmpe);
  878. }
  879. }
  880. static int router_add_exit_policy(routerinfo_t *router,
  881. directory_token_t *tok) {
  882. struct exit_policy_t *tmpe, *newe;
  883. char *arg, *colon;
  884. if (tok->val.cmd.n_args != 1)
  885. return -1;
  886. arg = tok->val.cmd.args[0];
  887. newe = tor_malloc(sizeof(struct exit_policy_t));
  888. memset(newe,0,sizeof(struct exit_policy_t));
  889. newe->string = tor_malloc(8+strlen(arg));
  890. if (tok->tp == K_REJECT) {
  891. strcpy(newe->string, "reject ");
  892. newe->policy_type = EXIT_POLICY_REJECT;
  893. } else {
  894. assert(tok->tp == K_ACCEPT);
  895. strcpy(newe->string, "accept ");
  896. newe->policy_type = EXIT_POLICY_ACCEPT;
  897. }
  898. strcat(newe->string, arg);
  899. colon = strchr(arg,':');
  900. if(!colon)
  901. goto policy_read_failed;
  902. *colon = 0;
  903. newe->address = strdup(arg);
  904. newe->port = strdup(colon+1);
  905. log_fn(LOG_DEBUG,"%s %s:%s",
  906. newe->policy_type == EXIT_POLICY_REJECT ? "reject" : "accept",
  907. newe->address, newe->port);
  908. /* now link newe onto the end of exit_policy */
  909. if(!router->exit_policy) {
  910. router->exit_policy = newe;
  911. return 0;
  912. }
  913. for(tmpe=router->exit_policy; tmpe->next; tmpe=tmpe->next) ;
  914. tmpe->next = newe;
  915. return 0;
  916. policy_read_failed:
  917. assert(newe->string);
  918. log_fn(LOG_WARNING,"Couldn't parse line '%s'. Dropping", newe->string);
  919. if(newe->string)
  920. free(newe->string);
  921. if(newe->address)
  922. free(newe->address);
  923. if(newe->port)
  924. free(newe->port);
  925. free(newe);
  926. return -1;
  927. }
  928. /* Return 0 if my exit policy says to allow connection to conn.
  929. * Else return -1.
  930. */
  931. int router_compare_to_exit_policy(connection_t *conn) {
  932. struct exit_policy_t *tmpe;
  933. if(!my_routerinfo) {
  934. log_fn(LOG_WARNING, "my_routerinfo undefined! Rejected.");
  935. return -1;
  936. }
  937. for(tmpe=my_routerinfo->exit_policy; tmpe; tmpe=tmpe->next) {
  938. assert(tmpe->address);
  939. assert(tmpe->port);
  940. /* Totally ignore the address field of the exit policy, for now. */
  941. if(!strcmp(tmpe->port,"*") || atoi(tmpe->port) == conn->port) {
  942. log_fn(LOG_INFO,"Port '%s' matches '%d'. %s.",
  943. tmpe->port, conn->port,
  944. tmpe->policy_type == EXIT_POLICY_ACCEPT ? "Accepting" : "Rejecting");
  945. if(tmpe->policy_type == EXIT_POLICY_ACCEPT)
  946. return 0;
  947. else
  948. return -1;
  949. }
  950. }
  951. return 0; /* accept all by default. */
  952. }
  953. static char descriptor[8192];
  954. /* XXX should this replace my_routerinfo? */
  955. static routerinfo_t *desc_routerinfo = NULL;
  956. const char *router_get_my_descriptor(void) {
  957. if (!desc_routerinfo) {
  958. if (init_descriptor())
  959. return NULL;
  960. }
  961. log_fn(LOG_DEBUG,"my desc is '%s'",descriptor);
  962. return descriptor;
  963. }
  964. const routerinfo_t *router_get_desc_routerinfo(void) {
  965. if (!desc_routerinfo) {
  966. if (init_descriptor())
  967. return NULL;
  968. }
  969. return desc_routerinfo;
  970. }
  971. static int init_descriptor(void) {
  972. routerinfo_t *ri;
  973. char localhostname[256];
  974. char *address = options.Address;
  975. if(!address) { /* if not specified in config, we find a default */
  976. if(gethostname(localhostname,sizeof(localhostname)) < 0) {
  977. log_fn(LOG_WARNING,"Error obtaining local hostname");
  978. return -1;
  979. }
  980. address = localhostname;
  981. }
  982. ri = tor_malloc(sizeof(routerinfo_t));
  983. ri->address = strdup(address);
  984. ri->nickname = strdup(options.Nickname);
  985. /* No need to set addr. */
  986. ri->or_port = options.ORPort;
  987. ri->ap_port = options.APPort;
  988. ri->dir_port = options.DirPort;
  989. ri->published_on = time(NULL);
  990. ri->onion_pkey = crypto_pk_dup_key(get_onion_key());
  991. ri->link_pkey = crypto_pk_dup_key(get_link_key());
  992. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  993. ri->bandwidth = options.TotalBandwidth;
  994. ri->exit_policy = NULL; /* XXX implement this. */
  995. if (desc_routerinfo)
  996. routerinfo_free(desc_routerinfo);
  997. desc_routerinfo = ri;
  998. if (router_dump_router_to_string(descriptor, 8192, ri, get_identity_key())<0) {
  999. log_fn(LOG_WARNING, "Couldn't dump router to string.");
  1000. return -1;
  1001. }
  1002. return 0;
  1003. }
  1004. static void get_platform_str(char *platform, int len)
  1005. {
  1006. #ifdef HAVE_UNAME
  1007. struct utsname u;
  1008. if (!uname(&u)) {
  1009. snprintf(platform, len-1, "Tor %s on %s %s %s %s %s",
  1010. VERSION, u.sysname, u.nodename, u.release, u.version, u.machine);
  1011. platform[len-1] = '\0';
  1012. return;
  1013. } else
  1014. #endif
  1015. {
  1016. snprintf(platform, len-1, "Tor %s", VERSION);
  1017. }
  1018. }
  1019. int router_dump_router_to_string(char *s, int maxlen, routerinfo_t *router,
  1020. crypto_pk_env_t *ident_key) {
  1021. char *onion_pkey;
  1022. char *link_pkey;
  1023. char *identity_pkey;
  1024. char platform[256];
  1025. char digest[20];
  1026. char signature[128];
  1027. char published[32];
  1028. int onion_pkeylen, link_pkeylen, identity_pkeylen;
  1029. int written;
  1030. int result=0;
  1031. struct exit_policy_t *tmpe;
  1032. get_platform_str(platform, sizeof(platform));
  1033. if(crypto_pk_write_public_key_to_string(router->onion_pkey,
  1034. &onion_pkey,&onion_pkeylen)<0) {
  1035. log_fn(LOG_WARNING,"write onion_pkey to string failed!");
  1036. return -1;
  1037. }
  1038. if(crypto_pk_write_public_key_to_string(router->identity_pkey,
  1039. &identity_pkey,&identity_pkeylen)<0) {
  1040. log_fn(LOG_WARNING,"write identity_pkey to string failed!");
  1041. return -1;
  1042. }
  1043. if(crypto_pk_write_public_key_to_string(router->link_pkey,
  1044. &link_pkey,&link_pkeylen)<0) {
  1045. log_fn(LOG_WARNING,"write link_pkey to string failed!");
  1046. return -1;
  1047. }
  1048. strftime(published, 32, "%Y-%m-%d %H:%M:%S", gmtime(&router->published_on));
  1049. result = snprintf(s, maxlen,
  1050. "router %s %s %d %d %d %d\n"
  1051. "platform %s\n"
  1052. "published %s\n"
  1053. "onion-key\n%s"
  1054. "link-key\n%s"
  1055. "signing-key\n%s",
  1056. router->nickname,
  1057. router->address,
  1058. router->or_port,
  1059. router->ap_port,
  1060. router->dir_port,
  1061. router->bandwidth,
  1062. platform,
  1063. published,
  1064. onion_pkey, link_pkey, identity_pkey);
  1065. free(onion_pkey);
  1066. free(link_pkey);
  1067. free(identity_pkey);
  1068. if(result < 0 || result >= maxlen) {
  1069. /* apparently different glibcs do different things on snprintf error.. so check both */
  1070. return -1;
  1071. }
  1072. written = result;
  1073. for(tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
  1074. result = snprintf(s+written, maxlen-written, "%s %s:%s\n",
  1075. tmpe->policy_type == EXIT_POLICY_ACCEPT ? "accept" : "reject",
  1076. tmpe->address, tmpe->port);
  1077. if(result < 0 || result+written > maxlen) {
  1078. /* apparently different glibcs do different things on snprintf error.. so check both */
  1079. return -1;
  1080. }
  1081. written += result;
  1082. }
  1083. if (written > maxlen-256) /* Not enough room for signature. */
  1084. return -1;
  1085. strcat(s+written, "router-signature\n");
  1086. written += strlen(s+written);
  1087. s[written] = '\0';
  1088. if (router_get_router_hash(s, digest) < 0)
  1089. return -1;
  1090. if (crypto_pk_private_sign(ident_key, digest, 20, signature) < 0) {
  1091. log_fn(LOG_WARNING, "Error signing digest");
  1092. return -1;
  1093. }
  1094. strcat(s+written, "-----BEGIN SIGNATURE-----\n");
  1095. written += strlen(s+written);
  1096. if (base64_encode(s+written, maxlen-written, signature, 128) < 0) {
  1097. log_fn(LOG_WARNING, "Couldn't base64-encode signature");
  1098. return -1;
  1099. }
  1100. written += strlen(s+written);
  1101. strcat(s+written, "-----END SIGNATURE-----\n");
  1102. written += strlen(s+written);
  1103. if (written > maxlen-2)
  1104. return -1;
  1105. /* include a last '\n' */
  1106. s[written] = '\n';
  1107. s[written+1] = 0;
  1108. return written+1;
  1109. }
  1110. /*
  1111. Local Variables:
  1112. mode:c
  1113. indent-tabs-mode:nil
  1114. c-basic-offset:2
  1115. End:
  1116. */