policies.c 58 KB

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