policies.c 50 KB

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