policies.c 44 KB

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