policies.c 42 KB

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