policies.c 50 KB

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