policies.c 71 KB

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