policies.c 49 KB

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