policies.c 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627
  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. if (port == 0) {
  652. log_info(LD_BUG, "Rejecting null address with 0 port (family %d)",
  653. addr ? tor_addr_family(addr) : -1);
  654. return ADDR_POLICY_REJECTED;
  655. }
  656. return compare_unknown_tor_addr_to_addr_policy(port, policy);
  657. } else if (port == 0) {
  658. return compare_known_tor_addr_to_addr_policy_noport(addr, policy);
  659. } else {
  660. return compare_known_tor_addr_to_addr_policy(addr, port, policy);
  661. }
  662. }
  663. /** Return true iff the address policy <b>a</b> covers every case that
  664. * would be covered by <b>b</b>, so that a,b is redundant. */
  665. static int
  666. addr_policy_covers(addr_policy_t *a, addr_policy_t *b)
  667. {
  668. /* We can ignore accept/reject, since "accept *:80, reject *:80" reduces
  669. * to "accept *:80". */
  670. if (a->maskbits > b->maskbits) {
  671. /* a has more fixed bits than b; it can't possibly cover b. */
  672. return 0;
  673. }
  674. if (tor_addr_compare_masked(&a->addr, &b->addr, a->maskbits, CMP_EXACT)) {
  675. /* There's a fixed bit in a that's set differently in b. */
  676. return 0;
  677. }
  678. return (a->prt_min <= b->prt_min && a->prt_max >= b->prt_max);
  679. }
  680. /** Return true iff the address policies <b>a</b> and <b>b</b> intersect,
  681. * that is, there exists an address/port that is covered by <b>a</b> that
  682. * is also covered by <b>b</b>.
  683. */
  684. static int
  685. addr_policy_intersects(addr_policy_t *a, addr_policy_t *b)
  686. {
  687. maskbits_t minbits;
  688. /* All the bits we care about are those that are set in both
  689. * netmasks. If they are equal in a and b's networkaddresses
  690. * then the networks intersect. If there is a difference,
  691. * then they do not. */
  692. if (a->maskbits < b->maskbits)
  693. minbits = a->maskbits;
  694. else
  695. minbits = b->maskbits;
  696. if (tor_addr_compare_masked(&a->addr, &b->addr, minbits, CMP_EXACT))
  697. return 0;
  698. if (a->prt_max < b->prt_min || b->prt_max < a->prt_min)
  699. return 0;
  700. return 1;
  701. }
  702. /** Add the exit policy described by <b>more</b> to <b>policy</b>.
  703. */
  704. static void
  705. append_exit_policy_string(smartlist_t **policy, const char *more)
  706. {
  707. config_line_t tmp;
  708. tmp.key = NULL;
  709. tmp.value = (char*) more;
  710. tmp.next = NULL;
  711. if (parse_addr_policy(&tmp, policy, -1)<0) {
  712. log_warn(LD_BUG, "Unable to parse internally generated policy %s",more);
  713. }
  714. }
  715. /** Detect and excise "dead code" from the policy *<b>dest</b>. */
  716. static void
  717. exit_policy_remove_redundancies(smartlist_t *dest)
  718. {
  719. addr_policy_t *ap, *tmp, *victim;
  720. int i, j;
  721. /* Step one: find a *:* entry and cut off everything after it. */
  722. for (i = 0; i < smartlist_len(dest); ++i) {
  723. ap = smartlist_get(dest, i);
  724. if (ap->maskbits == 0 && ap->prt_min <= 1 && ap->prt_max >= 65535) {
  725. /* This is a catch-all line -- later lines are unreachable. */
  726. while (i+1 < smartlist_len(dest)) {
  727. victim = smartlist_get(dest, i+1);
  728. smartlist_del(dest, i+1);
  729. addr_policy_free(victim);
  730. }
  731. break;
  732. }
  733. }
  734. /* Step two: for every entry, see if there's a redundant entry
  735. * later on, and remove it. */
  736. for (i = 0; i < smartlist_len(dest)-1; ++i) {
  737. ap = smartlist_get(dest, i);
  738. for (j = i+1; j < smartlist_len(dest); ++j) {
  739. tmp = smartlist_get(dest, j);
  740. tor_assert(j > i);
  741. if (addr_policy_covers(ap, tmp)) {
  742. char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
  743. policy_write_item(p1, sizeof(p1), tmp, 0);
  744. policy_write_item(p2, sizeof(p2), ap, 0);
  745. log(LOG_DEBUG, LD_CONFIG, "Removing exit policy %s (%d). It is made "
  746. "redundant by %s (%d).", p1, j, p2, i);
  747. smartlist_del_keeporder(dest, j--);
  748. addr_policy_free(tmp);
  749. }
  750. }
  751. }
  752. /* Step three: for every entry A, see if there's an entry B making this one
  753. * redundant later on. This is the case if A and B are of the same type
  754. * (accept/reject), A is a subset of B, and there is no other entry of
  755. * different type in between those two that intersects with A.
  756. *
  757. * Anybody want to double-check the logic here? XXX
  758. */
  759. for (i = 0; i < smartlist_len(dest)-1; ++i) {
  760. ap = smartlist_get(dest, i);
  761. for (j = i+1; j < smartlist_len(dest); ++j) {
  762. // tor_assert(j > i); // j starts out at i+1; j only increases; i only
  763. // // decreases.
  764. tmp = smartlist_get(dest, j);
  765. if (ap->policy_type != tmp->policy_type) {
  766. if (addr_policy_intersects(ap, tmp))
  767. break;
  768. } else { /* policy_types are equal. */
  769. if (addr_policy_covers(tmp, ap)) {
  770. char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
  771. policy_write_item(p1, sizeof(p1), ap, 0);
  772. policy_write_item(p2, sizeof(p2), tmp, 0);
  773. log(LOG_DEBUG, LD_CONFIG, "Removing exit policy %s. It is already "
  774. "covered by %s.", p1, p2);
  775. smartlist_del_keeporder(dest, i--);
  776. addr_policy_free(ap);
  777. break;
  778. }
  779. }
  780. }
  781. }
  782. }
  783. #define DEFAULT_EXIT_POLICY \
  784. "reject *:25,reject *:119,reject *:135-139,reject *:445," \
  785. "reject *:563,reject *:1214,reject *:4661-4666," \
  786. "reject *:6346-6429,reject *:6699,reject *:6881-6999,accept *:*"
  787. /** Parse the exit policy <b>cfg</b> into the linked list *<b>dest</b>. If
  788. * cfg doesn't end in an absolute accept or reject and if
  789. * <b>add_default_policy</b> is true, add the default exit
  790. * policy afterwards. If <b>rejectprivate</b> is true, prepend
  791. * "reject private:*" to the policy. Return -1 if we can't parse cfg,
  792. * else return 0.
  793. */
  794. int
  795. policies_parse_exit_policy(config_line_t *cfg, smartlist_t **dest,
  796. int rejectprivate, const char *local_address,
  797. int add_default_policy)
  798. {
  799. if (rejectprivate) {
  800. append_exit_policy_string(dest, "reject private:*");
  801. if (local_address) {
  802. char buf[POLICY_BUF_LEN];
  803. tor_snprintf(buf, sizeof(buf), "reject %s:*", local_address);
  804. append_exit_policy_string(dest, buf);
  805. }
  806. }
  807. if (parse_addr_policy(cfg, dest, -1))
  808. return -1;
  809. if (add_default_policy)
  810. append_exit_policy_string(dest, DEFAULT_EXIT_POLICY);
  811. else
  812. append_exit_policy_string(dest, "reject *:*");
  813. exit_policy_remove_redundancies(*dest);
  814. return 0;
  815. }
  816. /** Add "reject *:*" to the end of the policy in *<b>dest</b>, allocating
  817. * *<b>dest</b> as needed. */
  818. void
  819. policies_exit_policy_append_reject_star(smartlist_t **dest)
  820. {
  821. append_exit_policy_string(dest, "reject *:*");
  822. }
  823. /** Replace the exit policy of <b>node</b> with reject *:* */
  824. void
  825. policies_set_node_exitpolicy_to_reject_all(node_t *node)
  826. {
  827. node->rejects_all = 1;
  828. }
  829. /** Return 1 if there is at least one /8 subnet in <b>policy</b> that
  830. * allows exiting to <b>port</b>. Otherwise, return 0. */
  831. static int
  832. exit_policy_is_general_exit_helper(smartlist_t *policy, int port)
  833. {
  834. uint32_t mask, ip, i;
  835. /* Is this /8 rejected (1), or undecided (0)? */
  836. char subnet_status[256];
  837. memset(subnet_status, 0, sizeof(subnet_status));
  838. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
  839. if (tor_addr_family(&p->addr) != AF_INET)
  840. continue; /* IPv4 only for now */
  841. if (p->prt_min > port || p->prt_max < port)
  842. continue; /* Doesn't cover our port. */
  843. mask = 0;
  844. tor_assert(p->maskbits <= 32);
  845. if (p->maskbits)
  846. mask = UINT32_MAX<<(32-p->maskbits);
  847. ip = tor_addr_to_ipv4h(&p->addr);
  848. /* Calculate the first and last subnet that this exit policy touches
  849. * and set it as loop boundaries. */
  850. for (i = ((mask & ip)>>24); i <= (~((mask & ip) ^ mask)>>24); ++i) {
  851. tor_addr_t addr;
  852. if (subnet_status[i] != 0)
  853. continue; /* We already reject some part of this /8 */
  854. tor_addr_from_ipv4h(&addr, i<<24);
  855. if (tor_addr_is_internal(&addr, 0))
  856. continue; /* Local or non-routable addresses */
  857. if (p->policy_type == ADDR_POLICY_ACCEPT) {
  858. if (p->maskbits > 8)
  859. continue; /* Narrower than a /8. */
  860. /* We found an allowed subnet of at least size /8. Done
  861. * for this port! */
  862. return 1;
  863. } else if (p->policy_type == ADDR_POLICY_REJECT) {
  864. subnet_status[i] = 1;
  865. }
  866. }
  867. } SMARTLIST_FOREACH_END(p);
  868. return 0;
  869. }
  870. /** Return true iff <b>ri</b> is "useful as an exit node", meaning
  871. * it allows exit to at least one /8 address space for at least
  872. * two of ports 80, 443, and 6667. */
  873. int
  874. exit_policy_is_general_exit(smartlist_t *policy)
  875. {
  876. static const int ports[] = { 80, 443, 6667 };
  877. int n_allowed = 0;
  878. int i;
  879. if (!policy) /*XXXX disallow NULL policies? */
  880. return 0;
  881. for (i = 0; i < 3; ++i) {
  882. n_allowed += exit_policy_is_general_exit_helper(policy, ports[i]);
  883. }
  884. return n_allowed >= 2;
  885. }
  886. /** Return false if <b>policy</b> might permit access to some addr:port;
  887. * otherwise if we are certain it rejects everything, return true. */
  888. int
  889. policy_is_reject_star(const smartlist_t *policy)
  890. {
  891. if (!policy) /*XXXX disallow NULL policies? */
  892. return 1;
  893. SMARTLIST_FOREACH(policy, addr_policy_t *, p, {
  894. if (p->policy_type == ADDR_POLICY_ACCEPT)
  895. return 0;
  896. else if (p->policy_type == ADDR_POLICY_REJECT &&
  897. p->prt_min <= 1 && p->prt_max == 65535 &&
  898. p->maskbits == 0)
  899. return 1;
  900. });
  901. return 1;
  902. }
  903. /** Write a single address policy to the buf_len byte buffer at buf. Return
  904. * the number of characters written, or -1 on failure. */
  905. int
  906. policy_write_item(char *buf, size_t buflen, addr_policy_t *policy,
  907. int format_for_desc)
  908. {
  909. size_t written = 0;
  910. char addrbuf[TOR_ADDR_BUF_LEN];
  911. const char *addrpart;
  912. int result;
  913. const int is_accept = policy->policy_type == ADDR_POLICY_ACCEPT;
  914. const int is_ip6 = tor_addr_family(&policy->addr) == AF_INET6;
  915. tor_addr_to_str(addrbuf, &policy->addr, sizeof(addrbuf), 1);
  916. /* write accept/reject 1.2.3.4 */
  917. if (policy->is_private)
  918. addrpart = "private";
  919. else if (policy->maskbits == 0)
  920. addrpart = "*";
  921. else
  922. addrpart = addrbuf;
  923. result = tor_snprintf(buf, buflen, "%s%s %s",
  924. is_accept ? "accept" : "reject",
  925. (is_ip6&&format_for_desc)?"6":"",
  926. addrpart);
  927. if (result < 0)
  928. return -1;
  929. written += strlen(buf);
  930. /* If the maskbits is 32 we don't need to give it. If the mask is 0,
  931. * we already wrote "*". */
  932. if (policy->maskbits < 32 && policy->maskbits > 0) {
  933. if (tor_snprintf(buf+written, buflen-written, "/%d", policy->maskbits)<0)
  934. return -1;
  935. written += strlen(buf+written);
  936. }
  937. if (policy->prt_min <= 1 && policy->prt_max == 65535) {
  938. /* There is no port set; write ":*" */
  939. if (written+4 > buflen)
  940. return -1;
  941. strlcat(buf+written, ":*", buflen-written);
  942. written += 2;
  943. } else if (policy->prt_min == policy->prt_max) {
  944. /* There is only one port; write ":80". */
  945. result = tor_snprintf(buf+written, buflen-written, ":%d", policy->prt_min);
  946. if (result<0)
  947. return -1;
  948. written += result;
  949. } else {
  950. /* There is a range of ports; write ":79-80". */
  951. result = tor_snprintf(buf+written, buflen-written, ":%d-%d",
  952. policy->prt_min, policy->prt_max);
  953. if (result<0)
  954. return -1;
  955. written += result;
  956. }
  957. if (written < buflen)
  958. buf[written] = '\0';
  959. else
  960. return -1;
  961. return (int)written;
  962. }
  963. /** Create a new exit policy summary, initially only with a single
  964. * port 1-64k item */
  965. /* XXXX This entire thing will do most stuff in O(N^2), or worse. Use an
  966. * RB-tree if that turns out to matter. */
  967. static smartlist_t *
  968. policy_summary_create(void)
  969. {
  970. smartlist_t *summary;
  971. policy_summary_item_t* item;
  972. item = tor_malloc_zero(sizeof(policy_summary_item_t));
  973. item->prt_min = 1;
  974. item->prt_max = 65535;
  975. item->reject_count = 0;
  976. item->accepted = 0;
  977. summary = smartlist_new();
  978. smartlist_add(summary, item);
  979. return summary;
  980. }
  981. /** Split the summary item in <b>item</b> at the port <b>new_starts</b>.
  982. * The current item is changed to end at new-starts - 1, the new item
  983. * copies reject_count and accepted from the old item,
  984. * starts at new_starts and ends at the port where the original item
  985. * previously ended.
  986. */
  987. static policy_summary_item_t*
  988. policy_summary_item_split(policy_summary_item_t* old, uint16_t new_starts)
  989. {
  990. policy_summary_item_t* new;
  991. new = tor_malloc_zero(sizeof(policy_summary_item_t));
  992. new->prt_min = new_starts;
  993. new->prt_max = old->prt_max;
  994. new->reject_count = old->reject_count;
  995. new->accepted = old->accepted;
  996. old->prt_max = new_starts-1;
  997. tor_assert(old->prt_min <= old->prt_max);
  998. tor_assert(new->prt_min <= new->prt_max);
  999. return new;
  1000. }
  1001. /* XXXX Nick says I'm going to hell for this. If he feels charitably towards
  1002. * my immortal soul, he can clean it up himself. */
  1003. #define AT(x) ((policy_summary_item_t*)smartlist_get(summary, x))
  1004. #define REJECT_CUTOFF_COUNT (1<<25)
  1005. /** Split an exit policy summary so that prt_min and prt_max
  1006. * fall at exactly the start and end of an item respectively.
  1007. */
  1008. static int
  1009. policy_summary_split(smartlist_t *summary,
  1010. uint16_t prt_min, uint16_t prt_max)
  1011. {
  1012. int start_at_index;
  1013. int i = 0;
  1014. while (AT(i)->prt_max < prt_min)
  1015. i++;
  1016. if (AT(i)->prt_min != prt_min) {
  1017. policy_summary_item_t* new_item;
  1018. new_item = policy_summary_item_split(AT(i), prt_min);
  1019. smartlist_insert(summary, i+1, new_item);
  1020. i++;
  1021. }
  1022. start_at_index = i;
  1023. while (AT(i)->prt_max < prt_max)
  1024. i++;
  1025. if (AT(i)->prt_max != prt_max) {
  1026. policy_summary_item_t* new_item;
  1027. new_item = policy_summary_item_split(AT(i), prt_max+1);
  1028. smartlist_insert(summary, i+1, new_item);
  1029. }
  1030. return start_at_index;
  1031. }
  1032. /** Mark port ranges as accepted if they are below the reject_count */
  1033. static void
  1034. policy_summary_accept(smartlist_t *summary,
  1035. uint16_t prt_min, uint16_t prt_max)
  1036. {
  1037. int i = policy_summary_split(summary, prt_min, prt_max);
  1038. while (i < smartlist_len(summary) &&
  1039. AT(i)->prt_max <= prt_max) {
  1040. if (!AT(i)->accepted &&
  1041. AT(i)->reject_count <= REJECT_CUTOFF_COUNT)
  1042. AT(i)->accepted = 1;
  1043. i++;
  1044. }
  1045. tor_assert(i < smartlist_len(summary) || prt_max==65535);
  1046. }
  1047. /** Count the number of addresses in a network with prefixlen maskbits
  1048. * against the given portrange. */
  1049. static void
  1050. policy_summary_reject(smartlist_t *summary,
  1051. maskbits_t maskbits,
  1052. uint16_t prt_min, uint16_t prt_max)
  1053. {
  1054. int i = policy_summary_split(summary, prt_min, prt_max);
  1055. /* XXX: ipv4 specific */
  1056. uint64_t count = (U64_LITERAL(1) << (32-maskbits));
  1057. while (i < smartlist_len(summary) &&
  1058. AT(i)->prt_max <= prt_max) {
  1059. AT(i)->reject_count += count;
  1060. i++;
  1061. }
  1062. tor_assert(i < smartlist_len(summary) || prt_max==65535);
  1063. }
  1064. /** Add a single exit policy item to our summary:
  1065. * If it is an accept ignore it unless it is for all IP addresses
  1066. * ("*"), i.e. it's prefixlen/maskbits is 0, else call
  1067. * policy_summary_accept().
  1068. * If it's a reject ignore it if it is about one of the private
  1069. * networks, else call policy_summary_reject().
  1070. */
  1071. static void
  1072. policy_summary_add_item(smartlist_t *summary, addr_policy_t *p)
  1073. {
  1074. if (p->policy_type == ADDR_POLICY_ACCEPT) {
  1075. if (p->maskbits == 0) {
  1076. policy_summary_accept(summary, p->prt_min, p->prt_max);
  1077. }
  1078. } else if (p->policy_type == ADDR_POLICY_REJECT) {
  1079. int is_private = 0;
  1080. int i;
  1081. for (i = 0; private_nets[i]; ++i) {
  1082. tor_addr_t addr;
  1083. maskbits_t maskbits;
  1084. if (tor_addr_parse_mask_ports(private_nets[i], &addr,
  1085. &maskbits, NULL, NULL)<0) {
  1086. tor_assert(0);
  1087. }
  1088. if (tor_addr_compare(&p->addr, &addr, CMP_EXACT) == 0 &&
  1089. p->maskbits == maskbits) {
  1090. is_private = 1;
  1091. break;
  1092. }
  1093. }
  1094. if (!is_private) {
  1095. policy_summary_reject(summary, p->maskbits, p->prt_min, p->prt_max);
  1096. }
  1097. } else
  1098. tor_assert(0);
  1099. }
  1100. /** Create a string representing a summary for an exit policy.
  1101. * The summary will either be an "accept" plus a comma-separated list of port
  1102. * ranges or a "reject" plus port-ranges, depending on which is shorter.
  1103. *
  1104. * If no exits are allowed at all then NULL is returned, if no ports
  1105. * are blocked instead of "reject " we return "accept 1-65535" (this
  1106. * is an exception to the shorter-representation-wins rule).
  1107. */
  1108. char *
  1109. policy_summarize(smartlist_t *policy)
  1110. {
  1111. smartlist_t *summary = policy_summary_create();
  1112. smartlist_t *accepts, *rejects;
  1113. int i, last, start_prt;
  1114. size_t accepts_len, rejects_len;
  1115. char *accepts_str = NULL, *rejects_str = NULL, *shorter_str, *result;
  1116. const char *prefix;
  1117. tor_assert(policy);
  1118. /* Create the summary list */
  1119. SMARTLIST_FOREACH(policy, addr_policy_t *, p, {
  1120. policy_summary_add_item(summary, p);
  1121. });
  1122. /* Now create two lists of strings, one for accepted and one
  1123. * for rejected ports. We take care to merge ranges so that
  1124. * we avoid getting stuff like "1-4,5-9,10", instead we want
  1125. * "1-10"
  1126. */
  1127. i = 0;
  1128. start_prt = 1;
  1129. accepts = smartlist_new();
  1130. rejects = smartlist_new();
  1131. while (1) {
  1132. last = i == smartlist_len(summary)-1;
  1133. if (last ||
  1134. AT(i)->accepted != AT(i+1)->accepted) {
  1135. char buf[POLICY_BUF_LEN];
  1136. if (start_prt == AT(i)->prt_max)
  1137. tor_snprintf(buf, sizeof(buf), "%d", start_prt);
  1138. else
  1139. tor_snprintf(buf, sizeof(buf), "%d-%d", start_prt, AT(i)->prt_max);
  1140. if (AT(i)->accepted)
  1141. smartlist_add(accepts, tor_strdup(buf));
  1142. else
  1143. smartlist_add(rejects, tor_strdup(buf));
  1144. if (last)
  1145. break;
  1146. start_prt = AT(i+1)->prt_min;
  1147. };
  1148. i++;
  1149. };
  1150. /* Figure out which of the two stringlists will be shorter and use
  1151. * that to build the result
  1152. */
  1153. if (smartlist_len(accepts) == 0) { /* no exits at all */
  1154. result = tor_strdup("reject 1-65535");
  1155. goto cleanup;
  1156. }
  1157. if (smartlist_len(rejects) == 0) { /* no rejects at all */
  1158. result = tor_strdup("accept 1-65535");
  1159. goto cleanup;
  1160. }
  1161. accepts_str = smartlist_join_strings(accepts, ",", 0, &accepts_len);
  1162. rejects_str = smartlist_join_strings(rejects, ",", 0, &rejects_len);
  1163. if (rejects_len > MAX_EXITPOLICY_SUMMARY_LEN-strlen("reject")-1 &&
  1164. accepts_len > MAX_EXITPOLICY_SUMMARY_LEN-strlen("accept")-1) {
  1165. char *c;
  1166. shorter_str = accepts_str;
  1167. prefix = "accept";
  1168. c = shorter_str + (MAX_EXITPOLICY_SUMMARY_LEN-strlen(prefix)-1);
  1169. while (*c != ',' && c >= shorter_str)
  1170. c--;
  1171. tor_assert(c >= shorter_str);
  1172. tor_assert(*c == ',');
  1173. *c = '\0';
  1174. } else if (rejects_len < accepts_len) {
  1175. shorter_str = rejects_str;
  1176. prefix = "reject";
  1177. } else {
  1178. shorter_str = accepts_str;
  1179. prefix = "accept";
  1180. }
  1181. tor_asprintf(&result, "%s %s", prefix, shorter_str);
  1182. cleanup:
  1183. /* cleanup */
  1184. SMARTLIST_FOREACH(summary, policy_summary_item_t *, s, tor_free(s));
  1185. smartlist_free(summary);
  1186. tor_free(accepts_str);
  1187. SMARTLIST_FOREACH(accepts, char *, s, tor_free(s));
  1188. smartlist_free(accepts);
  1189. tor_free(rejects_str);
  1190. SMARTLIST_FOREACH(rejects, char *, s, tor_free(s));
  1191. smartlist_free(rejects);
  1192. return result;
  1193. }
  1194. /** Convert a summarized policy string into a short_policy_t. Return NULL
  1195. * if the string is not well-formed. */
  1196. short_policy_t *
  1197. parse_short_policy(const char *summary)
  1198. {
  1199. const char *orig_summary = summary;
  1200. short_policy_t *result;
  1201. int is_accept;
  1202. int n_entries;
  1203. short_policy_entry_t entries[MAX_EXITPOLICY_SUMMARY_LEN]; /* overkill */
  1204. const char *next;
  1205. if (!strcmpstart(summary, "accept ")) {
  1206. is_accept = 1;
  1207. summary += strlen("accept ");
  1208. } else if (!strcmpstart(summary, "reject ")) {
  1209. is_accept = 0;
  1210. summary += strlen("reject ");
  1211. } else {
  1212. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Unrecognized policy summary keyword");
  1213. return NULL;
  1214. }
  1215. n_entries = 0;
  1216. for ( ; *summary; summary = next) {
  1217. const char *comma = strchr(summary, ',');
  1218. unsigned low, high;
  1219. char dummy;
  1220. char ent_buf[32];
  1221. size_t len;
  1222. next = comma ? comma+1 : strchr(summary, '\0');
  1223. len = comma ? (size_t)(comma - summary) : strlen(summary);
  1224. if (n_entries == MAX_EXITPOLICY_SUMMARY_LEN) {
  1225. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Impossibly long policy summary %s",
  1226. escaped(orig_summary));
  1227. return NULL;
  1228. }
  1229. if (! TOR_ISDIGIT(*summary) || len > (sizeof(ent_buf)-1)) {
  1230. /* unrecognized entry format. skip it. */
  1231. continue;
  1232. }
  1233. if (len < 1) {
  1234. /* empty; skip it. */
  1235. /* XXX This happens to be unreachable, since if len==0, then *summary is
  1236. * ',' or '\0', and the TOR_ISDIGIT test above would have failed. */
  1237. continue;
  1238. }
  1239. memcpy(ent_buf, summary, len);
  1240. ent_buf[len] = '\0';
  1241. if (tor_sscanf(ent_buf, "%u-%u%c", &low, &high, &dummy) == 2) {
  1242. if (low<1 || low>65535 || high<1 || high>65535 || low>high) {
  1243. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  1244. "Found bad entry in policy summary %s", escaped(orig_summary));
  1245. return NULL;
  1246. }
  1247. } else if (tor_sscanf(ent_buf, "%u%c", &low, &dummy) == 1) {
  1248. if (low<1 || low>65535) {
  1249. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  1250. "Found bad entry in policy summary %s", escaped(orig_summary));
  1251. return NULL;
  1252. }
  1253. high = low;
  1254. } else {
  1255. log_fn(LOG_PROTOCOL_WARN, LD_DIR,"Found bad entry in policy summary %s",
  1256. escaped(orig_summary));
  1257. return NULL;
  1258. }
  1259. entries[n_entries].min_port = low;
  1260. entries[n_entries].max_port = high;
  1261. n_entries++;
  1262. }
  1263. if (n_entries == 0) {
  1264. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  1265. "Found no port-range entries in summary %s", escaped(orig_summary));
  1266. return NULL;
  1267. }
  1268. {
  1269. size_t size = STRUCT_OFFSET(short_policy_t, entries) +
  1270. sizeof(short_policy_entry_t)*(n_entries);
  1271. result = tor_malloc_zero(size);
  1272. tor_assert( (char*)&result->entries[n_entries-1] < ((char*)result)+size);
  1273. }
  1274. result->is_accept = is_accept;
  1275. result->n_entries = n_entries;
  1276. memcpy(result->entries, entries, sizeof(short_policy_entry_t)*n_entries);
  1277. return result;
  1278. }
  1279. /** Write <b>policy</b> back out into a string. Used only for unit tests
  1280. * currently. */
  1281. char *
  1282. write_short_policy(const short_policy_t *policy)
  1283. {
  1284. int i;
  1285. char *answer;
  1286. smartlist_t *sl = smartlist_new();
  1287. smartlist_add_asprintf(sl, "%s", policy->is_accept ? "accept " : "reject ");
  1288. for (i=0; i < policy->n_entries; i++) {
  1289. const short_policy_entry_t *e = &policy->entries[i];
  1290. if (e->min_port == e->max_port) {
  1291. smartlist_add_asprintf(sl, "%d", e->min_port);
  1292. } else {
  1293. smartlist_add_asprintf(sl, "%d-%d", e->min_port, e->max_port);
  1294. }
  1295. if (i < policy->n_entries-1)
  1296. smartlist_add(sl, tor_strdup(","));
  1297. }
  1298. answer = smartlist_join_strings(sl, "", 0, NULL);
  1299. SMARTLIST_FOREACH(sl, char *, a, tor_free(a));
  1300. smartlist_free(sl);
  1301. return answer;
  1302. }
  1303. /** Release all storage held in <b>policy</b>. */
  1304. void
  1305. short_policy_free(short_policy_t *policy)
  1306. {
  1307. tor_free(policy);
  1308. }
  1309. /** See whether the <b>addr</b>:<b>port</b> address is likely to be accepted
  1310. * or rejected by the summarized policy <b>policy</b>. Return values are as
  1311. * for compare_tor_addr_to_addr_policy. Unlike the regular addr_policy
  1312. * functions, requires the <b>port</b> be specified. */
  1313. addr_policy_result_t
  1314. compare_tor_addr_to_short_policy(const tor_addr_t *addr, uint16_t port,
  1315. const short_policy_t *policy)
  1316. {
  1317. int i;
  1318. int found_match = 0;
  1319. int accept;
  1320. tor_assert(port != 0);
  1321. if (addr && tor_addr_is_null(addr))
  1322. addr = NULL; /* Unspec means 'no address at all,' in this context. */
  1323. if (addr && get_options()->ClientRejectInternalAddresses &&
  1324. (tor_addr_is_internal(addr, 0) || tor_addr_is_loopback(addr)))
  1325. return ADDR_POLICY_REJECTED;
  1326. for (i=0; i < policy->n_entries; ++i) {
  1327. const short_policy_entry_t *e = &policy->entries[i];
  1328. if (e->min_port <= port && port <= e->max_port) {
  1329. found_match = 1;
  1330. break;
  1331. }
  1332. }
  1333. if (found_match)
  1334. accept = policy->is_accept;
  1335. else
  1336. accept = ! policy->is_accept;
  1337. /* ???? are these right? -NM */
  1338. /* We should be sure not to return ADDR_POLICY_ACCEPTED in the accept
  1339. * case here, because it would cause clients to believe that the node
  1340. * allows exit enclaving. Trying it anyway would open up a cool attack
  1341. * where the node refuses due to exitpolicy, the client reacts in
  1342. * surprise by rewriting the node's exitpolicy to reject *:*, and then
  1343. * a bad guy targets users by causing them to attempt such connections
  1344. * to 98% of the exits.
  1345. *
  1346. * Once microdescriptors can handle addresses in special cases (e.g. if
  1347. * we ever solve ticket 1774), we can provide certainty here. -RD */
  1348. if (accept)
  1349. return ADDR_POLICY_PROBABLY_ACCEPTED;
  1350. else
  1351. return ADDR_POLICY_REJECTED;
  1352. }
  1353. /** Return true iff <b>policy</b> seems reject all ports */
  1354. int
  1355. short_policy_is_reject_star(const short_policy_t *policy)
  1356. {
  1357. /* This doesn't need to be as much on the lookout as policy_is_reject_star,
  1358. * since policy summaries are from the consensus or from consensus
  1359. * microdescs.
  1360. */
  1361. tor_assert(policy);
  1362. /* Check for an exact match of "reject 1-65535". */
  1363. return (policy->is_accept == 0 && policy->n_entries == 1 &&
  1364. policy->entries[0].min_port == 1 &&
  1365. policy->entries[0].max_port == 65535);
  1366. }
  1367. /** Decides whether addr:port is probably or definitely accepted or rejected by
  1368. * <b>node</b>. See compare_tor_addr_to_addr_policy for details on addr/port
  1369. * interpretation. */
  1370. addr_policy_result_t
  1371. compare_tor_addr_to_node_policy(const tor_addr_t *addr, uint16_t port,
  1372. const node_t *node)
  1373. {
  1374. if (node->rejects_all)
  1375. return ADDR_POLICY_REJECTED;
  1376. if (node->ri)
  1377. return compare_tor_addr_to_addr_policy(addr, port, node->ri->exit_policy);
  1378. else if (node->md) {
  1379. if (node->md->exit_policy == NULL)
  1380. return ADDR_POLICY_REJECTED;
  1381. else
  1382. return compare_tor_addr_to_short_policy(addr, port,
  1383. node->md->exit_policy);
  1384. } else
  1385. return ADDR_POLICY_PROBABLY_REJECTED;
  1386. }
  1387. /** Implementation for GETINFO control command: knows the answer for questions
  1388. * about "exit-policy/..." */
  1389. int
  1390. getinfo_helper_policies(control_connection_t *conn,
  1391. const char *question, char **answer,
  1392. const char **errmsg)
  1393. {
  1394. (void) conn;
  1395. (void) errmsg;
  1396. if (!strcmp(question, "exit-policy/default")) {
  1397. *answer = tor_strdup(DEFAULT_EXIT_POLICY);
  1398. }
  1399. return 0;
  1400. }
  1401. /** Release all storage held by <b>p</b>. */
  1402. void
  1403. addr_policy_list_free(smartlist_t *lst)
  1404. {
  1405. if (!lst)
  1406. return;
  1407. SMARTLIST_FOREACH(lst, addr_policy_t *, policy, addr_policy_free(policy));
  1408. smartlist_free(lst);
  1409. }
  1410. /** Release all storage held by <b>p</b>. */
  1411. void
  1412. addr_policy_free(addr_policy_t *p)
  1413. {
  1414. if (!p)
  1415. return;
  1416. if (--p->refcnt <= 0) {
  1417. if (p->is_canonical) {
  1418. policy_map_ent_t search, *found;
  1419. search.policy = p;
  1420. found = HT_REMOVE(policy_map, &policy_root, &search);
  1421. if (found) {
  1422. tor_assert(p == found->policy);
  1423. tor_free(found);
  1424. }
  1425. }
  1426. tor_free(p);
  1427. }
  1428. }
  1429. /** Release all storage held by policy variables. */
  1430. void
  1431. policies_free_all(void)
  1432. {
  1433. addr_policy_list_free(reachable_or_addr_policy);
  1434. reachable_or_addr_policy = NULL;
  1435. addr_policy_list_free(reachable_dir_addr_policy);
  1436. reachable_dir_addr_policy = NULL;
  1437. addr_policy_list_free(socks_policy);
  1438. socks_policy = NULL;
  1439. addr_policy_list_free(dir_policy);
  1440. dir_policy = NULL;
  1441. addr_policy_list_free(authdir_reject_policy);
  1442. authdir_reject_policy = NULL;
  1443. addr_policy_list_free(authdir_invalid_policy);
  1444. authdir_invalid_policy = NULL;
  1445. addr_policy_list_free(authdir_baddir_policy);
  1446. authdir_baddir_policy = NULL;
  1447. addr_policy_list_free(authdir_badexit_policy);
  1448. authdir_badexit_policy = NULL;
  1449. if (!HT_EMPTY(&policy_root)) {
  1450. policy_map_ent_t **ent;
  1451. int n = 0;
  1452. char buf[POLICY_BUF_LEN];
  1453. log_warn(LD_MM, "Still had %d address policies cached at shutdown.",
  1454. (int)HT_SIZE(&policy_root));
  1455. /* Note the first 10 cached policies to try to figure out where they
  1456. * might be coming from. */
  1457. HT_FOREACH(ent, policy_map, &policy_root) {
  1458. if (++n > 10)
  1459. break;
  1460. if (policy_write_item(buf, sizeof(buf), (*ent)->policy, 0) >= 0)
  1461. log_warn(LD_MM," %d [%d]: %s", n, (*ent)->policy->refcnt, buf);
  1462. }
  1463. }
  1464. HT_CLEAR(policy_map, &policy_root);
  1465. }