policies.c 57 KB

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