policies.c 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2015, 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. #define POLICIES_PRIVATE
  10. #include "or.h"
  11. #include "config.h"
  12. #include "dirserv.h"
  13. #include "nodelist.h"
  14. #include "policies.h"
  15. #include "router.h"
  16. #include "routerparse.h"
  17. #include "geoip.h"
  18. #include "ht.h"
  19. /** Policy that addresses for incoming SOCKS connections must match. */
  20. static smartlist_t *socks_policy = NULL;
  21. /** Policy that addresses for incoming directory connections must match. */
  22. static smartlist_t *dir_policy = NULL;
  23. /** Policy that addresses for incoming router descriptors must match in order
  24. * to be published by us. */
  25. static smartlist_t *authdir_reject_policy = NULL;
  26. /** Policy that addresses for incoming router descriptors must match in order
  27. * to be marked as valid in our networkstatus. */
  28. static smartlist_t *authdir_invalid_policy = NULL;
  29. /** Policy that addresses for incoming router descriptors must <b>not</b>
  30. * match in order to not be marked as BadExit. */
  31. static smartlist_t *authdir_badexit_policy = NULL;
  32. /** Parsed addr_policy_t describing which addresses we believe we can start
  33. * circuits at. */
  34. static smartlist_t *reachable_or_addr_policy = NULL;
  35. /** Parsed addr_policy_t describing which addresses we believe we can connect
  36. * to directories at. */
  37. static smartlist_t *reachable_dir_addr_policy = NULL;
  38. /** Element of an exit policy summary */
  39. typedef struct policy_summary_item_t {
  40. uint16_t prt_min; /**< Lowest port number to accept/reject. */
  41. uint16_t prt_max; /**< Highest port number to accept/reject. */
  42. uint64_t reject_count; /**< Number of IP-Addresses that are rejected to
  43. this port range. */
  44. unsigned int accepted:1; /** Has this port already been accepted */
  45. } policy_summary_item_t;
  46. /** Private networks. This list is used in two places, once to expand the
  47. * "private" keyword when parsing our own exit policy, secondly to ignore
  48. * just such networks when building exit policy summaries. It is important
  49. * that all authorities agree on that list when creating summaries, so don't
  50. * just change this without a proper migration plan and a proposal and stuff.
  51. */
  52. static const char *private_nets[] = {
  53. "0.0.0.0/8", "169.254.0.0/16",
  54. "127.0.0.0/8", "192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12",
  55. "[::]/8",
  56. "[fc00::]/7", "[fe80::]/10", "[fec0::]/10", "[ff00::]/8", "[::]/127",
  57. NULL
  58. };
  59. static int policies_parse_exit_policy_internal(
  60. config_line_t *cfg,
  61. smartlist_t **dest,
  62. int ipv6_exit,
  63. int rejectprivate,
  64. const smartlist_t *configured_addresses,
  65. int reject_interface_addresses,
  66. int reject_configured_port_addresses,
  67. int add_default_policy);
  68. /** Replace all "private" entries in *<b>policy</b> with their expanded
  69. * equivalents. */
  70. void
  71. policy_expand_private(smartlist_t **policy)
  72. {
  73. uint16_t port_min, port_max;
  74. int i;
  75. smartlist_t *tmp;
  76. if (!*policy) /*XXXX disallow NULL policies? */
  77. return;
  78. tmp = smartlist_new();
  79. SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, p) {
  80. if (! p->is_private) {
  81. smartlist_add(tmp, p);
  82. continue;
  83. }
  84. for (i = 0; private_nets[i]; ++i) {
  85. addr_policy_t newpolicy;
  86. memcpy(&newpolicy, p, sizeof(addr_policy_t));
  87. newpolicy.is_private = 0;
  88. newpolicy.is_canonical = 0;
  89. if (tor_addr_parse_mask_ports(private_nets[i], 0,
  90. &newpolicy.addr,
  91. &newpolicy.maskbits, &port_min, &port_max)<0) {
  92. tor_assert(0);
  93. }
  94. smartlist_add(tmp, addr_policy_get_canonical_entry(&newpolicy));
  95. }
  96. addr_policy_free(p);
  97. } SMARTLIST_FOREACH_END(p);
  98. smartlist_free(*policy);
  99. *policy = tmp;
  100. }
  101. /** Expand each of the AF_UNSPEC elements in *<b>policy</b> (which indicate
  102. * protocol-neutral wildcards) into a pair of wildcard elements: one IPv4-
  103. * specific and one IPv6-specific. */
  104. void
  105. policy_expand_unspec(smartlist_t **policy)
  106. {
  107. smartlist_t *tmp;
  108. if (!*policy)
  109. return;
  110. tmp = smartlist_new();
  111. SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, p) {
  112. sa_family_t family = tor_addr_family(&p->addr);
  113. if (family == AF_INET6 || family == AF_INET || p->is_private) {
  114. smartlist_add(tmp, p);
  115. } else if (family == AF_UNSPEC) {
  116. addr_policy_t newpolicy_ipv4;
  117. addr_policy_t newpolicy_ipv6;
  118. memcpy(&newpolicy_ipv4, p, sizeof(addr_policy_t));
  119. memcpy(&newpolicy_ipv6, p, sizeof(addr_policy_t));
  120. newpolicy_ipv4.is_canonical = 0;
  121. newpolicy_ipv6.is_canonical = 0;
  122. if (p->maskbits != 0) {
  123. log_warn(LD_BUG, "AF_UNSPEC policy with maskbits==%d", p->maskbits);
  124. newpolicy_ipv4.maskbits = 0;
  125. newpolicy_ipv6.maskbits = 0;
  126. }
  127. tor_addr_from_ipv4h(&newpolicy_ipv4.addr, 0);
  128. tor_addr_from_ipv6_bytes(&newpolicy_ipv6.addr,
  129. "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
  130. smartlist_add(tmp, addr_policy_get_canonical_entry(&newpolicy_ipv4));
  131. smartlist_add(tmp, addr_policy_get_canonical_entry(&newpolicy_ipv6));
  132. addr_policy_free(p);
  133. } else {
  134. log_warn(LD_BUG, "Funny-looking address policy with family %d", family);
  135. smartlist_add(tmp, p);
  136. }
  137. } SMARTLIST_FOREACH_END(p);
  138. smartlist_free(*policy);
  139. *policy = tmp;
  140. }
  141. /**
  142. * Given a linked list of config lines containing "accept[6]" and "reject[6]"
  143. * tokens, parse them and append the result to <b>dest</b>. Return -1
  144. * if any tokens are malformed (and don't append any), else return 0.
  145. *
  146. * If <b>assume_action</b> is nonnegative, then insert its action
  147. * (ADDR_POLICY_ACCEPT or ADDR_POLICY_REJECT) for items that specify no
  148. * action.
  149. */
  150. static int
  151. parse_addr_policy(config_line_t *cfg, smartlist_t **dest,
  152. int assume_action)
  153. {
  154. smartlist_t *result;
  155. smartlist_t *entries;
  156. addr_policy_t *item;
  157. int malformed_list;
  158. int r = 0;
  159. if (!cfg)
  160. return 0;
  161. result = smartlist_new();
  162. entries = smartlist_new();
  163. for (; cfg; cfg = cfg->next) {
  164. smartlist_split_string(entries, cfg->value, ",",
  165. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  166. SMARTLIST_FOREACH_BEGIN(entries, const char *, ent) {
  167. log_debug(LD_CONFIG,"Adding new entry '%s'",ent);
  168. malformed_list = 0;
  169. item = router_parse_addr_policy_item_from_string(ent, assume_action,
  170. &malformed_list);
  171. if (item) {
  172. smartlist_add(result, item);
  173. } else if (malformed_list) {
  174. /* the error is so severe the entire list should be discarded */
  175. log_warn(LD_CONFIG, "Malformed policy '%s'. Discarding entire policy "
  176. "list.", ent);
  177. r = -1;
  178. } else {
  179. /* the error is minor: don't add the item, but keep processing the
  180. * rest of the policies in the list */
  181. log_debug(LD_CONFIG, "Ignored policy '%s' due to non-fatal error. "
  182. "The remainder of the policy list will be used.",
  183. ent);
  184. }
  185. } SMARTLIST_FOREACH_END(ent);
  186. SMARTLIST_FOREACH(entries, char *, ent, tor_free(ent));
  187. smartlist_clear(entries);
  188. }
  189. smartlist_free(entries);
  190. if (r == -1) {
  191. addr_policy_list_free(result);
  192. } else {
  193. policy_expand_private(&result);
  194. policy_expand_unspec(&result);
  195. if (*dest) {
  196. smartlist_add_all(*dest, result);
  197. smartlist_free(result);
  198. } else {
  199. *dest = result;
  200. }
  201. }
  202. return r;
  203. }
  204. /** Helper: parse the Reachable(Dir|OR)?Addresses fields into
  205. * reachable_(or|dir)_addr_policy. The options should already have
  206. * been validated by validate_addr_policies.
  207. */
  208. static int
  209. parse_reachable_addresses(void)
  210. {
  211. const or_options_t *options = get_options();
  212. int ret = 0;
  213. if (options->ReachableDirAddresses &&
  214. options->ReachableORAddresses &&
  215. options->ReachableAddresses) {
  216. log_warn(LD_CONFIG,
  217. "Both ReachableDirAddresses and ReachableORAddresses are set. "
  218. "ReachableAddresses setting will be ignored.");
  219. }
  220. addr_policy_list_free(reachable_or_addr_policy);
  221. reachable_or_addr_policy = NULL;
  222. if (!options->ReachableORAddresses && options->ReachableAddresses)
  223. log_info(LD_CONFIG,
  224. "Using ReachableAddresses as ReachableORAddresses.");
  225. if (parse_addr_policy(options->ReachableORAddresses ?
  226. options->ReachableORAddresses :
  227. options->ReachableAddresses,
  228. &reachable_or_addr_policy, ADDR_POLICY_ACCEPT)) {
  229. log_warn(LD_CONFIG,
  230. "Error parsing Reachable%sAddresses entry; ignoring.",
  231. options->ReachableORAddresses ? "OR" : "");
  232. ret = -1;
  233. }
  234. addr_policy_list_free(reachable_dir_addr_policy);
  235. reachable_dir_addr_policy = NULL;
  236. if (!options->ReachableDirAddresses && options->ReachableAddresses)
  237. log_info(LD_CONFIG,
  238. "Using ReachableAddresses as ReachableDirAddresses");
  239. if (parse_addr_policy(options->ReachableDirAddresses ?
  240. options->ReachableDirAddresses :
  241. options->ReachableAddresses,
  242. &reachable_dir_addr_policy, ADDR_POLICY_ACCEPT)) {
  243. if (options->ReachableDirAddresses)
  244. log_warn(LD_CONFIG,
  245. "Error parsing ReachableDirAddresses entry; ignoring.");
  246. ret = -1;
  247. }
  248. return ret;
  249. }
  250. /** Return true iff the firewall options might block any address:port
  251. * combination.
  252. */
  253. int
  254. firewall_is_fascist_or(void)
  255. {
  256. return reachable_or_addr_policy != NULL;
  257. }
  258. /** Return true iff <b>policy</b> (possibly NULL) will allow a
  259. * connection to <b>addr</b>:<b>port</b>.
  260. */
  261. static int
  262. addr_policy_permits_tor_addr(const tor_addr_t *addr, uint16_t port,
  263. smartlist_t *policy)
  264. {
  265. addr_policy_result_t p;
  266. p = compare_tor_addr_to_addr_policy(addr, port, policy);
  267. switch (p) {
  268. case ADDR_POLICY_PROBABLY_ACCEPTED:
  269. case ADDR_POLICY_ACCEPTED:
  270. return 1;
  271. case ADDR_POLICY_PROBABLY_REJECTED:
  272. case ADDR_POLICY_REJECTED:
  273. return 0;
  274. default:
  275. log_warn(LD_BUG, "Unexpected result: %d", (int)p);
  276. return 0;
  277. }
  278. }
  279. /** Return true iff <b> policy</b> (possibly NULL) will allow a connection to
  280. * <b>addr</b>:<b>port</b>. <b>addr</b> is an IPv4 address given in host
  281. * order. */
  282. /* XXXX deprecate when possible. */
  283. static int
  284. addr_policy_permits_address(uint32_t addr, uint16_t port,
  285. smartlist_t *policy)
  286. {
  287. tor_addr_t a;
  288. tor_addr_from_ipv4h(&a, addr);
  289. return addr_policy_permits_tor_addr(&a, port, policy);
  290. }
  291. /** Return true iff we think our firewall will let us make an OR connection to
  292. * addr:port. */
  293. int
  294. fascist_firewall_allows_address_or(const tor_addr_t *addr, uint16_t port)
  295. {
  296. return addr_policy_permits_tor_addr(addr, port,
  297. reachable_or_addr_policy);
  298. }
  299. /** Return true iff we think our firewall will let us make an OR connection to
  300. * <b>ri</b>. */
  301. int
  302. fascist_firewall_allows_or(const routerinfo_t *ri)
  303. {
  304. /* XXXX proposal 118 */
  305. tor_addr_t addr;
  306. tor_addr_from_ipv4h(&addr, ri->addr);
  307. return fascist_firewall_allows_address_or(&addr, ri->or_port);
  308. }
  309. /** Return true iff we think our firewall will let us make an OR connection to
  310. * <b>node</b>. */
  311. int
  312. fascist_firewall_allows_node(const node_t *node)
  313. {
  314. if (node->ri) {
  315. return fascist_firewall_allows_or(node->ri);
  316. } else if (node->rs) {
  317. tor_addr_t addr;
  318. tor_addr_from_ipv4h(&addr, node->rs->addr);
  319. return fascist_firewall_allows_address_or(&addr, node->rs->or_port);
  320. } else {
  321. return 1;
  322. }
  323. }
  324. /** Return true iff we think our firewall will let us make a directory
  325. * connection to addr:port. */
  326. int
  327. fascist_firewall_allows_address_dir(const tor_addr_t *addr, uint16_t port)
  328. {
  329. return addr_policy_permits_tor_addr(addr, port,
  330. reachable_dir_addr_policy);
  331. }
  332. /** Return 1 if <b>addr</b> is permitted to connect to our dir port,
  333. * based on <b>dir_policy</b>. Else return 0.
  334. */
  335. int
  336. dir_policy_permits_address(const tor_addr_t *addr)
  337. {
  338. return addr_policy_permits_tor_addr(addr, 1, dir_policy);
  339. }
  340. /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
  341. * based on <b>socks_policy</b>. Else return 0.
  342. */
  343. int
  344. socks_policy_permits_address(const tor_addr_t *addr)
  345. {
  346. return addr_policy_permits_tor_addr(addr, 1, socks_policy);
  347. }
  348. /** Return true iff the address <b>addr</b> is in a country listed in the
  349. * case-insensitive list of country codes <b>cc_list</b>. */
  350. static int
  351. addr_is_in_cc_list(uint32_t addr, const smartlist_t *cc_list)
  352. {
  353. country_t country;
  354. const char *name;
  355. tor_addr_t tar;
  356. if (!cc_list)
  357. return 0;
  358. /* XXXXipv6 */
  359. tor_addr_from_ipv4h(&tar, addr);
  360. country = geoip_get_country_by_addr(&tar);
  361. name = geoip_get_country_name(country);
  362. return smartlist_contains_string_case(cc_list, name);
  363. }
  364. /** Return 1 if <b>addr</b>:<b>port</b> is permitted to publish to our
  365. * directory, based on <b>authdir_reject_policy</b>. Else return 0.
  366. */
  367. int
  368. authdir_policy_permits_address(uint32_t addr, uint16_t port)
  369. {
  370. if (! addr_policy_permits_address(addr, port, authdir_reject_policy))
  371. return 0;
  372. return !addr_is_in_cc_list(addr, get_options()->AuthDirRejectCCs);
  373. }
  374. /** Return 1 if <b>addr</b>:<b>port</b> is considered valid in our
  375. * directory, based on <b>authdir_invalid_policy</b>. Else return 0.
  376. */
  377. int
  378. authdir_policy_valid_address(uint32_t addr, uint16_t port)
  379. {
  380. if (! addr_policy_permits_address(addr, port, authdir_invalid_policy))
  381. return 0;
  382. return !addr_is_in_cc_list(addr, get_options()->AuthDirInvalidCCs);
  383. }
  384. /** Return 1 if <b>addr</b>:<b>port</b> should be marked as a bad exit,
  385. * based on <b>authdir_badexit_policy</b>. Else return 0.
  386. */
  387. int
  388. authdir_policy_badexit_address(uint32_t addr, uint16_t port)
  389. {
  390. if (! addr_policy_permits_address(addr, port, authdir_badexit_policy))
  391. return 1;
  392. return addr_is_in_cc_list(addr, get_options()->AuthDirBadExitCCs);
  393. }
  394. #define REJECT(arg) \
  395. STMT_BEGIN *msg = tor_strdup(arg); goto err; STMT_END
  396. /** Config helper: If there's any problem with the policy configuration
  397. * options in <b>options</b>, return -1 and set <b>msg</b> to a newly
  398. * allocated description of the error. Else return 0. */
  399. int
  400. validate_addr_policies(const or_options_t *options, char **msg)
  401. {
  402. /* XXXX Maybe merge this into parse_policies_from_options, to make sure
  403. * that the two can't go out of sync. */
  404. smartlist_t *addr_policy=NULL;
  405. *msg = NULL;
  406. if (policies_parse_exit_policy_from_options(options,0,NULL,&addr_policy)) {
  407. REJECT("Error in ExitPolicy entry.");
  408. }
  409. static int warned_about_exitrelay = 0;
  410. const int exitrelay_setting_is_auto = options->ExitRelay == -1;
  411. const int policy_accepts_something =
  412. ! (policy_is_reject_star(addr_policy, AF_INET) &&
  413. policy_is_reject_star(addr_policy, AF_INET6));
  414. if (server_mode(options) &&
  415. ! warned_about_exitrelay &&
  416. exitrelay_setting_is_auto &&
  417. policy_accepts_something) {
  418. /* Policy accepts something */
  419. warned_about_exitrelay = 1;
  420. log_warn(LD_CONFIG,
  421. "Tor is running as an exit relay%s. If you did not want this "
  422. "behavior, please set the ExitRelay option to 0. If you do "
  423. "want to run an exit Relay, please set the ExitRelay option "
  424. "to 1 to disable this warning, and for forward compatibility.",
  425. options->ExitPolicy == NULL ?
  426. " with the default exit policy" : "");
  427. if (options->ExitPolicy == NULL) {
  428. log_warn(LD_CONFIG,
  429. "In a future version of Tor, ExitRelay 0 may become the "
  430. "default when no ExitPolicy is given.");
  431. }
  432. }
  433. /* The rest of these calls *append* to addr_policy. So don't actually
  434. * use the results for anything other than checking if they parse! */
  435. if (parse_addr_policy(options->DirPolicy, &addr_policy, -1))
  436. REJECT("Error in DirPolicy entry.");
  437. if (parse_addr_policy(options->SocksPolicy, &addr_policy, -1))
  438. REJECT("Error in SocksPolicy entry.");
  439. if (parse_addr_policy(options->AuthDirReject, &addr_policy,
  440. ADDR_POLICY_REJECT))
  441. REJECT("Error in AuthDirReject entry.");
  442. if (parse_addr_policy(options->AuthDirInvalid, &addr_policy,
  443. ADDR_POLICY_REJECT))
  444. REJECT("Error in AuthDirInvalid entry.");
  445. if (parse_addr_policy(options->AuthDirBadExit, &addr_policy,
  446. ADDR_POLICY_REJECT))
  447. REJECT("Error in AuthDirBadExit entry.");
  448. if (parse_addr_policy(options->ReachableAddresses, &addr_policy,
  449. ADDR_POLICY_ACCEPT))
  450. REJECT("Error in ReachableAddresses entry.");
  451. if (parse_addr_policy(options->ReachableORAddresses, &addr_policy,
  452. ADDR_POLICY_ACCEPT))
  453. REJECT("Error in ReachableORAddresses entry.");
  454. if (parse_addr_policy(options->ReachableDirAddresses, &addr_policy,
  455. ADDR_POLICY_ACCEPT))
  456. REJECT("Error in ReachableDirAddresses entry.");
  457. err:
  458. addr_policy_list_free(addr_policy);
  459. return *msg ? -1 : 0;
  460. #undef REJECT
  461. }
  462. /** Parse <b>string</b> in the same way that the exit policy
  463. * is parsed, and put the processed version in *<b>policy</b>.
  464. * Ignore port specifiers.
  465. */
  466. static int
  467. load_policy_from_option(config_line_t *config, const char *option_name,
  468. smartlist_t **policy,
  469. int assume_action)
  470. {
  471. int r;
  472. int killed_any_ports = 0;
  473. addr_policy_list_free(*policy);
  474. *policy = NULL;
  475. r = parse_addr_policy(config, policy, assume_action);
  476. if (r < 0) {
  477. return -1;
  478. }
  479. if (*policy) {
  480. SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, n) {
  481. /* ports aren't used in these. */
  482. if (n->prt_min > 1 || n->prt_max != 65535) {
  483. addr_policy_t newp, *c;
  484. memcpy(&newp, n, sizeof(newp));
  485. newp.prt_min = 1;
  486. newp.prt_max = 65535;
  487. newp.is_canonical = 0;
  488. c = addr_policy_get_canonical_entry(&newp);
  489. SMARTLIST_REPLACE_CURRENT(*policy, n, c);
  490. addr_policy_free(n);
  491. killed_any_ports = 1;
  492. }
  493. } SMARTLIST_FOREACH_END(n);
  494. }
  495. if (killed_any_ports) {
  496. log_warn(LD_CONFIG, "Ignoring ports in %s option.", option_name);
  497. }
  498. return 0;
  499. }
  500. /** Set all policies based on <b>options</b>, which should have been validated
  501. * first by validate_addr_policies. */
  502. int
  503. policies_parse_from_options(const or_options_t *options)
  504. {
  505. int ret = 0;
  506. if (load_policy_from_option(options->SocksPolicy, "SocksPolicy",
  507. &socks_policy, -1) < 0)
  508. ret = -1;
  509. if (load_policy_from_option(options->DirPolicy, "DirPolicy",
  510. &dir_policy, -1) < 0)
  511. ret = -1;
  512. if (load_policy_from_option(options->AuthDirReject, "AuthDirReject",
  513. &authdir_reject_policy, ADDR_POLICY_REJECT) < 0)
  514. ret = -1;
  515. if (load_policy_from_option(options->AuthDirInvalid, "AuthDirInvalid",
  516. &authdir_invalid_policy, ADDR_POLICY_REJECT) < 0)
  517. ret = -1;
  518. if (load_policy_from_option(options->AuthDirBadExit, "AuthDirBadExit",
  519. &authdir_badexit_policy, ADDR_POLICY_REJECT) < 0)
  520. ret = -1;
  521. if (parse_reachable_addresses() < 0)
  522. ret = -1;
  523. return ret;
  524. }
  525. /** Compare two provided address policy items, and return -1, 0, or 1
  526. * if the first is less than, equal to, or greater than the second. */
  527. static int
  528. cmp_single_addr_policy(addr_policy_t *a, addr_policy_t *b)
  529. {
  530. int r;
  531. if ((r=((int)a->policy_type - (int)b->policy_type)))
  532. return r;
  533. if ((r=((int)a->is_private - (int)b->is_private)))
  534. return r;
  535. /* refcnt and is_canonical are irrelevant to equality,
  536. * they are hash table implementation details */
  537. if ((r=tor_addr_compare(&a->addr, &b->addr, CMP_EXACT)))
  538. return r;
  539. if ((r=((int)a->maskbits - (int)b->maskbits)))
  540. return r;
  541. if ((r=((int)a->prt_min - (int)b->prt_min)))
  542. return r;
  543. if ((r=((int)a->prt_max - (int)b->prt_max)))
  544. return r;
  545. return 0;
  546. }
  547. /** Like cmp_single_addr_policy() above, but looks at the
  548. * whole set of policies in each case. */
  549. int
  550. cmp_addr_policies(smartlist_t *a, smartlist_t *b)
  551. {
  552. int r, i;
  553. int len_a = a ? smartlist_len(a) : 0;
  554. int len_b = b ? smartlist_len(b) : 0;
  555. for (i = 0; i < len_a && i < len_b; ++i) {
  556. if ((r = cmp_single_addr_policy(smartlist_get(a, i), smartlist_get(b, i))))
  557. return r;
  558. }
  559. if (i == len_a && i == len_b)
  560. return 0;
  561. if (i < len_a)
  562. return -1;
  563. else
  564. return 1;
  565. }
  566. /** Node in hashtable used to store address policy entries. */
  567. typedef struct policy_map_ent_t {
  568. HT_ENTRY(policy_map_ent_t) node;
  569. addr_policy_t *policy;
  570. } policy_map_ent_t;
  571. /* DOCDOC policy_root */
  572. static HT_HEAD(policy_map, policy_map_ent_t) policy_root = HT_INITIALIZER();
  573. /** Return true iff a and b are equal. */
  574. static inline int
  575. policy_eq(policy_map_ent_t *a, policy_map_ent_t *b)
  576. {
  577. return cmp_single_addr_policy(a->policy, b->policy) == 0;
  578. }
  579. /** Return a hashcode for <b>ent</b> */
  580. static unsigned int
  581. policy_hash(const policy_map_ent_t *ent)
  582. {
  583. const addr_policy_t *a = ent->policy;
  584. addr_policy_t aa;
  585. memset(&aa, 0, sizeof(aa));
  586. aa.prt_min = a->prt_min;
  587. aa.prt_max = a->prt_max;
  588. aa.maskbits = a->maskbits;
  589. aa.policy_type = a->policy_type;
  590. aa.is_private = a->is_private;
  591. if (a->is_private) {
  592. aa.is_private = 1;
  593. } else {
  594. tor_addr_copy_tight(&aa.addr, &a->addr);
  595. }
  596. return (unsigned) siphash24g(&aa, sizeof(aa));
  597. }
  598. HT_PROTOTYPE(policy_map, policy_map_ent_t, node, policy_hash,
  599. policy_eq)
  600. HT_GENERATE2(policy_map, policy_map_ent_t, node, policy_hash,
  601. policy_eq, 0.6, tor_reallocarray_, tor_free_)
  602. /** Given a pointer to an addr_policy_t, return a copy of the pointer to the
  603. * "canonical" copy of that addr_policy_t; the canonical copy is a single
  604. * reference-counted object. */
  605. addr_policy_t *
  606. addr_policy_get_canonical_entry(addr_policy_t *e)
  607. {
  608. policy_map_ent_t search, *found;
  609. if (e->is_canonical)
  610. return e;
  611. search.policy = e;
  612. found = HT_FIND(policy_map, &policy_root, &search);
  613. if (!found) {
  614. found = tor_malloc_zero(sizeof(policy_map_ent_t));
  615. found->policy = tor_memdup(e, sizeof(addr_policy_t));
  616. found->policy->is_canonical = 1;
  617. found->policy->refcnt = 0;
  618. HT_INSERT(policy_map, &policy_root, found);
  619. }
  620. tor_assert(!cmp_single_addr_policy(found->policy, e));
  621. ++found->policy->refcnt;
  622. return found->policy;
  623. }
  624. /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
  625. * addr and port are both known. */
  626. static addr_policy_result_t
  627. compare_known_tor_addr_to_addr_policy(const tor_addr_t *addr, uint16_t port,
  628. const smartlist_t *policy)
  629. {
  630. /* We know the address and port, and we know the policy, so we can just
  631. * compute an exact match. */
  632. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
  633. /* Address is known */
  634. if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
  635. CMP_EXACT)) {
  636. if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
  637. /* Exact match for the policy */
  638. return tmpe->policy_type == ADDR_POLICY_ACCEPT ?
  639. ADDR_POLICY_ACCEPTED : ADDR_POLICY_REJECTED;
  640. }
  641. }
  642. } SMARTLIST_FOREACH_END(tmpe);
  643. /* accept all by default. */
  644. return ADDR_POLICY_ACCEPTED;
  645. }
  646. /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
  647. * addr is known but port is not. */
  648. static addr_policy_result_t
  649. compare_known_tor_addr_to_addr_policy_noport(const tor_addr_t *addr,
  650. const smartlist_t *policy)
  651. {
  652. /* We look to see if there's a definite match. If so, we return that
  653. match's value, unless there's an intervening possible match that says
  654. something different. */
  655. int maybe_accept = 0, maybe_reject = 0;
  656. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
  657. if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
  658. CMP_EXACT)) {
  659. if (tmpe->prt_min <= 1 && tmpe->prt_max >= 65535) {
  660. /* Definitely matches, since it covers all ports. */
  661. if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
  662. /* If we already hit a clause that might trigger a 'reject', than we
  663. * can't be sure of this certain 'accept'.*/
  664. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
  665. ADDR_POLICY_ACCEPTED;
  666. } else {
  667. return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
  668. ADDR_POLICY_REJECTED;
  669. }
  670. } else {
  671. /* Might match. */
  672. if (tmpe->policy_type == ADDR_POLICY_REJECT)
  673. maybe_reject = 1;
  674. else
  675. maybe_accept = 1;
  676. }
  677. }
  678. } SMARTLIST_FOREACH_END(tmpe);
  679. /* accept all by default. */
  680. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  681. }
  682. /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
  683. * port is known but address is not. */
  684. static addr_policy_result_t
  685. compare_unknown_tor_addr_to_addr_policy(uint16_t port,
  686. const smartlist_t *policy)
  687. {
  688. /* We look to see if there's a definite match. If so, we return that
  689. match's value, unless there's an intervening possible match that says
  690. something different. */
  691. int maybe_accept = 0, maybe_reject = 0;
  692. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
  693. if (tmpe->prt_min <= port && port <= tmpe->prt_max) {
  694. if (tmpe->maskbits == 0) {
  695. /* Definitely matches, since it covers all addresses. */
  696. if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
  697. /* If we already hit a clause that might trigger a 'reject', than we
  698. * can't be sure of this certain 'accept'.*/
  699. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
  700. ADDR_POLICY_ACCEPTED;
  701. } else {
  702. return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
  703. ADDR_POLICY_REJECTED;
  704. }
  705. } else {
  706. /* Might match. */
  707. if (tmpe->policy_type == ADDR_POLICY_REJECT)
  708. maybe_reject = 1;
  709. else
  710. maybe_accept = 1;
  711. }
  712. }
  713. } SMARTLIST_FOREACH_END(tmpe);
  714. /* accept all by default. */
  715. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  716. }
  717. /** Decide whether a given addr:port is definitely accepted,
  718. * definitely rejected, probably accepted, or probably rejected by a
  719. * given policy. If <b>addr</b> is 0, we don't know the IP of the
  720. * target address. If <b>port</b> is 0, we don't know the port of the
  721. * target address. (At least one of <b>addr</b> and <b>port</b> must be
  722. * provided. If you want to know whether a policy would definitely reject
  723. * an unknown address:port, use policy_is_reject_star().)
  724. *
  725. * We could do better by assuming that some ranges never match typical
  726. * addresses (127.0.0.1, and so on). But we'll try this for now.
  727. */
  728. MOCK_IMPL(addr_policy_result_t,
  729. compare_tor_addr_to_addr_policy,(const tor_addr_t *addr, uint16_t port,
  730. const smartlist_t *policy))
  731. {
  732. if (!policy) {
  733. /* no policy? accept all. */
  734. return ADDR_POLICY_ACCEPTED;
  735. } else if (addr == NULL || tor_addr_is_null(addr)) {
  736. if (port == 0) {
  737. log_info(LD_BUG, "Rejecting null address with 0 port (family %d)",
  738. addr ? tor_addr_family(addr) : -1);
  739. return ADDR_POLICY_REJECTED;
  740. }
  741. return compare_unknown_tor_addr_to_addr_policy(port, policy);
  742. } else if (port == 0) {
  743. return compare_known_tor_addr_to_addr_policy_noport(addr, policy);
  744. } else {
  745. return compare_known_tor_addr_to_addr_policy(addr, port, policy);
  746. }
  747. }
  748. /** Return true iff the address policy <b>a</b> covers every case that
  749. * would be covered by <b>b</b>, so that a,b is redundant. */
  750. static int
  751. addr_policy_covers(addr_policy_t *a, addr_policy_t *b)
  752. {
  753. if (tor_addr_family(&a->addr) != tor_addr_family(&b->addr)) {
  754. /* You can't cover a different family. */
  755. return 0;
  756. }
  757. /* We can ignore accept/reject, since "accept *:80, reject *:80" reduces
  758. * to "accept *:80". */
  759. if (a->maskbits > b->maskbits) {
  760. /* a has more fixed bits than b; it can't possibly cover b. */
  761. return 0;
  762. }
  763. if (tor_addr_compare_masked(&a->addr, &b->addr, a->maskbits, CMP_EXACT)) {
  764. /* There's a fixed bit in a that's set differently in b. */
  765. return 0;
  766. }
  767. return (a->prt_min <= b->prt_min && a->prt_max >= b->prt_max);
  768. }
  769. /** Return true iff the address policies <b>a</b> and <b>b</b> intersect,
  770. * that is, there exists an address/port that is covered by <b>a</b> that
  771. * is also covered by <b>b</b>.
  772. */
  773. static int
  774. addr_policy_intersects(addr_policy_t *a, addr_policy_t *b)
  775. {
  776. maskbits_t minbits;
  777. /* All the bits we care about are those that are set in both
  778. * netmasks. If they are equal in a and b's networkaddresses
  779. * then the networks intersect. If there is a difference,
  780. * then they do not. */
  781. if (a->maskbits < b->maskbits)
  782. minbits = a->maskbits;
  783. else
  784. minbits = b->maskbits;
  785. if (tor_addr_compare_masked(&a->addr, &b->addr, minbits, CMP_EXACT))
  786. return 0;
  787. if (a->prt_max < b->prt_min || b->prt_max < a->prt_min)
  788. return 0;
  789. return 1;
  790. }
  791. /** Add the exit policy described by <b>more</b> to <b>policy</b>.
  792. */
  793. STATIC void
  794. append_exit_policy_string(smartlist_t **policy, const char *more)
  795. {
  796. config_line_t tmp;
  797. tmp.key = NULL;
  798. tmp.value = (char*) more;
  799. tmp.next = NULL;
  800. if (parse_addr_policy(&tmp, policy, -1)<0) {
  801. log_warn(LD_BUG, "Unable to parse internally generated policy %s",more);
  802. }
  803. }
  804. /** Add "reject <b>addr</b>:*" to <b>dest</b>, creating the list as needed. */
  805. void
  806. addr_policy_append_reject_addr(smartlist_t **dest, const tor_addr_t *addr)
  807. {
  808. tor_assert(dest);
  809. tor_assert(addr);
  810. addr_policy_t p, *add;
  811. memset(&p, 0, sizeof(p));
  812. p.policy_type = ADDR_POLICY_REJECT;
  813. p.maskbits = tor_addr_family(addr) == AF_INET6 ? 128 : 32;
  814. tor_addr_copy(&p.addr, addr);
  815. p.prt_min = 1;
  816. p.prt_max = 65535;
  817. add = addr_policy_get_canonical_entry(&p);
  818. if (!*dest)
  819. *dest = smartlist_new();
  820. smartlist_add(*dest, add);
  821. log_debug(LD_CONFIG, "Adding a reject ExitPolicy 'reject %s:*'",
  822. fmt_addr(addr));
  823. }
  824. /* Is addr public for the purposes of rejection? */
  825. static int
  826. tor_addr_is_public_for_reject(const tor_addr_t *addr)
  827. {
  828. return (!tor_addr_is_null(addr) && !tor_addr_is_internal(addr, 0)
  829. && !tor_addr_is_multicast(addr));
  830. }
  831. /* Add "reject <b>addr</b>:*" to <b>dest</b>, creating the list as needed.
  832. * Filter the address, only adding an IPv4 reject rule if ipv4_rules
  833. * is true, and similarly for ipv6_rules. Check each address returns true for
  834. * tor_addr_is_public_for_reject before adding it.
  835. */
  836. static void
  837. addr_policy_append_reject_addr_filter(smartlist_t **dest,
  838. const tor_addr_t *addr,
  839. int ipv4_rules,
  840. int ipv6_rules)
  841. {
  842. tor_assert(dest);
  843. tor_assert(addr);
  844. /* Only reject IP addresses which are public */
  845. if (tor_addr_is_public_for_reject(addr)) {
  846. /* Reject IPv4 addresses and IPv6 addresses based on the filters */
  847. int is_ipv4 = tor_addr_is_v4(addr);
  848. if ((is_ipv4 && ipv4_rules) || (!is_ipv4 && ipv6_rules)) {
  849. addr_policy_append_reject_addr(dest, addr);
  850. }
  851. }
  852. }
  853. /** Add "reject addr:*" to <b>dest</b>, for each addr in addrs, creating the
  854. * list as needed. */
  855. void
  856. addr_policy_append_reject_addr_list(smartlist_t **dest,
  857. const smartlist_t *addrs)
  858. {
  859. tor_assert(dest);
  860. tor_assert(addrs);
  861. SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, addr) {
  862. addr_policy_append_reject_addr(dest, addr);
  863. } SMARTLIST_FOREACH_END(addr);
  864. }
  865. /** Add "reject addr:*" to <b>dest</b>, for each addr in addrs, creating the
  866. * list as needed. Filter using */
  867. static void
  868. addr_policy_append_reject_addr_list_filter(smartlist_t **dest,
  869. const smartlist_t *addrs,
  870. int ipv4_rules,
  871. int ipv6_rules)
  872. {
  873. tor_assert(dest);
  874. tor_assert(addrs);
  875. SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, addr) {
  876. addr_policy_append_reject_addr_filter(dest, addr, ipv4_rules, ipv6_rules);
  877. } SMARTLIST_FOREACH_END(addr);
  878. }
  879. /** Detect and excise "dead code" from the policy *<b>dest</b>. */
  880. static void
  881. exit_policy_remove_redundancies(smartlist_t *dest)
  882. {
  883. addr_policy_t *ap, *tmp;
  884. int i, j;
  885. /* Step one: kill every ipv4 thing after *4:*, every IPv6 thing after *6:*
  886. */
  887. {
  888. int kill_v4=0, kill_v6=0;
  889. for (i = 0; i < smartlist_len(dest); ++i) {
  890. sa_family_t family;
  891. ap = smartlist_get(dest, i);
  892. family = tor_addr_family(&ap->addr);
  893. if ((family == AF_INET && kill_v4) ||
  894. (family == AF_INET6 && kill_v6)) {
  895. smartlist_del_keeporder(dest, i--);
  896. addr_policy_free(ap);
  897. continue;
  898. }
  899. if (ap->maskbits == 0 && ap->prt_min <= 1 && ap->prt_max >= 65535) {
  900. /* This is a catch-all line -- later lines are unreachable. */
  901. if (family == AF_INET) {
  902. kill_v4 = 1;
  903. } else if (family == AF_INET6) {
  904. kill_v6 = 1;
  905. }
  906. }
  907. }
  908. }
  909. /* Step two: for every entry, see if there's a redundant entry
  910. * later on, and remove it. */
  911. for (i = 0; i < smartlist_len(dest)-1; ++i) {
  912. ap = smartlist_get(dest, i);
  913. for (j = i+1; j < smartlist_len(dest); ++j) {
  914. tmp = smartlist_get(dest, j);
  915. tor_assert(j > i);
  916. if (addr_policy_covers(ap, tmp)) {
  917. char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
  918. policy_write_item(p1, sizeof(p1), tmp, 0);
  919. policy_write_item(p2, sizeof(p2), ap, 0);
  920. log_debug(LD_CONFIG, "Removing exit policy %s (%d). It is made "
  921. "redundant by %s (%d).", p1, j, p2, i);
  922. smartlist_del_keeporder(dest, j--);
  923. addr_policy_free(tmp);
  924. }
  925. }
  926. }
  927. /* Step three: for every entry A, see if there's an entry B making this one
  928. * redundant later on. This is the case if A and B are of the same type
  929. * (accept/reject), A is a subset of B, and there is no other entry of
  930. * different type in between those two that intersects with A.
  931. *
  932. * Anybody want to double-check the logic here? XXX
  933. */
  934. for (i = 0; i < smartlist_len(dest)-1; ++i) {
  935. ap = smartlist_get(dest, i);
  936. for (j = i+1; j < smartlist_len(dest); ++j) {
  937. // tor_assert(j > i); // j starts out at i+1; j only increases; i only
  938. // // decreases.
  939. tmp = smartlist_get(dest, j);
  940. if (ap->policy_type != tmp->policy_type) {
  941. if (addr_policy_intersects(ap, tmp))
  942. break;
  943. } else { /* policy_types are equal. */
  944. if (addr_policy_covers(tmp, ap)) {
  945. char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
  946. policy_write_item(p1, sizeof(p1), ap, 0);
  947. policy_write_item(p2, sizeof(p2), tmp, 0);
  948. log_debug(LD_CONFIG, "Removing exit policy %s. It is already "
  949. "covered by %s.", p1, p2);
  950. smartlist_del_keeporder(dest, i--);
  951. addr_policy_free(ap);
  952. break;
  953. }
  954. }
  955. }
  956. }
  957. }
  958. /** Reject private helper for policies_parse_exit_policy_internal: rejects
  959. * publicly routable addresses on this exit relay.
  960. *
  961. * Add reject entries to the linked list *dest:
  962. * - if configured_addresses is non-NULL, add entries that reject each
  963. * tor_addr_t* in the list as a destination.
  964. * - if reject_interface_addresses is true, add entries that reject each
  965. * public IPv4 and IPv6 address of each interface on this machine.
  966. * - if reject_configured_port_addresses is true, add entries that reject
  967. * each IPv4 and IPv6 address configured for a port.
  968. *
  969. * IPv6 entries are only added if ipv6_exit is true. (All IPv6 addresses are
  970. * already blocked by policies_parse_exit_policy_internal if ipv6_exit is
  971. * false.)
  972. *
  973. * The list *dest is created as needed.
  974. */
  975. void
  976. policies_parse_exit_policy_reject_private(
  977. smartlist_t **dest,
  978. int ipv6_exit,
  979. const smartlist_t *configured_addresses,
  980. int reject_interface_addresses,
  981. int reject_configured_port_addresses)
  982. {
  983. tor_assert(dest);
  984. /* Reject configured addresses, if they are from public netblocks. */
  985. if (configured_addresses) {
  986. addr_policy_append_reject_addr_list_filter(dest, configured_addresses,
  987. 1, ipv6_exit);
  988. }
  989. /* Reject configured port addresses, if they are from public netblocks. */
  990. if (reject_configured_port_addresses) {
  991. const smartlist_t *port_addrs = get_configured_ports();
  992. SMARTLIST_FOREACH_BEGIN(port_addrs, port_cfg_t *, port) {
  993. /* Only reject port IP addresses, not port unix sockets */
  994. if (!port->is_unix_addr) {
  995. addr_policy_append_reject_addr_filter(dest, &port->addr, 1, ipv6_exit);
  996. }
  997. } SMARTLIST_FOREACH_END(port);
  998. }
  999. /* Reject local addresses from public netblocks on any interface. */
  1000. if (reject_interface_addresses) {
  1001. smartlist_t *public_addresses = NULL;
  1002. /* Reject public IPv4 addresses on any interface */
  1003. public_addresses = get_interface_address6_list(LOG_INFO, AF_INET, 0);
  1004. addr_policy_append_reject_addr_list_filter(dest, public_addresses, 1, 0);
  1005. free_interface_address6_list(public_addresses);
  1006. /* Don't look for IPv6 addresses if we're configured as IPv4-only */
  1007. if (ipv6_exit) {
  1008. /* Reject public IPv6 addresses on any interface */
  1009. public_addresses = get_interface_address6_list(LOG_INFO, AF_INET6, 0);
  1010. addr_policy_append_reject_addr_list_filter(dest, public_addresses, 0, 1);
  1011. free_interface_address6_list(public_addresses);
  1012. }
  1013. }
  1014. /* If addresses were added multiple times, remove all but one of them. */
  1015. if (*dest) {
  1016. exit_policy_remove_redundancies(*dest);
  1017. }
  1018. }
  1019. /**
  1020. * Iterate through <b>policy</b> looking for redundant entries. Log a
  1021. * warning message with the first redundant entry, if any is found.
  1022. */
  1023. static void
  1024. policies_log_first_redundant_entry(const smartlist_t *policy)
  1025. {
  1026. int found_final_effective_entry = 0;
  1027. int first_redundant_entry = 0;
  1028. tor_assert(policy);
  1029. SMARTLIST_FOREACH_BEGIN(policy, const addr_policy_t *, p) {
  1030. sa_family_t family;
  1031. int found_ipv4_wildcard = 0, found_ipv6_wildcard = 0;
  1032. const int i = p_sl_idx;
  1033. /* Look for accept/reject *[4|6|]:* entires */
  1034. if (p->prt_min <= 1 && p->prt_max == 65535 && p->maskbits == 0) {
  1035. family = tor_addr_family(&p->addr);
  1036. /* accept/reject *:* may have already been expanded into
  1037. * accept/reject *4:*,accept/reject *6:*
  1038. * But handle both forms.
  1039. */
  1040. if (family == AF_INET || family == AF_UNSPEC) {
  1041. found_ipv4_wildcard = 1;
  1042. }
  1043. if (family == AF_INET6 || family == AF_UNSPEC) {
  1044. found_ipv6_wildcard = 1;
  1045. }
  1046. }
  1047. /* We also find accept *4:*,reject *6:* ; and
  1048. * accept *4:*,<other policies>,accept *6:* ; and similar.
  1049. * That's ok, because they make any subsequent entries redundant. */
  1050. if (found_ipv4_wildcard && found_ipv6_wildcard) {
  1051. found_final_effective_entry = 1;
  1052. /* if we're not on the final entry in the list */
  1053. if (i < smartlist_len(policy) - 1) {
  1054. first_redundant_entry = i + 1;
  1055. }
  1056. break;
  1057. }
  1058. } SMARTLIST_FOREACH_END(p);
  1059. /* Work out if there are redundant trailing entries in the policy list */
  1060. if (found_final_effective_entry && first_redundant_entry > 0) {
  1061. const addr_policy_t *p;
  1062. /* Longest possible policy is
  1063. * "accept6 ffff:ffff:..255/128:10000-65535",
  1064. * which contains a max-length IPv6 address, plus 24 characters. */
  1065. char line[TOR_ADDR_BUF_LEN + 32];
  1066. tor_assert(first_redundant_entry < smartlist_len(policy));
  1067. p = smartlist_get(policy, first_redundant_entry);
  1068. /* since we've already parsed the policy into an addr_policy_t struct,
  1069. * we might not log exactly what the user typed in */
  1070. policy_write_item(line, TOR_ADDR_BUF_LEN + 32, p, 0);
  1071. log_warn(LD_DIR, "Exit policy '%s' and all following policies are "
  1072. "redundant, as it follows accept/reject *:* rules for both "
  1073. "IPv4 and IPv6. They will be removed from the exit policy. (Use "
  1074. "accept/reject *:* as the last entry in any exit policy.)",
  1075. line);
  1076. }
  1077. }
  1078. #define DEFAULT_EXIT_POLICY \
  1079. "reject *:25,reject *:119,reject *:135-139,reject *:445," \
  1080. "reject *:563,reject *:1214,reject *:4661-4666," \
  1081. "reject *:6346-6429,reject *:6699,reject *:6881-6999,accept *:*"
  1082. /** Parse the exit policy <b>cfg</b> into the linked list *<b>dest</b>.
  1083. *
  1084. * If <b>ipv6_exit</b> is false, prepend "reject *6:*" to the policy.
  1085. *
  1086. * If <b>rejectprivate</b> is true:
  1087. * - prepend "reject private:*" to the policy.
  1088. * - prepend entries that reject publicly routable addresses on this exit
  1089. * relay by calling policies_parse_exit_policy_reject_private
  1090. *
  1091. * If cfg doesn't end in an absolute accept or reject and if
  1092. * <b>add_default_policy</b> is true, add the default exit
  1093. * policy afterwards.
  1094. *
  1095. * Return -1 if we can't parse cfg, else return 0.
  1096. *
  1097. * This function is used to parse the exit policy from our torrc. For
  1098. * the functions used to parse the exit policy from a router descriptor,
  1099. * see router_add_exit_policy.
  1100. */
  1101. static int
  1102. policies_parse_exit_policy_internal(config_line_t *cfg,
  1103. smartlist_t **dest,
  1104. int ipv6_exit,
  1105. int rejectprivate,
  1106. const smartlist_t *configured_addresses,
  1107. int reject_interface_addresses,
  1108. int reject_configured_port_addresses,
  1109. int add_default_policy)
  1110. {
  1111. if (!ipv6_exit) {
  1112. append_exit_policy_string(dest, "reject *6:*");
  1113. }
  1114. if (rejectprivate) {
  1115. /* Reject IPv4 and IPv6 reserved private netblocks */
  1116. append_exit_policy_string(dest, "reject private:*");
  1117. /* Reject IPv4 and IPv6 publicly routable addresses on this exit relay */
  1118. policies_parse_exit_policy_reject_private(
  1119. dest, ipv6_exit,
  1120. configured_addresses,
  1121. reject_interface_addresses,
  1122. reject_configured_port_addresses);
  1123. }
  1124. if (parse_addr_policy(cfg, dest, -1))
  1125. return -1;
  1126. /* Before we add the default policy and final rejects, check to see if
  1127. * there are any lines after accept *:* or reject *:*. These lines have no
  1128. * effect, and are most likely an error. */
  1129. policies_log_first_redundant_entry(*dest);
  1130. if (add_default_policy) {
  1131. append_exit_policy_string(dest, DEFAULT_EXIT_POLICY);
  1132. } else {
  1133. append_exit_policy_string(dest, "reject *4:*");
  1134. append_exit_policy_string(dest, "reject *6:*");
  1135. }
  1136. exit_policy_remove_redundancies(*dest);
  1137. return 0;
  1138. }
  1139. /** Parse exit policy in <b>cfg</b> into <b>dest</b> smartlist.
  1140. *
  1141. * Prepend an entry that rejects all IPv6 destinations unless
  1142. * <b>EXIT_POLICY_IPV6_ENABLED</b> bit is set in <b>options</b> bitmask.
  1143. *
  1144. * If <b>EXIT_POLICY_REJECT_PRIVATE</b> bit is set in <b>options</b>:
  1145. * - prepend an entry that rejects all destinations in all netblocks
  1146. * reserved for private use.
  1147. * - prepend entries that reject publicly routable addresses on this exit
  1148. * relay by calling policies_parse_exit_policy_internal
  1149. *
  1150. * If <b>EXIT_POLICY_ADD_DEFAULT</b> bit is set in <b>options</b>, append
  1151. * default exit policy entries to <b>result</b> smartlist.
  1152. */
  1153. int
  1154. policies_parse_exit_policy(config_line_t *cfg, smartlist_t **dest,
  1155. exit_policy_parser_cfg_t options,
  1156. const smartlist_t *configured_addresses)
  1157. {
  1158. int ipv6_enabled = (options & EXIT_POLICY_IPV6_ENABLED) ? 1 : 0;
  1159. int reject_private = (options & EXIT_POLICY_REJECT_PRIVATE) ? 1 : 0;
  1160. int add_default = (options & EXIT_POLICY_ADD_DEFAULT) ? 1 : 0;
  1161. return policies_parse_exit_policy_internal(cfg,dest,ipv6_enabled,
  1162. reject_private,
  1163. configured_addresses,
  1164. reject_private,
  1165. reject_private,
  1166. add_default);
  1167. }
  1168. /** Helper function that adds a copy of addr to a smartlist as long as it is
  1169. * non-NULL and not tor_addr_is_null().
  1170. *
  1171. * The caller is responsible for freeing all the tor_addr_t* in the smartlist.
  1172. */
  1173. static void
  1174. policies_copy_addr_to_smartlist(smartlist_t *addr_list, const tor_addr_t *addr)
  1175. {
  1176. if (addr && !tor_addr_is_null(addr)) {
  1177. tor_addr_t *addr_copy = tor_malloc(sizeof(tor_addr_t));
  1178. tor_addr_copy(addr_copy, addr);
  1179. smartlist_add(addr_list, addr_copy);
  1180. }
  1181. }
  1182. /** Helper function that adds ipv4h_addr to a smartlist as a tor_addr_t *,
  1183. * as long as it is not tor_addr_is_null(), by converting it to a tor_addr_t
  1184. * and passing it to policies_add_addr_to_smartlist.
  1185. *
  1186. * The caller is responsible for freeing all the tor_addr_t* in the smartlist.
  1187. */
  1188. static void
  1189. policies_copy_ipv4h_to_smartlist(smartlist_t *addr_list, uint32_t ipv4h_addr)
  1190. {
  1191. if (ipv4h_addr) {
  1192. tor_addr_t ipv4_tor_addr;
  1193. tor_addr_from_ipv4h(&ipv4_tor_addr, ipv4h_addr);
  1194. policies_copy_addr_to_smartlist(addr_list, &ipv4_tor_addr);
  1195. }
  1196. }
  1197. /** Helper function that adds copies of
  1198. * or_options->OutboundBindAddressIPv[4|6]_ to a smartlist as tor_addr_t *, as
  1199. * long as or_options is non-NULL, and the addresses are not
  1200. * tor_addr_is_null(), by passing them to policies_add_addr_to_smartlist.
  1201. *
  1202. * The caller is responsible for freeing all the tor_addr_t* in the smartlist.
  1203. */
  1204. static void
  1205. policies_copy_outbound_addresses_to_smartlist(smartlist_t *addr_list,
  1206. const or_options_t *or_options)
  1207. {
  1208. if (or_options) {
  1209. policies_copy_addr_to_smartlist(addr_list,
  1210. &or_options->OutboundBindAddressIPv4_);
  1211. policies_copy_addr_to_smartlist(addr_list,
  1212. &or_options->OutboundBindAddressIPv6_);
  1213. }
  1214. }
  1215. /** Parse <b>ExitPolicy</b> member of <b>or_options</b> into <b>result</b>
  1216. * smartlist.
  1217. * If <b>or_options->IPv6Exit</b> is false, prepend an entry that
  1218. * rejects all IPv6 destinations.
  1219. *
  1220. * If <b>or_options->ExitPolicyRejectPrivate</b> is true:
  1221. * - prepend an entry that rejects all destinations in all netblocks reserved
  1222. * for private use.
  1223. * - if local_address is non-zero, treat it as a host-order IPv4 address, and
  1224. * add it to the list of configured addresses.
  1225. * - if ipv6_local_address is non-NULL, and not the null tor_addr_t, add it
  1226. * to the list of configured addresses.
  1227. * - if or_options->OutboundBindAddressIPv4_ is not the null tor_addr_t, add
  1228. * it to the list of configured addresses.
  1229. * - if or_options->OutboundBindAddressIPv6_ is not the null tor_addr_t, add
  1230. * it to the list of configured addresses.
  1231. *
  1232. * If <b>or_options->BridgeRelay</b> is false, append entries of default
  1233. * Tor exit policy into <b>result</b> smartlist.
  1234. *
  1235. * If or_options->ExitRelay is false, then make our exit policy into
  1236. * "reject *:*" regardless.
  1237. */
  1238. int
  1239. policies_parse_exit_policy_from_options(const or_options_t *or_options,
  1240. uint32_t local_address,
  1241. const tor_addr_t *ipv6_local_address,
  1242. smartlist_t **result)
  1243. {
  1244. exit_policy_parser_cfg_t parser_cfg = 0;
  1245. smartlist_t *configured_addresses = NULL;
  1246. int rv = 0;
  1247. /* Short-circuit for non-exit relays */
  1248. if (or_options->ExitRelay == 0) {
  1249. append_exit_policy_string(result, "reject *4:*");
  1250. append_exit_policy_string(result, "reject *6:*");
  1251. return 0;
  1252. }
  1253. configured_addresses = smartlist_new();
  1254. /* Configure the parser */
  1255. if (or_options->IPv6Exit) {
  1256. parser_cfg |= EXIT_POLICY_IPV6_ENABLED;
  1257. }
  1258. if (or_options->ExitPolicyRejectPrivate) {
  1259. parser_cfg |= EXIT_POLICY_REJECT_PRIVATE;
  1260. }
  1261. if (!or_options->BridgeRelay) {
  1262. parser_cfg |= EXIT_POLICY_ADD_DEFAULT;
  1263. }
  1264. /* Copy the configured addresses into the tor_addr_t* list */
  1265. policies_copy_ipv4h_to_smartlist(configured_addresses, local_address);
  1266. policies_copy_addr_to_smartlist(configured_addresses, ipv6_local_address);
  1267. policies_copy_outbound_addresses_to_smartlist(configured_addresses,
  1268. or_options);
  1269. rv = policies_parse_exit_policy(or_options->ExitPolicy, result, parser_cfg,
  1270. configured_addresses);
  1271. SMARTLIST_FOREACH(configured_addresses, tor_addr_t *, a, tor_free(a));
  1272. smartlist_free(configured_addresses);
  1273. return rv;
  1274. }
  1275. /** Add "reject *:*" to the end of the policy in *<b>dest</b>, allocating
  1276. * *<b>dest</b> as needed. */
  1277. void
  1278. policies_exit_policy_append_reject_star(smartlist_t **dest)
  1279. {
  1280. append_exit_policy_string(dest, "reject *4:*");
  1281. append_exit_policy_string(dest, "reject *6:*");
  1282. }
  1283. /** Replace the exit policy of <b>node</b> with reject *:* */
  1284. void
  1285. policies_set_node_exitpolicy_to_reject_all(node_t *node)
  1286. {
  1287. node->rejects_all = 1;
  1288. }
  1289. /** Return 1 if there is at least one /8 subnet in <b>policy</b> that
  1290. * allows exiting to <b>port</b>. Otherwise, return 0. */
  1291. static int
  1292. exit_policy_is_general_exit_helper(smartlist_t *policy, int port)
  1293. {
  1294. uint32_t mask, ip, i;
  1295. /* Is this /8 rejected (1), or undecided (0)? */
  1296. char subnet_status[256];
  1297. memset(subnet_status, 0, sizeof(subnet_status));
  1298. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
  1299. if (tor_addr_family(&p->addr) != AF_INET)
  1300. continue; /* IPv4 only for now */
  1301. if (p->prt_min > port || p->prt_max < port)
  1302. continue; /* Doesn't cover our port. */
  1303. mask = 0;
  1304. tor_assert(p->maskbits <= 32);
  1305. if (p->maskbits)
  1306. mask = UINT32_MAX<<(32-p->maskbits);
  1307. ip = tor_addr_to_ipv4h(&p->addr);
  1308. /* Calculate the first and last subnet that this exit policy touches
  1309. * and set it as loop boundaries. */
  1310. for (i = ((mask & ip)>>24); i <= (~((mask & ip) ^ mask)>>24); ++i) {
  1311. tor_addr_t addr;
  1312. if (subnet_status[i] != 0)
  1313. continue; /* We already reject some part of this /8 */
  1314. tor_addr_from_ipv4h(&addr, i<<24);
  1315. if (tor_addr_is_internal(&addr, 0))
  1316. continue; /* Local or non-routable addresses */
  1317. if (p->policy_type == ADDR_POLICY_ACCEPT) {
  1318. if (p->maskbits > 8)
  1319. continue; /* Narrower than a /8. */
  1320. /* We found an allowed subnet of at least size /8. Done
  1321. * for this port! */
  1322. return 1;
  1323. } else if (p->policy_type == ADDR_POLICY_REJECT) {
  1324. subnet_status[i] = 1;
  1325. }
  1326. }
  1327. } SMARTLIST_FOREACH_END(p);
  1328. return 0;
  1329. }
  1330. /** Return true iff <b>ri</b> is "useful as an exit node", meaning
  1331. * it allows exit to at least one /8 address space for at least
  1332. * two of ports 80, 443, and 6667. */
  1333. int
  1334. exit_policy_is_general_exit(smartlist_t *policy)
  1335. {
  1336. static const int ports[] = { 80, 443, 6667 };
  1337. int n_allowed = 0;
  1338. int i;
  1339. if (!policy) /*XXXX disallow NULL policies? */
  1340. return 0;
  1341. for (i = 0; i < 3; ++i) {
  1342. n_allowed += exit_policy_is_general_exit_helper(policy, ports[i]);
  1343. }
  1344. return n_allowed >= 2;
  1345. }
  1346. /** Return false if <b>policy</b> might permit access to some addr:port;
  1347. * otherwise if we are certain it rejects everything, return true. */
  1348. int
  1349. policy_is_reject_star(const smartlist_t *policy, sa_family_t family)
  1350. {
  1351. if (!policy) /*XXXX disallow NULL policies? */
  1352. return 1;
  1353. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
  1354. if (p->policy_type == ADDR_POLICY_ACCEPT &&
  1355. (tor_addr_family(&p->addr) == family ||
  1356. tor_addr_family(&p->addr) == AF_UNSPEC)) {
  1357. return 0;
  1358. } else if (p->policy_type == ADDR_POLICY_REJECT &&
  1359. p->prt_min <= 1 && p->prt_max == 65535 &&
  1360. p->maskbits == 0 &&
  1361. (tor_addr_family(&p->addr) == family ||
  1362. tor_addr_family(&p->addr) == AF_UNSPEC)) {
  1363. return 1;
  1364. }
  1365. } SMARTLIST_FOREACH_END(p);
  1366. return 1;
  1367. }
  1368. /** Write a single address policy to the buf_len byte buffer at buf. Return
  1369. * the number of characters written, or -1 on failure. */
  1370. int
  1371. policy_write_item(char *buf, size_t buflen, const addr_policy_t *policy,
  1372. int format_for_desc)
  1373. {
  1374. size_t written = 0;
  1375. char addrbuf[TOR_ADDR_BUF_LEN];
  1376. const char *addrpart;
  1377. int result;
  1378. const int is_accept = policy->policy_type == ADDR_POLICY_ACCEPT;
  1379. const sa_family_t family = tor_addr_family(&policy->addr);
  1380. const int is_ip6 = (family == AF_INET6);
  1381. tor_addr_to_str(addrbuf, &policy->addr, sizeof(addrbuf), 1);
  1382. /* write accept/reject 1.2.3.4 */
  1383. if (policy->is_private) {
  1384. addrpart = "private";
  1385. } else if (policy->maskbits == 0) {
  1386. if (format_for_desc)
  1387. addrpart = "*";
  1388. else if (family == AF_INET6)
  1389. addrpart = "*6";
  1390. else if (family == AF_INET)
  1391. addrpart = "*4";
  1392. else
  1393. addrpart = "*";
  1394. } else {
  1395. addrpart = addrbuf;
  1396. }
  1397. result = tor_snprintf(buf, buflen, "%s%s %s",
  1398. is_accept ? "accept" : "reject",
  1399. (is_ip6&&format_for_desc)?"6":"",
  1400. addrpart);
  1401. if (result < 0)
  1402. return -1;
  1403. written += strlen(buf);
  1404. /* If the maskbits is 32 (IPv4) or 128 (IPv6) we don't need to give it. If
  1405. the mask is 0, we already wrote "*". */
  1406. if (policy->maskbits < (is_ip6?128:32) && policy->maskbits > 0) {
  1407. if (tor_snprintf(buf+written, buflen-written, "/%d", policy->maskbits)<0)
  1408. return -1;
  1409. written += strlen(buf+written);
  1410. }
  1411. if (policy->prt_min <= 1 && policy->prt_max == 65535) {
  1412. /* There is no port set; write ":*" */
  1413. if (written+4 > buflen)
  1414. return -1;
  1415. strlcat(buf+written, ":*", buflen-written);
  1416. written += 2;
  1417. } else if (policy->prt_min == policy->prt_max) {
  1418. /* There is only one port; write ":80". */
  1419. result = tor_snprintf(buf+written, buflen-written, ":%d", policy->prt_min);
  1420. if (result<0)
  1421. return -1;
  1422. written += result;
  1423. } else {
  1424. /* There is a range of ports; write ":79-80". */
  1425. result = tor_snprintf(buf+written, buflen-written, ":%d-%d",
  1426. policy->prt_min, policy->prt_max);
  1427. if (result<0)
  1428. return -1;
  1429. written += result;
  1430. }
  1431. if (written < buflen)
  1432. buf[written] = '\0';
  1433. else
  1434. return -1;
  1435. return (int)written;
  1436. }
  1437. /** Create a new exit policy summary, initially only with a single
  1438. * port 1-64k item */
  1439. /* XXXX This entire thing will do most stuff in O(N^2), or worse. Use an
  1440. * RB-tree if that turns out to matter. */
  1441. static smartlist_t *
  1442. policy_summary_create(void)
  1443. {
  1444. smartlist_t *summary;
  1445. policy_summary_item_t* item;
  1446. item = tor_malloc_zero(sizeof(policy_summary_item_t));
  1447. item->prt_min = 1;
  1448. item->prt_max = 65535;
  1449. item->reject_count = 0;
  1450. item->accepted = 0;
  1451. summary = smartlist_new();
  1452. smartlist_add(summary, item);
  1453. return summary;
  1454. }
  1455. /** Split the summary item in <b>item</b> at the port <b>new_starts</b>.
  1456. * The current item is changed to end at new-starts - 1, the new item
  1457. * copies reject_count and accepted from the old item,
  1458. * starts at new_starts and ends at the port where the original item
  1459. * previously ended.
  1460. */
  1461. static policy_summary_item_t*
  1462. policy_summary_item_split(policy_summary_item_t* old, uint16_t new_starts)
  1463. {
  1464. policy_summary_item_t* new;
  1465. new = tor_malloc_zero(sizeof(policy_summary_item_t));
  1466. new->prt_min = new_starts;
  1467. new->prt_max = old->prt_max;
  1468. new->reject_count = old->reject_count;
  1469. new->accepted = old->accepted;
  1470. old->prt_max = new_starts-1;
  1471. tor_assert(old->prt_min <= old->prt_max);
  1472. tor_assert(new->prt_min <= new->prt_max);
  1473. return new;
  1474. }
  1475. /* XXXX Nick says I'm going to hell for this. If he feels charitably towards
  1476. * my immortal soul, he can clean it up himself. */
  1477. #define AT(x) ((policy_summary_item_t*)smartlist_get(summary, x))
  1478. #define REJECT_CUTOFF_COUNT (1<<25)
  1479. /** Split an exit policy summary so that prt_min and prt_max
  1480. * fall at exactly the start and end of an item respectively.
  1481. */
  1482. static int
  1483. policy_summary_split(smartlist_t *summary,
  1484. uint16_t prt_min, uint16_t prt_max)
  1485. {
  1486. int start_at_index;
  1487. int i = 0;
  1488. while (AT(i)->prt_max < prt_min)
  1489. i++;
  1490. if (AT(i)->prt_min != prt_min) {
  1491. policy_summary_item_t* new_item;
  1492. new_item = policy_summary_item_split(AT(i), prt_min);
  1493. smartlist_insert(summary, i+1, new_item);
  1494. i++;
  1495. }
  1496. start_at_index = i;
  1497. while (AT(i)->prt_max < prt_max)
  1498. i++;
  1499. if (AT(i)->prt_max != prt_max) {
  1500. policy_summary_item_t* new_item;
  1501. new_item = policy_summary_item_split(AT(i), prt_max+1);
  1502. smartlist_insert(summary, i+1, new_item);
  1503. }
  1504. return start_at_index;
  1505. }
  1506. /** Mark port ranges as accepted if they are below the reject_count */
  1507. static void
  1508. policy_summary_accept(smartlist_t *summary,
  1509. uint16_t prt_min, uint16_t prt_max)
  1510. {
  1511. int i = policy_summary_split(summary, prt_min, prt_max);
  1512. while (i < smartlist_len(summary) &&
  1513. AT(i)->prt_max <= prt_max) {
  1514. if (!AT(i)->accepted &&
  1515. AT(i)->reject_count <= REJECT_CUTOFF_COUNT)
  1516. AT(i)->accepted = 1;
  1517. i++;
  1518. }
  1519. tor_assert(i < smartlist_len(summary) || prt_max==65535);
  1520. }
  1521. /** Count the number of addresses in a network with prefixlen maskbits
  1522. * against the given portrange. */
  1523. static void
  1524. policy_summary_reject(smartlist_t *summary,
  1525. maskbits_t maskbits,
  1526. uint16_t prt_min, uint16_t prt_max)
  1527. {
  1528. int i = policy_summary_split(summary, prt_min, prt_max);
  1529. /* XXX: ipv4 specific */
  1530. uint64_t count = (U64_LITERAL(1) << (32-maskbits));
  1531. while (i < smartlist_len(summary) &&
  1532. AT(i)->prt_max <= prt_max) {
  1533. AT(i)->reject_count += count;
  1534. i++;
  1535. }
  1536. tor_assert(i < smartlist_len(summary) || prt_max==65535);
  1537. }
  1538. /** Add a single exit policy item to our summary:
  1539. * If it is an accept ignore it unless it is for all IP addresses
  1540. * ("*"), i.e. it's prefixlen/maskbits is 0, else call
  1541. * policy_summary_accept().
  1542. * If it's a reject ignore it if it is about one of the private
  1543. * networks, else call policy_summary_reject().
  1544. */
  1545. static void
  1546. policy_summary_add_item(smartlist_t *summary, addr_policy_t *p)
  1547. {
  1548. if (p->policy_type == ADDR_POLICY_ACCEPT) {
  1549. if (p->maskbits == 0) {
  1550. policy_summary_accept(summary, p->prt_min, p->prt_max);
  1551. }
  1552. } else if (p->policy_type == ADDR_POLICY_REJECT) {
  1553. int is_private = 0;
  1554. int i;
  1555. for (i = 0; private_nets[i]; ++i) {
  1556. tor_addr_t addr;
  1557. maskbits_t maskbits;
  1558. if (tor_addr_parse_mask_ports(private_nets[i], 0, &addr,
  1559. &maskbits, NULL, NULL)<0) {
  1560. tor_assert(0);
  1561. }
  1562. if (tor_addr_compare(&p->addr, &addr, CMP_EXACT) == 0 &&
  1563. p->maskbits == maskbits) {
  1564. is_private = 1;
  1565. break;
  1566. }
  1567. }
  1568. if (!is_private) {
  1569. policy_summary_reject(summary, p->maskbits, p->prt_min, p->prt_max);
  1570. }
  1571. } else
  1572. tor_assert(0);
  1573. }
  1574. /** Create a string representing a summary for an exit policy.
  1575. * The summary will either be an "accept" plus a comma-separated list of port
  1576. * ranges or a "reject" plus port-ranges, depending on which is shorter.
  1577. *
  1578. * If no exits are allowed at all then "reject 1-65535" is returned. If no
  1579. * ports are blocked instead of "reject " we return "accept 1-65535". (These
  1580. * are an exception to the shorter-representation-wins rule).
  1581. */
  1582. char *
  1583. policy_summarize(smartlist_t *policy, sa_family_t family)
  1584. {
  1585. smartlist_t *summary = policy_summary_create();
  1586. smartlist_t *accepts, *rejects;
  1587. int i, last, start_prt;
  1588. size_t accepts_len, rejects_len;
  1589. char *accepts_str = NULL, *rejects_str = NULL, *shorter_str, *result;
  1590. const char *prefix;
  1591. tor_assert(policy);
  1592. /* Create the summary list */
  1593. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
  1594. sa_family_t f = tor_addr_family(&p->addr);
  1595. if (f != AF_INET && f != AF_INET6) {
  1596. log_warn(LD_BUG, "Weird family when summarizing address policy");
  1597. }
  1598. if (f != family)
  1599. continue;
  1600. /* XXXX-ipv6 More family work is needed */
  1601. policy_summary_add_item(summary, p);
  1602. } SMARTLIST_FOREACH_END(p);
  1603. /* Now create two lists of strings, one for accepted and one
  1604. * for rejected ports. We take care to merge ranges so that
  1605. * we avoid getting stuff like "1-4,5-9,10", instead we want
  1606. * "1-10"
  1607. */
  1608. i = 0;
  1609. start_prt = 1;
  1610. accepts = smartlist_new();
  1611. rejects = smartlist_new();
  1612. while (1) {
  1613. last = i == smartlist_len(summary)-1;
  1614. if (last ||
  1615. AT(i)->accepted != AT(i+1)->accepted) {
  1616. char buf[POLICY_BUF_LEN];
  1617. if (start_prt == AT(i)->prt_max)
  1618. tor_snprintf(buf, sizeof(buf), "%d", start_prt);
  1619. else
  1620. tor_snprintf(buf, sizeof(buf), "%d-%d", start_prt, AT(i)->prt_max);
  1621. if (AT(i)->accepted)
  1622. smartlist_add(accepts, tor_strdup(buf));
  1623. else
  1624. smartlist_add(rejects, tor_strdup(buf));
  1625. if (last)
  1626. break;
  1627. start_prt = AT(i+1)->prt_min;
  1628. };
  1629. i++;
  1630. };
  1631. /* Figure out which of the two stringlists will be shorter and use
  1632. * that to build the result
  1633. */
  1634. if (smartlist_len(accepts) == 0) { /* no exits at all */
  1635. result = tor_strdup("reject 1-65535");
  1636. goto cleanup;
  1637. }
  1638. if (smartlist_len(rejects) == 0) { /* no rejects at all */
  1639. result = tor_strdup("accept 1-65535");
  1640. goto cleanup;
  1641. }
  1642. accepts_str = smartlist_join_strings(accepts, ",", 0, &accepts_len);
  1643. rejects_str = smartlist_join_strings(rejects, ",", 0, &rejects_len);
  1644. if (rejects_len > MAX_EXITPOLICY_SUMMARY_LEN-strlen("reject")-1 &&
  1645. accepts_len > MAX_EXITPOLICY_SUMMARY_LEN-strlen("accept")-1) {
  1646. char *c;
  1647. shorter_str = accepts_str;
  1648. prefix = "accept";
  1649. c = shorter_str + (MAX_EXITPOLICY_SUMMARY_LEN-strlen(prefix)-1);
  1650. while (*c != ',' && c >= shorter_str)
  1651. c--;
  1652. tor_assert(c >= shorter_str);
  1653. tor_assert(*c == ',');
  1654. *c = '\0';
  1655. } else if (rejects_len < accepts_len) {
  1656. shorter_str = rejects_str;
  1657. prefix = "reject";
  1658. } else {
  1659. shorter_str = accepts_str;
  1660. prefix = "accept";
  1661. }
  1662. tor_asprintf(&result, "%s %s", prefix, shorter_str);
  1663. cleanup:
  1664. /* cleanup */
  1665. SMARTLIST_FOREACH(summary, policy_summary_item_t *, s, tor_free(s));
  1666. smartlist_free(summary);
  1667. tor_free(accepts_str);
  1668. SMARTLIST_FOREACH(accepts, char *, s, tor_free(s));
  1669. smartlist_free(accepts);
  1670. tor_free(rejects_str);
  1671. SMARTLIST_FOREACH(rejects, char *, s, tor_free(s));
  1672. smartlist_free(rejects);
  1673. return result;
  1674. }
  1675. /** Convert a summarized policy string into a short_policy_t. Return NULL
  1676. * if the string is not well-formed. */
  1677. short_policy_t *
  1678. parse_short_policy(const char *summary)
  1679. {
  1680. const char *orig_summary = summary;
  1681. short_policy_t *result;
  1682. int is_accept;
  1683. int n_entries;
  1684. short_policy_entry_t entries[MAX_EXITPOLICY_SUMMARY_LEN]; /* overkill */
  1685. const char *next;
  1686. if (!strcmpstart(summary, "accept ")) {
  1687. is_accept = 1;
  1688. summary += strlen("accept ");
  1689. } else if (!strcmpstart(summary, "reject ")) {
  1690. is_accept = 0;
  1691. summary += strlen("reject ");
  1692. } else {
  1693. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Unrecognized policy summary keyword");
  1694. return NULL;
  1695. }
  1696. n_entries = 0;
  1697. for ( ; *summary; summary = next) {
  1698. const char *comma = strchr(summary, ',');
  1699. unsigned low, high;
  1700. char dummy;
  1701. char ent_buf[32];
  1702. size_t len;
  1703. next = comma ? comma+1 : strchr(summary, '\0');
  1704. len = comma ? (size_t)(comma - summary) : strlen(summary);
  1705. if (n_entries == MAX_EXITPOLICY_SUMMARY_LEN) {
  1706. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Impossibly long policy summary %s",
  1707. escaped(orig_summary));
  1708. return NULL;
  1709. }
  1710. if (! TOR_ISDIGIT(*summary) || len > (sizeof(ent_buf)-1)) {
  1711. /* unrecognized entry format. skip it. */
  1712. continue;
  1713. }
  1714. if (len < 1) {
  1715. /* empty; skip it. */
  1716. /* XXX This happens to be unreachable, since if len==0, then *summary is
  1717. * ',' or '\0', and the TOR_ISDIGIT test above would have failed. */
  1718. continue;
  1719. }
  1720. memcpy(ent_buf, summary, len);
  1721. ent_buf[len] = '\0';
  1722. if (tor_sscanf(ent_buf, "%u-%u%c", &low, &high, &dummy) == 2) {
  1723. if (low<1 || low>65535 || high<1 || high>65535 || low>high) {
  1724. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  1725. "Found bad entry in policy summary %s", escaped(orig_summary));
  1726. return NULL;
  1727. }
  1728. } else if (tor_sscanf(ent_buf, "%u%c", &low, &dummy) == 1) {
  1729. if (low<1 || low>65535) {
  1730. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  1731. "Found bad entry in policy summary %s", escaped(orig_summary));
  1732. return NULL;
  1733. }
  1734. high = low;
  1735. } else {
  1736. log_fn(LOG_PROTOCOL_WARN, LD_DIR,"Found bad entry in policy summary %s",
  1737. escaped(orig_summary));
  1738. return NULL;
  1739. }
  1740. entries[n_entries].min_port = low;
  1741. entries[n_entries].max_port = high;
  1742. n_entries++;
  1743. }
  1744. if (n_entries == 0) {
  1745. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  1746. "Found no port-range entries in summary %s", escaped(orig_summary));
  1747. return NULL;
  1748. }
  1749. {
  1750. size_t size = STRUCT_OFFSET(short_policy_t, entries) +
  1751. sizeof(short_policy_entry_t)*(n_entries);
  1752. result = tor_malloc_zero(size);
  1753. tor_assert( (char*)&result->entries[n_entries-1] < ((char*)result)+size);
  1754. }
  1755. result->is_accept = is_accept;
  1756. result->n_entries = n_entries;
  1757. memcpy(result->entries, entries, sizeof(short_policy_entry_t)*n_entries);
  1758. return result;
  1759. }
  1760. /** Write <b>policy</b> back out into a string. Used only for unit tests
  1761. * currently. */
  1762. char *
  1763. write_short_policy(const short_policy_t *policy)
  1764. {
  1765. int i;
  1766. char *answer;
  1767. smartlist_t *sl = smartlist_new();
  1768. smartlist_add_asprintf(sl, "%s", policy->is_accept ? "accept " : "reject ");
  1769. for (i=0; i < policy->n_entries; i++) {
  1770. const short_policy_entry_t *e = &policy->entries[i];
  1771. if (e->min_port == e->max_port) {
  1772. smartlist_add_asprintf(sl, "%d", e->min_port);
  1773. } else {
  1774. smartlist_add_asprintf(sl, "%d-%d", e->min_port, e->max_port);
  1775. }
  1776. if (i < policy->n_entries-1)
  1777. smartlist_add(sl, tor_strdup(","));
  1778. }
  1779. answer = smartlist_join_strings(sl, "", 0, NULL);
  1780. SMARTLIST_FOREACH(sl, char *, a, tor_free(a));
  1781. smartlist_free(sl);
  1782. return answer;
  1783. }
  1784. /** Release all storage held in <b>policy</b>. */
  1785. void
  1786. short_policy_free(short_policy_t *policy)
  1787. {
  1788. tor_free(policy);
  1789. }
  1790. /** See whether the <b>addr</b>:<b>port</b> address is likely to be accepted
  1791. * or rejected by the summarized policy <b>policy</b>. Return values are as
  1792. * for compare_tor_addr_to_addr_policy. Unlike the regular addr_policy
  1793. * functions, requires the <b>port</b> be specified. */
  1794. addr_policy_result_t
  1795. compare_tor_addr_to_short_policy(const tor_addr_t *addr, uint16_t port,
  1796. const short_policy_t *policy)
  1797. {
  1798. int i;
  1799. int found_match = 0;
  1800. int accept;
  1801. tor_assert(port != 0);
  1802. if (addr && tor_addr_is_null(addr))
  1803. addr = NULL; /* Unspec means 'no address at all,' in this context. */
  1804. if (addr && get_options()->ClientRejectInternalAddresses &&
  1805. (tor_addr_is_internal(addr, 0) || tor_addr_is_loopback(addr)))
  1806. return ADDR_POLICY_REJECTED;
  1807. for (i=0; i < policy->n_entries; ++i) {
  1808. const short_policy_entry_t *e = &policy->entries[i];
  1809. if (e->min_port <= port && port <= e->max_port) {
  1810. found_match = 1;
  1811. break;
  1812. }
  1813. }
  1814. if (found_match)
  1815. accept = policy->is_accept;
  1816. else
  1817. accept = ! policy->is_accept;
  1818. /* ???? are these right? -NM */
  1819. /* We should be sure not to return ADDR_POLICY_ACCEPTED in the accept
  1820. * case here, because it would cause clients to believe that the node
  1821. * allows exit enclaving. Trying it anyway would open up a cool attack
  1822. * where the node refuses due to exitpolicy, the client reacts in
  1823. * surprise by rewriting the node's exitpolicy to reject *:*, and then
  1824. * a bad guy targets users by causing them to attempt such connections
  1825. * to 98% of the exits.
  1826. *
  1827. * Once microdescriptors can handle addresses in special cases (e.g. if
  1828. * we ever solve ticket 1774), we can provide certainty here. -RD */
  1829. if (accept)
  1830. return ADDR_POLICY_PROBABLY_ACCEPTED;
  1831. else
  1832. return ADDR_POLICY_REJECTED;
  1833. }
  1834. /** Return true iff <b>policy</b> seems reject all ports */
  1835. int
  1836. short_policy_is_reject_star(const short_policy_t *policy)
  1837. {
  1838. /* This doesn't need to be as much on the lookout as policy_is_reject_star,
  1839. * since policy summaries are from the consensus or from consensus
  1840. * microdescs.
  1841. */
  1842. tor_assert(policy);
  1843. /* Check for an exact match of "reject 1-65535". */
  1844. return (policy->is_accept == 0 && policy->n_entries == 1 &&
  1845. policy->entries[0].min_port == 1 &&
  1846. policy->entries[0].max_port == 65535);
  1847. }
  1848. /** Decide whether addr:port is probably or definitely accepted or rejected by
  1849. * <b>node</b>. See compare_tor_addr_to_addr_policy for details on addr/port
  1850. * interpretation. */
  1851. addr_policy_result_t
  1852. compare_tor_addr_to_node_policy(const tor_addr_t *addr, uint16_t port,
  1853. const node_t *node)
  1854. {
  1855. if (node->rejects_all)
  1856. return ADDR_POLICY_REJECTED;
  1857. if (addr && tor_addr_family(addr) == AF_INET6) {
  1858. const short_policy_t *p = NULL;
  1859. if (node->ri)
  1860. p = node->ri->ipv6_exit_policy;
  1861. else if (node->md)
  1862. p = node->md->ipv6_exit_policy;
  1863. if (p)
  1864. return compare_tor_addr_to_short_policy(addr, port, p);
  1865. else
  1866. return ADDR_POLICY_REJECTED;
  1867. }
  1868. if (node->ri) {
  1869. return compare_tor_addr_to_addr_policy(addr, port, node->ri->exit_policy);
  1870. } else if (node->md) {
  1871. if (node->md->exit_policy == NULL)
  1872. return ADDR_POLICY_REJECTED;
  1873. else
  1874. return compare_tor_addr_to_short_policy(addr, port,
  1875. node->md->exit_policy);
  1876. } else {
  1877. return ADDR_POLICY_PROBABLY_REJECTED;
  1878. }
  1879. }
  1880. /**
  1881. * Given <b>policy_list</b>, a list of addr_policy_t, produce a string
  1882. * representation of the list.
  1883. * If <b>include_ipv4</b> is true, include IPv4 entries.
  1884. * If <b>include_ipv6</b> is true, include IPv6 entries.
  1885. */
  1886. char *
  1887. policy_dump_to_string(const smartlist_t *policy_list,
  1888. int include_ipv4,
  1889. int include_ipv6)
  1890. {
  1891. smartlist_t *policy_string_list;
  1892. char *policy_string = NULL;
  1893. policy_string_list = smartlist_new();
  1894. SMARTLIST_FOREACH_BEGIN(policy_list, addr_policy_t *, tmpe) {
  1895. char *pbuf;
  1896. int bytes_written_to_pbuf;
  1897. if ((tor_addr_family(&tmpe->addr) == AF_INET6) && (!include_ipv6)) {
  1898. continue; /* Don't include IPv6 parts of address policy */
  1899. }
  1900. if ((tor_addr_family(&tmpe->addr) == AF_INET) && (!include_ipv4)) {
  1901. continue; /* Don't include IPv4 parts of address policy */
  1902. }
  1903. pbuf = tor_malloc(POLICY_BUF_LEN);
  1904. bytes_written_to_pbuf = policy_write_item(pbuf,POLICY_BUF_LEN, tmpe, 1);
  1905. if (bytes_written_to_pbuf < 0) {
  1906. log_warn(LD_BUG, "policy_dump_to_string ran out of room!");
  1907. tor_free(pbuf);
  1908. goto done;
  1909. }
  1910. smartlist_add(policy_string_list,pbuf);
  1911. } SMARTLIST_FOREACH_END(tmpe);
  1912. policy_string = smartlist_join_strings(policy_string_list, "\n", 0, NULL);
  1913. done:
  1914. SMARTLIST_FOREACH(policy_string_list, char *, str, tor_free(str));
  1915. smartlist_free(policy_string_list);
  1916. return policy_string;
  1917. }
  1918. /** Implementation for GETINFO control command: knows the answer for questions
  1919. * about "exit-policy/..." */
  1920. int
  1921. getinfo_helper_policies(control_connection_t *conn,
  1922. const char *question, char **answer,
  1923. const char **errmsg)
  1924. {
  1925. (void) conn;
  1926. (void) errmsg;
  1927. if (!strcmp(question, "exit-policy/default")) {
  1928. *answer = tor_strdup(DEFAULT_EXIT_POLICY);
  1929. } else if (!strcmp(question, "exit-policy/reject-private/default")) {
  1930. smartlist_t *private_policy_strings;
  1931. const char **priv = private_nets;
  1932. private_policy_strings = smartlist_new();
  1933. while (*priv != NULL) {
  1934. /* IPv6 addresses are in "[]" and contain ":",
  1935. * IPv4 addresses are not in "[]" and contain "." */
  1936. smartlist_add_asprintf(private_policy_strings, "reject %s:*", *priv);
  1937. priv++;
  1938. }
  1939. *answer = smartlist_join_strings(private_policy_strings,
  1940. ",", 0, NULL);
  1941. SMARTLIST_FOREACH(private_policy_strings, char *, str, tor_free(str));
  1942. smartlist_free(private_policy_strings);
  1943. } else if (!strcmp(question, "exit-policy/reject-private/relay")) {
  1944. const or_options_t *options = get_options();
  1945. const routerinfo_t *me = router_get_my_routerinfo();
  1946. if (!me) {
  1947. *errmsg = "router_get_my_routerinfo returned NULL";
  1948. return -1;
  1949. }
  1950. if (!options->ExitPolicyRejectPrivate) {
  1951. *answer = tor_strdup("");
  1952. return 0;
  1953. }
  1954. smartlist_t *private_policy_list = smartlist_new();
  1955. smartlist_t *configured_addresses = smartlist_new();
  1956. /* Copy the configured addresses into the tor_addr_t* list */
  1957. policies_copy_ipv4h_to_smartlist(configured_addresses, me->addr);
  1958. policies_copy_addr_to_smartlist(configured_addresses, &me->ipv6_addr);
  1959. policies_copy_outbound_addresses_to_smartlist(configured_addresses,
  1960. options);
  1961. policies_parse_exit_policy_reject_private(
  1962. &private_policy_list,
  1963. options->IPv6Exit,
  1964. configured_addresses,
  1965. 1, 1);
  1966. *answer = policy_dump_to_string(private_policy_list, 1, 1);
  1967. addr_policy_list_free(private_policy_list);
  1968. SMARTLIST_FOREACH(configured_addresses, tor_addr_t *, a, tor_free(a));
  1969. smartlist_free(configured_addresses);
  1970. } else if (!strcmpstart(question, "exit-policy/")) {
  1971. const routerinfo_t *me = router_get_my_routerinfo();
  1972. int include_ipv4 = 0;
  1973. int include_ipv6 = 0;
  1974. if (!strcmp(question, "exit-policy/ipv4")) {
  1975. include_ipv4 = 1;
  1976. } else if (!strcmp(question, "exit-policy/ipv6")) {
  1977. include_ipv6 = 1;
  1978. } else if (!strcmp(question, "exit-policy/full")) {
  1979. include_ipv4 = include_ipv6 = 1;
  1980. } else {
  1981. return 0; /* No such key. */
  1982. }
  1983. if (!me) {
  1984. *errmsg = "router_get_my_routerinfo returned NULL";
  1985. return -1;
  1986. }
  1987. *answer = router_dump_exit_policy_to_string(me,include_ipv4,include_ipv6);
  1988. }
  1989. return 0;
  1990. }
  1991. /** Release all storage held by <b>p</b>. */
  1992. void
  1993. addr_policy_list_free(smartlist_t *lst)
  1994. {
  1995. if (!lst)
  1996. return;
  1997. SMARTLIST_FOREACH(lst, addr_policy_t *, policy, addr_policy_free(policy));
  1998. smartlist_free(lst);
  1999. }
  2000. /** Release all storage held by <b>p</b>. */
  2001. void
  2002. addr_policy_free(addr_policy_t *p)
  2003. {
  2004. if (!p)
  2005. return;
  2006. if (--p->refcnt <= 0) {
  2007. if (p->is_canonical) {
  2008. policy_map_ent_t search, *found;
  2009. search.policy = p;
  2010. found = HT_REMOVE(policy_map, &policy_root, &search);
  2011. if (found) {
  2012. tor_assert(p == found->policy);
  2013. tor_free(found);
  2014. }
  2015. }
  2016. tor_free(p);
  2017. }
  2018. }
  2019. /** Release all storage held by policy variables. */
  2020. void
  2021. policies_free_all(void)
  2022. {
  2023. addr_policy_list_free(reachable_or_addr_policy);
  2024. reachable_or_addr_policy = NULL;
  2025. addr_policy_list_free(reachable_dir_addr_policy);
  2026. reachable_dir_addr_policy = NULL;
  2027. addr_policy_list_free(socks_policy);
  2028. socks_policy = NULL;
  2029. addr_policy_list_free(dir_policy);
  2030. dir_policy = NULL;
  2031. addr_policy_list_free(authdir_reject_policy);
  2032. authdir_reject_policy = NULL;
  2033. addr_policy_list_free(authdir_invalid_policy);
  2034. authdir_invalid_policy = NULL;
  2035. addr_policy_list_free(authdir_badexit_policy);
  2036. authdir_badexit_policy = NULL;
  2037. if (!HT_EMPTY(&policy_root)) {
  2038. policy_map_ent_t **ent;
  2039. int n = 0;
  2040. char buf[POLICY_BUF_LEN];
  2041. log_warn(LD_MM, "Still had %d address policies cached at shutdown.",
  2042. (int)HT_SIZE(&policy_root));
  2043. /* Note the first 10 cached policies to try to figure out where they
  2044. * might be coming from. */
  2045. HT_FOREACH(ent, policy_map, &policy_root) {
  2046. if (++n > 10)
  2047. break;
  2048. if (policy_write_item(buf, sizeof(buf), (*ent)->policy, 0) >= 0)
  2049. log_warn(LD_MM," %d [%d]: %s", n, (*ent)->policy->refcnt, buf);
  2050. }
  2051. }
  2052. HT_CLEAR(policy_map, &policy_root);
  2053. }