policies.c 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2013, 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 "nodelist.h"
  13. #include "policies.h"
  14. #include "router.h"
  15. #include "routerparse.h"
  16. #include "geoip.h"
  17. #include "ht.h"
  18. /** Policy that addresses for incoming SOCKS connections must match. */
  19. static smartlist_t *socks_policy = NULL;
  20. /** Policy that addresses for incoming directory connections must match. */
  21. static smartlist_t *dir_policy = NULL;
  22. /** Policy that addresses for incoming router descriptors must match in order
  23. * to be published by us. */
  24. static smartlist_t *authdir_reject_policy = NULL;
  25. /** Policy that addresses for incoming router descriptors must match in order
  26. * to be marked as valid in our networkstatus. */
  27. static smartlist_t *authdir_invalid_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. unsigned 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. "[::]/8",
  55. "[fc00::]/7", "[fe80::]/10", "[fec0::]/10", "[ff00::]/8", "[::]/127",
  56. NULL
  57. };
  58. /** Replace all "private" entries in *<b>policy</b> with their expanded
  59. * equivalents. */
  60. void
  61. policy_expand_private(smartlist_t **policy)
  62. {
  63. uint16_t port_min, port_max;
  64. int i;
  65. smartlist_t *tmp;
  66. if (!*policy) /*XXXX disallow NULL policies? */
  67. return;
  68. tmp = smartlist_new();
  69. SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, p) {
  70. if (! p->is_private) {
  71. smartlist_add(tmp, p);
  72. continue;
  73. }
  74. for (i = 0; private_nets[i]; ++i) {
  75. addr_policy_t newpolicy;
  76. memcpy(&newpolicy, p, sizeof(addr_policy_t));
  77. newpolicy.is_private = 0;
  78. newpolicy.is_canonical = 0;
  79. if (tor_addr_parse_mask_ports(private_nets[i], 0,
  80. &newpolicy.addr,
  81. &newpolicy.maskbits, &port_min, &port_max)<0) {
  82. tor_assert(0);
  83. }
  84. smartlist_add(tmp, addr_policy_get_canonical_entry(&newpolicy));
  85. }
  86. addr_policy_free(p);
  87. } SMARTLIST_FOREACH_END(p);
  88. smartlist_free(*policy);
  89. *policy = tmp;
  90. }
  91. /** Expand each of the AF_UNSPEC elements in *<b>policy</b> (which indicate
  92. * protocol-neutral wildcards) into a pair of wildcard elements: one IPv4-
  93. * specific and one IPv6-specific. */
  94. void
  95. policy_expand_unspec(smartlist_t **policy)
  96. {
  97. smartlist_t *tmp;
  98. if (!*policy)
  99. return;
  100. tmp = smartlist_new();
  101. SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, p) {
  102. sa_family_t family = tor_addr_family(&p->addr);
  103. if (family == AF_INET6 || family == AF_INET || p->is_private) {
  104. smartlist_add(tmp, p);
  105. } else if (family == AF_UNSPEC) {
  106. addr_policy_t newpolicy_ipv4;
  107. addr_policy_t newpolicy_ipv6;
  108. memcpy(&newpolicy_ipv4, p, sizeof(addr_policy_t));
  109. memcpy(&newpolicy_ipv6, p, sizeof(addr_policy_t));
  110. newpolicy_ipv4.is_canonical = 0;
  111. newpolicy_ipv6.is_canonical = 0;
  112. if (p->maskbits != 0) {
  113. log_warn(LD_BUG, "AF_UNSPEC policy with maskbits==%d", p->maskbits);
  114. newpolicy_ipv4.maskbits = 0;
  115. newpolicy_ipv6.maskbits = 0;
  116. }
  117. tor_addr_from_ipv4h(&newpolicy_ipv4.addr, 0);
  118. tor_addr_from_ipv6_bytes(&newpolicy_ipv6.addr,
  119. "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
  120. smartlist_add(tmp, addr_policy_get_canonical_entry(&newpolicy_ipv4));
  121. smartlist_add(tmp, addr_policy_get_canonical_entry(&newpolicy_ipv6));
  122. addr_policy_free(p);
  123. } else {
  124. log_warn(LD_BUG, "Funny-looking address policy with family %d", family);
  125. smartlist_add(tmp, p);
  126. }
  127. } SMARTLIST_FOREACH_END(p);
  128. smartlist_free(*policy);
  129. *policy = tmp;
  130. }
  131. /**
  132. * Given a linked list of config lines containing "allow" and "deny"
  133. * tokens, parse them and append the result to <b>dest</b>. Return -1
  134. * if any tokens are malformed (and don't append any), else return 0.
  135. *
  136. * If <b>assume_action</b> is nonnegative, then insert its action
  137. * (ADDR_POLICY_ACCEPT or ADDR_POLICY_REJECT) for items that specify no
  138. * action.
  139. */
  140. static int
  141. parse_addr_policy(config_line_t *cfg, smartlist_t **dest,
  142. int assume_action)
  143. {
  144. smartlist_t *result;
  145. smartlist_t *entries;
  146. addr_policy_t *item;
  147. int r = 0;
  148. if (!cfg)
  149. return 0;
  150. result = smartlist_new();
  151. entries = smartlist_new();
  152. for (; cfg; cfg = cfg->next) {
  153. smartlist_split_string(entries, cfg->value, ",",
  154. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  155. SMARTLIST_FOREACH_BEGIN(entries, const char *, ent) {
  156. log_debug(LD_CONFIG,"Adding new entry '%s'",ent);
  157. item = router_parse_addr_policy_item_from_string(ent, assume_action);
  158. if (item) {
  159. smartlist_add(result, item);
  160. } else {
  161. log_warn(LD_CONFIG,"Malformed policy '%s'.", ent);
  162. r = -1;
  163. }
  164. } SMARTLIST_FOREACH_END(ent);
  165. SMARTLIST_FOREACH(entries, char *, ent, tor_free(ent));
  166. smartlist_clear(entries);
  167. }
  168. smartlist_free(entries);
  169. if (r == -1) {
  170. addr_policy_list_free(result);
  171. } else {
  172. policy_expand_private(&result);
  173. policy_expand_unspec(&result);
  174. if (*dest) {
  175. smartlist_add_all(*dest, result);
  176. smartlist_free(result);
  177. } else {
  178. *dest = result;
  179. }
  180. }
  181. return r;
  182. }
  183. /** Helper: parse the Reachable(Dir|OR)?Addresses fields into
  184. * reachable_(or|dir)_addr_policy. The options should already have
  185. * been validated by validate_addr_policies.
  186. */
  187. static int
  188. parse_reachable_addresses(void)
  189. {
  190. const or_options_t *options = get_options();
  191. int ret = 0;
  192. if (options->ReachableDirAddresses &&
  193. options->ReachableORAddresses &&
  194. options->ReachableAddresses) {
  195. log_warn(LD_CONFIG,
  196. "Both ReachableDirAddresses and ReachableORAddresses are set. "
  197. "ReachableAddresses setting will be ignored.");
  198. }
  199. addr_policy_list_free(reachable_or_addr_policy);
  200. reachable_or_addr_policy = NULL;
  201. if (!options->ReachableORAddresses && options->ReachableAddresses)
  202. log_info(LD_CONFIG,
  203. "Using ReachableAddresses as ReachableORAddresses.");
  204. if (parse_addr_policy(options->ReachableORAddresses ?
  205. options->ReachableORAddresses :
  206. options->ReachableAddresses,
  207. &reachable_or_addr_policy, ADDR_POLICY_ACCEPT)) {
  208. log_warn(LD_CONFIG,
  209. "Error parsing Reachable%sAddresses entry; ignoring.",
  210. options->ReachableORAddresses ? "OR" : "");
  211. ret = -1;
  212. }
  213. addr_policy_list_free(reachable_dir_addr_policy);
  214. reachable_dir_addr_policy = NULL;
  215. if (!options->ReachableDirAddresses && options->ReachableAddresses)
  216. log_info(LD_CONFIG,
  217. "Using ReachableAddresses as ReachableDirAddresses");
  218. if (parse_addr_policy(options->ReachableDirAddresses ?
  219. options->ReachableDirAddresses :
  220. options->ReachableAddresses,
  221. &reachable_dir_addr_policy, ADDR_POLICY_ACCEPT)) {
  222. if (options->ReachableDirAddresses)
  223. log_warn(LD_CONFIG,
  224. "Error parsing ReachableDirAddresses entry; ignoring.");
  225. ret = -1;
  226. }
  227. return ret;
  228. }
  229. /** Return true iff the firewall options might block any address:port
  230. * combination.
  231. */
  232. int
  233. firewall_is_fascist_or(void)
  234. {
  235. return reachable_or_addr_policy != NULL;
  236. }
  237. /** Return true iff <b>policy</b> (possibly NULL) will allow a
  238. * connection to <b>addr</b>:<b>port</b>.
  239. */
  240. static int
  241. addr_policy_permits_tor_addr(const tor_addr_t *addr, uint16_t port,
  242. smartlist_t *policy)
  243. {
  244. addr_policy_result_t p;
  245. p = compare_tor_addr_to_addr_policy(addr, port, policy);
  246. switch (p) {
  247. case ADDR_POLICY_PROBABLY_ACCEPTED:
  248. case ADDR_POLICY_ACCEPTED:
  249. return 1;
  250. case ADDR_POLICY_PROBABLY_REJECTED:
  251. case ADDR_POLICY_REJECTED:
  252. return 0;
  253. default:
  254. log_warn(LD_BUG, "Unexpected result: %d", (int)p);
  255. return 0;
  256. }
  257. }
  258. /** Return true iff <b> policy</b> (possibly NULL) will allow a connection to
  259. * <b>addr</b>:<b>port</b>. <b>addr</b> is an IPv4 address given in host
  260. * order. */
  261. /* XXXX deprecate when possible. */
  262. static int
  263. addr_policy_permits_address(uint32_t addr, uint16_t port,
  264. smartlist_t *policy)
  265. {
  266. tor_addr_t a;
  267. tor_addr_from_ipv4h(&a, addr);
  268. return addr_policy_permits_tor_addr(&a, port, policy);
  269. }
  270. /** Return true iff we think our firewall will let us make an OR connection to
  271. * addr:port. */
  272. int
  273. fascist_firewall_allows_address_or(const tor_addr_t *addr, uint16_t port)
  274. {
  275. return addr_policy_permits_tor_addr(addr, port,
  276. reachable_or_addr_policy);
  277. }
  278. /** Return true iff we think our firewall will let us make an OR connection to
  279. * <b>ri</b>. */
  280. int
  281. fascist_firewall_allows_or(const routerinfo_t *ri)
  282. {
  283. /* XXXX proposal 118 */
  284. tor_addr_t addr;
  285. tor_addr_from_ipv4h(&addr, ri->addr);
  286. return fascist_firewall_allows_address_or(&addr, ri->or_port);
  287. }
  288. /** Return true iff we think our firewall will let us make an OR connection to
  289. * <b>node</b>. */
  290. int
  291. fascist_firewall_allows_node(const node_t *node)
  292. {
  293. if (node->ri) {
  294. return fascist_firewall_allows_or(node->ri);
  295. } else if (node->rs) {
  296. tor_addr_t addr;
  297. tor_addr_from_ipv4h(&addr, node->rs->addr);
  298. return fascist_firewall_allows_address_or(&addr, node->rs->or_port);
  299. } else {
  300. return 1;
  301. }
  302. }
  303. /** Return true iff we think our firewall will let us make a directory
  304. * connection to addr:port. */
  305. int
  306. fascist_firewall_allows_address_dir(const tor_addr_t *addr, uint16_t port)
  307. {
  308. return addr_policy_permits_tor_addr(addr, port,
  309. reachable_dir_addr_policy);
  310. }
  311. /** Return 1 if <b>addr</b> is permitted to connect to our dir port,
  312. * based on <b>dir_policy</b>. Else return 0.
  313. */
  314. int
  315. dir_policy_permits_address(const tor_addr_t *addr)
  316. {
  317. return addr_policy_permits_tor_addr(addr, 1, dir_policy);
  318. }
  319. /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
  320. * based on <b>socks_policy</b>. Else return 0.
  321. */
  322. int
  323. socks_policy_permits_address(const tor_addr_t *addr)
  324. {
  325. return addr_policy_permits_tor_addr(addr, 1, socks_policy);
  326. }
  327. /** Return true iff the address <b>addr</b> is in a country listed in the
  328. * case-insensitive list of country codes <b>cc_list</b>. */
  329. static int
  330. addr_is_in_cc_list(uint32_t addr, const smartlist_t *cc_list)
  331. {
  332. country_t country;
  333. const char *name;
  334. tor_addr_t tar;
  335. if (!cc_list)
  336. return 0;
  337. /* XXXXipv6 */
  338. tor_addr_from_ipv4h(&tar, addr);
  339. country = geoip_get_country_by_addr(&tar);
  340. name = geoip_get_country_name(country);
  341. return smartlist_contains_string_case(cc_list, name);
  342. }
  343. /** Return 1 if <b>addr</b>:<b>port</b> is permitted to publish to our
  344. * directory, based on <b>authdir_reject_policy</b>. Else return 0.
  345. */
  346. int
  347. authdir_policy_permits_address(uint32_t addr, uint16_t port)
  348. {
  349. if (! addr_policy_permits_address(addr, port, authdir_reject_policy))
  350. return 0;
  351. return !addr_is_in_cc_list(addr, get_options()->AuthDirRejectCCs);
  352. }
  353. /** Return 1 if <b>addr</b>:<b>port</b> is considered valid in our
  354. * directory, based on <b>authdir_invalid_policy</b>. Else return 0.
  355. */
  356. int
  357. authdir_policy_valid_address(uint32_t addr, uint16_t port)
  358. {
  359. if (! addr_policy_permits_address(addr, port, authdir_invalid_policy))
  360. return 0;
  361. return !addr_is_in_cc_list(addr, get_options()->AuthDirInvalidCCs);
  362. }
  363. /** Return 1 if <b>addr</b>:<b>port</b> should be marked as a bad exit,
  364. * based on <b>authdir_badexit_policy</b>. Else return 0.
  365. */
  366. int
  367. authdir_policy_badexit_address(uint32_t addr, uint16_t port)
  368. {
  369. if (! addr_policy_permits_address(addr, port, authdir_badexit_policy))
  370. return 1;
  371. return addr_is_in_cc_list(addr, get_options()->AuthDirBadExitCCs);
  372. }
  373. #define REJECT(arg) \
  374. STMT_BEGIN *msg = tor_strdup(arg); goto err; STMT_END
  375. /** Config helper: If there's any problem with the policy configuration
  376. * options in <b>options</b>, return -1 and set <b>msg</b> to a newly
  377. * allocated description of the error. Else return 0. */
  378. int
  379. validate_addr_policies(const or_options_t *options, char **msg)
  380. {
  381. /* XXXX Maybe merge this into parse_policies_from_options, to make sure
  382. * that the two can't go out of sync. */
  383. smartlist_t *addr_policy=NULL;
  384. *msg = NULL;
  385. if (policies_parse_exit_policy(options->ExitPolicy, &addr_policy,
  386. options->IPv6Exit,
  387. options->ExitPolicyRejectPrivate, 0,
  388. !options->BridgeRelay))
  389. REJECT("Error in ExitPolicy entry.");
  390. /* The rest of these calls *append* to addr_policy. So don't actually
  391. * use the results for anything other than checking if they parse! */
  392. if (parse_addr_policy(options->DirPolicy, &addr_policy, -1))
  393. REJECT("Error in DirPolicy entry.");
  394. if (parse_addr_policy(options->SocksPolicy, &addr_policy, -1))
  395. REJECT("Error in SocksPolicy entry.");
  396. if (parse_addr_policy(options->AuthDirReject, &addr_policy,
  397. ADDR_POLICY_REJECT))
  398. REJECT("Error in AuthDirReject entry.");
  399. if (parse_addr_policy(options->AuthDirInvalid, &addr_policy,
  400. ADDR_POLICY_REJECT))
  401. REJECT("Error in AuthDirInvalid entry.");
  402. if (parse_addr_policy(options->AuthDirBadExit, &addr_policy,
  403. ADDR_POLICY_REJECT))
  404. REJECT("Error in AuthDirBadExit entry.");
  405. if (parse_addr_policy(options->ReachableAddresses, &addr_policy,
  406. ADDR_POLICY_ACCEPT))
  407. REJECT("Error in ReachableAddresses entry.");
  408. if (parse_addr_policy(options->ReachableORAddresses, &addr_policy,
  409. ADDR_POLICY_ACCEPT))
  410. REJECT("Error in ReachableORAddresses entry.");
  411. if (parse_addr_policy(options->ReachableDirAddresses, &addr_policy,
  412. ADDR_POLICY_ACCEPT))
  413. REJECT("Error in ReachableDirAddresses entry.");
  414. err:
  415. addr_policy_list_free(addr_policy);
  416. return *msg ? -1 : 0;
  417. #undef REJECT
  418. }
  419. /** Parse <b>string</b> in the same way that the exit policy
  420. * is parsed, and put the processed version in *<b>policy</b>.
  421. * Ignore port specifiers.
  422. */
  423. static int
  424. load_policy_from_option(config_line_t *config, const char *option_name,
  425. smartlist_t **policy,
  426. int assume_action)
  427. {
  428. int r;
  429. int killed_any_ports = 0;
  430. addr_policy_list_free(*policy);
  431. *policy = NULL;
  432. r = parse_addr_policy(config, policy, assume_action);
  433. if (r < 0) {
  434. return -1;
  435. }
  436. if (*policy) {
  437. SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, n) {
  438. /* ports aren't used in these. */
  439. if (n->prt_min > 1 || n->prt_max != 65535) {
  440. addr_policy_t newp, *c;
  441. memcpy(&newp, n, sizeof(newp));
  442. newp.prt_min = 1;
  443. newp.prt_max = 65535;
  444. newp.is_canonical = 0;
  445. c = addr_policy_get_canonical_entry(&newp);
  446. SMARTLIST_REPLACE_CURRENT(*policy, n, c);
  447. addr_policy_free(n);
  448. killed_any_ports = 1;
  449. }
  450. } SMARTLIST_FOREACH_END(n);
  451. }
  452. if (killed_any_ports) {
  453. log_warn(LD_CONFIG, "Ignoring ports in %s option.", option_name);
  454. }
  455. return 0;
  456. }
  457. /** Set all policies based on <b>options</b>, which should have been validated
  458. * first by validate_addr_policies. */
  459. int
  460. policies_parse_from_options(const or_options_t *options)
  461. {
  462. int ret = 0;
  463. if (load_policy_from_option(options->SocksPolicy, "SocksPolicy",
  464. &socks_policy, -1) < 0)
  465. ret = -1;
  466. if (load_policy_from_option(options->DirPolicy, "DirPolicy",
  467. &dir_policy, -1) < 0)
  468. ret = -1;
  469. if (load_policy_from_option(options->AuthDirReject, "AuthDirReject",
  470. &authdir_reject_policy, ADDR_POLICY_REJECT) < 0)
  471. ret = -1;
  472. if (load_policy_from_option(options->AuthDirInvalid, "AuthDirInvalid",
  473. &authdir_invalid_policy, ADDR_POLICY_REJECT) < 0)
  474. ret = -1;
  475. if (load_policy_from_option(options->AuthDirBadExit, "AuthDirBadExit",
  476. &authdir_badexit_policy, ADDR_POLICY_REJECT) < 0)
  477. ret = -1;
  478. if (parse_reachable_addresses() < 0)
  479. ret = -1;
  480. return ret;
  481. }
  482. /** Compare two provided address policy items, and return -1, 0, or 1
  483. * if the first is less than, equal to, or greater than the second. */
  484. static int
  485. cmp_single_addr_policy(addr_policy_t *a, addr_policy_t *b)
  486. {
  487. int r;
  488. if ((r=((int)a->policy_type - (int)b->policy_type)))
  489. return r;
  490. if ((r=((int)a->is_private - (int)b->is_private)))
  491. return r;
  492. if ((r=tor_addr_compare(&a->addr, &b->addr, CMP_EXACT)))
  493. return r;
  494. if ((r=((int)a->maskbits - (int)b->maskbits)))
  495. return r;
  496. if ((r=((int)a->prt_min - (int)b->prt_min)))
  497. return r;
  498. if ((r=((int)a->prt_max - (int)b->prt_max)))
  499. return r;
  500. return 0;
  501. }
  502. /** Like cmp_single_addr_policy() above, but looks at the
  503. * whole set of policies in each case. */
  504. int
  505. cmp_addr_policies(smartlist_t *a, smartlist_t *b)
  506. {
  507. int r, i;
  508. int len_a = a ? smartlist_len(a) : 0;
  509. int len_b = b ? smartlist_len(b) : 0;
  510. for (i = 0; i < len_a && i < len_b; ++i) {
  511. if ((r = cmp_single_addr_policy(smartlist_get(a, i), smartlist_get(b, i))))
  512. return r;
  513. }
  514. if (i == len_a && i == len_b)
  515. return 0;
  516. if (i < len_a)
  517. return -1;
  518. else
  519. return 1;
  520. }
  521. /** Node in hashtable used to store address policy entries. */
  522. typedef struct policy_map_ent_t {
  523. HT_ENTRY(policy_map_ent_t) node;
  524. addr_policy_t *policy;
  525. } policy_map_ent_t;
  526. /* DOCDOC policy_root */
  527. static HT_HEAD(policy_map, policy_map_ent_t) policy_root = HT_INITIALIZER();
  528. /** Return true iff a and b are equal. */
  529. static INLINE int
  530. policy_eq(policy_map_ent_t *a, policy_map_ent_t *b)
  531. {
  532. return cmp_single_addr_policy(a->policy, b->policy) == 0;
  533. }
  534. /** Return a hashcode for <b>ent</b> */
  535. static unsigned int
  536. policy_hash(const policy_map_ent_t *ent)
  537. {
  538. const addr_policy_t *a = ent->policy;
  539. addr_policy_t aa;
  540. memset(&aa, 0, sizeof(aa));
  541. aa.prt_min = a->prt_min;
  542. aa.prt_max = a->prt_max;
  543. aa.maskbits = a->maskbits;
  544. aa.policy_type = a->policy_type;
  545. aa.is_private = a->is_private;
  546. if (a->is_private) {
  547. aa.is_private = 1;
  548. } else {
  549. tor_addr_copy_tight(&aa.addr, &a->addr);
  550. }
  551. return (unsigned) siphash24g(&aa, sizeof(aa));
  552. }
  553. HT_PROTOTYPE(policy_map, policy_map_ent_t, node, policy_hash,
  554. policy_eq)
  555. HT_GENERATE2(policy_map, policy_map_ent_t, node, policy_hash,
  556. policy_eq, 0.6, tor_reallocarray_, tor_free_)
  557. /** Given a pointer to an addr_policy_t, return a copy of the pointer to the
  558. * "canonical" copy of that addr_policy_t; the canonical copy is a single
  559. * reference-counted object. */
  560. addr_policy_t *
  561. addr_policy_get_canonical_entry(addr_policy_t *e)
  562. {
  563. policy_map_ent_t search, *found;
  564. if (e->is_canonical)
  565. return e;
  566. search.policy = e;
  567. found = HT_FIND(policy_map, &policy_root, &search);
  568. if (!found) {
  569. found = tor_malloc_zero(sizeof(policy_map_ent_t));
  570. found->policy = tor_memdup(e, sizeof(addr_policy_t));
  571. found->policy->is_canonical = 1;
  572. found->policy->refcnt = 0;
  573. HT_INSERT(policy_map, &policy_root, found);
  574. }
  575. tor_assert(!cmp_single_addr_policy(found->policy, e));
  576. ++found->policy->refcnt;
  577. return found->policy;
  578. }
  579. /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
  580. * addr and port are both known. */
  581. static addr_policy_result_t
  582. compare_known_tor_addr_to_addr_policy(const tor_addr_t *addr, uint16_t port,
  583. const smartlist_t *policy)
  584. {
  585. /* We know the address and port, and we know the policy, so we can just
  586. * compute an exact match. */
  587. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
  588. /* Address is known */
  589. if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
  590. CMP_EXACT)) {
  591. if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
  592. /* Exact match for the policy */
  593. return tmpe->policy_type == ADDR_POLICY_ACCEPT ?
  594. ADDR_POLICY_ACCEPTED : ADDR_POLICY_REJECTED;
  595. }
  596. }
  597. } SMARTLIST_FOREACH_END(tmpe);
  598. /* accept all by default. */
  599. return ADDR_POLICY_ACCEPTED;
  600. }
  601. /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
  602. * addr is known but port is not. */
  603. static addr_policy_result_t
  604. compare_known_tor_addr_to_addr_policy_noport(const tor_addr_t *addr,
  605. const smartlist_t *policy)
  606. {
  607. /* We look to see if there's a definite match. If so, we return that
  608. match's value, unless there's an intervening possible match that says
  609. something different. */
  610. int maybe_accept = 0, maybe_reject = 0;
  611. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
  612. if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
  613. CMP_EXACT)) {
  614. if (tmpe->prt_min <= 1 && tmpe->prt_max >= 65535) {
  615. /* Definitely matches, since it covers all ports. */
  616. if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
  617. /* If we already hit a clause that might trigger a 'reject', than we
  618. * can't be sure of this certain 'accept'.*/
  619. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
  620. ADDR_POLICY_ACCEPTED;
  621. } else {
  622. return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
  623. ADDR_POLICY_REJECTED;
  624. }
  625. } else {
  626. /* Might match. */
  627. if (tmpe->policy_type == ADDR_POLICY_REJECT)
  628. maybe_reject = 1;
  629. else
  630. maybe_accept = 1;
  631. }
  632. }
  633. } SMARTLIST_FOREACH_END(tmpe);
  634. /* accept all by default. */
  635. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  636. }
  637. /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
  638. * port is known but address is not. */
  639. static addr_policy_result_t
  640. compare_unknown_tor_addr_to_addr_policy(uint16_t port,
  641. const smartlist_t *policy)
  642. {
  643. /* We look to see if there's a definite match. If so, we return that
  644. match's value, unless there's an intervening possible match that says
  645. something different. */
  646. int maybe_accept = 0, maybe_reject = 0;
  647. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
  648. if (tmpe->prt_min <= port && port <= tmpe->prt_max) {
  649. if (tmpe->maskbits == 0) {
  650. /* Definitely matches, since it covers all addresses. */
  651. if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
  652. /* If we already hit a clause that might trigger a 'reject', than we
  653. * can't be sure of this certain 'accept'.*/
  654. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
  655. ADDR_POLICY_ACCEPTED;
  656. } else {
  657. return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
  658. ADDR_POLICY_REJECTED;
  659. }
  660. } else {
  661. /* Might match. */
  662. if (tmpe->policy_type == ADDR_POLICY_REJECT)
  663. maybe_reject = 1;
  664. else
  665. maybe_accept = 1;
  666. }
  667. }
  668. } SMARTLIST_FOREACH_END(tmpe);
  669. /* accept all by default. */
  670. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  671. }
  672. /** Decide whether a given addr:port is definitely accepted,
  673. * definitely rejected, probably accepted, or probably rejected by a
  674. * given policy. If <b>addr</b> is 0, we don't know the IP of the
  675. * target address. If <b>port</b> is 0, we don't know the port of the
  676. * target address. (At least one of <b>addr</b> and <b>port</b> must be
  677. * provided. If you want to know whether a policy would definitely reject
  678. * an unknown address:port, use policy_is_reject_star().)
  679. *
  680. * We could do better by assuming that some ranges never match typical
  681. * addresses (127.0.0.1, and so on). But we'll try this for now.
  682. */
  683. MOCK_IMPL(addr_policy_result_t,
  684. compare_tor_addr_to_addr_policy,(const tor_addr_t *addr, uint16_t port,
  685. const smartlist_t *policy))
  686. {
  687. if (!policy) {
  688. /* no policy? accept all. */
  689. return ADDR_POLICY_ACCEPTED;
  690. } else if (addr == NULL || tor_addr_is_null(addr)) {
  691. if (port == 0) {
  692. log_info(LD_BUG, "Rejecting null address with 0 port (family %d)",
  693. addr ? tor_addr_family(addr) : -1);
  694. return ADDR_POLICY_REJECTED;
  695. }
  696. return compare_unknown_tor_addr_to_addr_policy(port, policy);
  697. } else if (port == 0) {
  698. return compare_known_tor_addr_to_addr_policy_noport(addr, policy);
  699. } else {
  700. return compare_known_tor_addr_to_addr_policy(addr, port, policy);
  701. }
  702. }
  703. /** Return true iff the address policy <b>a</b> covers every case that
  704. * would be covered by <b>b</b>, so that a,b is redundant. */
  705. static int
  706. addr_policy_covers(addr_policy_t *a, addr_policy_t *b)
  707. {
  708. if (tor_addr_family(&a->addr) != tor_addr_family(&b->addr)) {
  709. /* You can't cover a different family. */
  710. return 0;
  711. }
  712. /* We can ignore accept/reject, since "accept *:80, reject *:80" reduces
  713. * to "accept *:80". */
  714. if (a->maskbits > b->maskbits) {
  715. /* a has more fixed bits than b; it can't possibly cover b. */
  716. return 0;
  717. }
  718. if (tor_addr_compare_masked(&a->addr, &b->addr, a->maskbits, CMP_EXACT)) {
  719. /* There's a fixed bit in a that's set differently in b. */
  720. return 0;
  721. }
  722. return (a->prt_min <= b->prt_min && a->prt_max >= b->prt_max);
  723. }
  724. /** Return true iff the address policies <b>a</b> and <b>b</b> intersect,
  725. * that is, there exists an address/port that is covered by <b>a</b> that
  726. * is also covered by <b>b</b>.
  727. */
  728. static int
  729. addr_policy_intersects(addr_policy_t *a, addr_policy_t *b)
  730. {
  731. maskbits_t minbits;
  732. /* All the bits we care about are those that are set in both
  733. * netmasks. If they are equal in a and b's networkaddresses
  734. * then the networks intersect. If there is a difference,
  735. * then they do not. */
  736. if (a->maskbits < b->maskbits)
  737. minbits = a->maskbits;
  738. else
  739. minbits = b->maskbits;
  740. if (tor_addr_compare_masked(&a->addr, &b->addr, minbits, CMP_EXACT))
  741. return 0;
  742. if (a->prt_max < b->prt_min || b->prt_max < a->prt_min)
  743. return 0;
  744. return 1;
  745. }
  746. /** Add the exit policy described by <b>more</b> to <b>policy</b>.
  747. */
  748. static void
  749. append_exit_policy_string(smartlist_t **policy, const char *more)
  750. {
  751. config_line_t tmp;
  752. tmp.key = NULL;
  753. tmp.value = (char*) more;
  754. tmp.next = NULL;
  755. if (parse_addr_policy(&tmp, policy, -1)<0) {
  756. log_warn(LD_BUG, "Unable to parse internally generated policy %s",more);
  757. }
  758. }
  759. /** Add "reject <b>addr</b>:*" to <b>dest</b>, creating the list as needed. */
  760. void
  761. addr_policy_append_reject_addr(smartlist_t **dest, const tor_addr_t *addr)
  762. {
  763. addr_policy_t p, *add;
  764. memset(&p, 0, sizeof(p));
  765. p.policy_type = ADDR_POLICY_REJECT;
  766. p.maskbits = tor_addr_family(addr) == AF_INET6 ? 128 : 32;
  767. tor_addr_copy(&p.addr, addr);
  768. p.prt_min = 1;
  769. p.prt_max = 65535;
  770. add = addr_policy_get_canonical_entry(&p);
  771. if (!*dest)
  772. *dest = smartlist_new();
  773. smartlist_add(*dest, add);
  774. }
  775. /** Detect and excise "dead code" from the policy *<b>dest</b>. */
  776. static void
  777. exit_policy_remove_redundancies(smartlist_t *dest)
  778. {
  779. addr_policy_t *ap, *tmp;
  780. int i, j;
  781. /* Step one: kill every ipv4 thing after *4:*, every IPv6 thing after *6:*
  782. */
  783. {
  784. int kill_v4=0, kill_v6=0;
  785. for (i = 0; i < smartlist_len(dest); ++i) {
  786. sa_family_t family;
  787. ap = smartlist_get(dest, i);
  788. family = tor_addr_family(&ap->addr);
  789. if ((family == AF_INET && kill_v4) ||
  790. (family == AF_INET6 && kill_v6)) {
  791. smartlist_del_keeporder(dest, i--);
  792. addr_policy_free(ap);
  793. continue;
  794. }
  795. if (ap->maskbits == 0 && ap->prt_min <= 1 && ap->prt_max >= 65535) {
  796. /* This is a catch-all line -- later lines are unreachable. */
  797. if (family == AF_INET) {
  798. kill_v4 = 1;
  799. } else if (family == AF_INET6) {
  800. kill_v6 = 1;
  801. }
  802. }
  803. }
  804. }
  805. /* Step two: for every entry, see if there's a redundant entry
  806. * later on, and remove it. */
  807. for (i = 0; i < smartlist_len(dest)-1; ++i) {
  808. ap = smartlist_get(dest, i);
  809. for (j = i+1; j < smartlist_len(dest); ++j) {
  810. tmp = smartlist_get(dest, j);
  811. tor_assert(j > i);
  812. if (addr_policy_covers(ap, tmp)) {
  813. char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
  814. policy_write_item(p1, sizeof(p1), tmp, 0);
  815. policy_write_item(p2, sizeof(p2), ap, 0);
  816. log_debug(LD_CONFIG, "Removing exit policy %s (%d). It is made "
  817. "redundant by %s (%d).", p1, j, p2, i);
  818. smartlist_del_keeporder(dest, j--);
  819. addr_policy_free(tmp);
  820. }
  821. }
  822. }
  823. /* Step three: for every entry A, see if there's an entry B making this one
  824. * redundant later on. This is the case if A and B are of the same type
  825. * (accept/reject), A is a subset of B, and there is no other entry of
  826. * different type in between those two that intersects with A.
  827. *
  828. * Anybody want to double-check the logic here? XXX
  829. */
  830. for (i = 0; i < smartlist_len(dest)-1; ++i) {
  831. ap = smartlist_get(dest, i);
  832. for (j = i+1; j < smartlist_len(dest); ++j) {
  833. // tor_assert(j > i); // j starts out at i+1; j only increases; i only
  834. // // decreases.
  835. tmp = smartlist_get(dest, j);
  836. if (ap->policy_type != tmp->policy_type) {
  837. if (addr_policy_intersects(ap, tmp))
  838. break;
  839. } else { /* policy_types are equal. */
  840. if (addr_policy_covers(tmp, ap)) {
  841. char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
  842. policy_write_item(p1, sizeof(p1), ap, 0);
  843. policy_write_item(p2, sizeof(p2), tmp, 0);
  844. log_debug(LD_CONFIG, "Removing exit policy %s. It is already "
  845. "covered by %s.", p1, p2);
  846. smartlist_del_keeporder(dest, i--);
  847. addr_policy_free(ap);
  848. break;
  849. }
  850. }
  851. }
  852. }
  853. }
  854. #define DEFAULT_EXIT_POLICY \
  855. "reject *:25,reject *:119,reject *:135-139,reject *:445," \
  856. "reject *:563,reject *:1214,reject *:4661-4666," \
  857. "reject *:6346-6429,reject *:6699,reject *:6881-6999,accept *:*"
  858. /** Parse the exit policy <b>cfg</b> into the linked list *<b>dest</b>. If
  859. * cfg doesn't end in an absolute accept or reject and if
  860. * <b>add_default_policy</b> is true, add the default exit
  861. * policy afterwards. If <b>rejectprivate</b> is true, prepend
  862. * "reject private:*" to the policy. Return -1 if we can't parse cfg,
  863. * else return 0.
  864. *
  865. * This function is used to parse the exit policy from our torrc. For
  866. * the functions used to parse the exit policy from a router descriptor,
  867. * see router_add_exit_policy.
  868. */
  869. int
  870. policies_parse_exit_policy(config_line_t *cfg, smartlist_t **dest,
  871. int ipv6_exit,
  872. int rejectprivate, uint32_t local_address,
  873. int add_default_policy)
  874. {
  875. if (!ipv6_exit) {
  876. append_exit_policy_string(dest, "reject *6:*");
  877. }
  878. if (rejectprivate) {
  879. append_exit_policy_string(dest, "reject private:*");
  880. if (local_address) {
  881. char buf[POLICY_BUF_LEN];
  882. tor_snprintf(buf, sizeof(buf), "reject %s:*", fmt_addr32(local_address));
  883. append_exit_policy_string(dest, buf);
  884. }
  885. }
  886. if (parse_addr_policy(cfg, dest, -1))
  887. return -1;
  888. if (add_default_policy) {
  889. append_exit_policy_string(dest, DEFAULT_EXIT_POLICY);
  890. } else {
  891. append_exit_policy_string(dest, "reject *4:*");
  892. append_exit_policy_string(dest, "reject *6:*");
  893. }
  894. exit_policy_remove_redundancies(*dest);
  895. return 0;
  896. }
  897. /** Add "reject *:*" to the end of the policy in *<b>dest</b>, allocating
  898. * *<b>dest</b> as needed. */
  899. void
  900. policies_exit_policy_append_reject_star(smartlist_t **dest)
  901. {
  902. append_exit_policy_string(dest, "reject *4:*");
  903. append_exit_policy_string(dest, "reject *6:*");
  904. }
  905. /** Replace the exit policy of <b>node</b> with reject *:* */
  906. void
  907. policies_set_node_exitpolicy_to_reject_all(node_t *node)
  908. {
  909. node->rejects_all = 1;
  910. }
  911. /** Return 1 if there is at least one /8 subnet in <b>policy</b> that
  912. * allows exiting to <b>port</b>. Otherwise, return 0. */
  913. static int
  914. exit_policy_is_general_exit_helper(smartlist_t *policy, int port)
  915. {
  916. uint32_t mask, ip, i;
  917. /* Is this /8 rejected (1), or undecided (0)? */
  918. char subnet_status[256];
  919. memset(subnet_status, 0, sizeof(subnet_status));
  920. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
  921. if (tor_addr_family(&p->addr) != AF_INET)
  922. continue; /* IPv4 only for now */
  923. if (p->prt_min > port || p->prt_max < port)
  924. continue; /* Doesn't cover our port. */
  925. mask = 0;
  926. tor_assert(p->maskbits <= 32);
  927. if (p->maskbits)
  928. mask = UINT32_MAX<<(32-p->maskbits);
  929. ip = tor_addr_to_ipv4h(&p->addr);
  930. /* Calculate the first and last subnet that this exit policy touches
  931. * and set it as loop boundaries. */
  932. for (i = ((mask & ip)>>24); i <= (~((mask & ip) ^ mask)>>24); ++i) {
  933. tor_addr_t addr;
  934. if (subnet_status[i] != 0)
  935. continue; /* We already reject some part of this /8 */
  936. tor_addr_from_ipv4h(&addr, i<<24);
  937. if (tor_addr_is_internal(&addr, 0))
  938. continue; /* Local or non-routable addresses */
  939. if (p->policy_type == ADDR_POLICY_ACCEPT) {
  940. if (p->maskbits > 8)
  941. continue; /* Narrower than a /8. */
  942. /* We found an allowed subnet of at least size /8. Done
  943. * for this port! */
  944. return 1;
  945. } else if (p->policy_type == ADDR_POLICY_REJECT) {
  946. subnet_status[i] = 1;
  947. }
  948. }
  949. } SMARTLIST_FOREACH_END(p);
  950. return 0;
  951. }
  952. /** Return true iff <b>ri</b> is "useful as an exit node", meaning
  953. * it allows exit to at least one /8 address space for at least
  954. * two of ports 80, 443, and 6667. */
  955. int
  956. exit_policy_is_general_exit(smartlist_t *policy)
  957. {
  958. static const int ports[] = { 80, 443, 6667 };
  959. int n_allowed = 0;
  960. int i;
  961. if (!policy) /*XXXX disallow NULL policies? */
  962. return 0;
  963. for (i = 0; i < 3; ++i) {
  964. n_allowed += exit_policy_is_general_exit_helper(policy, ports[i]);
  965. }
  966. return n_allowed >= 2;
  967. }
  968. /** Return false if <b>policy</b> might permit access to some addr:port;
  969. * otherwise if we are certain it rejects everything, return true. */
  970. int
  971. policy_is_reject_star(const smartlist_t *policy, sa_family_t family)
  972. {
  973. if (!policy) /*XXXX disallow NULL policies? */
  974. return 1;
  975. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
  976. if (p->policy_type == ADDR_POLICY_ACCEPT &&
  977. (tor_addr_family(&p->addr) == family ||
  978. tor_addr_family(&p->addr) == AF_UNSPEC)) {
  979. return 0;
  980. } else if (p->policy_type == ADDR_POLICY_REJECT &&
  981. p->prt_min <= 1 && p->prt_max == 65535 &&
  982. p->maskbits == 0 &&
  983. (tor_addr_family(&p->addr) == family ||
  984. tor_addr_family(&p->addr) == AF_UNSPEC)) {
  985. return 1;
  986. }
  987. } SMARTLIST_FOREACH_END(p);
  988. return 1;
  989. }
  990. /** Write a single address policy to the buf_len byte buffer at buf. Return
  991. * the number of characters written, or -1 on failure. */
  992. int
  993. policy_write_item(char *buf, size_t buflen, addr_policy_t *policy,
  994. int format_for_desc)
  995. {
  996. size_t written = 0;
  997. char addrbuf[TOR_ADDR_BUF_LEN];
  998. const char *addrpart;
  999. int result;
  1000. const int is_accept = policy->policy_type == ADDR_POLICY_ACCEPT;
  1001. const sa_family_t family = tor_addr_family(&policy->addr);
  1002. const int is_ip6 = (family == AF_INET6);
  1003. tor_addr_to_str(addrbuf, &policy->addr, sizeof(addrbuf), 1);
  1004. /* write accept/reject 1.2.3.4 */
  1005. if (policy->is_private) {
  1006. addrpart = "private";
  1007. } else if (policy->maskbits == 0) {
  1008. if (format_for_desc)
  1009. addrpart = "*";
  1010. else if (family == AF_INET6)
  1011. addrpart = "*6";
  1012. else if (family == AF_INET)
  1013. addrpart = "*4";
  1014. else
  1015. addrpart = "*";
  1016. } else {
  1017. addrpart = addrbuf;
  1018. }
  1019. result = tor_snprintf(buf, buflen, "%s%s %s",
  1020. is_accept ? "accept" : "reject",
  1021. (is_ip6&&format_for_desc)?"6":"",
  1022. addrpart);
  1023. if (result < 0)
  1024. return -1;
  1025. written += strlen(buf);
  1026. /* If the maskbits is 32 we don't need to give it. If the mask is 0,
  1027. * we already wrote "*". */
  1028. if (policy->maskbits < 32 && policy->maskbits > 0) {
  1029. if (tor_snprintf(buf+written, buflen-written, "/%d", policy->maskbits)<0)
  1030. return -1;
  1031. written += strlen(buf+written);
  1032. }
  1033. if (policy->prt_min <= 1 && policy->prt_max == 65535) {
  1034. /* There is no port set; write ":*" */
  1035. if (written+4 > buflen)
  1036. return -1;
  1037. strlcat(buf+written, ":*", buflen-written);
  1038. written += 2;
  1039. } else if (policy->prt_min == policy->prt_max) {
  1040. /* There is only one port; write ":80". */
  1041. result = tor_snprintf(buf+written, buflen-written, ":%d", policy->prt_min);
  1042. if (result<0)
  1043. return -1;
  1044. written += result;
  1045. } else {
  1046. /* There is a range of ports; write ":79-80". */
  1047. result = tor_snprintf(buf+written, buflen-written, ":%d-%d",
  1048. policy->prt_min, policy->prt_max);
  1049. if (result<0)
  1050. return -1;
  1051. written += result;
  1052. }
  1053. if (written < buflen)
  1054. buf[written] = '\0';
  1055. else
  1056. return -1;
  1057. return (int)written;
  1058. }
  1059. /** Create a new exit policy summary, initially only with a single
  1060. * port 1-64k item */
  1061. /* XXXX This entire thing will do most stuff in O(N^2), or worse. Use an
  1062. * RB-tree if that turns out to matter. */
  1063. static smartlist_t *
  1064. policy_summary_create(void)
  1065. {
  1066. smartlist_t *summary;
  1067. policy_summary_item_t* item;
  1068. item = tor_malloc_zero(sizeof(policy_summary_item_t));
  1069. item->prt_min = 1;
  1070. item->prt_max = 65535;
  1071. item->reject_count = 0;
  1072. item->accepted = 0;
  1073. summary = smartlist_new();
  1074. smartlist_add(summary, item);
  1075. return summary;
  1076. }
  1077. /** Split the summary item in <b>item</b> at the port <b>new_starts</b>.
  1078. * The current item is changed to end at new-starts - 1, the new item
  1079. * copies reject_count and accepted from the old item,
  1080. * starts at new_starts and ends at the port where the original item
  1081. * previously ended.
  1082. */
  1083. static policy_summary_item_t*
  1084. policy_summary_item_split(policy_summary_item_t* old, uint16_t new_starts)
  1085. {
  1086. policy_summary_item_t* new;
  1087. new = tor_malloc_zero(sizeof(policy_summary_item_t));
  1088. new->prt_min = new_starts;
  1089. new->prt_max = old->prt_max;
  1090. new->reject_count = old->reject_count;
  1091. new->accepted = old->accepted;
  1092. old->prt_max = new_starts-1;
  1093. tor_assert(old->prt_min <= old->prt_max);
  1094. tor_assert(new->prt_min <= new->prt_max);
  1095. return new;
  1096. }
  1097. /* XXXX Nick says I'm going to hell for this. If he feels charitably towards
  1098. * my immortal soul, he can clean it up himself. */
  1099. #define AT(x) ((policy_summary_item_t*)smartlist_get(summary, x))
  1100. #define REJECT_CUTOFF_COUNT (1<<25)
  1101. /** Split an exit policy summary so that prt_min and prt_max
  1102. * fall at exactly the start and end of an item respectively.
  1103. */
  1104. static int
  1105. policy_summary_split(smartlist_t *summary,
  1106. uint16_t prt_min, uint16_t prt_max)
  1107. {
  1108. int start_at_index;
  1109. int i = 0;
  1110. while (AT(i)->prt_max < prt_min)
  1111. i++;
  1112. if (AT(i)->prt_min != prt_min) {
  1113. policy_summary_item_t* new_item;
  1114. new_item = policy_summary_item_split(AT(i), prt_min);
  1115. smartlist_insert(summary, i+1, new_item);
  1116. i++;
  1117. }
  1118. start_at_index = i;
  1119. while (AT(i)->prt_max < prt_max)
  1120. i++;
  1121. if (AT(i)->prt_max != prt_max) {
  1122. policy_summary_item_t* new_item;
  1123. new_item = policy_summary_item_split(AT(i), prt_max+1);
  1124. smartlist_insert(summary, i+1, new_item);
  1125. }
  1126. return start_at_index;
  1127. }
  1128. /** Mark port ranges as accepted if they are below the reject_count */
  1129. static void
  1130. policy_summary_accept(smartlist_t *summary,
  1131. uint16_t prt_min, uint16_t prt_max)
  1132. {
  1133. int i = policy_summary_split(summary, prt_min, prt_max);
  1134. while (i < smartlist_len(summary) &&
  1135. AT(i)->prt_max <= prt_max) {
  1136. if (!AT(i)->accepted &&
  1137. AT(i)->reject_count <= REJECT_CUTOFF_COUNT)
  1138. AT(i)->accepted = 1;
  1139. i++;
  1140. }
  1141. tor_assert(i < smartlist_len(summary) || prt_max==65535);
  1142. }
  1143. /** Count the number of addresses in a network with prefixlen maskbits
  1144. * against the given portrange. */
  1145. static void
  1146. policy_summary_reject(smartlist_t *summary,
  1147. maskbits_t maskbits,
  1148. uint16_t prt_min, uint16_t prt_max)
  1149. {
  1150. int i = policy_summary_split(summary, prt_min, prt_max);
  1151. /* XXX: ipv4 specific */
  1152. uint64_t count = (U64_LITERAL(1) << (32-maskbits));
  1153. while (i < smartlist_len(summary) &&
  1154. AT(i)->prt_max <= prt_max) {
  1155. AT(i)->reject_count += count;
  1156. i++;
  1157. }
  1158. tor_assert(i < smartlist_len(summary) || prt_max==65535);
  1159. }
  1160. /** Add a single exit policy item to our summary:
  1161. * If it is an accept ignore it unless it is for all IP addresses
  1162. * ("*"), i.e. it's prefixlen/maskbits is 0, else call
  1163. * policy_summary_accept().
  1164. * If it's a reject ignore it if it is about one of the private
  1165. * networks, else call policy_summary_reject().
  1166. */
  1167. static void
  1168. policy_summary_add_item(smartlist_t *summary, addr_policy_t *p)
  1169. {
  1170. if (p->policy_type == ADDR_POLICY_ACCEPT) {
  1171. if (p->maskbits == 0) {
  1172. policy_summary_accept(summary, p->prt_min, p->prt_max);
  1173. }
  1174. } else if (p->policy_type == ADDR_POLICY_REJECT) {
  1175. int is_private = 0;
  1176. int i;
  1177. for (i = 0; private_nets[i]; ++i) {
  1178. tor_addr_t addr;
  1179. maskbits_t maskbits;
  1180. if (tor_addr_parse_mask_ports(private_nets[i], 0, &addr,
  1181. &maskbits, NULL, NULL)<0) {
  1182. tor_assert(0);
  1183. }
  1184. if (tor_addr_compare(&p->addr, &addr, CMP_EXACT) == 0 &&
  1185. p->maskbits == maskbits) {
  1186. is_private = 1;
  1187. break;
  1188. }
  1189. }
  1190. if (!is_private) {
  1191. policy_summary_reject(summary, p->maskbits, p->prt_min, p->prt_max);
  1192. }
  1193. } else
  1194. tor_assert(0);
  1195. }
  1196. /** Create a string representing a summary for an exit policy.
  1197. * The summary will either be an "accept" plus a comma-separated list of port
  1198. * ranges or a "reject" plus port-ranges, depending on which is shorter.
  1199. *
  1200. * If no exits are allowed at all then "reject 1-65535" is returned. If no
  1201. * ports are blocked instead of "reject " we return "accept 1-65535". (These
  1202. * are an exception to the shorter-representation-wins rule).
  1203. */
  1204. char *
  1205. policy_summarize(smartlist_t *policy, sa_family_t family)
  1206. {
  1207. smartlist_t *summary = policy_summary_create();
  1208. smartlist_t *accepts, *rejects;
  1209. int i, last, start_prt;
  1210. size_t accepts_len, rejects_len;
  1211. char *accepts_str = NULL, *rejects_str = NULL, *shorter_str, *result;
  1212. const char *prefix;
  1213. tor_assert(policy);
  1214. /* Create the summary list */
  1215. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
  1216. sa_family_t f = tor_addr_family(&p->addr);
  1217. if (f != AF_INET && f != AF_INET6) {
  1218. log_warn(LD_BUG, "Weird family when summarizing address policy");
  1219. }
  1220. if (f != family)
  1221. continue;
  1222. /* XXXX-ipv6 More family work is needed */
  1223. policy_summary_add_item(summary, p);
  1224. } SMARTLIST_FOREACH_END(p);
  1225. /* Now create two lists of strings, one for accepted and one
  1226. * for rejected ports. We take care to merge ranges so that
  1227. * we avoid getting stuff like "1-4,5-9,10", instead we want
  1228. * "1-10"
  1229. */
  1230. i = 0;
  1231. start_prt = 1;
  1232. accepts = smartlist_new();
  1233. rejects = smartlist_new();
  1234. while (1) {
  1235. last = i == smartlist_len(summary)-1;
  1236. if (last ||
  1237. AT(i)->accepted != AT(i+1)->accepted) {
  1238. char buf[POLICY_BUF_LEN];
  1239. if (start_prt == AT(i)->prt_max)
  1240. tor_snprintf(buf, sizeof(buf), "%d", start_prt);
  1241. else
  1242. tor_snprintf(buf, sizeof(buf), "%d-%d", start_prt, AT(i)->prt_max);
  1243. if (AT(i)->accepted)
  1244. smartlist_add(accepts, tor_strdup(buf));
  1245. else
  1246. smartlist_add(rejects, tor_strdup(buf));
  1247. if (last)
  1248. break;
  1249. start_prt = AT(i+1)->prt_min;
  1250. };
  1251. i++;
  1252. };
  1253. /* Figure out which of the two stringlists will be shorter and use
  1254. * that to build the result
  1255. */
  1256. if (smartlist_len(accepts) == 0) { /* no exits at all */
  1257. result = tor_strdup("reject 1-65535");
  1258. goto cleanup;
  1259. }
  1260. if (smartlist_len(rejects) == 0) { /* no rejects at all */
  1261. result = tor_strdup("accept 1-65535");
  1262. goto cleanup;
  1263. }
  1264. accepts_str = smartlist_join_strings(accepts, ",", 0, &accepts_len);
  1265. rejects_str = smartlist_join_strings(rejects, ",", 0, &rejects_len);
  1266. if (rejects_len > MAX_EXITPOLICY_SUMMARY_LEN-strlen("reject")-1 &&
  1267. accepts_len > MAX_EXITPOLICY_SUMMARY_LEN-strlen("accept")-1) {
  1268. char *c;
  1269. shorter_str = accepts_str;
  1270. prefix = "accept";
  1271. c = shorter_str + (MAX_EXITPOLICY_SUMMARY_LEN-strlen(prefix)-1);
  1272. while (*c != ',' && c >= shorter_str)
  1273. c--;
  1274. tor_assert(c >= shorter_str);
  1275. tor_assert(*c == ',');
  1276. *c = '\0';
  1277. } else if (rejects_len < accepts_len) {
  1278. shorter_str = rejects_str;
  1279. prefix = "reject";
  1280. } else {
  1281. shorter_str = accepts_str;
  1282. prefix = "accept";
  1283. }
  1284. tor_asprintf(&result, "%s %s", prefix, shorter_str);
  1285. cleanup:
  1286. /* cleanup */
  1287. SMARTLIST_FOREACH(summary, policy_summary_item_t *, s, tor_free(s));
  1288. smartlist_free(summary);
  1289. tor_free(accepts_str);
  1290. SMARTLIST_FOREACH(accepts, char *, s, tor_free(s));
  1291. smartlist_free(accepts);
  1292. tor_free(rejects_str);
  1293. SMARTLIST_FOREACH(rejects, char *, s, tor_free(s));
  1294. smartlist_free(rejects);
  1295. return result;
  1296. }
  1297. /** Convert a summarized policy string into a short_policy_t. Return NULL
  1298. * if the string is not well-formed. */
  1299. short_policy_t *
  1300. parse_short_policy(const char *summary)
  1301. {
  1302. const char *orig_summary = summary;
  1303. short_policy_t *result;
  1304. int is_accept;
  1305. int n_entries;
  1306. short_policy_entry_t entries[MAX_EXITPOLICY_SUMMARY_LEN]; /* overkill */
  1307. const char *next;
  1308. if (!strcmpstart(summary, "accept ")) {
  1309. is_accept = 1;
  1310. summary += strlen("accept ");
  1311. } else if (!strcmpstart(summary, "reject ")) {
  1312. is_accept = 0;
  1313. summary += strlen("reject ");
  1314. } else {
  1315. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Unrecognized policy summary keyword");
  1316. return NULL;
  1317. }
  1318. n_entries = 0;
  1319. for ( ; *summary; summary = next) {
  1320. const char *comma = strchr(summary, ',');
  1321. unsigned low, high;
  1322. char dummy;
  1323. char ent_buf[32];
  1324. size_t len;
  1325. next = comma ? comma+1 : strchr(summary, '\0');
  1326. len = comma ? (size_t)(comma - summary) : strlen(summary);
  1327. if (n_entries == MAX_EXITPOLICY_SUMMARY_LEN) {
  1328. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Impossibly long policy summary %s",
  1329. escaped(orig_summary));
  1330. return NULL;
  1331. }
  1332. if (! TOR_ISDIGIT(*summary) || len > (sizeof(ent_buf)-1)) {
  1333. /* unrecognized entry format. skip it. */
  1334. continue;
  1335. }
  1336. if (len < 1) {
  1337. /* empty; skip it. */
  1338. /* XXX This happens to be unreachable, since if len==0, then *summary is
  1339. * ',' or '\0', and the TOR_ISDIGIT test above would have failed. */
  1340. continue;
  1341. }
  1342. memcpy(ent_buf, summary, len);
  1343. ent_buf[len] = '\0';
  1344. if (tor_sscanf(ent_buf, "%u-%u%c", &low, &high, &dummy) == 2) {
  1345. if (low<1 || low>65535 || high<1 || high>65535 || low>high) {
  1346. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  1347. "Found bad entry in policy summary %s", escaped(orig_summary));
  1348. return NULL;
  1349. }
  1350. } else if (tor_sscanf(ent_buf, "%u%c", &low, &dummy) == 1) {
  1351. if (low<1 || low>65535) {
  1352. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  1353. "Found bad entry in policy summary %s", escaped(orig_summary));
  1354. return NULL;
  1355. }
  1356. high = low;
  1357. } else {
  1358. log_fn(LOG_PROTOCOL_WARN, LD_DIR,"Found bad entry in policy summary %s",
  1359. escaped(orig_summary));
  1360. return NULL;
  1361. }
  1362. entries[n_entries].min_port = low;
  1363. entries[n_entries].max_port = high;
  1364. n_entries++;
  1365. }
  1366. if (n_entries == 0) {
  1367. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  1368. "Found no port-range entries in summary %s", escaped(orig_summary));
  1369. return NULL;
  1370. }
  1371. {
  1372. size_t size = STRUCT_OFFSET(short_policy_t, entries) +
  1373. sizeof(short_policy_entry_t)*(n_entries);
  1374. result = tor_malloc_zero(size);
  1375. tor_assert( (char*)&result->entries[n_entries-1] < ((char*)result)+size);
  1376. }
  1377. result->is_accept = is_accept;
  1378. result->n_entries = n_entries;
  1379. memcpy(result->entries, entries, sizeof(short_policy_entry_t)*n_entries);
  1380. return result;
  1381. }
  1382. /** Write <b>policy</b> back out into a string. Used only for unit tests
  1383. * currently. */
  1384. char *
  1385. write_short_policy(const short_policy_t *policy)
  1386. {
  1387. int i;
  1388. char *answer;
  1389. smartlist_t *sl = smartlist_new();
  1390. smartlist_add_asprintf(sl, "%s", policy->is_accept ? "accept " : "reject ");
  1391. for (i=0; i < policy->n_entries; i++) {
  1392. const short_policy_entry_t *e = &policy->entries[i];
  1393. if (e->min_port == e->max_port) {
  1394. smartlist_add_asprintf(sl, "%d", e->min_port);
  1395. } else {
  1396. smartlist_add_asprintf(sl, "%d-%d", e->min_port, e->max_port);
  1397. }
  1398. if (i < policy->n_entries-1)
  1399. smartlist_add(sl, tor_strdup(","));
  1400. }
  1401. answer = smartlist_join_strings(sl, "", 0, NULL);
  1402. SMARTLIST_FOREACH(sl, char *, a, tor_free(a));
  1403. smartlist_free(sl);
  1404. return answer;
  1405. }
  1406. /** Release all storage held in <b>policy</b>. */
  1407. void
  1408. short_policy_free(short_policy_t *policy)
  1409. {
  1410. tor_free(policy);
  1411. }
  1412. /** See whether the <b>addr</b>:<b>port</b> address is likely to be accepted
  1413. * or rejected by the summarized policy <b>policy</b>. Return values are as
  1414. * for compare_tor_addr_to_addr_policy. Unlike the regular addr_policy
  1415. * functions, requires the <b>port</b> be specified. */
  1416. addr_policy_result_t
  1417. compare_tor_addr_to_short_policy(const tor_addr_t *addr, uint16_t port,
  1418. const short_policy_t *policy)
  1419. {
  1420. int i;
  1421. int found_match = 0;
  1422. int accept;
  1423. tor_assert(port != 0);
  1424. if (addr && tor_addr_is_null(addr))
  1425. addr = NULL; /* Unspec means 'no address at all,' in this context. */
  1426. if (addr && get_options()->ClientRejectInternalAddresses &&
  1427. (tor_addr_is_internal(addr, 0) || tor_addr_is_loopback(addr)))
  1428. return ADDR_POLICY_REJECTED;
  1429. for (i=0; i < policy->n_entries; ++i) {
  1430. const short_policy_entry_t *e = &policy->entries[i];
  1431. if (e->min_port <= port && port <= e->max_port) {
  1432. found_match = 1;
  1433. break;
  1434. }
  1435. }
  1436. if (found_match)
  1437. accept = policy->is_accept;
  1438. else
  1439. accept = ! policy->is_accept;
  1440. /* ???? are these right? -NM */
  1441. /* We should be sure not to return ADDR_POLICY_ACCEPTED in the accept
  1442. * case here, because it would cause clients to believe that the node
  1443. * allows exit enclaving. Trying it anyway would open up a cool attack
  1444. * where the node refuses due to exitpolicy, the client reacts in
  1445. * surprise by rewriting the node's exitpolicy to reject *:*, and then
  1446. * a bad guy targets users by causing them to attempt such connections
  1447. * to 98% of the exits.
  1448. *
  1449. * Once microdescriptors can handle addresses in special cases (e.g. if
  1450. * we ever solve ticket 1774), we can provide certainty here. -RD */
  1451. if (accept)
  1452. return ADDR_POLICY_PROBABLY_ACCEPTED;
  1453. else
  1454. return ADDR_POLICY_REJECTED;
  1455. }
  1456. /** Return true iff <b>policy</b> seems reject all ports */
  1457. int
  1458. short_policy_is_reject_star(const short_policy_t *policy)
  1459. {
  1460. /* This doesn't need to be as much on the lookout as policy_is_reject_star,
  1461. * since policy summaries are from the consensus or from consensus
  1462. * microdescs.
  1463. */
  1464. tor_assert(policy);
  1465. /* Check for an exact match of "reject 1-65535". */
  1466. return (policy->is_accept == 0 && policy->n_entries == 1 &&
  1467. policy->entries[0].min_port == 1 &&
  1468. policy->entries[0].max_port == 65535);
  1469. }
  1470. /** Decide whether addr:port is probably or definitely accepted or rejected by
  1471. * <b>node</b>. See compare_tor_addr_to_addr_policy for details on addr/port
  1472. * interpretation. */
  1473. addr_policy_result_t
  1474. compare_tor_addr_to_node_policy(const tor_addr_t *addr, uint16_t port,
  1475. const node_t *node)
  1476. {
  1477. if (node->rejects_all)
  1478. return ADDR_POLICY_REJECTED;
  1479. if (addr && tor_addr_family(addr) == AF_INET6) {
  1480. const short_policy_t *p = NULL;
  1481. if (node->ri)
  1482. p = node->ri->ipv6_exit_policy;
  1483. else if (node->md)
  1484. p = node->md->ipv6_exit_policy;
  1485. if (p)
  1486. return compare_tor_addr_to_short_policy(addr, port, p);
  1487. else
  1488. return ADDR_POLICY_REJECTED;
  1489. }
  1490. if (node->ri) {
  1491. return compare_tor_addr_to_addr_policy(addr, port, node->ri->exit_policy);
  1492. } else if (node->md) {
  1493. if (node->md->exit_policy == NULL)
  1494. return ADDR_POLICY_REJECTED;
  1495. else
  1496. return compare_tor_addr_to_short_policy(addr, port,
  1497. node->md->exit_policy);
  1498. } else {
  1499. return ADDR_POLICY_PROBABLY_REJECTED;
  1500. }
  1501. }
  1502. /** Implementation for GETINFO control command: knows the answer for questions
  1503. * about "exit-policy/..." */
  1504. int
  1505. getinfo_helper_policies(control_connection_t *conn,
  1506. const char *question, char **answer,
  1507. const char **errmsg)
  1508. {
  1509. (void) conn;
  1510. (void) errmsg;
  1511. if (!strcmp(question, "exit-policy/default")) {
  1512. *answer = tor_strdup(DEFAULT_EXIT_POLICY);
  1513. } else if (!strcmpstart(question, "exit-policy/")) {
  1514. const routerinfo_t *me = router_get_my_routerinfo();
  1515. int include_ipv4 = 0;
  1516. int include_ipv6 = 0;
  1517. if (!strcmp(question, "exit-policy/ipv4")) {
  1518. include_ipv4 = 1;
  1519. } else if (!strcmp(question, "exit-policy/ipv6")) {
  1520. include_ipv6 = 1;
  1521. } else if (!strcmp(question, "exit-policy/full")) {
  1522. include_ipv4 = include_ipv6 = 1;
  1523. } else {
  1524. return 0; /* No such key. */
  1525. }
  1526. if (!me) {
  1527. *errmsg = "router_get_my_routerinfo returned NULL";
  1528. return -1;
  1529. }
  1530. *answer = router_dump_exit_policy_to_string(me,include_ipv4,include_ipv6);
  1531. }
  1532. return 0;
  1533. }
  1534. /** Release all storage held by <b>p</b>. */
  1535. void
  1536. addr_policy_list_free(smartlist_t *lst)
  1537. {
  1538. if (!lst)
  1539. return;
  1540. SMARTLIST_FOREACH(lst, addr_policy_t *, policy, addr_policy_free(policy));
  1541. smartlist_free(lst);
  1542. }
  1543. /** Release all storage held by <b>p</b>. */
  1544. void
  1545. addr_policy_free(addr_policy_t *p)
  1546. {
  1547. if (!p)
  1548. return;
  1549. if (--p->refcnt <= 0) {
  1550. if (p->is_canonical) {
  1551. policy_map_ent_t search, *found;
  1552. search.policy = p;
  1553. found = HT_REMOVE(policy_map, &policy_root, &search);
  1554. if (found) {
  1555. tor_assert(p == found->policy);
  1556. tor_free(found);
  1557. }
  1558. }
  1559. tor_free(p);
  1560. }
  1561. }
  1562. /** Release all storage held by policy variables. */
  1563. void
  1564. policies_free_all(void)
  1565. {
  1566. addr_policy_list_free(reachable_or_addr_policy);
  1567. reachable_or_addr_policy = NULL;
  1568. addr_policy_list_free(reachable_dir_addr_policy);
  1569. reachable_dir_addr_policy = NULL;
  1570. addr_policy_list_free(socks_policy);
  1571. socks_policy = NULL;
  1572. addr_policy_list_free(dir_policy);
  1573. dir_policy = NULL;
  1574. addr_policy_list_free(authdir_reject_policy);
  1575. authdir_reject_policy = NULL;
  1576. addr_policy_list_free(authdir_invalid_policy);
  1577. authdir_invalid_policy = NULL;
  1578. addr_policy_list_free(authdir_badexit_policy);
  1579. authdir_badexit_policy = NULL;
  1580. if (!HT_EMPTY(&policy_root)) {
  1581. policy_map_ent_t **ent;
  1582. int n = 0;
  1583. char buf[POLICY_BUF_LEN];
  1584. log_warn(LD_MM, "Still had %d address policies cached at shutdown.",
  1585. (int)HT_SIZE(&policy_root));
  1586. /* Note the first 10 cached policies to try to figure out where they
  1587. * might be coming from. */
  1588. HT_FOREACH(ent, policy_map, &policy_root) {
  1589. if (++n > 10)
  1590. break;
  1591. if (policy_write_item(buf, sizeof(buf), (*ent)->policy, 0) >= 0)
  1592. log_warn(LD_MM," %d [%d]: %s", n, (*ent)->policy->refcnt, buf);
  1593. }
  1594. }
  1595. HT_CLEAR(policy_map, &policy_root);
  1596. }