policies.c 60 KB

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