policies.c 50 KB

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