policies.c 64 KB

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