policies.c 55 KB

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