policies.c 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875
  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. #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 "accept[6]" and "reject[6]"
  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. static int warned_about_exitrelay = 0;
  395. const int exitrelay_setting_is_auto = options->ExitRelay == -1;
  396. const int policy_accepts_something =
  397. ! (policy_is_reject_star(addr_policy, AF_INET) &&
  398. policy_is_reject_star(addr_policy, AF_INET6));
  399. if (server_mode(options) &&
  400. ! warned_about_exitrelay &&
  401. exitrelay_setting_is_auto &&
  402. policy_accepts_something) {
  403. /* Policy accepts something */
  404. warned_about_exitrelay = 1;
  405. log_warn(LD_CONFIG,
  406. "Tor is running as an exit relay%s. If you did not want this "
  407. "behavior, please set the ExitRelay option to 0. If you do "
  408. "want to run an exit Relay, please set the ExitRelay option "
  409. "to 1 to disable this warning, and for forward compatibility.",
  410. options->ExitPolicy == NULL ?
  411. " with the default exit policy" : "");
  412. if (options->ExitPolicy == NULL) {
  413. log_warn(LD_CONFIG,
  414. "In a future version of Tor, ExitRelay 0 may become the "
  415. "default when no ExitPolicy is given.");
  416. }
  417. }
  418. /* The rest of these calls *append* to addr_policy. So don't actually
  419. * use the results for anything other than checking if they parse! */
  420. if (parse_addr_policy(options->DirPolicy, &addr_policy, -1))
  421. REJECT("Error in DirPolicy entry.");
  422. if (parse_addr_policy(options->SocksPolicy, &addr_policy, -1))
  423. REJECT("Error in SocksPolicy entry.");
  424. if (parse_addr_policy(options->AuthDirReject, &addr_policy,
  425. ADDR_POLICY_REJECT))
  426. REJECT("Error in AuthDirReject entry.");
  427. if (parse_addr_policy(options->AuthDirInvalid, &addr_policy,
  428. ADDR_POLICY_REJECT))
  429. REJECT("Error in AuthDirInvalid entry.");
  430. if (parse_addr_policy(options->AuthDirBadExit, &addr_policy,
  431. ADDR_POLICY_REJECT))
  432. REJECT("Error in AuthDirBadExit entry.");
  433. if (parse_addr_policy(options->ReachableAddresses, &addr_policy,
  434. ADDR_POLICY_ACCEPT))
  435. REJECT("Error in ReachableAddresses entry.");
  436. if (parse_addr_policy(options->ReachableORAddresses, &addr_policy,
  437. ADDR_POLICY_ACCEPT))
  438. REJECT("Error in ReachableORAddresses entry.");
  439. if (parse_addr_policy(options->ReachableDirAddresses, &addr_policy,
  440. ADDR_POLICY_ACCEPT))
  441. REJECT("Error in ReachableDirAddresses entry.");
  442. err:
  443. addr_policy_list_free(addr_policy);
  444. return *msg ? -1 : 0;
  445. #undef REJECT
  446. }
  447. /** Parse <b>string</b> in the same way that the exit policy
  448. * is parsed, and put the processed version in *<b>policy</b>.
  449. * Ignore port specifiers.
  450. */
  451. static int
  452. load_policy_from_option(config_line_t *config, const char *option_name,
  453. smartlist_t **policy,
  454. int assume_action)
  455. {
  456. int r;
  457. int killed_any_ports = 0;
  458. addr_policy_list_free(*policy);
  459. *policy = NULL;
  460. r = parse_addr_policy(config, policy, assume_action);
  461. if (r < 0) {
  462. return -1;
  463. }
  464. if (*policy) {
  465. SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, n) {
  466. /* ports aren't used in these. */
  467. if (n->prt_min > 1 || n->prt_max != 65535) {
  468. addr_policy_t newp, *c;
  469. memcpy(&newp, n, sizeof(newp));
  470. newp.prt_min = 1;
  471. newp.prt_max = 65535;
  472. newp.is_canonical = 0;
  473. c = addr_policy_get_canonical_entry(&newp);
  474. SMARTLIST_REPLACE_CURRENT(*policy, n, c);
  475. addr_policy_free(n);
  476. killed_any_ports = 1;
  477. }
  478. } SMARTLIST_FOREACH_END(n);
  479. }
  480. if (killed_any_ports) {
  481. log_warn(LD_CONFIG, "Ignoring ports in %s option.", option_name);
  482. }
  483. return 0;
  484. }
  485. /** Set all policies based on <b>options</b>, which should have been validated
  486. * first by validate_addr_policies. */
  487. int
  488. policies_parse_from_options(const or_options_t *options)
  489. {
  490. int ret = 0;
  491. if (load_policy_from_option(options->SocksPolicy, "SocksPolicy",
  492. &socks_policy, -1) < 0)
  493. ret = -1;
  494. if (load_policy_from_option(options->DirPolicy, "DirPolicy",
  495. &dir_policy, -1) < 0)
  496. ret = -1;
  497. if (load_policy_from_option(options->AuthDirReject, "AuthDirReject",
  498. &authdir_reject_policy, ADDR_POLICY_REJECT) < 0)
  499. ret = -1;
  500. if (load_policy_from_option(options->AuthDirInvalid, "AuthDirInvalid",
  501. &authdir_invalid_policy, ADDR_POLICY_REJECT) < 0)
  502. ret = -1;
  503. if (load_policy_from_option(options->AuthDirBadExit, "AuthDirBadExit",
  504. &authdir_badexit_policy, ADDR_POLICY_REJECT) < 0)
  505. ret = -1;
  506. if (parse_reachable_addresses() < 0)
  507. ret = -1;
  508. return ret;
  509. }
  510. /** Compare two provided address policy items, and return -1, 0, or 1
  511. * if the first is less than, equal to, or greater than the second. */
  512. static int
  513. cmp_single_addr_policy(addr_policy_t *a, addr_policy_t *b)
  514. {
  515. int r;
  516. if ((r=((int)a->policy_type - (int)b->policy_type)))
  517. return r;
  518. if ((r=((int)a->is_private - (int)b->is_private)))
  519. return r;
  520. if ((r=tor_addr_compare(&a->addr, &b->addr, CMP_EXACT)))
  521. return r;
  522. if ((r=((int)a->maskbits - (int)b->maskbits)))
  523. return r;
  524. if ((r=((int)a->prt_min - (int)b->prt_min)))
  525. return r;
  526. if ((r=((int)a->prt_max - (int)b->prt_max)))
  527. return r;
  528. return 0;
  529. }
  530. /** Like cmp_single_addr_policy() above, but looks at the
  531. * whole set of policies in each case. */
  532. int
  533. cmp_addr_policies(smartlist_t *a, smartlist_t *b)
  534. {
  535. int r, i;
  536. int len_a = a ? smartlist_len(a) : 0;
  537. int len_b = b ? smartlist_len(b) : 0;
  538. for (i = 0; i < len_a && i < len_b; ++i) {
  539. if ((r = cmp_single_addr_policy(smartlist_get(a, i), smartlist_get(b, i))))
  540. return r;
  541. }
  542. if (i == len_a && i == len_b)
  543. return 0;
  544. if (i < len_a)
  545. return -1;
  546. else
  547. return 1;
  548. }
  549. /** Node in hashtable used to store address policy entries. */
  550. typedef struct policy_map_ent_t {
  551. HT_ENTRY(policy_map_ent_t) node;
  552. addr_policy_t *policy;
  553. } policy_map_ent_t;
  554. /* DOCDOC policy_root */
  555. static HT_HEAD(policy_map, policy_map_ent_t) policy_root = HT_INITIALIZER();
  556. /** Return true iff a and b are equal. */
  557. static INLINE int
  558. policy_eq(policy_map_ent_t *a, policy_map_ent_t *b)
  559. {
  560. return cmp_single_addr_policy(a->policy, b->policy) == 0;
  561. }
  562. /** Return a hashcode for <b>ent</b> */
  563. static unsigned int
  564. policy_hash(const policy_map_ent_t *ent)
  565. {
  566. const addr_policy_t *a = ent->policy;
  567. addr_policy_t aa;
  568. memset(&aa, 0, sizeof(aa));
  569. aa.prt_min = a->prt_min;
  570. aa.prt_max = a->prt_max;
  571. aa.maskbits = a->maskbits;
  572. aa.policy_type = a->policy_type;
  573. aa.is_private = a->is_private;
  574. if (a->is_private) {
  575. aa.is_private = 1;
  576. } else {
  577. tor_addr_copy_tight(&aa.addr, &a->addr);
  578. }
  579. return (unsigned) siphash24g(&aa, sizeof(aa));
  580. }
  581. HT_PROTOTYPE(policy_map, policy_map_ent_t, node, policy_hash,
  582. policy_eq)
  583. HT_GENERATE2(policy_map, policy_map_ent_t, node, policy_hash,
  584. policy_eq, 0.6, tor_reallocarray_, tor_free_)
  585. /** Given a pointer to an addr_policy_t, return a copy of the pointer to the
  586. * "canonical" copy of that addr_policy_t; the canonical copy is a single
  587. * reference-counted object. */
  588. addr_policy_t *
  589. addr_policy_get_canonical_entry(addr_policy_t *e)
  590. {
  591. policy_map_ent_t search, *found;
  592. if (e->is_canonical)
  593. return e;
  594. search.policy = e;
  595. found = HT_FIND(policy_map, &policy_root, &search);
  596. if (!found) {
  597. found = tor_malloc_zero(sizeof(policy_map_ent_t));
  598. found->policy = tor_memdup(e, sizeof(addr_policy_t));
  599. found->policy->is_canonical = 1;
  600. found->policy->refcnt = 0;
  601. HT_INSERT(policy_map, &policy_root, found);
  602. }
  603. tor_assert(!cmp_single_addr_policy(found->policy, e));
  604. ++found->policy->refcnt;
  605. return found->policy;
  606. }
  607. /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
  608. * addr and port are both known. */
  609. static addr_policy_result_t
  610. compare_known_tor_addr_to_addr_policy(const tor_addr_t *addr, uint16_t port,
  611. const smartlist_t *policy)
  612. {
  613. /* We know the address and port, and we know the policy, so we can just
  614. * compute an exact match. */
  615. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
  616. /* Address is known */
  617. if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
  618. CMP_EXACT)) {
  619. if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
  620. /* Exact match for the policy */
  621. return tmpe->policy_type == ADDR_POLICY_ACCEPT ?
  622. ADDR_POLICY_ACCEPTED : ADDR_POLICY_REJECTED;
  623. }
  624. }
  625. } SMARTLIST_FOREACH_END(tmpe);
  626. /* accept all by default. */
  627. return ADDR_POLICY_ACCEPTED;
  628. }
  629. /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
  630. * addr is known but port is not. */
  631. static addr_policy_result_t
  632. compare_known_tor_addr_to_addr_policy_noport(const tor_addr_t *addr,
  633. const smartlist_t *policy)
  634. {
  635. /* We look to see if there's a definite match. If so, we return that
  636. match's value, unless there's an intervening possible match that says
  637. something different. */
  638. int maybe_accept = 0, maybe_reject = 0;
  639. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
  640. if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
  641. CMP_EXACT)) {
  642. if (tmpe->prt_min <= 1 && tmpe->prt_max >= 65535) {
  643. /* Definitely matches, since it covers all ports. */
  644. if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
  645. /* If we already hit a clause that might trigger a 'reject', than we
  646. * can't be sure of this certain 'accept'.*/
  647. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
  648. ADDR_POLICY_ACCEPTED;
  649. } else {
  650. return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
  651. ADDR_POLICY_REJECTED;
  652. }
  653. } else {
  654. /* Might match. */
  655. if (tmpe->policy_type == ADDR_POLICY_REJECT)
  656. maybe_reject = 1;
  657. else
  658. maybe_accept = 1;
  659. }
  660. }
  661. } SMARTLIST_FOREACH_END(tmpe);
  662. /* accept all by default. */
  663. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  664. }
  665. /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
  666. * port is known but address is not. */
  667. static addr_policy_result_t
  668. compare_unknown_tor_addr_to_addr_policy(uint16_t port,
  669. const smartlist_t *policy)
  670. {
  671. /* We look to see if there's a definite match. If so, we return that
  672. match's value, unless there's an intervening possible match that says
  673. something different. */
  674. int maybe_accept = 0, maybe_reject = 0;
  675. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
  676. if (tmpe->prt_min <= port && port <= tmpe->prt_max) {
  677. if (tmpe->maskbits == 0) {
  678. /* Definitely matches, since it covers all addresses. */
  679. if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
  680. /* If we already hit a clause that might trigger a 'reject', than we
  681. * can't be sure of this certain 'accept'.*/
  682. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
  683. ADDR_POLICY_ACCEPTED;
  684. } else {
  685. return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
  686. ADDR_POLICY_REJECTED;
  687. }
  688. } else {
  689. /* Might match. */
  690. if (tmpe->policy_type == ADDR_POLICY_REJECT)
  691. maybe_reject = 1;
  692. else
  693. maybe_accept = 1;
  694. }
  695. }
  696. } SMARTLIST_FOREACH_END(tmpe);
  697. /* accept all by default. */
  698. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  699. }
  700. /** Decide whether a given addr:port is definitely accepted,
  701. * definitely rejected, probably accepted, or probably rejected by a
  702. * given policy. If <b>addr</b> is 0, we don't know the IP of the
  703. * target address. If <b>port</b> is 0, we don't know the port of the
  704. * target address. (At least one of <b>addr</b> and <b>port</b> must be
  705. * provided. If you want to know whether a policy would definitely reject
  706. * an unknown address:port, use policy_is_reject_star().)
  707. *
  708. * We could do better by assuming that some ranges never match typical
  709. * addresses (127.0.0.1, and so on). But we'll try this for now.
  710. */
  711. MOCK_IMPL(addr_policy_result_t,
  712. compare_tor_addr_to_addr_policy,(const tor_addr_t *addr, uint16_t port,
  713. const smartlist_t *policy))
  714. {
  715. if (!policy) {
  716. /* no policy? accept all. */
  717. return ADDR_POLICY_ACCEPTED;
  718. } else if (addr == NULL || tor_addr_is_null(addr)) {
  719. if (port == 0) {
  720. log_info(LD_BUG, "Rejecting null address with 0 port (family %d)",
  721. addr ? tor_addr_family(addr) : -1);
  722. return ADDR_POLICY_REJECTED;
  723. }
  724. return compare_unknown_tor_addr_to_addr_policy(port, policy);
  725. } else if (port == 0) {
  726. return compare_known_tor_addr_to_addr_policy_noport(addr, policy);
  727. } else {
  728. return compare_known_tor_addr_to_addr_policy(addr, port, policy);
  729. }
  730. }
  731. /** Return true iff the address policy <b>a</b> covers every case that
  732. * would be covered by <b>b</b>, so that a,b is redundant. */
  733. static int
  734. addr_policy_covers(addr_policy_t *a, addr_policy_t *b)
  735. {
  736. if (tor_addr_family(&a->addr) != tor_addr_family(&b->addr)) {
  737. /* You can't cover a different family. */
  738. return 0;
  739. }
  740. /* We can ignore accept/reject, since "accept *:80, reject *:80" reduces
  741. * to "accept *:80". */
  742. if (a->maskbits > b->maskbits) {
  743. /* a has more fixed bits than b; it can't possibly cover b. */
  744. return 0;
  745. }
  746. if (tor_addr_compare_masked(&a->addr, &b->addr, a->maskbits, CMP_EXACT)) {
  747. /* There's a fixed bit in a that's set differently in b. */
  748. return 0;
  749. }
  750. return (a->prt_min <= b->prt_min && a->prt_max >= b->prt_max);
  751. }
  752. /** Return true iff the address policies <b>a</b> and <b>b</b> intersect,
  753. * that is, there exists an address/port that is covered by <b>a</b> that
  754. * is also covered by <b>b</b>.
  755. */
  756. static int
  757. addr_policy_intersects(addr_policy_t *a, addr_policy_t *b)
  758. {
  759. maskbits_t minbits;
  760. /* All the bits we care about are those that are set in both
  761. * netmasks. If they are equal in a and b's networkaddresses
  762. * then the networks intersect. If there is a difference,
  763. * then they do not. */
  764. if (a->maskbits < b->maskbits)
  765. minbits = a->maskbits;
  766. else
  767. minbits = b->maskbits;
  768. if (tor_addr_compare_masked(&a->addr, &b->addr, minbits, CMP_EXACT))
  769. return 0;
  770. if (a->prt_max < b->prt_min || b->prt_max < a->prt_min)
  771. return 0;
  772. return 1;
  773. }
  774. /** Add the exit policy described by <b>more</b> to <b>policy</b>.
  775. */
  776. static void
  777. append_exit_policy_string(smartlist_t **policy, const char *more)
  778. {
  779. config_line_t tmp;
  780. tmp.key = NULL;
  781. tmp.value = (char*) more;
  782. tmp.next = NULL;
  783. if (parse_addr_policy(&tmp, policy, -1)<0) {
  784. log_warn(LD_BUG, "Unable to parse internally generated policy %s",more);
  785. }
  786. }
  787. /** Add "reject <b>addr</b>:*" to <b>dest</b>, creating the list as needed. */
  788. void
  789. addr_policy_append_reject_addr(smartlist_t **dest, const tor_addr_t *addr)
  790. {
  791. addr_policy_t p, *add;
  792. memset(&p, 0, sizeof(p));
  793. p.policy_type = ADDR_POLICY_REJECT;
  794. p.maskbits = tor_addr_family(addr) == AF_INET6 ? 128 : 32;
  795. tor_addr_copy(&p.addr, addr);
  796. p.prt_min = 1;
  797. p.prt_max = 65535;
  798. add = addr_policy_get_canonical_entry(&p);
  799. if (!*dest)
  800. *dest = smartlist_new();
  801. smartlist_add(*dest, add);
  802. }
  803. /** Detect and excise "dead code" from the policy *<b>dest</b>. */
  804. static void
  805. exit_policy_remove_redundancies(smartlist_t *dest)
  806. {
  807. addr_policy_t *ap, *tmp;
  808. int i, j;
  809. /* Step one: kill every ipv4 thing after *4:*, every IPv6 thing after *6:*
  810. */
  811. {
  812. int kill_v4=0, kill_v6=0;
  813. for (i = 0; i < smartlist_len(dest); ++i) {
  814. sa_family_t family;
  815. ap = smartlist_get(dest, i);
  816. family = tor_addr_family(&ap->addr);
  817. if ((family == AF_INET && kill_v4) ||
  818. (family == AF_INET6 && kill_v6)) {
  819. smartlist_del_keeporder(dest, i--);
  820. addr_policy_free(ap);
  821. continue;
  822. }
  823. if (ap->maskbits == 0 && ap->prt_min <= 1 && ap->prt_max >= 65535) {
  824. /* This is a catch-all line -- later lines are unreachable. */
  825. if (family == AF_INET) {
  826. kill_v4 = 1;
  827. } else if (family == AF_INET6) {
  828. kill_v6 = 1;
  829. }
  830. }
  831. }
  832. }
  833. /* Step two: for every entry, see if there's a redundant entry
  834. * later on, and remove it. */
  835. for (i = 0; i < smartlist_len(dest)-1; ++i) {
  836. ap = smartlist_get(dest, i);
  837. for (j = i+1; j < smartlist_len(dest); ++j) {
  838. tmp = smartlist_get(dest, j);
  839. tor_assert(j > i);
  840. if (addr_policy_covers(ap, tmp)) {
  841. char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
  842. policy_write_item(p1, sizeof(p1), tmp, 0);
  843. policy_write_item(p2, sizeof(p2), ap, 0);
  844. log_debug(LD_CONFIG, "Removing exit policy %s (%d). It is made "
  845. "redundant by %s (%d).", p1, j, p2, i);
  846. smartlist_del_keeporder(dest, j--);
  847. addr_policy_free(tmp);
  848. }
  849. }
  850. }
  851. /* Step three: for every entry A, see if there's an entry B making this one
  852. * redundant later on. This is the case if A and B are of the same type
  853. * (accept/reject), A is a subset of B, and there is no other entry of
  854. * different type in between those two that intersects with A.
  855. *
  856. * Anybody want to double-check the logic here? XXX
  857. */
  858. for (i = 0; i < smartlist_len(dest)-1; ++i) {
  859. ap = smartlist_get(dest, i);
  860. for (j = i+1; j < smartlist_len(dest); ++j) {
  861. // tor_assert(j > i); // j starts out at i+1; j only increases; i only
  862. // // decreases.
  863. tmp = smartlist_get(dest, j);
  864. if (ap->policy_type != tmp->policy_type) {
  865. if (addr_policy_intersects(ap, tmp))
  866. break;
  867. } else { /* policy_types are equal. */
  868. if (addr_policy_covers(tmp, ap)) {
  869. char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
  870. policy_write_item(p1, sizeof(p1), ap, 0);
  871. policy_write_item(p2, sizeof(p2), tmp, 0);
  872. log_debug(LD_CONFIG, "Removing exit policy %s. It is already "
  873. "covered by %s.", p1, p2);
  874. smartlist_del_keeporder(dest, i--);
  875. addr_policy_free(ap);
  876. break;
  877. }
  878. }
  879. }
  880. }
  881. }
  882. #define DEFAULT_EXIT_POLICY \
  883. "reject *:25,reject *:119,reject *:135-139,reject *:445," \
  884. "reject *:563,reject *:1214,reject *:4661-4666," \
  885. "reject *:6346-6429,reject *:6699,reject *:6881-6999,accept *:*"
  886. /** Parse the exit policy <b>cfg</b> into the linked list *<b>dest</b>. If
  887. * cfg doesn't end in an absolute accept or reject and if
  888. * <b>add_default_policy</b> is true, add the default exit
  889. * policy afterwards. If <b>rejectprivate</b> is true, prepend
  890. * "reject private:*" to the policy. Return -1 if we can't parse cfg,
  891. * else return 0.
  892. *
  893. * This function is used to parse the exit policy from our torrc. For
  894. * the functions used to parse the exit policy from a router descriptor,
  895. * see router_add_exit_policy.
  896. */
  897. static int
  898. policies_parse_exit_policy_internal(config_line_t *cfg, smartlist_t **dest,
  899. int ipv6_exit,
  900. int rejectprivate,
  901. uint32_t local_address,
  902. int add_default_policy)
  903. {
  904. if (!ipv6_exit) {
  905. append_exit_policy_string(dest, "reject *6:*");
  906. }
  907. if (rejectprivate) {
  908. append_exit_policy_string(dest, "reject private:*");
  909. if (local_address) {
  910. char buf[POLICY_BUF_LEN];
  911. tor_snprintf(buf, sizeof(buf), "reject %s:*", fmt_addr32(local_address));
  912. append_exit_policy_string(dest, buf);
  913. }
  914. }
  915. if (parse_addr_policy(cfg, dest, -1))
  916. return -1;
  917. if (add_default_policy) {
  918. append_exit_policy_string(dest, DEFAULT_EXIT_POLICY);
  919. } else {
  920. append_exit_policy_string(dest, "reject *4:*");
  921. append_exit_policy_string(dest, "reject *6:*");
  922. }
  923. exit_policy_remove_redundancies(*dest);
  924. return 0;
  925. }
  926. /** Parse exit policy in <b>cfg</b> into <b>dest</b> smartlist.
  927. *
  928. * Add entry that rejects all IPv6 destinations unless
  929. * <b>EXIT_POLICY_IPV6_ENABLED</b> bit is set in <b>options</b> bitmask.
  930. *
  931. * If <b>EXIT_POLICY_REJECT_PRIVATE</b> bit is set in <b>options</b>,
  932. * do add entry that rejects all destinations in private subnetwork
  933. * Tor is running in.
  934. *
  935. * Respectively, if <b>EXIT_POLICY_ADD_DEFAULT</b> bit is set, add
  936. * default exit policy entries to <b>result</b> smartlist.
  937. */
  938. int
  939. policies_parse_exit_policy(config_line_t *cfg, smartlist_t **dest,
  940. exit_policy_parser_cfg_t options,
  941. uint32_t local_address)
  942. {
  943. int ipv6_enabled = (options & EXIT_POLICY_IPV6_ENABLED) ? 1 : 0;
  944. int reject_private = (options & EXIT_POLICY_REJECT_PRIVATE) ? 1 : 0;
  945. int add_default = (options & EXIT_POLICY_ADD_DEFAULT) ? 1 : 0;
  946. return policies_parse_exit_policy_internal(cfg,dest,ipv6_enabled,
  947. reject_private,
  948. local_address,
  949. add_default);
  950. }
  951. /** Parse <b>ExitPolicy</b> member of <b>or_options</b> into <b>result</b>
  952. * smartlist.
  953. * If <b>or_options->IPv6Exit</b> is false, add an entry that
  954. * rejects all IPv6 destinations.
  955. *
  956. * If <b>or_options->ExitPolicyRejectPrivate</b> is true, add entry that
  957. * rejects all destinations in the private subnetwork of machine Tor
  958. * instance is running in.
  959. *
  960. * If <b>or_options->BridgeRelay</b> is false, add entries of default
  961. * Tor exit policy into <b>result</b> smartlist.
  962. *
  963. * If or_options->ExitRelay is false, then make our exit policy into
  964. * "reject *:*" regardless.
  965. */
  966. int
  967. policies_parse_exit_policy_from_options(const or_options_t *or_options,
  968. uint32_t local_address,
  969. smartlist_t **result)
  970. {
  971. exit_policy_parser_cfg_t parser_cfg = 0;
  972. if (or_options->ExitRelay == 0) {
  973. append_exit_policy_string(result, "reject *4:*");
  974. append_exit_policy_string(result, "reject *6:*");
  975. return 0;
  976. }
  977. if (or_options->IPv6Exit) {
  978. parser_cfg |= EXIT_POLICY_IPV6_ENABLED;
  979. }
  980. if (or_options->ExitPolicyRejectPrivate) {
  981. parser_cfg |= EXIT_POLICY_REJECT_PRIVATE;
  982. }
  983. if (!or_options->BridgeRelay) {
  984. parser_cfg |= EXIT_POLICY_ADD_DEFAULT;
  985. }
  986. return policies_parse_exit_policy(or_options->ExitPolicy,result,
  987. parser_cfg,local_address);
  988. }
  989. /** Add "reject *:*" to the end of the policy in *<b>dest</b>, allocating
  990. * *<b>dest</b> as needed. */
  991. void
  992. policies_exit_policy_append_reject_star(smartlist_t **dest)
  993. {
  994. append_exit_policy_string(dest, "reject *4:*");
  995. append_exit_policy_string(dest, "reject *6:*");
  996. }
  997. /** Replace the exit policy of <b>node</b> with reject *:* */
  998. void
  999. policies_set_node_exitpolicy_to_reject_all(node_t *node)
  1000. {
  1001. node->rejects_all = 1;
  1002. }
  1003. /** Return 1 if there is at least one /8 subnet in <b>policy</b> that
  1004. * allows exiting to <b>port</b>. Otherwise, return 0. */
  1005. static int
  1006. exit_policy_is_general_exit_helper(smartlist_t *policy, int port)
  1007. {
  1008. uint32_t mask, ip, i;
  1009. /* Is this /8 rejected (1), or undecided (0)? */
  1010. char subnet_status[256];
  1011. memset(subnet_status, 0, sizeof(subnet_status));
  1012. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
  1013. if (tor_addr_family(&p->addr) != AF_INET)
  1014. continue; /* IPv4 only for now */
  1015. if (p->prt_min > port || p->prt_max < port)
  1016. continue; /* Doesn't cover our port. */
  1017. mask = 0;
  1018. tor_assert(p->maskbits <= 32);
  1019. if (p->maskbits)
  1020. mask = UINT32_MAX<<(32-p->maskbits);
  1021. ip = tor_addr_to_ipv4h(&p->addr);
  1022. /* Calculate the first and last subnet that this exit policy touches
  1023. * and set it as loop boundaries. */
  1024. for (i = ((mask & ip)>>24); i <= (~((mask & ip) ^ mask)>>24); ++i) {
  1025. tor_addr_t addr;
  1026. if (subnet_status[i] != 0)
  1027. continue; /* We already reject some part of this /8 */
  1028. tor_addr_from_ipv4h(&addr, i<<24);
  1029. if (tor_addr_is_internal(&addr, 0))
  1030. continue; /* Local or non-routable addresses */
  1031. if (p->policy_type == ADDR_POLICY_ACCEPT) {
  1032. if (p->maskbits > 8)
  1033. continue; /* Narrower than a /8. */
  1034. /* We found an allowed subnet of at least size /8. Done
  1035. * for this port! */
  1036. return 1;
  1037. } else if (p->policy_type == ADDR_POLICY_REJECT) {
  1038. subnet_status[i] = 1;
  1039. }
  1040. }
  1041. } SMARTLIST_FOREACH_END(p);
  1042. return 0;
  1043. }
  1044. /** Return true iff <b>ri</b> is "useful as an exit node", meaning
  1045. * it allows exit to at least one /8 address space for at least
  1046. * two of ports 80, 443, and 6667. */
  1047. int
  1048. exit_policy_is_general_exit(smartlist_t *policy)
  1049. {
  1050. static const int ports[] = { 80, 443, 6667 };
  1051. int n_allowed = 0;
  1052. int i;
  1053. if (!policy) /*XXXX disallow NULL policies? */
  1054. return 0;
  1055. for (i = 0; i < 3; ++i) {
  1056. n_allowed += exit_policy_is_general_exit_helper(policy, ports[i]);
  1057. }
  1058. return n_allowed >= 2;
  1059. }
  1060. /** Return false if <b>policy</b> might permit access to some addr:port;
  1061. * otherwise if we are certain it rejects everything, return true. */
  1062. int
  1063. policy_is_reject_star(const smartlist_t *policy, sa_family_t family)
  1064. {
  1065. if (!policy) /*XXXX disallow NULL policies? */
  1066. return 1;
  1067. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
  1068. if (p->policy_type == ADDR_POLICY_ACCEPT &&
  1069. (tor_addr_family(&p->addr) == family ||
  1070. tor_addr_family(&p->addr) == AF_UNSPEC)) {
  1071. return 0;
  1072. } else if (p->policy_type == ADDR_POLICY_REJECT &&
  1073. p->prt_min <= 1 && p->prt_max == 65535 &&
  1074. p->maskbits == 0 &&
  1075. (tor_addr_family(&p->addr) == family ||
  1076. tor_addr_family(&p->addr) == AF_UNSPEC)) {
  1077. return 1;
  1078. }
  1079. } SMARTLIST_FOREACH_END(p);
  1080. return 1;
  1081. }
  1082. /** Write a single address policy to the buf_len byte buffer at buf. Return
  1083. * the number of characters written, or -1 on failure. */
  1084. int
  1085. policy_write_item(char *buf, size_t buflen, addr_policy_t *policy,
  1086. int format_for_desc)
  1087. {
  1088. size_t written = 0;
  1089. char addrbuf[TOR_ADDR_BUF_LEN];
  1090. const char *addrpart;
  1091. int result;
  1092. const int is_accept = policy->policy_type == ADDR_POLICY_ACCEPT;
  1093. const sa_family_t family = tor_addr_family(&policy->addr);
  1094. const int is_ip6 = (family == AF_INET6);
  1095. tor_addr_to_str(addrbuf, &policy->addr, sizeof(addrbuf), 1);
  1096. /* write accept/reject 1.2.3.4 */
  1097. if (policy->is_private) {
  1098. addrpart = "private";
  1099. } else if (policy->maskbits == 0) {
  1100. if (format_for_desc)
  1101. addrpart = "*";
  1102. else if (family == AF_INET6)
  1103. addrpart = "*6";
  1104. else if (family == AF_INET)
  1105. addrpart = "*4";
  1106. else
  1107. addrpart = "*";
  1108. } else {
  1109. addrpart = addrbuf;
  1110. }
  1111. result = tor_snprintf(buf, buflen, "%s%s %s",
  1112. is_accept ? "accept" : "reject",
  1113. (is_ip6&&format_for_desc)?"6":"",
  1114. addrpart);
  1115. if (result < 0)
  1116. return -1;
  1117. written += strlen(buf);
  1118. /* If the maskbits is 32 we don't need to give it. If the mask is 0,
  1119. * we already wrote "*". */
  1120. if (policy->maskbits < 32 && policy->maskbits > 0) {
  1121. if (tor_snprintf(buf+written, buflen-written, "/%d", policy->maskbits)<0)
  1122. return -1;
  1123. written += strlen(buf+written);
  1124. }
  1125. if (policy->prt_min <= 1 && policy->prt_max == 65535) {
  1126. /* There is no port set; write ":*" */
  1127. if (written+4 > buflen)
  1128. return -1;
  1129. strlcat(buf+written, ":*", buflen-written);
  1130. written += 2;
  1131. } else if (policy->prt_min == policy->prt_max) {
  1132. /* There is only one port; write ":80". */
  1133. result = tor_snprintf(buf+written, buflen-written, ":%d", policy->prt_min);
  1134. if (result<0)
  1135. return -1;
  1136. written += result;
  1137. } else {
  1138. /* There is a range of ports; write ":79-80". */
  1139. result = tor_snprintf(buf+written, buflen-written, ":%d-%d",
  1140. policy->prt_min, policy->prt_max);
  1141. if (result<0)
  1142. return -1;
  1143. written += result;
  1144. }
  1145. if (written < buflen)
  1146. buf[written] = '\0';
  1147. else
  1148. return -1;
  1149. return (int)written;
  1150. }
  1151. /** Create a new exit policy summary, initially only with a single
  1152. * port 1-64k item */
  1153. /* XXXX This entire thing will do most stuff in O(N^2), or worse. Use an
  1154. * RB-tree if that turns out to matter. */
  1155. static smartlist_t *
  1156. policy_summary_create(void)
  1157. {
  1158. smartlist_t *summary;
  1159. policy_summary_item_t* item;
  1160. item = tor_malloc_zero(sizeof(policy_summary_item_t));
  1161. item->prt_min = 1;
  1162. item->prt_max = 65535;
  1163. item->reject_count = 0;
  1164. item->accepted = 0;
  1165. summary = smartlist_new();
  1166. smartlist_add(summary, item);
  1167. return summary;
  1168. }
  1169. /** Split the summary item in <b>item</b> at the port <b>new_starts</b>.
  1170. * The current item is changed to end at new-starts - 1, the new item
  1171. * copies reject_count and accepted from the old item,
  1172. * starts at new_starts and ends at the port where the original item
  1173. * previously ended.
  1174. */
  1175. static policy_summary_item_t*
  1176. policy_summary_item_split(policy_summary_item_t* old, uint16_t new_starts)
  1177. {
  1178. policy_summary_item_t* new;
  1179. new = tor_malloc_zero(sizeof(policy_summary_item_t));
  1180. new->prt_min = new_starts;
  1181. new->prt_max = old->prt_max;
  1182. new->reject_count = old->reject_count;
  1183. new->accepted = old->accepted;
  1184. old->prt_max = new_starts-1;
  1185. tor_assert(old->prt_min <= old->prt_max);
  1186. tor_assert(new->prt_min <= new->prt_max);
  1187. return new;
  1188. }
  1189. /* XXXX Nick says I'm going to hell for this. If he feels charitably towards
  1190. * my immortal soul, he can clean it up himself. */
  1191. #define AT(x) ((policy_summary_item_t*)smartlist_get(summary, x))
  1192. #define REJECT_CUTOFF_COUNT (1<<25)
  1193. /** Split an exit policy summary so that prt_min and prt_max
  1194. * fall at exactly the start and end of an item respectively.
  1195. */
  1196. static int
  1197. policy_summary_split(smartlist_t *summary,
  1198. uint16_t prt_min, uint16_t prt_max)
  1199. {
  1200. int start_at_index;
  1201. int i = 0;
  1202. while (AT(i)->prt_max < prt_min)
  1203. i++;
  1204. if (AT(i)->prt_min != prt_min) {
  1205. policy_summary_item_t* new_item;
  1206. new_item = policy_summary_item_split(AT(i), prt_min);
  1207. smartlist_insert(summary, i+1, new_item);
  1208. i++;
  1209. }
  1210. start_at_index = i;
  1211. while (AT(i)->prt_max < prt_max)
  1212. i++;
  1213. if (AT(i)->prt_max != prt_max) {
  1214. policy_summary_item_t* new_item;
  1215. new_item = policy_summary_item_split(AT(i), prt_max+1);
  1216. smartlist_insert(summary, i+1, new_item);
  1217. }
  1218. return start_at_index;
  1219. }
  1220. /** Mark port ranges as accepted if they are below the reject_count */
  1221. static void
  1222. policy_summary_accept(smartlist_t *summary,
  1223. uint16_t prt_min, uint16_t prt_max)
  1224. {
  1225. int i = policy_summary_split(summary, prt_min, prt_max);
  1226. while (i < smartlist_len(summary) &&
  1227. AT(i)->prt_max <= prt_max) {
  1228. if (!AT(i)->accepted &&
  1229. AT(i)->reject_count <= REJECT_CUTOFF_COUNT)
  1230. AT(i)->accepted = 1;
  1231. i++;
  1232. }
  1233. tor_assert(i < smartlist_len(summary) || prt_max==65535);
  1234. }
  1235. /** Count the number of addresses in a network with prefixlen maskbits
  1236. * against the given portrange. */
  1237. static void
  1238. policy_summary_reject(smartlist_t *summary,
  1239. maskbits_t maskbits,
  1240. uint16_t prt_min, uint16_t prt_max)
  1241. {
  1242. int i = policy_summary_split(summary, prt_min, prt_max);
  1243. /* XXX: ipv4 specific */
  1244. uint64_t count = (U64_LITERAL(1) << (32-maskbits));
  1245. while (i < smartlist_len(summary) &&
  1246. AT(i)->prt_max <= prt_max) {
  1247. AT(i)->reject_count += count;
  1248. i++;
  1249. }
  1250. tor_assert(i < smartlist_len(summary) || prt_max==65535);
  1251. }
  1252. /** Add a single exit policy item to our summary:
  1253. * If it is an accept ignore it unless it is for all IP addresses
  1254. * ("*"), i.e. it's prefixlen/maskbits is 0, else call
  1255. * policy_summary_accept().
  1256. * If it's a reject ignore it if it is about one of the private
  1257. * networks, else call policy_summary_reject().
  1258. */
  1259. static void
  1260. policy_summary_add_item(smartlist_t *summary, addr_policy_t *p)
  1261. {
  1262. if (p->policy_type == ADDR_POLICY_ACCEPT) {
  1263. if (p->maskbits == 0) {
  1264. policy_summary_accept(summary, p->prt_min, p->prt_max);
  1265. }
  1266. } else if (p->policy_type == ADDR_POLICY_REJECT) {
  1267. int is_private = 0;
  1268. int i;
  1269. for (i = 0; private_nets[i]; ++i) {
  1270. tor_addr_t addr;
  1271. maskbits_t maskbits;
  1272. if (tor_addr_parse_mask_ports(private_nets[i], 0, &addr,
  1273. &maskbits, NULL, NULL)<0) {
  1274. tor_assert(0);
  1275. }
  1276. if (tor_addr_compare(&p->addr, &addr, CMP_EXACT) == 0 &&
  1277. p->maskbits == maskbits) {
  1278. is_private = 1;
  1279. break;
  1280. }
  1281. }
  1282. if (!is_private) {
  1283. policy_summary_reject(summary, p->maskbits, p->prt_min, p->prt_max);
  1284. }
  1285. } else
  1286. tor_assert(0);
  1287. }
  1288. /** Create a string representing a summary for an exit policy.
  1289. * The summary will either be an "accept" plus a comma-separated list of port
  1290. * ranges or a "reject" plus port-ranges, depending on which is shorter.
  1291. *
  1292. * If no exits are allowed at all then "reject 1-65535" is returned. If no
  1293. * ports are blocked instead of "reject " we return "accept 1-65535". (These
  1294. * are an exception to the shorter-representation-wins rule).
  1295. */
  1296. char *
  1297. policy_summarize(smartlist_t *policy, sa_family_t family)
  1298. {
  1299. smartlist_t *summary = policy_summary_create();
  1300. smartlist_t *accepts, *rejects;
  1301. int i, last, start_prt;
  1302. size_t accepts_len, rejects_len;
  1303. char *accepts_str = NULL, *rejects_str = NULL, *shorter_str, *result;
  1304. const char *prefix;
  1305. tor_assert(policy);
  1306. /* Create the summary list */
  1307. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
  1308. sa_family_t f = tor_addr_family(&p->addr);
  1309. if (f != AF_INET && f != AF_INET6) {
  1310. log_warn(LD_BUG, "Weird family when summarizing address policy");
  1311. }
  1312. if (f != family)
  1313. continue;
  1314. /* XXXX-ipv6 More family work is needed */
  1315. policy_summary_add_item(summary, p);
  1316. } SMARTLIST_FOREACH_END(p);
  1317. /* Now create two lists of strings, one for accepted and one
  1318. * for rejected ports. We take care to merge ranges so that
  1319. * we avoid getting stuff like "1-4,5-9,10", instead we want
  1320. * "1-10"
  1321. */
  1322. i = 0;
  1323. start_prt = 1;
  1324. accepts = smartlist_new();
  1325. rejects = smartlist_new();
  1326. while (1) {
  1327. last = i == smartlist_len(summary)-1;
  1328. if (last ||
  1329. AT(i)->accepted != AT(i+1)->accepted) {
  1330. char buf[POLICY_BUF_LEN];
  1331. if (start_prt == AT(i)->prt_max)
  1332. tor_snprintf(buf, sizeof(buf), "%d", start_prt);
  1333. else
  1334. tor_snprintf(buf, sizeof(buf), "%d-%d", start_prt, AT(i)->prt_max);
  1335. if (AT(i)->accepted)
  1336. smartlist_add(accepts, tor_strdup(buf));
  1337. else
  1338. smartlist_add(rejects, tor_strdup(buf));
  1339. if (last)
  1340. break;
  1341. start_prt = AT(i+1)->prt_min;
  1342. };
  1343. i++;
  1344. };
  1345. /* Figure out which of the two stringlists will be shorter and use
  1346. * that to build the result
  1347. */
  1348. if (smartlist_len(accepts) == 0) { /* no exits at all */
  1349. result = tor_strdup("reject 1-65535");
  1350. goto cleanup;
  1351. }
  1352. if (smartlist_len(rejects) == 0) { /* no rejects at all */
  1353. result = tor_strdup("accept 1-65535");
  1354. goto cleanup;
  1355. }
  1356. accepts_str = smartlist_join_strings(accepts, ",", 0, &accepts_len);
  1357. rejects_str = smartlist_join_strings(rejects, ",", 0, &rejects_len);
  1358. if (rejects_len > MAX_EXITPOLICY_SUMMARY_LEN-strlen("reject")-1 &&
  1359. accepts_len > MAX_EXITPOLICY_SUMMARY_LEN-strlen("accept")-1) {
  1360. char *c;
  1361. shorter_str = accepts_str;
  1362. prefix = "accept";
  1363. c = shorter_str + (MAX_EXITPOLICY_SUMMARY_LEN-strlen(prefix)-1);
  1364. while (*c != ',' && c >= shorter_str)
  1365. c--;
  1366. tor_assert(c >= shorter_str);
  1367. tor_assert(*c == ',');
  1368. *c = '\0';
  1369. } else if (rejects_len < accepts_len) {
  1370. shorter_str = rejects_str;
  1371. prefix = "reject";
  1372. } else {
  1373. shorter_str = accepts_str;
  1374. prefix = "accept";
  1375. }
  1376. tor_asprintf(&result, "%s %s", prefix, shorter_str);
  1377. cleanup:
  1378. /* cleanup */
  1379. SMARTLIST_FOREACH(summary, policy_summary_item_t *, s, tor_free(s));
  1380. smartlist_free(summary);
  1381. tor_free(accepts_str);
  1382. SMARTLIST_FOREACH(accepts, char *, s, tor_free(s));
  1383. smartlist_free(accepts);
  1384. tor_free(rejects_str);
  1385. SMARTLIST_FOREACH(rejects, char *, s, tor_free(s));
  1386. smartlist_free(rejects);
  1387. return result;
  1388. }
  1389. /** Convert a summarized policy string into a short_policy_t. Return NULL
  1390. * if the string is not well-formed. */
  1391. short_policy_t *
  1392. parse_short_policy(const char *summary)
  1393. {
  1394. const char *orig_summary = summary;
  1395. short_policy_t *result;
  1396. int is_accept;
  1397. int n_entries;
  1398. short_policy_entry_t entries[MAX_EXITPOLICY_SUMMARY_LEN]; /* overkill */
  1399. const char *next;
  1400. if (!strcmpstart(summary, "accept ")) {
  1401. is_accept = 1;
  1402. summary += strlen("accept ");
  1403. } else if (!strcmpstart(summary, "reject ")) {
  1404. is_accept = 0;
  1405. summary += strlen("reject ");
  1406. } else {
  1407. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Unrecognized policy summary keyword");
  1408. return NULL;
  1409. }
  1410. n_entries = 0;
  1411. for ( ; *summary; summary = next) {
  1412. const char *comma = strchr(summary, ',');
  1413. unsigned low, high;
  1414. char dummy;
  1415. char ent_buf[32];
  1416. size_t len;
  1417. next = comma ? comma+1 : strchr(summary, '\0');
  1418. len = comma ? (size_t)(comma - summary) : strlen(summary);
  1419. if (n_entries == MAX_EXITPOLICY_SUMMARY_LEN) {
  1420. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Impossibly long policy summary %s",
  1421. escaped(orig_summary));
  1422. return NULL;
  1423. }
  1424. if (! TOR_ISDIGIT(*summary) || len > (sizeof(ent_buf)-1)) {
  1425. /* unrecognized entry format. skip it. */
  1426. continue;
  1427. }
  1428. if (len < 1) {
  1429. /* empty; skip it. */
  1430. /* XXX This happens to be unreachable, since if len==0, then *summary is
  1431. * ',' or '\0', and the TOR_ISDIGIT test above would have failed. */
  1432. continue;
  1433. }
  1434. memcpy(ent_buf, summary, len);
  1435. ent_buf[len] = '\0';
  1436. if (tor_sscanf(ent_buf, "%u-%u%c", &low, &high, &dummy) == 2) {
  1437. if (low<1 || low>65535 || high<1 || high>65535 || low>high) {
  1438. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  1439. "Found bad entry in policy summary %s", escaped(orig_summary));
  1440. return NULL;
  1441. }
  1442. } else if (tor_sscanf(ent_buf, "%u%c", &low, &dummy) == 1) {
  1443. if (low<1 || low>65535) {
  1444. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  1445. "Found bad entry in policy summary %s", escaped(orig_summary));
  1446. return NULL;
  1447. }
  1448. high = low;
  1449. } else {
  1450. log_fn(LOG_PROTOCOL_WARN, LD_DIR,"Found bad entry in policy summary %s",
  1451. escaped(orig_summary));
  1452. return NULL;
  1453. }
  1454. entries[n_entries].min_port = low;
  1455. entries[n_entries].max_port = high;
  1456. n_entries++;
  1457. }
  1458. if (n_entries == 0) {
  1459. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  1460. "Found no port-range entries in summary %s", escaped(orig_summary));
  1461. return NULL;
  1462. }
  1463. {
  1464. size_t size = STRUCT_OFFSET(short_policy_t, entries) +
  1465. sizeof(short_policy_entry_t)*(n_entries);
  1466. result = tor_malloc_zero(size);
  1467. tor_assert( (char*)&result->entries[n_entries-1] < ((char*)result)+size);
  1468. }
  1469. result->is_accept = is_accept;
  1470. result->n_entries = n_entries;
  1471. memcpy(result->entries, entries, sizeof(short_policy_entry_t)*n_entries);
  1472. return result;
  1473. }
  1474. /** Write <b>policy</b> back out into a string. Used only for unit tests
  1475. * currently. */
  1476. char *
  1477. write_short_policy(const short_policy_t *policy)
  1478. {
  1479. int i;
  1480. char *answer;
  1481. smartlist_t *sl = smartlist_new();
  1482. smartlist_add_asprintf(sl, "%s", policy->is_accept ? "accept " : "reject ");
  1483. for (i=0; i < policy->n_entries; i++) {
  1484. const short_policy_entry_t *e = &policy->entries[i];
  1485. if (e->min_port == e->max_port) {
  1486. smartlist_add_asprintf(sl, "%d", e->min_port);
  1487. } else {
  1488. smartlist_add_asprintf(sl, "%d-%d", e->min_port, e->max_port);
  1489. }
  1490. if (i < policy->n_entries-1)
  1491. smartlist_add(sl, tor_strdup(","));
  1492. }
  1493. answer = smartlist_join_strings(sl, "", 0, NULL);
  1494. SMARTLIST_FOREACH(sl, char *, a, tor_free(a));
  1495. smartlist_free(sl);
  1496. return answer;
  1497. }
  1498. /** Release all storage held in <b>policy</b>. */
  1499. void
  1500. short_policy_free(short_policy_t *policy)
  1501. {
  1502. tor_free(policy);
  1503. }
  1504. /** See whether the <b>addr</b>:<b>port</b> address is likely to be accepted
  1505. * or rejected by the summarized policy <b>policy</b>. Return values are as
  1506. * for compare_tor_addr_to_addr_policy. Unlike the regular addr_policy
  1507. * functions, requires the <b>port</b> be specified. */
  1508. addr_policy_result_t
  1509. compare_tor_addr_to_short_policy(const tor_addr_t *addr, uint16_t port,
  1510. const short_policy_t *policy)
  1511. {
  1512. int i;
  1513. int found_match = 0;
  1514. int accept;
  1515. tor_assert(port != 0);
  1516. if (addr && tor_addr_is_null(addr))
  1517. addr = NULL; /* Unspec means 'no address at all,' in this context. */
  1518. if (addr && get_options()->ClientRejectInternalAddresses &&
  1519. (tor_addr_is_internal(addr, 0) || tor_addr_is_loopback(addr)))
  1520. return ADDR_POLICY_REJECTED;
  1521. for (i=0; i < policy->n_entries; ++i) {
  1522. const short_policy_entry_t *e = &policy->entries[i];
  1523. if (e->min_port <= port && port <= e->max_port) {
  1524. found_match = 1;
  1525. break;
  1526. }
  1527. }
  1528. if (found_match)
  1529. accept = policy->is_accept;
  1530. else
  1531. accept = ! policy->is_accept;
  1532. /* ???? are these right? -NM */
  1533. /* We should be sure not to return ADDR_POLICY_ACCEPTED in the accept
  1534. * case here, because it would cause clients to believe that the node
  1535. * allows exit enclaving. Trying it anyway would open up a cool attack
  1536. * where the node refuses due to exitpolicy, the client reacts in
  1537. * surprise by rewriting the node's exitpolicy to reject *:*, and then
  1538. * a bad guy targets users by causing them to attempt such connections
  1539. * to 98% of the exits.
  1540. *
  1541. * Once microdescriptors can handle addresses in special cases (e.g. if
  1542. * we ever solve ticket 1774), we can provide certainty here. -RD */
  1543. if (accept)
  1544. return ADDR_POLICY_PROBABLY_ACCEPTED;
  1545. else
  1546. return ADDR_POLICY_REJECTED;
  1547. }
  1548. /** Return true iff <b>policy</b> seems reject all ports */
  1549. int
  1550. short_policy_is_reject_star(const short_policy_t *policy)
  1551. {
  1552. /* This doesn't need to be as much on the lookout as policy_is_reject_star,
  1553. * since policy summaries are from the consensus or from consensus
  1554. * microdescs.
  1555. */
  1556. tor_assert(policy);
  1557. /* Check for an exact match of "reject 1-65535". */
  1558. return (policy->is_accept == 0 && policy->n_entries == 1 &&
  1559. policy->entries[0].min_port == 1 &&
  1560. policy->entries[0].max_port == 65535);
  1561. }
  1562. /** Decide whether addr:port is probably or definitely accepted or rejected by
  1563. * <b>node</b>. See compare_tor_addr_to_addr_policy for details on addr/port
  1564. * interpretation. */
  1565. addr_policy_result_t
  1566. compare_tor_addr_to_node_policy(const tor_addr_t *addr, uint16_t port,
  1567. const node_t *node)
  1568. {
  1569. if (node->rejects_all)
  1570. return ADDR_POLICY_REJECTED;
  1571. if (addr && tor_addr_family(addr) == AF_INET6) {
  1572. const short_policy_t *p = NULL;
  1573. if (node->ri)
  1574. p = node->ri->ipv6_exit_policy;
  1575. else if (node->md)
  1576. p = node->md->ipv6_exit_policy;
  1577. if (p)
  1578. return compare_tor_addr_to_short_policy(addr, port, p);
  1579. else
  1580. return ADDR_POLICY_REJECTED;
  1581. }
  1582. if (node->ri) {
  1583. return compare_tor_addr_to_addr_policy(addr, port, node->ri->exit_policy);
  1584. } else if (node->md) {
  1585. if (node->md->exit_policy == NULL)
  1586. return ADDR_POLICY_REJECTED;
  1587. else
  1588. return compare_tor_addr_to_short_policy(addr, port,
  1589. node->md->exit_policy);
  1590. } else {
  1591. return ADDR_POLICY_PROBABLY_REJECTED;
  1592. }
  1593. }
  1594. /** Implementation for GETINFO control command: knows the answer for questions
  1595. * about "exit-policy/..." */
  1596. int
  1597. getinfo_helper_policies(control_connection_t *conn,
  1598. const char *question, char **answer,
  1599. const char **errmsg)
  1600. {
  1601. (void) conn;
  1602. (void) errmsg;
  1603. if (!strcmp(question, "exit-policy/default")) {
  1604. *answer = tor_strdup(DEFAULT_EXIT_POLICY);
  1605. } else if (!strcmpstart(question, "exit-policy/")) {
  1606. const routerinfo_t *me = router_get_my_routerinfo();
  1607. int include_ipv4 = 0;
  1608. int include_ipv6 = 0;
  1609. if (!strcmp(question, "exit-policy/ipv4")) {
  1610. include_ipv4 = 1;
  1611. } else if (!strcmp(question, "exit-policy/ipv6")) {
  1612. include_ipv6 = 1;
  1613. } else if (!strcmp(question, "exit-policy/full")) {
  1614. include_ipv4 = include_ipv6 = 1;
  1615. } else {
  1616. return 0; /* No such key. */
  1617. }
  1618. if (!me) {
  1619. *errmsg = "router_get_my_routerinfo returned NULL";
  1620. return -1;
  1621. }
  1622. *answer = router_dump_exit_policy_to_string(me,include_ipv4,include_ipv6);
  1623. }
  1624. return 0;
  1625. }
  1626. /** Release all storage held by <b>p</b>. */
  1627. void
  1628. addr_policy_list_free(smartlist_t *lst)
  1629. {
  1630. if (!lst)
  1631. return;
  1632. SMARTLIST_FOREACH(lst, addr_policy_t *, policy, addr_policy_free(policy));
  1633. smartlist_free(lst);
  1634. }
  1635. /** Release all storage held by <b>p</b>. */
  1636. void
  1637. addr_policy_free(addr_policy_t *p)
  1638. {
  1639. if (!p)
  1640. return;
  1641. if (--p->refcnt <= 0) {
  1642. if (p->is_canonical) {
  1643. policy_map_ent_t search, *found;
  1644. search.policy = p;
  1645. found = HT_REMOVE(policy_map, &policy_root, &search);
  1646. if (found) {
  1647. tor_assert(p == found->policy);
  1648. tor_free(found);
  1649. }
  1650. }
  1651. tor_free(p);
  1652. }
  1653. }
  1654. /** Release all storage held by policy variables. */
  1655. void
  1656. policies_free_all(void)
  1657. {
  1658. addr_policy_list_free(reachable_or_addr_policy);
  1659. reachable_or_addr_policy = NULL;
  1660. addr_policy_list_free(reachable_dir_addr_policy);
  1661. reachable_dir_addr_policy = NULL;
  1662. addr_policy_list_free(socks_policy);
  1663. socks_policy = NULL;
  1664. addr_policy_list_free(dir_policy);
  1665. dir_policy = NULL;
  1666. addr_policy_list_free(authdir_reject_policy);
  1667. authdir_reject_policy = NULL;
  1668. addr_policy_list_free(authdir_invalid_policy);
  1669. authdir_invalid_policy = NULL;
  1670. addr_policy_list_free(authdir_badexit_policy);
  1671. authdir_badexit_policy = NULL;
  1672. if (!HT_EMPTY(&policy_root)) {
  1673. policy_map_ent_t **ent;
  1674. int n = 0;
  1675. char buf[POLICY_BUF_LEN];
  1676. log_warn(LD_MM, "Still had %d address policies cached at shutdown.",
  1677. (int)HT_SIZE(&policy_root));
  1678. /* Note the first 10 cached policies to try to figure out where they
  1679. * might be coming from. */
  1680. HT_FOREACH(ent, policy_map, &policy_root) {
  1681. if (++n > 10)
  1682. break;
  1683. if (policy_write_item(buf, sizeof(buf), (*ent)->policy, 0) >= 0)
  1684. log_warn(LD_MM," %d [%d]: %s", n, (*ent)->policy->refcnt, buf);
  1685. }
  1686. }
  1687. HT_CLEAR(policy_map, &policy_root);
  1688. }