policies.c 67 KB

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