policies.c 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2010, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file policies.c
  7. * \brief Code to parse and use address policies and exit policies.
  8. **/
  9. #include "or.h"
  10. #include "config.h"
  11. #include "ht.h"
  12. /** Policy that addresses for incoming SOCKS connections must match. */
  13. static smartlist_t *socks_policy = NULL;
  14. /** Policy that addresses for incoming directory connections must match. */
  15. static smartlist_t *dir_policy = NULL;
  16. /** Policy that addresses for incoming router descriptors must match in order
  17. * to be published by us. */
  18. static smartlist_t *authdir_reject_policy = NULL;
  19. /** Policy that addresses for incoming router descriptors must match in order
  20. * to be marked as valid in our networkstatus. */
  21. static smartlist_t *authdir_invalid_policy = NULL;
  22. /** Policy that addresses for incoming router descriptors must <b>not</b>
  23. * match in order to not be marked as BadDirectory. */
  24. static smartlist_t *authdir_baddir_policy = NULL;
  25. /** Policy that addresses for incoming router descriptors must <b>not</b>
  26. * match in order to not be marked as BadExit. */
  27. static smartlist_t *authdir_badexit_policy = NULL;
  28. /** Parsed addr_policy_t describing which addresses we believe we can start
  29. * circuits at. */
  30. static smartlist_t *reachable_or_addr_policy = NULL;
  31. /** Parsed addr_policy_t describing which addresses we believe we can connect
  32. * to directories at. */
  33. static smartlist_t *reachable_dir_addr_policy = NULL;
  34. /** Element of an exit policy summary */
  35. typedef struct policy_summary_item_t {
  36. uint16_t prt_min; /**< Lowest port number to accept/reject. */
  37. uint16_t prt_max; /**< Highest port number to accept/reject. */
  38. uint64_t reject_count; /**< Number of IP-Addresses that are rejected to
  39. this port range. */
  40. int accepted:1; /** Has this port already been accepted */
  41. } policy_summary_item_t;
  42. /** Private networks. This list is used in two places, once to expand the
  43. * "private" keyword when parsing our own exit policy, secondly to ignore
  44. * just such networks when building exit policy summaries. It is important
  45. * that all authorities agree on that list when creating summaries, so don't
  46. * just change this without a proper migration plan and a proposal and stuff.
  47. */
  48. static const char *private_nets[] = {
  49. "0.0.0.0/8", "169.254.0.0/16",
  50. "127.0.0.0/8", "192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12",
  51. // "fc00::/7", "fe80::/10", "fec0::/10", "::/127",
  52. NULL };
  53. /** Replace all "private" entries in *<b>policy</b> with their expanded
  54. * equivalents. */
  55. void
  56. policy_expand_private(smartlist_t **policy)
  57. {
  58. uint16_t port_min, port_max;
  59. int i;
  60. smartlist_t *tmp;
  61. if (!*policy) /*XXXX disallow NULL policies? */
  62. return;
  63. tmp = smartlist_create();
  64. SMARTLIST_FOREACH(*policy, addr_policy_t *, p,
  65. {
  66. if (! p->is_private) {
  67. smartlist_add(tmp, p);
  68. continue;
  69. }
  70. for (i = 0; private_nets[i]; ++i) {
  71. addr_policy_t policy;
  72. memcpy(&policy, p, sizeof(addr_policy_t));
  73. policy.is_private = 0;
  74. policy.is_canonical = 0;
  75. if (tor_addr_parse_mask_ports(private_nets[i], &policy.addr,
  76. &policy.maskbits, &port_min, &port_max)<0) {
  77. tor_assert(0);
  78. }
  79. smartlist_add(tmp, addr_policy_get_canonical_entry(&policy));
  80. }
  81. addr_policy_free(p);
  82. });
  83. smartlist_free(*policy);
  84. *policy = tmp;
  85. }
  86. /**
  87. * Given a linked list of config lines containing "allow" and "deny"
  88. * tokens, parse them and append the result to <b>dest</b>. Return -1
  89. * if any tokens are malformed (and don't append any), else return 0.
  90. *
  91. * If <b>assume_action</b> is nonnegative, then insert its action
  92. * (ADDR_POLICY_ACCEPT or ADDR_POLICY_REJECT) for items that specify no
  93. * action.
  94. */
  95. static int
  96. parse_addr_policy(config_line_t *cfg, smartlist_t **dest,
  97. int assume_action)
  98. {
  99. smartlist_t *result;
  100. smartlist_t *entries;
  101. addr_policy_t *item;
  102. int r = 0;
  103. if (!cfg)
  104. return 0;
  105. result = smartlist_create();
  106. entries = smartlist_create();
  107. for (; cfg; cfg = cfg->next) {
  108. smartlist_split_string(entries, cfg->value, ",",
  109. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  110. SMARTLIST_FOREACH(entries, const char *, ent,
  111. {
  112. log_debug(LD_CONFIG,"Adding new entry '%s'",ent);
  113. item = router_parse_addr_policy_item_from_string(ent, assume_action);
  114. if (item) {
  115. smartlist_add(result, item);
  116. } else {
  117. log_warn(LD_CONFIG,"Malformed policy '%s'.", ent);
  118. r = -1;
  119. }
  120. });
  121. SMARTLIST_FOREACH(entries, char *, ent, tor_free(ent));
  122. smartlist_clear(entries);
  123. }
  124. smartlist_free(entries);
  125. if (r == -1) {
  126. addr_policy_list_free(result);
  127. } else {
  128. policy_expand_private(&result);
  129. if (*dest) {
  130. smartlist_add_all(*dest, result);
  131. smartlist_free(result);
  132. } else {
  133. *dest = result;
  134. }
  135. }
  136. return r;
  137. }
  138. /** Helper: parse the Reachable(Dir|OR)?Addresses fields into
  139. * reachable_(or|dir)_addr_policy. The options should already have
  140. * been validated by validate_addr_policies.
  141. */
  142. static int
  143. parse_reachable_addresses(void)
  144. {
  145. or_options_t *options = get_options();
  146. int ret = 0;
  147. if (options->ReachableDirAddresses &&
  148. options->ReachableORAddresses &&
  149. options->ReachableAddresses) {
  150. log_warn(LD_CONFIG,
  151. "Both ReachableDirAddresses and ReachableORAddresses are set. "
  152. "ReachableAddresses setting will be ignored.");
  153. }
  154. addr_policy_list_free(reachable_or_addr_policy);
  155. reachable_or_addr_policy = NULL;
  156. if (!options->ReachableORAddresses && options->ReachableAddresses)
  157. log_info(LD_CONFIG,
  158. "Using ReachableAddresses as ReachableORAddresses.");
  159. if (parse_addr_policy(options->ReachableORAddresses ?
  160. options->ReachableORAddresses :
  161. options->ReachableAddresses,
  162. &reachable_or_addr_policy, ADDR_POLICY_ACCEPT)) {
  163. log_warn(LD_CONFIG,
  164. "Error parsing Reachable%sAddresses entry; ignoring.",
  165. options->ReachableORAddresses ? "OR" : "");
  166. ret = -1;
  167. }
  168. addr_policy_list_free(reachable_dir_addr_policy);
  169. reachable_dir_addr_policy = NULL;
  170. if (!options->ReachableDirAddresses && options->ReachableAddresses)
  171. log_info(LD_CONFIG,
  172. "Using ReachableAddresses as ReachableDirAddresses");
  173. if (parse_addr_policy(options->ReachableDirAddresses ?
  174. options->ReachableDirAddresses :
  175. options->ReachableAddresses,
  176. &reachable_dir_addr_policy, ADDR_POLICY_ACCEPT)) {
  177. if (options->ReachableDirAddresses)
  178. log_warn(LD_CONFIG,
  179. "Error parsing ReachableDirAddresses entry; ignoring.");
  180. ret = -1;
  181. }
  182. return ret;
  183. }
  184. /** Return true iff the firewall options might block any address:port
  185. * combination.
  186. */
  187. int
  188. firewall_is_fascist_or(void)
  189. {
  190. return reachable_or_addr_policy != NULL;
  191. }
  192. /** Return true iff <b>policy</b> (possibly NULL) will allow a
  193. * connection to <b>addr</b>:<b>port</b>.
  194. */
  195. static int
  196. addr_policy_permits_tor_addr(const tor_addr_t *addr, uint16_t port,
  197. smartlist_t *policy)
  198. {
  199. addr_policy_result_t p;
  200. p = compare_tor_addr_to_addr_policy(addr, port, policy);
  201. switch (p) {
  202. case ADDR_POLICY_PROBABLY_ACCEPTED:
  203. case ADDR_POLICY_ACCEPTED:
  204. return 1;
  205. case ADDR_POLICY_PROBABLY_REJECTED:
  206. case ADDR_POLICY_REJECTED:
  207. return 0;
  208. default:
  209. log_warn(LD_BUG, "Unexpected result: %d", (int)p);
  210. return 0;
  211. }
  212. }
  213. /** Return true iff <b> policy</b> (possibly NULL) will allow a connection to
  214. * <b>addr</b>:<b>port</b>. <b>addr</b> is an IPv4 address given in host
  215. * order. */
  216. /* XXXX deprecate when possible. */
  217. static int
  218. addr_policy_permits_address(uint32_t addr, uint16_t port,
  219. smartlist_t *policy)
  220. {
  221. tor_addr_t a;
  222. tor_addr_from_ipv4h(&a, addr);
  223. return addr_policy_permits_tor_addr(&a, port, policy);
  224. }
  225. /** Return true iff we think our firewall will let us make an OR connection to
  226. * addr:port. */
  227. int
  228. fascist_firewall_allows_address_or(const tor_addr_t *addr, uint16_t port)
  229. {
  230. return addr_policy_permits_tor_addr(addr, port,
  231. reachable_or_addr_policy);
  232. }
  233. /** Return true iff we think our firewall will let us make an OR connection to
  234. * <b>ri</b>. */
  235. int
  236. fascist_firewall_allows_or(routerinfo_t *ri)
  237. {
  238. /* XXXX proposal 118 */
  239. tor_addr_t addr;
  240. tor_addr_from_ipv4h(&addr, ri->addr);
  241. return fascist_firewall_allows_address_or(&addr, ri->or_port);
  242. }
  243. /** Return true iff we think our firewall will let us make a directory
  244. * connection to addr:port. */
  245. int
  246. fascist_firewall_allows_address_dir(const tor_addr_t *addr, uint16_t port)
  247. {
  248. return addr_policy_permits_tor_addr(addr, port,
  249. reachable_dir_addr_policy);
  250. }
  251. /** Return 1 if <b>addr</b> is permitted to connect to our dir port,
  252. * based on <b>dir_policy</b>. Else return 0.
  253. */
  254. int
  255. dir_policy_permits_address(const tor_addr_t *addr)
  256. {
  257. return addr_policy_permits_tor_addr(addr, 1, dir_policy);
  258. }
  259. /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
  260. * based on <b>socks_policy</b>. Else return 0.
  261. */
  262. int
  263. socks_policy_permits_address(const tor_addr_t *addr)
  264. {
  265. return addr_policy_permits_tor_addr(addr, 1, socks_policy);
  266. }
  267. /** Return 1 if <b>addr</b>:<b>port</b> is permitted to publish to our
  268. * directory, based on <b>authdir_reject_policy</b>. Else return 0.
  269. */
  270. int
  271. authdir_policy_permits_address(uint32_t addr, uint16_t port)
  272. {
  273. return addr_policy_permits_address(addr, port, authdir_reject_policy);
  274. }
  275. /** Return 1 if <b>addr</b>:<b>port</b> is considered valid in our
  276. * directory, based on <b>authdir_invalid_policy</b>. Else return 0.
  277. */
  278. int
  279. authdir_policy_valid_address(uint32_t addr, uint16_t port)
  280. {
  281. return addr_policy_permits_address(addr, port, authdir_invalid_policy);
  282. }
  283. /** Return 1 if <b>addr</b>:<b>port</b> should be marked as a bad dir,
  284. * based on <b>authdir_baddir_policy</b>. Else return 0.
  285. */
  286. int
  287. authdir_policy_baddir_address(uint32_t addr, uint16_t port)
  288. {
  289. return ! addr_policy_permits_address(addr, port, authdir_baddir_policy);
  290. }
  291. /** Return 1 if <b>addr</b>:<b>port</b> should be marked as a bad exit,
  292. * based on <b>authdir_badexit_policy</b>. Else return 0.
  293. */
  294. int
  295. authdir_policy_badexit_address(uint32_t addr, uint16_t port)
  296. {
  297. return ! addr_policy_permits_address(addr, port, authdir_badexit_policy);
  298. }
  299. #define REJECT(arg) \
  300. STMT_BEGIN *msg = tor_strdup(arg); goto err; STMT_END
  301. /** Config helper: If there's any problem with the policy configuration
  302. * options in <b>options</b>, return -1 and set <b>msg</b> to a newly
  303. * allocated description of the error. Else return 0. */
  304. int
  305. validate_addr_policies(or_options_t *options, char **msg)
  306. {
  307. /* XXXX Maybe merge this into parse_policies_from_options, to make sure
  308. * that the two can't go out of sync. */
  309. smartlist_t *addr_policy=NULL;
  310. *msg = NULL;
  311. if (policies_parse_exit_policy(options->ExitPolicy, &addr_policy,
  312. options->ExitPolicyRejectPrivate, NULL,
  313. !options->BridgeRelay))
  314. REJECT("Error in ExitPolicy entry.");
  315. /* The rest of these calls *append* to addr_policy. So don't actually
  316. * use the results for anything other than checking if they parse! */
  317. if (parse_addr_policy(options->DirPolicy, &addr_policy, -1))
  318. REJECT("Error in DirPolicy entry.");
  319. if (parse_addr_policy(options->SocksPolicy, &addr_policy, -1))
  320. REJECT("Error in SocksPolicy entry.");
  321. if (parse_addr_policy(options->AuthDirReject, &addr_policy,
  322. ADDR_POLICY_REJECT))
  323. REJECT("Error in AuthDirReject entry.");
  324. if (parse_addr_policy(options->AuthDirInvalid, &addr_policy,
  325. ADDR_POLICY_REJECT))
  326. REJECT("Error in AuthDirInvalid entry.");
  327. if (parse_addr_policy(options->AuthDirBadDir, &addr_policy,
  328. ADDR_POLICY_REJECT))
  329. REJECT("Error in AuthDirBadDir entry.");
  330. if (parse_addr_policy(options->AuthDirBadExit, &addr_policy,
  331. ADDR_POLICY_REJECT))
  332. REJECT("Error in AuthDirBadExit entry.");
  333. if (parse_addr_policy(options->ReachableAddresses, &addr_policy,
  334. ADDR_POLICY_ACCEPT))
  335. REJECT("Error in ReachableAddresses entry.");
  336. if (parse_addr_policy(options->ReachableORAddresses, &addr_policy,
  337. ADDR_POLICY_ACCEPT))
  338. REJECT("Error in ReachableORAddresses entry.");
  339. if (parse_addr_policy(options->ReachableDirAddresses, &addr_policy,
  340. ADDR_POLICY_ACCEPT))
  341. REJECT("Error in ReachableDirAddresses entry.");
  342. err:
  343. addr_policy_list_free(addr_policy);
  344. return *msg ? -1 : 0;
  345. #undef REJECT
  346. }
  347. /** Parse <b>string</b> in the same way that the exit policy
  348. * is parsed, and put the processed version in *<b>policy</b>.
  349. * Ignore port specifiers.
  350. */
  351. static int
  352. load_policy_from_option(config_line_t *config, smartlist_t **policy,
  353. int assume_action)
  354. {
  355. int r;
  356. addr_policy_list_free(*policy);
  357. *policy = NULL;
  358. r = parse_addr_policy(config, policy, assume_action);
  359. if (r < 0) {
  360. return -1;
  361. }
  362. if (*policy) {
  363. SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, n) {
  364. /* ports aren't used in these. */
  365. if (n->prt_min > 1 || n->prt_max != 65535) {
  366. addr_policy_t newp, *c;
  367. memcpy(&newp, n, sizeof(newp));
  368. newp.prt_min = 1;
  369. newp.prt_max = 65535;
  370. newp.is_canonical = 0;
  371. c = addr_policy_get_canonical_entry(&newp);
  372. SMARTLIST_REPLACE_CURRENT(*policy, n, c);
  373. addr_policy_free(n);
  374. }
  375. } SMARTLIST_FOREACH_END(n);
  376. }
  377. return 0;
  378. }
  379. /** Set all policies based on <b>options</b>, which should have been validated
  380. * first by validate_addr_policies. */
  381. int
  382. policies_parse_from_options(or_options_t *options)
  383. {
  384. int ret = 0;
  385. if (load_policy_from_option(options->SocksPolicy, &socks_policy, -1) < 0)
  386. ret = -1;
  387. if (load_policy_from_option(options->DirPolicy, &dir_policy, -1) < 0)
  388. ret = -1;
  389. if (load_policy_from_option(options->AuthDirReject,
  390. &authdir_reject_policy, ADDR_POLICY_REJECT) < 0)
  391. ret = -1;
  392. if (load_policy_from_option(options->AuthDirInvalid,
  393. &authdir_invalid_policy, ADDR_POLICY_REJECT) < 0)
  394. ret = -1;
  395. if (load_policy_from_option(options->AuthDirBadDir,
  396. &authdir_baddir_policy, ADDR_POLICY_REJECT) < 0)
  397. ret = -1;
  398. if (load_policy_from_option(options->AuthDirBadExit,
  399. &authdir_badexit_policy, ADDR_POLICY_REJECT) < 0)
  400. ret = -1;
  401. if (parse_reachable_addresses() < 0)
  402. ret = -1;
  403. return ret;
  404. }
  405. /** Compare two provided address policy items, and return -1, 0, or 1
  406. * if the first is less than, equal to, or greater than the second. */
  407. static int
  408. cmp_single_addr_policy(addr_policy_t *a, addr_policy_t *b)
  409. {
  410. int r;
  411. if ((r=((int)a->policy_type - (int)b->policy_type)))
  412. return r;
  413. if ((r=((int)a->is_private - (int)b->is_private)))
  414. return r;
  415. if ((r=tor_addr_compare(&a->addr, &b->addr, CMP_EXACT)))
  416. return r;
  417. if ((r=((int)a->maskbits - (int)b->maskbits)))
  418. return r;
  419. if ((r=((int)a->prt_min - (int)b->prt_min)))
  420. return r;
  421. if ((r=((int)a->prt_max - (int)b->prt_max)))
  422. return r;
  423. return 0;
  424. }
  425. /** Like cmp_single_addr_policy() above, but looks at the
  426. * whole set of policies in each case. */
  427. int
  428. cmp_addr_policies(smartlist_t *a, smartlist_t *b)
  429. {
  430. int r, i;
  431. int len_a = a ? smartlist_len(a) : 0;
  432. int len_b = b ? smartlist_len(b) : 0;
  433. for (i = 0; i < len_a && i < len_b; ++i) {
  434. if ((r = cmp_single_addr_policy(smartlist_get(a, i), smartlist_get(b, i))))
  435. return r;
  436. }
  437. if (i == len_a && i == len_b)
  438. return 0;
  439. if (i < len_a)
  440. return -1;
  441. else
  442. return 1;
  443. }
  444. /** Node in hashtable used to store address policy entries. */
  445. typedef struct policy_map_ent_t {
  446. HT_ENTRY(policy_map_ent_t) node;
  447. addr_policy_t *policy;
  448. } policy_map_ent_t;
  449. static HT_HEAD(policy_map, policy_map_ent_t) policy_root = HT_INITIALIZER();
  450. /** Return true iff a and b are equal. */
  451. static INLINE int
  452. policy_eq(policy_map_ent_t *a, policy_map_ent_t *b)
  453. {
  454. return cmp_single_addr_policy(a->policy, b->policy) == 0;
  455. }
  456. /** Return a hashcode for <b>ent</b> */
  457. static unsigned int
  458. policy_hash(policy_map_ent_t *ent)
  459. {
  460. addr_policy_t *a = ent->policy;
  461. unsigned int r;
  462. if (a->is_private)
  463. r = 0x1234abcd;
  464. else
  465. r = tor_addr_hash(&a->addr);
  466. r += a->prt_min << 8;
  467. r += a->prt_max << 16;
  468. r += a->maskbits;
  469. if (a->policy_type == ADDR_POLICY_REJECT)
  470. r ^= 0xffffffff;
  471. return r;
  472. }
  473. HT_PROTOTYPE(policy_map, policy_map_ent_t, node, policy_hash,
  474. policy_eq)
  475. HT_GENERATE(policy_map, policy_map_ent_t, node, policy_hash,
  476. policy_eq, 0.6, malloc, realloc, free)
  477. /** Given a pointer to an addr_policy_t, return a copy of the pointer to the
  478. * "canonical" copy of that addr_policy_t; the canonical copy is a single
  479. * reference-counted object. */
  480. addr_policy_t *
  481. addr_policy_get_canonical_entry(addr_policy_t *e)
  482. {
  483. policy_map_ent_t search, *found;
  484. if (e->is_canonical)
  485. return e;
  486. search.policy = e;
  487. found = HT_FIND(policy_map, &policy_root, &search);
  488. if (!found) {
  489. found = tor_malloc_zero(sizeof(policy_map_ent_t));
  490. found->policy = tor_memdup(e, sizeof(addr_policy_t));
  491. found->policy->is_canonical = 1;
  492. found->policy->refcnt = 0;
  493. HT_INSERT(policy_map, &policy_root, found);
  494. }
  495. tor_assert(!cmp_single_addr_policy(found->policy, e));
  496. ++found->policy->refcnt;
  497. return found->policy;
  498. }
  499. /** As compare_tor_addr_to_addr_policy, but instead of a tor_addr_t, takes
  500. * in host order. */
  501. addr_policy_result_t
  502. compare_addr_to_addr_policy(uint32_t addr, uint16_t port,
  503. const smartlist_t *policy)
  504. {
  505. /*XXXX deprecate this function when possible. */
  506. tor_addr_t a;
  507. tor_addr_from_ipv4h(&a, addr);
  508. return compare_tor_addr_to_addr_policy(&a, port, policy);
  509. }
  510. /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
  511. * addr and port are both known. */
  512. static addr_policy_result_t
  513. compare_known_tor_addr_to_addr_policy(const tor_addr_t *addr, uint16_t port,
  514. const smartlist_t *policy)
  515. {
  516. /* We know the address and port, and we know the policy, so we can just
  517. * compute an exact match. */
  518. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
  519. /* Address is known */
  520. if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
  521. CMP_EXACT)) {
  522. if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
  523. /* Exact match for the policy */
  524. return tmpe->policy_type == ADDR_POLICY_ACCEPT ?
  525. ADDR_POLICY_ACCEPTED : ADDR_POLICY_REJECTED;
  526. }
  527. }
  528. } SMARTLIST_FOREACH_END(tmpe);
  529. /* accept all by default. */
  530. return ADDR_POLICY_ACCEPTED;
  531. }
  532. /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
  533. * addr is known but port is not. */
  534. static addr_policy_result_t
  535. compare_known_tor_addr_to_addr_policy_noport(const tor_addr_t *addr,
  536. const smartlist_t *policy)
  537. {
  538. /* We look to see if there's a definite match. If so, we return that
  539. match's value, unless there's an intervening possible match that says
  540. something different. */
  541. int maybe_accept = 0, maybe_reject = 0;
  542. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
  543. if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
  544. CMP_EXACT)) {
  545. if (tmpe->prt_min <= 1 && tmpe->prt_max >= 65535) {
  546. /* Definitely matches, since it covers all ports. */
  547. if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
  548. /* If we already hit a clause that might trigger a 'reject', than we
  549. * can't be sure of this certain 'accept'.*/
  550. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
  551. ADDR_POLICY_ACCEPTED;
  552. } else {
  553. return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
  554. ADDR_POLICY_REJECTED;
  555. }
  556. } else {
  557. /* Might match. */
  558. if (tmpe->policy_type == ADDR_POLICY_REJECT)
  559. maybe_reject = 1;
  560. else
  561. maybe_accept = 1;
  562. }
  563. }
  564. } SMARTLIST_FOREACH_END(tmpe);
  565. /* accept all by default. */
  566. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  567. }
  568. /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
  569. * port is known but address is not. */
  570. static addr_policy_result_t
  571. compare_unknown_tor_addr_to_addr_policy(uint16_t port,
  572. const smartlist_t *policy)
  573. {
  574. /* We look to see if there's a definite match. If so, we return that
  575. match's value, unless there's an intervening possible match that says
  576. something different. */
  577. int maybe_accept = 0, maybe_reject = 0;
  578. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
  579. if (tmpe->prt_min <= port && port <= tmpe->prt_max) {
  580. if (tmpe->maskbits == 0) {
  581. /* Definitely matches, since it covers all addresses. */
  582. if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
  583. /* If we already hit a clause that might trigger a 'reject', than we
  584. * can't be sure of this certain 'accept'.*/
  585. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
  586. ADDR_POLICY_ACCEPTED;
  587. } else {
  588. return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
  589. ADDR_POLICY_REJECTED;
  590. }
  591. } else {
  592. /* Might match. */
  593. if (tmpe->policy_type == ADDR_POLICY_REJECT)
  594. maybe_reject = 1;
  595. else
  596. maybe_accept = 1;
  597. }
  598. }
  599. } SMARTLIST_FOREACH_END(tmpe);
  600. /* accept all by default. */
  601. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  602. }
  603. /** Decide whether a given addr:port is definitely accepted,
  604. * definitely rejected, probably accepted, or probably rejected by a
  605. * given policy. If <b>addr</b> is 0, we don't know the IP of the
  606. * target address. If <b>port</b> is 0, we don't know the port of the
  607. * target address. (At least one of <b>addr</b> and <b>port</b> must be
  608. * provided. If you want to know whether a policy would definitely reject
  609. * an unknown address:port, use policy_is_reject_star().)
  610. *
  611. * We could do better by assuming that some ranges never match typical
  612. * addresses (127.0.0.1, and so on). But we'll try this for now.
  613. */
  614. addr_policy_result_t
  615. compare_tor_addr_to_addr_policy(const tor_addr_t *addr, uint16_t port,
  616. const smartlist_t *policy)
  617. {
  618. if (!policy) {
  619. /* no policy? accept all. */
  620. return ADDR_POLICY_ACCEPTED;
  621. } else if (tor_addr_is_null(addr)) {
  622. tor_assert(port != 0);
  623. return compare_unknown_tor_addr_to_addr_policy(port, policy);
  624. } else if (port == 0) {
  625. return compare_known_tor_addr_to_addr_policy_noport(addr, policy);
  626. } else {
  627. return compare_known_tor_addr_to_addr_policy(addr, port, policy);
  628. }
  629. }
  630. /** Return true iff the address policy <b>a</b> covers every case that
  631. * would be covered by <b>b</b>, so that a,b is redundant. */
  632. static int
  633. addr_policy_covers(addr_policy_t *a, addr_policy_t *b)
  634. {
  635. /* We can ignore accept/reject, since "accept *:80, reject *:80" reduces
  636. * to "accept *:80". */
  637. if (a->maskbits > b->maskbits) {
  638. /* a has more fixed bits than b; it can't possibly cover b. */
  639. return 0;
  640. }
  641. if (tor_addr_compare_masked(&a->addr, &b->addr, a->maskbits, CMP_EXACT)) {
  642. /* There's a fixed bit in a that's set differently in b. */
  643. return 0;
  644. }
  645. return (a->prt_min <= b->prt_min && a->prt_max >= b->prt_max);
  646. }
  647. /** Return true iff the address policies <b>a</b> and <b>b</b> intersect,
  648. * that is, there exists an address/port that is covered by <b>a</b> that
  649. * is also covered by <b>b</b>.
  650. */
  651. static int
  652. addr_policy_intersects(addr_policy_t *a, addr_policy_t *b)
  653. {
  654. maskbits_t minbits;
  655. /* All the bits we care about are those that are set in both
  656. * netmasks. If they are equal in a and b's networkaddresses
  657. * then the networks intersect. If there is a difference,
  658. * then they do not. */
  659. if (a->maskbits < b->maskbits)
  660. minbits = a->maskbits;
  661. else
  662. minbits = b->maskbits;
  663. if (tor_addr_compare_masked(&a->addr, &b->addr, minbits, CMP_EXACT))
  664. return 0;
  665. if (a->prt_max < b->prt_min || b->prt_max < a->prt_min)
  666. return 0;
  667. return 1;
  668. }
  669. /** Add the exit policy described by <b>more</b> to <b>policy</b>.
  670. */
  671. static void
  672. append_exit_policy_string(smartlist_t **policy, const char *more)
  673. {
  674. config_line_t tmp;
  675. tmp.key = NULL;
  676. tmp.value = (char*) more;
  677. tmp.next = NULL;
  678. if (parse_addr_policy(&tmp, policy, -1)<0) {
  679. log_warn(LD_BUG, "Unable to parse internally generated policy %s",more);
  680. }
  681. }
  682. /** Detect and excise "dead code" from the policy *<b>dest</b>. */
  683. static void
  684. exit_policy_remove_redundancies(smartlist_t *dest)
  685. {
  686. addr_policy_t *ap, *tmp, *victim;
  687. int i, j;
  688. /* Step one: find a *:* entry and cut off everything after it. */
  689. for (i = 0; i < smartlist_len(dest); ++i) {
  690. ap = smartlist_get(dest, i);
  691. if (ap->maskbits == 0 && ap->prt_min <= 1 && ap->prt_max >= 65535) {
  692. /* This is a catch-all line -- later lines are unreachable. */
  693. while (i+1 < smartlist_len(dest)) {
  694. victim = smartlist_get(dest, i+1);
  695. smartlist_del(dest, i+1);
  696. addr_policy_free(victim);
  697. }
  698. break;
  699. }
  700. }
  701. /* Step two: for every entry, see if there's a redundant entry
  702. * later on, and remove it. */
  703. for (i = 0; i < smartlist_len(dest)-1; ++i) {
  704. ap = smartlist_get(dest, i);
  705. for (j = i+1; j < smartlist_len(dest); ++j) {
  706. tmp = smartlist_get(dest, j);
  707. tor_assert(j > i);
  708. if (addr_policy_covers(ap, tmp)) {
  709. char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
  710. policy_write_item(p1, sizeof(p1), tmp, 0);
  711. policy_write_item(p2, sizeof(p2), ap, 0);
  712. log(LOG_DEBUG, LD_CONFIG, "Removing exit policy %s (%d). It is made "
  713. "redundant by %s (%d).", p1, j, p2, i);
  714. smartlist_del_keeporder(dest, j--);
  715. addr_policy_free(tmp);
  716. }
  717. }
  718. }
  719. /* Step three: for every entry A, see if there's an entry B making this one
  720. * redundant later on. This is the case if A and B are of the same type
  721. * (accept/reject), A is a subset of B, and there is no other entry of
  722. * different type in between those two that intersects with A.
  723. *
  724. * Anybody want to double-check the logic here? XXX
  725. */
  726. for (i = 0; i < smartlist_len(dest)-1; ++i) {
  727. ap = smartlist_get(dest, i);
  728. for (j = i+1; j < smartlist_len(dest); ++j) {
  729. // tor_assert(j > i); // j starts out at i+1; j only increases; i only
  730. // // decreases.
  731. tmp = smartlist_get(dest, j);
  732. if (ap->policy_type != tmp->policy_type) {
  733. if (addr_policy_intersects(ap, tmp))
  734. break;
  735. } else { /* policy_types are equal. */
  736. if (addr_policy_covers(tmp, ap)) {
  737. char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
  738. policy_write_item(p1, sizeof(p1), ap, 0);
  739. policy_write_item(p2, sizeof(p2), tmp, 0);
  740. log(LOG_DEBUG, LD_CONFIG, "Removing exit policy %s. It is already "
  741. "covered by %s.", p1, p2);
  742. smartlist_del_keeporder(dest, i--);
  743. addr_policy_free(ap);
  744. break;
  745. }
  746. }
  747. }
  748. }
  749. }
  750. #define DEFAULT_EXIT_POLICY \
  751. "reject *:25,reject *:119,reject *:135-139,reject *:445," \
  752. "reject *:563,reject *:1214,reject *:4661-4666," \
  753. "reject *:6346-6429,reject *:6699,reject *:6881-6999,accept *:*"
  754. /** Parse the exit policy <b>cfg</b> into the linked list *<b>dest</b>. If
  755. * cfg doesn't end in an absolute accept or reject and if
  756. * <b>add_default_policy</b> is true, add the default exit
  757. * policy afterwards. If <b>rejectprivate</b> is true, prepend
  758. * "reject private:*" to the policy. Return -1 if we can't parse cfg,
  759. * else return 0.
  760. */
  761. int
  762. policies_parse_exit_policy(config_line_t *cfg, smartlist_t **dest,
  763. int rejectprivate, const char *local_address,
  764. int add_default_policy)
  765. {
  766. if (rejectprivate) {
  767. append_exit_policy_string(dest, "reject private:*");
  768. if (local_address) {
  769. char buf[POLICY_BUF_LEN];
  770. tor_snprintf(buf, sizeof(buf), "reject %s:*", local_address);
  771. append_exit_policy_string(dest, buf);
  772. }
  773. }
  774. if (parse_addr_policy(cfg, dest, -1))
  775. return -1;
  776. if (add_default_policy)
  777. append_exit_policy_string(dest, DEFAULT_EXIT_POLICY);
  778. else
  779. append_exit_policy_string(dest, "reject *:*");
  780. exit_policy_remove_redundancies(*dest);
  781. return 0;
  782. }
  783. /** Replace the exit policy of <b>r</b> with reject *:*. */
  784. void
  785. policies_set_router_exitpolicy_to_reject_all(routerinfo_t *r)
  786. {
  787. addr_policy_t *item;
  788. addr_policy_list_free(r->exit_policy);
  789. r->exit_policy = smartlist_create();
  790. item = router_parse_addr_policy_item_from_string("reject *:*", -1);
  791. smartlist_add(r->exit_policy, item);
  792. }
  793. /** Return 1 if there is at least one /8 subnet in <b>policy</b> that
  794. * allows exiting to <b>port</b>. Otherwise, return 0. */
  795. static int
  796. exit_policy_is_general_exit_helper(smartlist_t *policy, int port)
  797. {
  798. uint32_t mask, ip, i;
  799. /* Is this /8 rejected (1), or undecided (0)? */
  800. char subnet_status[256];
  801. memset(subnet_status, 0, sizeof(subnet_status));
  802. SMARTLIST_FOREACH(policy, addr_policy_t *, p, {
  803. if (p->prt_min > port || p->prt_max < port)
  804. continue; /* Doesn't cover our port. */
  805. mask = 0;
  806. tor_assert(p->maskbits <= 32);
  807. if (p->maskbits)
  808. mask = UINT32_MAX<<(32-p->maskbits);
  809. ip = tor_addr_to_ipv4h(&p->addr);
  810. /* Calculate the first and last subnet that this exit policy touches
  811. * and set it as loop boundaries. */
  812. for (i = ((mask & ip)>>24); i <= (~((mask & ip) ^ mask)>>24); ++i) {
  813. tor_addr_t addr;
  814. if (subnet_status[i] != 0)
  815. continue; /* We already reject some part of this /8 */
  816. tor_addr_from_ipv4h(&addr, i<<24);
  817. if (tor_addr_is_internal(&addr, 0))
  818. continue; /* Local or non-routable addresses */
  819. if (p->policy_type == ADDR_POLICY_ACCEPT) {
  820. if (p->maskbits > 8)
  821. continue; /* Narrower than a /8. */
  822. /* We found an allowed subnet of at least size /8. Done
  823. * for this port! */
  824. return 1;
  825. } else if (p->policy_type == ADDR_POLICY_REJECT) {
  826. subnet_status[i] = 1;
  827. }
  828. }
  829. });
  830. return 0;
  831. }
  832. /** Return true iff <b>ri</b> is "useful as an exit node", meaning
  833. * it allows exit to at least one /8 address space for at least
  834. * two of ports 80, 443, and 6667. */
  835. int
  836. exit_policy_is_general_exit(smartlist_t *policy)
  837. {
  838. static const int ports[] = { 80, 443, 6667 };
  839. int n_allowed = 0;
  840. int i;
  841. if (!policy) /*XXXX disallow NULL policies? */
  842. return 0;
  843. for (i = 0; i < 3; ++i) {
  844. n_allowed += exit_policy_is_general_exit_helper(policy, ports[i]);
  845. }
  846. return n_allowed >= 2;
  847. }
  848. /** Return false if <b>policy</b> might permit access to some addr:port;
  849. * otherwise if we are certain it rejects everything, return true. */
  850. int
  851. policy_is_reject_star(const smartlist_t *policy)
  852. {
  853. if (!policy) /*XXXX disallow NULL policies? */
  854. return 1;
  855. SMARTLIST_FOREACH(policy, addr_policy_t *, p, {
  856. if (p->policy_type == ADDR_POLICY_ACCEPT)
  857. return 0;
  858. else if (p->policy_type == ADDR_POLICY_REJECT &&
  859. p->prt_min <= 1 && p->prt_max == 65535 &&
  860. p->maskbits == 0)
  861. return 1;
  862. });
  863. return 1;
  864. }
  865. /** Write a single address policy to the buf_len byte buffer at buf. Return
  866. * the number of characters written, or -1 on failure. */
  867. int
  868. policy_write_item(char *buf, size_t buflen, addr_policy_t *policy,
  869. int format_for_desc)
  870. {
  871. size_t written = 0;
  872. char addrbuf[TOR_ADDR_BUF_LEN];
  873. const char *addrpart;
  874. int result;
  875. const int is_accept = policy->policy_type == ADDR_POLICY_ACCEPT;
  876. const int is_ip6 = tor_addr_family(&policy->addr) == AF_INET6;
  877. tor_addr_to_str(addrbuf, &policy->addr, sizeof(addrbuf), 1);
  878. /* write accept/reject 1.2.3.4 */
  879. if (policy->is_private)
  880. addrpart = "private";
  881. else if (policy->maskbits == 0)
  882. addrpart = "*";
  883. else
  884. addrpart = addrbuf;
  885. result = tor_snprintf(buf, buflen, "%s%s%s %s",
  886. (is_ip6&&format_for_desc)?"opt ":"",
  887. is_accept ? "accept" : "reject",
  888. (is_ip6&&format_for_desc)?"6":"",
  889. addrpart);
  890. if (result < 0)
  891. return -1;
  892. written += strlen(buf);
  893. /* If the maskbits is 32 we don't need to give it. If the mask is 0,
  894. * we already wrote "*". */
  895. if (policy->maskbits < 32 && policy->maskbits > 0) {
  896. if (tor_snprintf(buf+written, buflen-written, "/%d", policy->maskbits)<0)
  897. return -1;
  898. written += strlen(buf+written);
  899. }
  900. if (policy->prt_min <= 1 && policy->prt_max == 65535) {
  901. /* There is no port set; write ":*" */
  902. if (written+4 > buflen)
  903. return -1;
  904. strlcat(buf+written, ":*", buflen-written);
  905. written += 2;
  906. } else if (policy->prt_min == policy->prt_max) {
  907. /* There is only one port; write ":80". */
  908. result = tor_snprintf(buf+written, buflen-written, ":%d", policy->prt_min);
  909. if (result<0)
  910. return -1;
  911. written += result;
  912. } else {
  913. /* There is a range of ports; write ":79-80". */
  914. result = tor_snprintf(buf+written, buflen-written, ":%d-%d",
  915. policy->prt_min, policy->prt_max);
  916. if (result<0)
  917. return -1;
  918. written += result;
  919. }
  920. if (written < buflen)
  921. buf[written] = '\0';
  922. else
  923. return -1;
  924. return (int)written;
  925. }
  926. /** Create a new exit policy summary, initially only with a single
  927. * port 1-64k item */
  928. /* XXXX This entire thing will do most stuff in O(N^2), or worse. Use an
  929. * RB-tree if that turns out to matter. */
  930. static smartlist_t *
  931. policy_summary_create(void)
  932. {
  933. smartlist_t *summary;
  934. policy_summary_item_t* item;
  935. item = tor_malloc_zero(sizeof(policy_summary_item_t));
  936. item->prt_min = 1;
  937. item->prt_max = 65535;
  938. item->reject_count = 0;
  939. item->accepted = 0;
  940. summary = smartlist_create();
  941. smartlist_add(summary, item);
  942. return summary;
  943. }
  944. /** Split the summary item in <b>item</b> at the port <b>new_starts</b>.
  945. * The current item is changed to end at new-starts - 1, the new item
  946. * copies reject_count and accepted from the old item,
  947. * starts at new_starts and ends at the port where the original item
  948. * previously ended.
  949. */
  950. static policy_summary_item_t*
  951. policy_summary_item_split(policy_summary_item_t* old, uint16_t new_starts)
  952. {
  953. policy_summary_item_t* new;
  954. new = tor_malloc_zero(sizeof(policy_summary_item_t));
  955. new->prt_min = new_starts;
  956. new->prt_max = old->prt_max;
  957. new->reject_count = old->reject_count;
  958. new->accepted = old->accepted;
  959. old->prt_max = new_starts-1;
  960. tor_assert(old->prt_min <= old->prt_max);
  961. tor_assert(new->prt_min <= new->prt_max);
  962. return new;
  963. }
  964. /* XXXX Nick says I'm going to hell for this. If he feels charitably towards
  965. * my immortal soul, he can clean it up himself. */
  966. #define AT(x) ((policy_summary_item_t*)smartlist_get(summary, x))
  967. #define REJECT_CUTOFF_COUNT (1<<25)
  968. /** Split an exit policy summary so that prt_min and prt_max
  969. * fall at exactly the start and end of an item respectively.
  970. */
  971. static int
  972. policy_summary_split(smartlist_t *summary,
  973. uint16_t prt_min, uint16_t prt_max)
  974. {
  975. int start_at_index;
  976. int i = 0;
  977. /* XXXX Do a binary search if run time matters */
  978. while (AT(i)->prt_max < prt_min)
  979. i++;
  980. if (AT(i)->prt_min != prt_min) {
  981. policy_summary_item_t* new_item;
  982. new_item = policy_summary_item_split(AT(i), prt_min);
  983. smartlist_insert(summary, i+1, new_item);
  984. i++;
  985. }
  986. start_at_index = i;
  987. while (AT(i)->prt_max < prt_max)
  988. i++;
  989. if (AT(i)->prt_max != prt_max) {
  990. policy_summary_item_t* new_item;
  991. new_item = policy_summary_item_split(AT(i), prt_max+1);
  992. smartlist_insert(summary, i+1, new_item);
  993. }
  994. return start_at_index;
  995. }
  996. /** Mark port ranges as accepted if they are below the reject_count */
  997. static void
  998. policy_summary_accept(smartlist_t *summary,
  999. uint16_t prt_min, uint16_t prt_max)
  1000. {
  1001. int i = policy_summary_split(summary, prt_min, prt_max);
  1002. while (i < smartlist_len(summary) &&
  1003. AT(i)->prt_max <= prt_max) {
  1004. if (!AT(i)->accepted &&
  1005. AT(i)->reject_count <= REJECT_CUTOFF_COUNT)
  1006. AT(i)->accepted = 1;
  1007. i++;
  1008. }
  1009. tor_assert(i < smartlist_len(summary) || prt_max==65535);
  1010. }
  1011. /** Count the number of addresses in a network with prefixlen maskbits
  1012. * against the given portrange. */
  1013. static void
  1014. policy_summary_reject(smartlist_t *summary,
  1015. maskbits_t maskbits,
  1016. uint16_t prt_min, uint16_t prt_max)
  1017. {
  1018. int i = policy_summary_split(summary, prt_min, prt_max);
  1019. /* XXX: ipv4 specific */
  1020. uint64_t count = (U64_LITERAL(1) << (32-maskbits));
  1021. while (i < smartlist_len(summary) &&
  1022. AT(i)->prt_max <= prt_max) {
  1023. AT(i)->reject_count += count;
  1024. i++;
  1025. }
  1026. tor_assert(i < smartlist_len(summary) || prt_max==65535);
  1027. }
  1028. /** Add a single exit policy item to our summary:
  1029. * If it is an accept ignore it unless it is for all IP addresses
  1030. * ("*"), i.e. it's prefixlen/maskbits is 0, else call
  1031. * policy_summary_accept().
  1032. * If it's a reject ignore it if it is about one of the private
  1033. * networks, else call policy_summary_reject().
  1034. */
  1035. static void
  1036. policy_summary_add_item(smartlist_t *summary, addr_policy_t *p)
  1037. {
  1038. if (p->policy_type == ADDR_POLICY_ACCEPT) {
  1039. if (p->maskbits == 0) {
  1040. policy_summary_accept(summary, p->prt_min, p->prt_max);
  1041. }
  1042. } else if (p->policy_type == ADDR_POLICY_REJECT) {
  1043. int is_private = 0;
  1044. int i;
  1045. for (i = 0; private_nets[i]; ++i) {
  1046. tor_addr_t addr;
  1047. maskbits_t maskbits;
  1048. if (tor_addr_parse_mask_ports(private_nets[i], &addr,
  1049. &maskbits, NULL, NULL)<0) {
  1050. tor_assert(0);
  1051. }
  1052. if (tor_addr_compare(&p->addr, &addr, CMP_EXACT) == 0 &&
  1053. p->maskbits == maskbits) {
  1054. is_private = 1;
  1055. break;
  1056. }
  1057. }
  1058. if (!is_private) {
  1059. policy_summary_reject(summary, p->maskbits, p->prt_min, p->prt_max);
  1060. }
  1061. } else
  1062. tor_assert(0);
  1063. }
  1064. /** Create a string representing a summary for an exit policy.
  1065. * The summary will either be an "accept" plus a comma-separated list of port
  1066. * ranges or a "reject" plus port-ranges, depending on which is shorter.
  1067. *
  1068. * If no exits are allowed at all then NULL is returned, if no ports
  1069. * are blocked instead of "reject " we return "accept 1-65535" (this
  1070. * is an exception to the shorter-representation-wins rule).
  1071. */
  1072. char *
  1073. policy_summarize(smartlist_t *policy)
  1074. {
  1075. smartlist_t *summary = policy_summary_create();
  1076. smartlist_t *accepts, *rejects;
  1077. int i, last, start_prt;
  1078. size_t accepts_len, rejects_len, shorter_len, final_size;
  1079. char *accepts_str = NULL, *rejects_str = NULL, *shorter_str, *result;
  1080. const char *prefix;
  1081. tor_assert(policy);
  1082. /* Create the summary list */
  1083. SMARTLIST_FOREACH(policy, addr_policy_t *, p, {
  1084. policy_summary_add_item(summary, p);
  1085. });
  1086. /* Now create two lists of strings, one for accepted and one
  1087. * for rejected ports. We take care to merge ranges so that
  1088. * we avoid getting stuff like "1-4,5-9,10", instead we want
  1089. * "1-10"
  1090. */
  1091. i = 0;
  1092. start_prt = 1;
  1093. accepts = smartlist_create();
  1094. rejects = smartlist_create();
  1095. while (1) {
  1096. last = i == smartlist_len(summary)-1;
  1097. if (last ||
  1098. AT(i)->accepted != AT(i+1)->accepted) {
  1099. char buf[POLICY_BUF_LEN];
  1100. if (start_prt == AT(i)->prt_max)
  1101. tor_snprintf(buf, sizeof(buf), "%d", start_prt);
  1102. else
  1103. tor_snprintf(buf, sizeof(buf), "%d-%d", start_prt, AT(i)->prt_max);
  1104. if (AT(i)->accepted)
  1105. smartlist_add(accepts, tor_strdup(buf));
  1106. else
  1107. smartlist_add(rejects, tor_strdup(buf));
  1108. if (last)
  1109. break;
  1110. start_prt = AT(i+1)->prt_min;
  1111. };
  1112. i++;
  1113. };
  1114. /* Figure out which of the two stringlists will be shorter and use
  1115. * that to build the result
  1116. */
  1117. if (smartlist_len(accepts) == 0) { /* no exits at all */
  1118. result = tor_strdup("reject 1-65535");
  1119. goto cleanup;
  1120. }
  1121. if (smartlist_len(rejects) == 0) { /* no rejects at all */
  1122. result = tor_strdup("accept 1-65535");
  1123. goto cleanup;
  1124. }
  1125. accepts_str = smartlist_join_strings(accepts, ",", 0, &accepts_len);
  1126. rejects_str = smartlist_join_strings(rejects, ",", 0, &rejects_len);
  1127. if (rejects_len > MAX_EXITPOLICY_SUMMARY_LEN &&
  1128. accepts_len > MAX_EXITPOLICY_SUMMARY_LEN) {
  1129. char *c;
  1130. shorter_str = accepts_str;
  1131. prefix = "accept";
  1132. c = shorter_str + (MAX_EXITPOLICY_SUMMARY_LEN-strlen(prefix)-1);
  1133. while (*c != ',' && c >= shorter_str)
  1134. c--;
  1135. tor_assert(c >= shorter_str);
  1136. tor_assert(*c == ',');
  1137. *c = '\0';
  1138. shorter_len = strlen(shorter_str);
  1139. } else if (rejects_len < accepts_len) {
  1140. shorter_str = rejects_str;
  1141. shorter_len = rejects_len;
  1142. prefix = "reject";
  1143. } else {
  1144. shorter_str = accepts_str;
  1145. shorter_len = accepts_len;
  1146. prefix = "accept";
  1147. }
  1148. final_size = strlen(prefix)+1+shorter_len+1;
  1149. tor_assert(final_size <= MAX_EXITPOLICY_SUMMARY_LEN+1);
  1150. result = tor_malloc(final_size);
  1151. tor_snprintf(result, final_size, "%s %s", prefix, shorter_str);
  1152. cleanup:
  1153. /* cleanup */
  1154. SMARTLIST_FOREACH(summary, policy_summary_item_t *, s, tor_free(s));
  1155. smartlist_free(summary);
  1156. tor_free(accepts_str);
  1157. SMARTLIST_FOREACH(accepts, char *, s, tor_free(s));
  1158. smartlist_free(accepts);
  1159. tor_free(rejects_str);
  1160. SMARTLIST_FOREACH(rejects, char *, s, tor_free(s));
  1161. smartlist_free(rejects);
  1162. return result;
  1163. }
  1164. /** Implementation for GETINFO control command: knows the answer for questions
  1165. * about "exit-policy/..." */
  1166. int
  1167. getinfo_helper_policies(control_connection_t *conn,
  1168. const char *question, char **answer,
  1169. const char **errmsg)
  1170. {
  1171. (void) conn;
  1172. (void) errmsg;
  1173. if (!strcmp(question, "exit-policy/default")) {
  1174. *answer = tor_strdup(DEFAULT_EXIT_POLICY);
  1175. }
  1176. return 0;
  1177. }
  1178. /** Release all storage held by <b>p</b>. */
  1179. void
  1180. addr_policy_list_free(smartlist_t *lst)
  1181. {
  1182. if (!lst)
  1183. return;
  1184. SMARTLIST_FOREACH(lst, addr_policy_t *, policy, addr_policy_free(policy));
  1185. smartlist_free(lst);
  1186. }
  1187. /** Release all storage held by <b>p</b>. */
  1188. void
  1189. addr_policy_free(addr_policy_t *p)
  1190. {
  1191. if (!p)
  1192. return;
  1193. if (--p->refcnt <= 0) {
  1194. if (p->is_canonical) {
  1195. policy_map_ent_t search, *found;
  1196. search.policy = p;
  1197. found = HT_REMOVE(policy_map, &policy_root, &search);
  1198. if (found) {
  1199. tor_assert(p == found->policy);
  1200. tor_free(found);
  1201. }
  1202. }
  1203. tor_free(p);
  1204. }
  1205. }
  1206. /** Release all storage held by policy variables. */
  1207. void
  1208. policies_free_all(void)
  1209. {
  1210. addr_policy_list_free(reachable_or_addr_policy);
  1211. reachable_or_addr_policy = NULL;
  1212. addr_policy_list_free(reachable_dir_addr_policy);
  1213. reachable_dir_addr_policy = NULL;
  1214. addr_policy_list_free(socks_policy);
  1215. socks_policy = NULL;
  1216. addr_policy_list_free(dir_policy);
  1217. dir_policy = NULL;
  1218. addr_policy_list_free(authdir_reject_policy);
  1219. authdir_reject_policy = NULL;
  1220. addr_policy_list_free(authdir_invalid_policy);
  1221. authdir_invalid_policy = NULL;
  1222. addr_policy_list_free(authdir_baddir_policy);
  1223. authdir_baddir_policy = NULL;
  1224. addr_policy_list_free(authdir_badexit_policy);
  1225. authdir_badexit_policy = NULL;
  1226. if (!HT_EMPTY(&policy_root)) {
  1227. policy_map_ent_t **ent;
  1228. int n = 0;
  1229. char buf[POLICY_BUF_LEN];
  1230. log_warn(LD_MM, "Still had %d address policies cached at shutdown.",
  1231. (int)HT_SIZE(&policy_root));
  1232. /* Note the first 10 cached policies to try to figure out where they
  1233. * might be coming from. */
  1234. HT_FOREACH(ent, policy_map, &policy_root) {
  1235. if (++n > 10)
  1236. break;
  1237. if (policy_write_item(buf, sizeof(buf), (*ent)->policy, 0) >= 0)
  1238. log_warn(LD_MM," %d [%d]: %s", n, (*ent)->policy->refcnt, buf);
  1239. }
  1240. }
  1241. HT_CLEAR(policy_map, &policy_root);
  1242. }