policies.c 102 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2016, 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. #define POLICIES_PRIVATE
  10. #include "or.h"
  11. #include "config.h"
  12. #include "dirserv.h"
  13. #include "networkstatus.h"
  14. #include "nodelist.h"
  15. #include "policies.h"
  16. #include "router.h"
  17. #include "routerparse.h"
  18. #include "geoip.h"
  19. #include "ht.h"
  20. /** Policy that addresses for incoming SOCKS connections must match. */
  21. static smartlist_t *socks_policy = NULL;
  22. /** Policy that addresses for incoming directory connections must match. */
  23. static smartlist_t *dir_policy = NULL;
  24. /** Policy that addresses for incoming router descriptors must match in order
  25. * to be published by us. */
  26. static smartlist_t *authdir_reject_policy = NULL;
  27. /** Policy that addresses for incoming router descriptors must match in order
  28. * to be marked as valid in our networkstatus. */
  29. static smartlist_t *authdir_invalid_policy = NULL;
  30. /** Policy that addresses for incoming router descriptors must <b>not</b>
  31. * match in order to not be marked as BadExit. */
  32. static smartlist_t *authdir_badexit_policy = NULL;
  33. /** Parsed addr_policy_t describing which addresses we believe we can start
  34. * circuits at. */
  35. static smartlist_t *reachable_or_addr_policy = NULL;
  36. /** Parsed addr_policy_t describing which addresses we believe we can connect
  37. * to directories at. */
  38. static smartlist_t *reachable_dir_addr_policy = NULL;
  39. /** Element of an exit policy summary */
  40. typedef struct policy_summary_item_t {
  41. uint16_t prt_min; /**< Lowest port number to accept/reject. */
  42. uint16_t prt_max; /**< Highest port number to accept/reject. */
  43. uint64_t reject_count; /**< Number of IP-Addresses that are rejected to
  44. this port range. */
  45. unsigned int accepted:1; /** Has this port already been accepted */
  46. } policy_summary_item_t;
  47. /** Private networks. This list is used in two places, once to expand the
  48. * "private" keyword when parsing our own exit policy, secondly to ignore
  49. * just such networks when building exit policy summaries. It is important
  50. * that all authorities agree on that list when creating summaries, so don't
  51. * just change this without a proper migration plan and a proposal and stuff.
  52. */
  53. static const char *private_nets[] = {
  54. "0.0.0.0/8", "169.254.0.0/16",
  55. "127.0.0.0/8", "192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12",
  56. "[::]/8",
  57. "[fc00::]/7", "[fe80::]/10", "[fec0::]/10", "[ff00::]/8", "[::]/127",
  58. NULL
  59. };
  60. static int policies_parse_exit_policy_internal(
  61. config_line_t *cfg,
  62. smartlist_t **dest,
  63. int ipv6_exit,
  64. int rejectprivate,
  65. const smartlist_t *configured_addresses,
  66. int reject_interface_addresses,
  67. int reject_configured_port_addresses,
  68. int add_default_policy);
  69. /** Replace all "private" entries in *<b>policy</b> with their expanded
  70. * equivalents. */
  71. void
  72. policy_expand_private(smartlist_t **policy)
  73. {
  74. uint16_t port_min, port_max;
  75. int i;
  76. smartlist_t *tmp;
  77. if (!*policy) /*XXXX disallow NULL policies? */
  78. return;
  79. tmp = smartlist_new();
  80. SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, p) {
  81. if (! p->is_private) {
  82. smartlist_add(tmp, p);
  83. continue;
  84. }
  85. for (i = 0; private_nets[i]; ++i) {
  86. addr_policy_t newpolicy;
  87. memcpy(&newpolicy, p, sizeof(addr_policy_t));
  88. newpolicy.is_private = 0;
  89. newpolicy.is_canonical = 0;
  90. if (tor_addr_parse_mask_ports(private_nets[i], 0,
  91. &newpolicy.addr,
  92. &newpolicy.maskbits, &port_min, &port_max)<0) {
  93. tor_assert_unreached();
  94. }
  95. smartlist_add(tmp, addr_policy_get_canonical_entry(&newpolicy));
  96. }
  97. addr_policy_free(p);
  98. } SMARTLIST_FOREACH_END(p);
  99. smartlist_free(*policy);
  100. *policy = tmp;
  101. }
  102. /** Expand each of the AF_UNSPEC elements in *<b>policy</b> (which indicate
  103. * protocol-neutral wildcards) into a pair of wildcard elements: one IPv4-
  104. * specific and one IPv6-specific. */
  105. void
  106. policy_expand_unspec(smartlist_t **policy)
  107. {
  108. smartlist_t *tmp;
  109. if (!*policy)
  110. return;
  111. tmp = smartlist_new();
  112. SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, p) {
  113. sa_family_t family = tor_addr_family(&p->addr);
  114. if (family == AF_INET6 || family == AF_INET || p->is_private) {
  115. smartlist_add(tmp, p);
  116. } else if (family == AF_UNSPEC) {
  117. addr_policy_t newpolicy_ipv4;
  118. addr_policy_t newpolicy_ipv6;
  119. memcpy(&newpolicy_ipv4, p, sizeof(addr_policy_t));
  120. memcpy(&newpolicy_ipv6, p, sizeof(addr_policy_t));
  121. newpolicy_ipv4.is_canonical = 0;
  122. newpolicy_ipv6.is_canonical = 0;
  123. if (p->maskbits != 0) {
  124. log_warn(LD_BUG, "AF_UNSPEC policy with maskbits==%d", p->maskbits);
  125. newpolicy_ipv4.maskbits = 0;
  126. newpolicy_ipv6.maskbits = 0;
  127. }
  128. tor_addr_from_ipv4h(&newpolicy_ipv4.addr, 0);
  129. tor_addr_from_ipv6_bytes(&newpolicy_ipv6.addr,
  130. "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
  131. smartlist_add(tmp, addr_policy_get_canonical_entry(&newpolicy_ipv4));
  132. smartlist_add(tmp, addr_policy_get_canonical_entry(&newpolicy_ipv6));
  133. addr_policy_free(p);
  134. } else {
  135. log_warn(LD_BUG, "Funny-looking address policy with family %d", family);
  136. smartlist_add(tmp, p);
  137. }
  138. } SMARTLIST_FOREACH_END(p);
  139. smartlist_free(*policy);
  140. *policy = tmp;
  141. }
  142. /**
  143. * Given a linked list of config lines containing "accept[6]" and "reject[6]"
  144. * tokens, parse them and append the result to <b>dest</b>. Return -1
  145. * if any tokens are malformed (and don't append any), else return 0.
  146. *
  147. * If <b>assume_action</b> is nonnegative, then insert its action
  148. * (ADDR_POLICY_ACCEPT or ADDR_POLICY_REJECT) for items that specify no
  149. * action.
  150. */
  151. static int
  152. parse_addr_policy(config_line_t *cfg, smartlist_t **dest,
  153. int assume_action)
  154. {
  155. smartlist_t *result;
  156. smartlist_t *entries;
  157. addr_policy_t *item;
  158. int malformed_list;
  159. int r = 0;
  160. if (!cfg)
  161. return 0;
  162. result = smartlist_new();
  163. entries = smartlist_new();
  164. for (; cfg; cfg = cfg->next) {
  165. smartlist_split_string(entries, cfg->value, ",",
  166. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  167. SMARTLIST_FOREACH_BEGIN(entries, const char *, ent) {
  168. log_debug(LD_CONFIG,"Adding new entry '%s'",ent);
  169. malformed_list = 0;
  170. item = router_parse_addr_policy_item_from_string(ent, assume_action,
  171. &malformed_list);
  172. if (item) {
  173. smartlist_add(result, item);
  174. } else if (malformed_list) {
  175. /* the error is so severe the entire list should be discarded */
  176. log_warn(LD_CONFIG, "Malformed policy '%s'. Discarding entire policy "
  177. "list.", ent);
  178. r = -1;
  179. } else {
  180. /* the error is minor: don't add the item, but keep processing the
  181. * rest of the policies in the list */
  182. log_debug(LD_CONFIG, "Ignored policy '%s' due to non-fatal error. "
  183. "The remainder of the policy list will be used.",
  184. ent);
  185. }
  186. } SMARTLIST_FOREACH_END(ent);
  187. SMARTLIST_FOREACH(entries, char *, ent, tor_free(ent));
  188. smartlist_clear(entries);
  189. }
  190. smartlist_free(entries);
  191. if (r == -1) {
  192. addr_policy_list_free(result);
  193. } else {
  194. policy_expand_private(&result);
  195. policy_expand_unspec(&result);
  196. if (*dest) {
  197. smartlist_add_all(*dest, result);
  198. smartlist_free(result);
  199. } else {
  200. *dest = result;
  201. }
  202. }
  203. return r;
  204. }
  205. /** Helper: parse the Reachable(Dir|OR)?Addresses fields into
  206. * reachable_(or|dir)_addr_policy. The options should already have
  207. * been validated by validate_addr_policies.
  208. */
  209. static int
  210. parse_reachable_addresses(void)
  211. {
  212. const or_options_t *options = get_options();
  213. int ret = 0;
  214. if (options->ReachableDirAddresses &&
  215. options->ReachableORAddresses &&
  216. options->ReachableAddresses) {
  217. log_warn(LD_CONFIG,
  218. "Both ReachableDirAddresses and ReachableORAddresses are set. "
  219. "ReachableAddresses setting will be ignored.");
  220. }
  221. addr_policy_list_free(reachable_or_addr_policy);
  222. reachable_or_addr_policy = NULL;
  223. if (!options->ReachableORAddresses && options->ReachableAddresses)
  224. log_info(LD_CONFIG,
  225. "Using ReachableAddresses as ReachableORAddresses.");
  226. if (parse_addr_policy(options->ReachableORAddresses ?
  227. options->ReachableORAddresses :
  228. options->ReachableAddresses,
  229. &reachable_or_addr_policy, ADDR_POLICY_ACCEPT)) {
  230. log_warn(LD_CONFIG,
  231. "Error parsing Reachable%sAddresses entry; ignoring.",
  232. options->ReachableORAddresses ? "OR" : "");
  233. ret = -1;
  234. }
  235. addr_policy_list_free(reachable_dir_addr_policy);
  236. reachable_dir_addr_policy = NULL;
  237. if (!options->ReachableDirAddresses && options->ReachableAddresses)
  238. log_info(LD_CONFIG,
  239. "Using ReachableAddresses as ReachableDirAddresses");
  240. if (parse_addr_policy(options->ReachableDirAddresses ?
  241. options->ReachableDirAddresses :
  242. options->ReachableAddresses,
  243. &reachable_dir_addr_policy, ADDR_POLICY_ACCEPT)) {
  244. if (options->ReachableDirAddresses)
  245. log_warn(LD_CONFIG,
  246. "Error parsing ReachableDirAddresses entry; ignoring.");
  247. ret = -1;
  248. }
  249. /* We ignore ReachableAddresses for relays */
  250. if (!server_mode(options)) {
  251. if (policy_is_reject_star(reachable_or_addr_policy, AF_UNSPEC, 0)
  252. || policy_is_reject_star(reachable_dir_addr_policy, AF_UNSPEC,0)) {
  253. log_warn(LD_CONFIG, "Tor cannot connect to the Internet if "
  254. "ReachableAddresses, ReachableORAddresses, or "
  255. "ReachableDirAddresses reject all addresses. Please accept "
  256. "some addresses in these options.");
  257. } else if (options->ClientUseIPv4 == 1
  258. && (policy_is_reject_star(reachable_or_addr_policy, AF_INET, 0)
  259. || policy_is_reject_star(reachable_dir_addr_policy, AF_INET, 0))) {
  260. log_warn(LD_CONFIG, "You have set ClientUseIPv4 1, but "
  261. "ReachableAddresses, ReachableORAddresses, or "
  262. "ReachableDirAddresses reject all IPv4 addresses. "
  263. "Tor will not connect using IPv4.");
  264. } else if (fascist_firewall_use_ipv6(options)
  265. && (policy_is_reject_star(reachable_or_addr_policy, AF_INET6, 0)
  266. || policy_is_reject_star(reachable_dir_addr_policy, AF_INET6, 0))) {
  267. log_warn(LD_CONFIG, "You have configured tor to use IPv6 "
  268. "(ClientUseIPv6 1 or UseBridges 1), but "
  269. "ReachableAddresses, ReachableORAddresses, or "
  270. "ReachableDirAddresses reject all IPv6 addresses. "
  271. "Tor will not connect using IPv6.");
  272. }
  273. }
  274. return ret;
  275. }
  276. /* Return true iff ClientUseIPv4 0 or ClientUseIPv6 0 might block any OR or Dir
  277. * address:port combination. */
  278. static int
  279. firewall_is_fascist_impl(void)
  280. {
  281. const or_options_t *options = get_options();
  282. /* Assume every non-bridge relay has an IPv4 address.
  283. * Clients which use bridges may only know the IPv6 address of their
  284. * bridge. */
  285. return (options->ClientUseIPv4 == 0
  286. || (!fascist_firewall_use_ipv6(options)
  287. && options->UseBridges == 1));
  288. }
  289. /** Return true iff the firewall options, including ClientUseIPv4 0 and
  290. * ClientUseIPv6 0, might block any OR address:port combination.
  291. * Address preferences may still change which address is selected even if
  292. * this function returns false.
  293. */
  294. int
  295. firewall_is_fascist_or(void)
  296. {
  297. return (reachable_or_addr_policy != NULL || firewall_is_fascist_impl());
  298. }
  299. /** Return true iff the firewall options, including ClientUseIPv4 0 and
  300. * ClientUseIPv6 0, might block any Dir address:port combination.
  301. * Address preferences may still change which address is selected even if
  302. * this function returns false.
  303. */
  304. int
  305. firewall_is_fascist_dir(void)
  306. {
  307. return (reachable_dir_addr_policy != NULL || firewall_is_fascist_impl());
  308. }
  309. /** Return true iff <b>policy</b> (possibly NULL) will allow a
  310. * connection to <b>addr</b>:<b>port</b>.
  311. */
  312. static int
  313. addr_policy_permits_tor_addr(const tor_addr_t *addr, uint16_t port,
  314. smartlist_t *policy)
  315. {
  316. addr_policy_result_t p;
  317. p = compare_tor_addr_to_addr_policy(addr, port, policy);
  318. switch (p) {
  319. case ADDR_POLICY_PROBABLY_ACCEPTED:
  320. case ADDR_POLICY_ACCEPTED:
  321. return 1;
  322. case ADDR_POLICY_PROBABLY_REJECTED:
  323. case ADDR_POLICY_REJECTED:
  324. return 0;
  325. default:
  326. log_warn(LD_BUG, "Unexpected result: %d", (int)p);
  327. return 0;
  328. }
  329. }
  330. /** Return true iff <b> policy</b> (possibly NULL) will allow a connection to
  331. * <b>addr</b>:<b>port</b>. <b>addr</b> is an IPv4 address given in host
  332. * order. */
  333. /* XXXX deprecate when possible. */
  334. static int
  335. addr_policy_permits_address(uint32_t addr, uint16_t port,
  336. smartlist_t *policy)
  337. {
  338. tor_addr_t a;
  339. tor_addr_from_ipv4h(&a, addr);
  340. return addr_policy_permits_tor_addr(&a, port, policy);
  341. }
  342. /** Return true iff we think our firewall will let us make a connection to
  343. * addr:port.
  344. *
  345. * If we are configured as a server, ignore any address family preference and
  346. * just use IPv4.
  347. * Otherwise:
  348. * - return false for all IPv4 addresses:
  349. * - if ClientUseIPv4 is 0, or
  350. * if pref_only and pref_ipv6 are both true;
  351. * - return false for all IPv6 addresses:
  352. * - if fascist_firewall_use_ipv6() is 0, or
  353. * - if pref_only is true and pref_ipv6 is false.
  354. *
  355. * Return false if addr is NULL or tor_addr_is_null(), or if port is 0. */
  356. STATIC int
  357. fascist_firewall_allows_address(const tor_addr_t *addr,
  358. uint16_t port,
  359. smartlist_t *firewall_policy,
  360. int pref_only, int pref_ipv6)
  361. {
  362. const or_options_t *options = get_options();
  363. const int client_mode = !server_mode(options);
  364. if (!addr || tor_addr_is_null(addr) || !port) {
  365. return 0;
  366. }
  367. /* Clients stop using IPv4 if it's disabled. In most cases, clients also
  368. * stop using IPv4 if it's not preferred.
  369. * Servers must have IPv4 enabled and preferred. */
  370. if (tor_addr_family(addr) == AF_INET && client_mode &&
  371. (!options->ClientUseIPv4 || (pref_only && pref_ipv6))) {
  372. return 0;
  373. }
  374. /* Clients and Servers won't use IPv6 unless it's enabled (and in most
  375. * cases, IPv6 must also be preferred before it will be used). */
  376. if (tor_addr_family(addr) == AF_INET6 &&
  377. (!fascist_firewall_use_ipv6(options) || (pref_only && !pref_ipv6))) {
  378. return 0;
  379. }
  380. return addr_policy_permits_tor_addr(addr, port,
  381. firewall_policy);
  382. }
  383. /** Is this client configured to use IPv6?
  384. * Use node_ipv6_or/dir_preferred() when checking a specific node and OR/Dir
  385. * port: it supports bridge client per-node IPv6 preferences.
  386. */
  387. int
  388. fascist_firewall_use_ipv6(const or_options_t *options)
  389. {
  390. /* Clients use IPv6 if it's set, or they use bridges, or they don't use
  391. * IPv4 */
  392. return (options->ClientUseIPv6 == 1 || options->UseBridges == 1
  393. || options->ClientUseIPv4 == 0);
  394. }
  395. /** Do we prefer to connect to IPv6, ignoring ClientPreferIPv6ORPort and
  396. * ClientPreferIPv6DirPort?
  397. * If we're unsure, return -1, otherwise, return 1 for IPv6 and 0 for IPv4.
  398. */
  399. static int
  400. fascist_firewall_prefer_ipv6_impl(const or_options_t *options)
  401. {
  402. /*
  403. Cheap implementation of config options ClientUseIPv4 & ClientUseIPv6 --
  404. If we're a server or IPv6 is disabled, use IPv4.
  405. If IPv4 is disabled, use IPv6.
  406. */
  407. if (server_mode(options) || !fascist_firewall_use_ipv6(options)) {
  408. return 0;
  409. }
  410. if (!options->ClientUseIPv4) {
  411. return 1;
  412. }
  413. return -1;
  414. }
  415. /** Do we prefer to connect to IPv6 ORPorts?
  416. * Use node_ipv6_or_preferred() whenever possible: it supports bridge client
  417. * per-node IPv6 preferences.
  418. */
  419. int
  420. fascist_firewall_prefer_ipv6_orport(const or_options_t *options)
  421. {
  422. int pref_ipv6 = fascist_firewall_prefer_ipv6_impl(options);
  423. if (pref_ipv6 >= 0) {
  424. return pref_ipv6;
  425. }
  426. /* We can use both IPv4 and IPv6 - which do we prefer? */
  427. if (options->ClientPreferIPv6ORPort == 1) {
  428. return 1;
  429. }
  430. return 0;
  431. }
  432. /** Do we prefer to connect to IPv6 DirPorts?
  433. *
  434. * (node_ipv6_dir_preferred() doesn't support bridge client per-node IPv6
  435. * preferences. There's no reason to use it instead of this function.)
  436. */
  437. int
  438. fascist_firewall_prefer_ipv6_dirport(const or_options_t *options)
  439. {
  440. int pref_ipv6 = fascist_firewall_prefer_ipv6_impl(options);
  441. if (pref_ipv6 >= 0) {
  442. return pref_ipv6;
  443. }
  444. /* We can use both IPv4 and IPv6 - which do we prefer? */
  445. if (options->ClientPreferIPv6DirPort == 1) {
  446. return 1;
  447. }
  448. return 0;
  449. }
  450. /** Return true iff we think our firewall will let us make a connection to
  451. * addr:port. Uses ReachableORAddresses or ReachableDirAddresses based on
  452. * fw_connection.
  453. * If pref_only is true, return true if addr is in the client's preferred
  454. * address family, which is IPv6 if pref_ipv6 is true, and IPv4 otherwise.
  455. * If pref_only is false, ignore pref_ipv6, and return true if addr is allowed.
  456. */
  457. int
  458. fascist_firewall_allows_address_addr(const tor_addr_t *addr, uint16_t port,
  459. firewall_connection_t fw_connection,
  460. int pref_only, int pref_ipv6)
  461. {
  462. if (fw_connection == FIREWALL_OR_CONNECTION) {
  463. return fascist_firewall_allows_address(addr, port,
  464. reachable_or_addr_policy,
  465. pref_only, pref_ipv6);
  466. } else if (fw_connection == FIREWALL_DIR_CONNECTION) {
  467. return fascist_firewall_allows_address(addr, port,
  468. reachable_dir_addr_policy,
  469. pref_only, pref_ipv6);
  470. } else {
  471. log_warn(LD_BUG, "Bad firewall_connection_t value %d.",
  472. fw_connection);
  473. return 0;
  474. }
  475. }
  476. /** Return true iff we think our firewall will let us make a connection to
  477. * addr:port (ap). Uses ReachableORAddresses or ReachableDirAddresses based on
  478. * fw_connection.
  479. * pref_only and pref_ipv6 work as in fascist_firewall_allows_address_addr().
  480. */
  481. static int
  482. fascist_firewall_allows_address_ap(const tor_addr_port_t *ap,
  483. firewall_connection_t fw_connection,
  484. int pref_only, int pref_ipv6)
  485. {
  486. tor_assert(ap);
  487. return fascist_firewall_allows_address_addr(&ap->addr, ap->port,
  488. fw_connection, pref_only,
  489. pref_ipv6);
  490. }
  491. /* Return true iff we think our firewall will let us make a connection to
  492. * ipv4h_or_addr:ipv4_or_port. ipv4h_or_addr is interpreted in host order.
  493. * Uses ReachableORAddresses or ReachableDirAddresses based on
  494. * fw_connection.
  495. * pref_only and pref_ipv6 work as in fascist_firewall_allows_address_addr().
  496. */
  497. static int
  498. fascist_firewall_allows_address_ipv4h(uint32_t ipv4h_or_addr,
  499. uint16_t ipv4_or_port,
  500. firewall_connection_t fw_connection,
  501. int pref_only, int pref_ipv6)
  502. {
  503. tor_addr_t ipv4_or_addr;
  504. tor_addr_from_ipv4h(&ipv4_or_addr, ipv4h_or_addr);
  505. return fascist_firewall_allows_address_addr(&ipv4_or_addr, ipv4_or_port,
  506. fw_connection, pref_only,
  507. pref_ipv6);
  508. }
  509. /** Return true iff we think our firewall will let us make a connection to
  510. * ipv4h_addr/ipv6_addr. Uses ipv4_orport/ipv6_orport/ReachableORAddresses or
  511. * ipv4_dirport/ipv6_dirport/ReachableDirAddresses based on IPv4/IPv6 and
  512. * <b>fw_connection</b>.
  513. * pref_only and pref_ipv6 work as in fascist_firewall_allows_address_addr().
  514. */
  515. static int
  516. fascist_firewall_allows_base(uint32_t ipv4h_addr, uint16_t ipv4_orport,
  517. uint16_t ipv4_dirport,
  518. const tor_addr_t *ipv6_addr, uint16_t ipv6_orport,
  519. uint16_t ipv6_dirport,
  520. firewall_connection_t fw_connection,
  521. int pref_only, int pref_ipv6)
  522. {
  523. if (fascist_firewall_allows_address_ipv4h(ipv4h_addr,
  524. (fw_connection == FIREWALL_OR_CONNECTION
  525. ? ipv4_orport
  526. : ipv4_dirport),
  527. fw_connection,
  528. pref_only, pref_ipv6)) {
  529. return 1;
  530. }
  531. if (fascist_firewall_allows_address_addr(ipv6_addr,
  532. (fw_connection == FIREWALL_OR_CONNECTION
  533. ? ipv6_orport
  534. : ipv6_dirport),
  535. fw_connection,
  536. pref_only, pref_ipv6)) {
  537. return 1;
  538. }
  539. return 0;
  540. }
  541. /** Like fascist_firewall_allows_base(), but takes ri. */
  542. static int
  543. fascist_firewall_allows_ri_impl(const routerinfo_t *ri,
  544. firewall_connection_t fw_connection,
  545. int pref_only, int pref_ipv6)
  546. {
  547. if (!ri) {
  548. return 0;
  549. }
  550. /* Assume IPv4 and IPv6 DirPorts are the same */
  551. return fascist_firewall_allows_base(ri->addr, ri->or_port, ri->dir_port,
  552. &ri->ipv6_addr, ri->ipv6_orport,
  553. ri->dir_port, fw_connection, pref_only,
  554. pref_ipv6);
  555. }
  556. /** Like fascist_firewall_allows_rs, but takes pref_ipv6. */
  557. static int
  558. fascist_firewall_allows_rs_impl(const routerstatus_t *rs,
  559. firewall_connection_t fw_connection,
  560. int pref_only, int pref_ipv6)
  561. {
  562. if (!rs) {
  563. return 0;
  564. }
  565. /* Assume IPv4 and IPv6 DirPorts are the same */
  566. return fascist_firewall_allows_base(rs->addr, rs->or_port, rs->dir_port,
  567. &rs->ipv6_addr, rs->ipv6_orport,
  568. rs->dir_port, fw_connection, pref_only,
  569. pref_ipv6);
  570. }
  571. /** Like fascist_firewall_allows_base(), but takes rs.
  572. * When rs is a fake_status from a dir_server_t, it can have a reachable
  573. * address, even when the corresponding node does not.
  574. * nodes can be missing addresses when there's no consensus (IPv4 and IPv6),
  575. * or when there is a microdescriptor consensus, but no microdescriptors
  576. * (microdescriptors have IPv6, the microdesc consensus does not). */
  577. int
  578. fascist_firewall_allows_rs(const routerstatus_t *rs,
  579. firewall_connection_t fw_connection, int pref_only)
  580. {
  581. if (!rs) {
  582. return 0;
  583. }
  584. /* We don't have access to the node-specific IPv6 preference, so use the
  585. * generic IPv6 preference instead. */
  586. const or_options_t *options = get_options();
  587. int pref_ipv6 = (fw_connection == FIREWALL_OR_CONNECTION
  588. ? fascist_firewall_prefer_ipv6_orport(options)
  589. : fascist_firewall_prefer_ipv6_dirport(options));
  590. return fascist_firewall_allows_rs_impl(rs, fw_connection, pref_only,
  591. pref_ipv6);
  592. }
  593. /** Return true iff we think our firewall will let us make a connection to
  594. * ipv6_addr:ipv6_orport based on ReachableORAddresses.
  595. * If <b>fw_connection</b> is FIREWALL_DIR_CONNECTION, returns 0.
  596. * pref_only and pref_ipv6 work as in fascist_firewall_allows_address_addr().
  597. */
  598. static int
  599. fascist_firewall_allows_md_impl(const microdesc_t *md,
  600. firewall_connection_t fw_connection,
  601. int pref_only, int pref_ipv6)
  602. {
  603. if (!md) {
  604. return 0;
  605. }
  606. /* Can't check dirport, it doesn't have one */
  607. if (fw_connection == FIREWALL_DIR_CONNECTION) {
  608. return 0;
  609. }
  610. /* Also can't check IPv4, doesn't have that either */
  611. return fascist_firewall_allows_address_addr(&md->ipv6_addr, md->ipv6_orport,
  612. fw_connection, pref_only,
  613. pref_ipv6);
  614. }
  615. /** Like fascist_firewall_allows_base(), but takes node, and looks up pref_ipv6
  616. * from node_ipv6_or/dir_preferred(). */
  617. int
  618. fascist_firewall_allows_node(const node_t *node,
  619. firewall_connection_t fw_connection,
  620. int pref_only)
  621. {
  622. if (!node) {
  623. return 0;
  624. }
  625. node_assert_ok(node);
  626. const int pref_ipv6 = (fw_connection == FIREWALL_OR_CONNECTION
  627. ? node_ipv6_or_preferred(node)
  628. : node_ipv6_dir_preferred(node));
  629. /* Sometimes, the rs is missing the IPv6 address info, and we need to go
  630. * all the way to the md */
  631. if (node->ri && fascist_firewall_allows_ri_impl(node->ri, fw_connection,
  632. pref_only, pref_ipv6)) {
  633. return 1;
  634. } else if (node->rs && fascist_firewall_allows_rs_impl(node->rs,
  635. fw_connection,
  636. pref_only,
  637. pref_ipv6)) {
  638. return 1;
  639. } else if (node->md && fascist_firewall_allows_md_impl(node->md,
  640. fw_connection,
  641. pref_only,
  642. pref_ipv6)) {
  643. return 1;
  644. } else {
  645. /* If we know nothing, assume it's unreachable, we'll never get an address
  646. * to connect to. */
  647. return 0;
  648. }
  649. }
  650. /** Like fascist_firewall_allows_rs(), but takes ds. */
  651. int
  652. fascist_firewall_allows_dir_server(const dir_server_t *ds,
  653. firewall_connection_t fw_connection,
  654. int pref_only)
  655. {
  656. if (!ds) {
  657. return 0;
  658. }
  659. /* A dir_server_t always has a fake_status. As long as it has the same
  660. * addresses/ports in both fake_status and dir_server_t, this works fine.
  661. * (See #17867.)
  662. * fascist_firewall_allows_rs only checks the addresses in fake_status. */
  663. return fascist_firewall_allows_rs(&ds->fake_status, fw_connection,
  664. pref_only);
  665. }
  666. /** If a and b are both valid and allowed by fw_connection,
  667. * choose one based on want_a and return it.
  668. * Otherwise, return whichever is allowed.
  669. * Otherwise, return NULL.
  670. * pref_only and pref_ipv6 work as in fascist_firewall_allows_address_addr().
  671. */
  672. static const tor_addr_port_t *
  673. fascist_firewall_choose_address_impl(const tor_addr_port_t *a,
  674. const tor_addr_port_t *b,
  675. int want_a,
  676. firewall_connection_t fw_connection,
  677. int pref_only, int pref_ipv6)
  678. {
  679. const tor_addr_port_t *use_a = NULL;
  680. const tor_addr_port_t *use_b = NULL;
  681. if (fascist_firewall_allows_address_ap(a, fw_connection, pref_only,
  682. pref_ipv6)) {
  683. use_a = a;
  684. }
  685. if (fascist_firewall_allows_address_ap(b, fw_connection, pref_only,
  686. pref_ipv6)) {
  687. use_b = b;
  688. }
  689. /* If both are allowed */
  690. if (use_a && use_b) {
  691. /* Choose a if we want it */
  692. return (want_a ? use_a : use_b);
  693. } else {
  694. /* Choose a if we have it */
  695. return (use_a ? use_a : use_b);
  696. }
  697. }
  698. /** If a and b are both valid and preferred by fw_connection,
  699. * choose one based on want_a and return it.
  700. * Otherwise, return whichever is preferred.
  701. * If neither are preferred, and pref_only is false:
  702. * - If a and b are both allowed by fw_connection,
  703. * choose one based on want_a and return it.
  704. * - Otherwise, return whichever is preferred.
  705. * Otherwise, return NULL. */
  706. STATIC const tor_addr_port_t *
  707. fascist_firewall_choose_address(const tor_addr_port_t *a,
  708. const tor_addr_port_t *b,
  709. int want_a,
  710. firewall_connection_t fw_connection,
  711. int pref_only, int pref_ipv6)
  712. {
  713. const tor_addr_port_t *pref = fascist_firewall_choose_address_impl(
  714. a, b, want_a,
  715. fw_connection,
  716. 1, pref_ipv6);
  717. if (pref_only || pref) {
  718. /* If there is a preferred address, use it. If we can only use preferred
  719. * addresses, and neither address is preferred, pref will be NULL, and we
  720. * want to return NULL, so return it. */
  721. return pref;
  722. } else {
  723. /* If there's no preferred address, and we can return addresses that are
  724. * not preferred, use an address that's allowed */
  725. return fascist_firewall_choose_address_impl(a, b, want_a, fw_connection,
  726. 0, pref_ipv6);
  727. }
  728. }
  729. /** Copy an address and port into <b>ap</b> that we think our firewall will
  730. * let us connect to. Uses ipv4_addr/ipv6_addr and
  731. * ipv4_orport/ipv6_orport/ReachableORAddresses or
  732. * ipv4_dirport/ipv6_dirport/ReachableDirAddresses based on IPv4/IPv6 and
  733. * <b>fw_connection</b>.
  734. * If pref_only, only choose preferred addresses. In either case, choose
  735. * a preferred address before an address that's not preferred.
  736. * If both addresses could be chosen (they are both preferred or both allowed)
  737. * choose IPv6 if pref_ipv6 is true, otherwise choose IPv4.
  738. * If neither address is chosen, return 0, else return 1. */
  739. static int
  740. fascist_firewall_choose_address_base(const tor_addr_t *ipv4_addr,
  741. uint16_t ipv4_orport,
  742. uint16_t ipv4_dirport,
  743. const tor_addr_t *ipv6_addr,
  744. uint16_t ipv6_orport,
  745. uint16_t ipv6_dirport,
  746. firewall_connection_t fw_connection,
  747. int pref_only,
  748. int pref_ipv6,
  749. tor_addr_port_t* ap)
  750. {
  751. const tor_addr_port_t *result = NULL;
  752. const int want_ipv4 = !pref_ipv6;
  753. tor_assert(ipv6_addr);
  754. tor_assert(ap);
  755. tor_addr_port_t ipv4_ap;
  756. tor_addr_copy(&ipv4_ap.addr, ipv4_addr);
  757. ipv4_ap.port = (fw_connection == FIREWALL_OR_CONNECTION
  758. ? ipv4_orport
  759. : ipv4_dirport);
  760. tor_addr_port_t ipv6_ap;
  761. tor_addr_copy(&ipv6_ap.addr, ipv6_addr);
  762. ipv6_ap.port = (fw_connection == FIREWALL_OR_CONNECTION
  763. ? ipv6_orport
  764. : ipv6_dirport);
  765. result = fascist_firewall_choose_address(&ipv4_ap, &ipv6_ap,
  766. want_ipv4,
  767. fw_connection, pref_only,
  768. pref_ipv6);
  769. if (result) {
  770. tor_addr_copy(&ap->addr, &result->addr);
  771. ap->port = result->port;
  772. return 1;
  773. } else {
  774. return 0;
  775. }
  776. }
  777. /** Like fascist_firewall_choose_address_base(), but takes a host-order IPv4
  778. * address as the first parameter. */
  779. static int
  780. fascist_firewall_choose_address_ipv4h(uint32_t ipv4h_addr,
  781. uint16_t ipv4_orport,
  782. uint16_t ipv4_dirport,
  783. const tor_addr_t *ipv6_addr,
  784. uint16_t ipv6_orport,
  785. uint16_t ipv6_dirport,
  786. firewall_connection_t fw_connection,
  787. int pref_only,
  788. int pref_ipv6,
  789. tor_addr_port_t* ap)
  790. {
  791. tor_addr_t ipv4_addr;
  792. tor_addr_from_ipv4h(&ipv4_addr, ipv4h_addr);
  793. return fascist_firewall_choose_address_base(&ipv4_addr, ipv4_orport,
  794. ipv4_dirport, ipv6_addr,
  795. ipv6_orport, ipv6_dirport,
  796. fw_connection, pref_only,
  797. pref_ipv6, ap);
  798. }
  799. /** Like fascist_firewall_choose_address_base(), but takes <b>rs</b>.
  800. * Consults the corresponding node, then falls back to rs if node is NULL.
  801. * This should only happen when there's no valid consensus, and rs doesn't
  802. * correspond to a bridge client's bridge.
  803. */
  804. int
  805. fascist_firewall_choose_address_rs(const routerstatus_t *rs,
  806. firewall_connection_t fw_connection,
  807. int pref_only, tor_addr_port_t* ap)
  808. {
  809. if (!rs) {
  810. return 0;
  811. }
  812. tor_assert(ap);
  813. const node_t *node = node_get_by_id(rs->identity_digest);
  814. if (node) {
  815. return fascist_firewall_choose_address_node(node, fw_connection, pref_only,
  816. ap);
  817. } else {
  818. /* There's no node-specific IPv6 preference, so use the generic IPv6
  819. * preference instead. */
  820. const or_options_t *options = get_options();
  821. int pref_ipv6 = (fw_connection == FIREWALL_OR_CONNECTION
  822. ? fascist_firewall_prefer_ipv6_orport(options)
  823. : fascist_firewall_prefer_ipv6_dirport(options));
  824. /* Assume IPv4 and IPv6 DirPorts are the same.
  825. * Assume the IPv6 OR and Dir addresses are the same. */
  826. return fascist_firewall_choose_address_ipv4h(rs->addr,
  827. rs->or_port,
  828. rs->dir_port,
  829. &rs->ipv6_addr,
  830. rs->ipv6_orport,
  831. rs->dir_port,
  832. fw_connection,
  833. pref_only,
  834. pref_ipv6,
  835. ap);
  836. }
  837. }
  838. /** Like fascist_firewall_choose_address_base(), but takes <b>node</b>, and
  839. * looks up the node's IPv6 preference rather than taking an argument
  840. * for pref_ipv6. */
  841. int
  842. fascist_firewall_choose_address_node(const node_t *node,
  843. firewall_connection_t fw_connection,
  844. int pref_only, tor_addr_port_t *ap)
  845. {
  846. if (!node) {
  847. return 0;
  848. }
  849. node_assert_ok(node);
  850. const int pref_ipv6_node = (fw_connection == FIREWALL_OR_CONNECTION
  851. ? node_ipv6_or_preferred(node)
  852. : node_ipv6_dir_preferred(node));
  853. tor_addr_port_t ipv4_or_ap;
  854. node_get_prim_orport(node, &ipv4_or_ap);
  855. tor_addr_port_t ipv4_dir_ap;
  856. node_get_prim_dirport(node, &ipv4_dir_ap);
  857. tor_addr_port_t ipv6_or_ap;
  858. node_get_pref_ipv6_orport(node, &ipv6_or_ap);
  859. tor_addr_port_t ipv6_dir_ap;
  860. node_get_pref_ipv6_dirport(node, &ipv6_dir_ap);
  861. /* Assume the IPv6 OR and Dir addresses are the same. */
  862. return fascist_firewall_choose_address_base(&ipv4_or_ap.addr,
  863. ipv4_or_ap.port,
  864. ipv4_dir_ap.port,
  865. &ipv6_or_ap.addr,
  866. ipv6_or_ap.port,
  867. ipv6_dir_ap.port,
  868. fw_connection,
  869. pref_only,
  870. pref_ipv6_node,
  871. ap);
  872. }
  873. /** Like fascist_firewall_choose_address_rs(), but takes <b>ds</b>. */
  874. int
  875. fascist_firewall_choose_address_dir_server(const dir_server_t *ds,
  876. firewall_connection_t fw_connection,
  877. int pref_only,
  878. tor_addr_port_t *ap)
  879. {
  880. if (!ds) {
  881. return 0;
  882. }
  883. /* A dir_server_t always has a fake_status. As long as it has the same
  884. * addresses/ports in both fake_status and dir_server_t, this works fine.
  885. * (See #17867.)
  886. * This function relies on fascist_firewall_choose_address_rs looking up the
  887. * node if it can, because that will get the latest info for the relay. */
  888. return fascist_firewall_choose_address_rs(&ds->fake_status, fw_connection,
  889. pref_only, ap);
  890. }
  891. /** Return 1 if <b>addr</b> is permitted to connect to our dir port,
  892. * based on <b>dir_policy</b>. Else return 0.
  893. */
  894. int
  895. dir_policy_permits_address(const tor_addr_t *addr)
  896. {
  897. return addr_policy_permits_tor_addr(addr, 1, dir_policy);
  898. }
  899. /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
  900. * based on <b>socks_policy</b>. Else return 0.
  901. */
  902. int
  903. socks_policy_permits_address(const tor_addr_t *addr)
  904. {
  905. return addr_policy_permits_tor_addr(addr, 1, socks_policy);
  906. }
  907. /** Return true iff the address <b>addr</b> is in a country listed in the
  908. * case-insensitive list of country codes <b>cc_list</b>. */
  909. static int
  910. addr_is_in_cc_list(uint32_t addr, const smartlist_t *cc_list)
  911. {
  912. country_t country;
  913. const char *name;
  914. tor_addr_t tar;
  915. if (!cc_list)
  916. return 0;
  917. /* XXXXipv6 */
  918. tor_addr_from_ipv4h(&tar, addr);
  919. country = geoip_get_country_by_addr(&tar);
  920. name = geoip_get_country_name(country);
  921. return smartlist_contains_string_case(cc_list, name);
  922. }
  923. /** Return 1 if <b>addr</b>:<b>port</b> is permitted to publish to our
  924. * directory, based on <b>authdir_reject_policy</b>. Else return 0.
  925. */
  926. int
  927. authdir_policy_permits_address(uint32_t addr, uint16_t port)
  928. {
  929. if (! addr_policy_permits_address(addr, port, authdir_reject_policy))
  930. return 0;
  931. return !addr_is_in_cc_list(addr, get_options()->AuthDirRejectCCs);
  932. }
  933. /** Return 1 if <b>addr</b>:<b>port</b> is considered valid in our
  934. * directory, based on <b>authdir_invalid_policy</b>. Else return 0.
  935. */
  936. int
  937. authdir_policy_valid_address(uint32_t addr, uint16_t port)
  938. {
  939. if (! addr_policy_permits_address(addr, port, authdir_invalid_policy))
  940. return 0;
  941. return !addr_is_in_cc_list(addr, get_options()->AuthDirInvalidCCs);
  942. }
  943. /** Return 1 if <b>addr</b>:<b>port</b> should be marked as a bad exit,
  944. * based on <b>authdir_badexit_policy</b>. Else return 0.
  945. */
  946. int
  947. authdir_policy_badexit_address(uint32_t addr, uint16_t port)
  948. {
  949. if (! addr_policy_permits_address(addr, port, authdir_badexit_policy))
  950. return 1;
  951. return addr_is_in_cc_list(addr, get_options()->AuthDirBadExitCCs);
  952. }
  953. #define REJECT(arg) \
  954. STMT_BEGIN *msg = tor_strdup(arg); goto err; STMT_END
  955. /** Config helper: If there's any problem with the policy configuration
  956. * options in <b>options</b>, return -1 and set <b>msg</b> to a newly
  957. * allocated description of the error. Else return 0. */
  958. int
  959. validate_addr_policies(const or_options_t *options, char **msg)
  960. {
  961. /* XXXX Maybe merge this into parse_policies_from_options, to make sure
  962. * that the two can't go out of sync. */
  963. smartlist_t *addr_policy=NULL;
  964. *msg = NULL;
  965. if (policies_parse_exit_policy_from_options(options,0,NULL,&addr_policy)) {
  966. REJECT("Error in ExitPolicy entry.");
  967. }
  968. static int warned_about_exitrelay = 0;
  969. const int exitrelay_setting_is_auto = options->ExitRelay == -1;
  970. const int policy_accepts_something =
  971. ! (policy_is_reject_star(addr_policy, AF_INET, 1) &&
  972. policy_is_reject_star(addr_policy, AF_INET6, 1));
  973. if (server_mode(options) &&
  974. ! warned_about_exitrelay &&
  975. exitrelay_setting_is_auto &&
  976. policy_accepts_something) {
  977. /* Policy accepts something */
  978. warned_about_exitrelay = 1;
  979. log_warn(LD_CONFIG,
  980. "Tor is running as an exit relay%s. If you did not want this "
  981. "behavior, please set the ExitRelay option to 0. If you do "
  982. "want to run an exit Relay, please set the ExitRelay option "
  983. "to 1 to disable this warning, and for forward compatibility.",
  984. options->ExitPolicy == NULL ?
  985. " with the default exit policy" : "");
  986. if (options->ExitPolicy == NULL) {
  987. log_warn(LD_CONFIG,
  988. "In a future version of Tor, ExitRelay 0 may become the "
  989. "default when no ExitPolicy is given.");
  990. }
  991. }
  992. /* The rest of these calls *append* to addr_policy. So don't actually
  993. * use the results for anything other than checking if they parse! */
  994. if (parse_addr_policy(options->DirPolicy, &addr_policy, -1))
  995. REJECT("Error in DirPolicy entry.");
  996. if (parse_addr_policy(options->SocksPolicy, &addr_policy, -1))
  997. REJECT("Error in SocksPolicy entry.");
  998. if (parse_addr_policy(options->AuthDirReject, &addr_policy,
  999. ADDR_POLICY_REJECT))
  1000. REJECT("Error in AuthDirReject entry.");
  1001. if (parse_addr_policy(options->AuthDirInvalid, &addr_policy,
  1002. ADDR_POLICY_REJECT))
  1003. REJECT("Error in AuthDirInvalid entry.");
  1004. if (parse_addr_policy(options->AuthDirBadExit, &addr_policy,
  1005. ADDR_POLICY_REJECT))
  1006. REJECT("Error in AuthDirBadExit entry.");
  1007. if (parse_addr_policy(options->ReachableAddresses, &addr_policy,
  1008. ADDR_POLICY_ACCEPT))
  1009. REJECT("Error in ReachableAddresses entry.");
  1010. if (parse_addr_policy(options->ReachableORAddresses, &addr_policy,
  1011. ADDR_POLICY_ACCEPT))
  1012. REJECT("Error in ReachableORAddresses entry.");
  1013. if (parse_addr_policy(options->ReachableDirAddresses, &addr_policy,
  1014. ADDR_POLICY_ACCEPT))
  1015. REJECT("Error in ReachableDirAddresses entry.");
  1016. err:
  1017. addr_policy_list_free(addr_policy);
  1018. return *msg ? -1 : 0;
  1019. #undef REJECT
  1020. }
  1021. /** Parse <b>string</b> in the same way that the exit policy
  1022. * is parsed, and put the processed version in *<b>policy</b>.
  1023. * Ignore port specifiers.
  1024. */
  1025. static int
  1026. load_policy_from_option(config_line_t *config, const char *option_name,
  1027. smartlist_t **policy,
  1028. int assume_action)
  1029. {
  1030. int r;
  1031. int killed_any_ports = 0;
  1032. addr_policy_list_free(*policy);
  1033. *policy = NULL;
  1034. r = parse_addr_policy(config, policy, assume_action);
  1035. if (r < 0) {
  1036. return -1;
  1037. }
  1038. if (*policy) {
  1039. SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, n) {
  1040. /* ports aren't used in these. */
  1041. if (n->prt_min > 1 || n->prt_max != 65535) {
  1042. addr_policy_t newp, *c;
  1043. memcpy(&newp, n, sizeof(newp));
  1044. newp.prt_min = 1;
  1045. newp.prt_max = 65535;
  1046. newp.is_canonical = 0;
  1047. c = addr_policy_get_canonical_entry(&newp);
  1048. SMARTLIST_REPLACE_CURRENT(*policy, n, c);
  1049. addr_policy_free(n);
  1050. killed_any_ports = 1;
  1051. }
  1052. } SMARTLIST_FOREACH_END(n);
  1053. }
  1054. if (killed_any_ports) {
  1055. log_warn(LD_CONFIG, "Ignoring ports in %s option.", option_name);
  1056. }
  1057. return 0;
  1058. }
  1059. /** Set all policies based on <b>options</b>, which should have been validated
  1060. * first by validate_addr_policies. */
  1061. int
  1062. policies_parse_from_options(const or_options_t *options)
  1063. {
  1064. int ret = 0;
  1065. if (load_policy_from_option(options->SocksPolicy, "SocksPolicy",
  1066. &socks_policy, -1) < 0)
  1067. ret = -1;
  1068. if (load_policy_from_option(options->DirPolicy, "DirPolicy",
  1069. &dir_policy, -1) < 0)
  1070. ret = -1;
  1071. if (load_policy_from_option(options->AuthDirReject, "AuthDirReject",
  1072. &authdir_reject_policy, ADDR_POLICY_REJECT) < 0)
  1073. ret = -1;
  1074. if (load_policy_from_option(options->AuthDirInvalid, "AuthDirInvalid",
  1075. &authdir_invalid_policy, ADDR_POLICY_REJECT) < 0)
  1076. ret = -1;
  1077. if (load_policy_from_option(options->AuthDirBadExit, "AuthDirBadExit",
  1078. &authdir_badexit_policy, ADDR_POLICY_REJECT) < 0)
  1079. ret = -1;
  1080. if (parse_reachable_addresses() < 0)
  1081. ret = -1;
  1082. return ret;
  1083. }
  1084. /** Compare two provided address policy items, and return -1, 0, or 1
  1085. * if the first is less than, equal to, or greater than the second. */
  1086. static int
  1087. cmp_single_addr_policy(addr_policy_t *a, addr_policy_t *b)
  1088. {
  1089. int r;
  1090. if ((r=((int)a->policy_type - (int)b->policy_type)))
  1091. return r;
  1092. if ((r=((int)a->is_private - (int)b->is_private)))
  1093. return r;
  1094. /* refcnt and is_canonical are irrelevant to equality,
  1095. * they are hash table implementation details */
  1096. if ((r=tor_addr_compare(&a->addr, &b->addr, CMP_EXACT)))
  1097. return r;
  1098. if ((r=((int)a->maskbits - (int)b->maskbits)))
  1099. return r;
  1100. if ((r=((int)a->prt_min - (int)b->prt_min)))
  1101. return r;
  1102. if ((r=((int)a->prt_max - (int)b->prt_max)))
  1103. return r;
  1104. return 0;
  1105. }
  1106. /** Like cmp_single_addr_policy() above, but looks at the
  1107. * whole set of policies in each case. */
  1108. int
  1109. cmp_addr_policies(smartlist_t *a, smartlist_t *b)
  1110. {
  1111. int r, i;
  1112. int len_a = a ? smartlist_len(a) : 0;
  1113. int len_b = b ? smartlist_len(b) : 0;
  1114. for (i = 0; i < len_a && i < len_b; ++i) {
  1115. if ((r = cmp_single_addr_policy(smartlist_get(a, i), smartlist_get(b, i))))
  1116. return r;
  1117. }
  1118. if (i == len_a && i == len_b)
  1119. return 0;
  1120. if (i < len_a)
  1121. return -1;
  1122. else
  1123. return 1;
  1124. }
  1125. /** Node in hashtable used to store address policy entries. */
  1126. typedef struct policy_map_ent_t {
  1127. HT_ENTRY(policy_map_ent_t) node;
  1128. addr_policy_t *policy;
  1129. } policy_map_ent_t;
  1130. /* DOCDOC policy_root */
  1131. static HT_HEAD(policy_map, policy_map_ent_t) policy_root = HT_INITIALIZER();
  1132. /** Return true iff a and b are equal. */
  1133. static inline int
  1134. policy_eq(policy_map_ent_t *a, policy_map_ent_t *b)
  1135. {
  1136. return cmp_single_addr_policy(a->policy, b->policy) == 0;
  1137. }
  1138. /** Return a hashcode for <b>ent</b> */
  1139. static unsigned int
  1140. policy_hash(const policy_map_ent_t *ent)
  1141. {
  1142. const addr_policy_t *a = ent->policy;
  1143. addr_policy_t aa;
  1144. memset(&aa, 0, sizeof(aa));
  1145. aa.prt_min = a->prt_min;
  1146. aa.prt_max = a->prt_max;
  1147. aa.maskbits = a->maskbits;
  1148. aa.policy_type = a->policy_type;
  1149. aa.is_private = a->is_private;
  1150. if (a->is_private) {
  1151. aa.is_private = 1;
  1152. } else {
  1153. tor_addr_copy_tight(&aa.addr, &a->addr);
  1154. }
  1155. return (unsigned) siphash24g(&aa, sizeof(aa));
  1156. }
  1157. HT_PROTOTYPE(policy_map, policy_map_ent_t, node, policy_hash,
  1158. policy_eq)
  1159. HT_GENERATE2(policy_map, policy_map_ent_t, node, policy_hash,
  1160. policy_eq, 0.6, tor_reallocarray_, tor_free_)
  1161. /** Given a pointer to an addr_policy_t, return a copy of the pointer to the
  1162. * "canonical" copy of that addr_policy_t; the canonical copy is a single
  1163. * reference-counted object. */
  1164. addr_policy_t *
  1165. addr_policy_get_canonical_entry(addr_policy_t *e)
  1166. {
  1167. policy_map_ent_t search, *found;
  1168. if (e->is_canonical)
  1169. return e;
  1170. search.policy = e;
  1171. found = HT_FIND(policy_map, &policy_root, &search);
  1172. if (!found) {
  1173. found = tor_malloc_zero(sizeof(policy_map_ent_t));
  1174. found->policy = tor_memdup(e, sizeof(addr_policy_t));
  1175. found->policy->is_canonical = 1;
  1176. found->policy->refcnt = 0;
  1177. HT_INSERT(policy_map, &policy_root, found);
  1178. }
  1179. tor_assert(!cmp_single_addr_policy(found->policy, e));
  1180. ++found->policy->refcnt;
  1181. return found->policy;
  1182. }
  1183. /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
  1184. * addr and port are both known. */
  1185. static addr_policy_result_t
  1186. compare_known_tor_addr_to_addr_policy(const tor_addr_t *addr, uint16_t port,
  1187. const smartlist_t *policy)
  1188. {
  1189. /* We know the address and port, and we know the policy, so we can just
  1190. * compute an exact match. */
  1191. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
  1192. if (tmpe->addr.family == AF_UNSPEC) {
  1193. log_warn(LD_BUG, "Policy contains an AF_UNSPEC address, which only "
  1194. "matches other AF_UNSPEC addresses.");
  1195. }
  1196. /* Address is known */
  1197. if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
  1198. CMP_EXACT)) {
  1199. if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
  1200. /* Exact match for the policy */
  1201. return tmpe->policy_type == ADDR_POLICY_ACCEPT ?
  1202. ADDR_POLICY_ACCEPTED : ADDR_POLICY_REJECTED;
  1203. }
  1204. }
  1205. } SMARTLIST_FOREACH_END(tmpe);
  1206. /* accept all by default. */
  1207. return ADDR_POLICY_ACCEPTED;
  1208. }
  1209. /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
  1210. * addr is known but port is not. */
  1211. static addr_policy_result_t
  1212. compare_known_tor_addr_to_addr_policy_noport(const tor_addr_t *addr,
  1213. const smartlist_t *policy)
  1214. {
  1215. /* We look to see if there's a definite match. If so, we return that
  1216. match's value, unless there's an intervening possible match that says
  1217. something different. */
  1218. int maybe_accept = 0, maybe_reject = 0;
  1219. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
  1220. if (tmpe->addr.family == AF_UNSPEC) {
  1221. log_warn(LD_BUG, "Policy contains an AF_UNSPEC address, which only "
  1222. "matches other AF_UNSPEC addresses.");
  1223. }
  1224. if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
  1225. CMP_EXACT)) {
  1226. if (tmpe->prt_min <= 1 && tmpe->prt_max >= 65535) {
  1227. /* Definitely matches, since it covers all ports. */
  1228. if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
  1229. /* If we already hit a clause that might trigger a 'reject', than we
  1230. * can't be sure of this certain 'accept'.*/
  1231. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
  1232. ADDR_POLICY_ACCEPTED;
  1233. } else {
  1234. return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
  1235. ADDR_POLICY_REJECTED;
  1236. }
  1237. } else {
  1238. /* Might match. */
  1239. if (tmpe->policy_type == ADDR_POLICY_REJECT)
  1240. maybe_reject = 1;
  1241. else
  1242. maybe_accept = 1;
  1243. }
  1244. }
  1245. } SMARTLIST_FOREACH_END(tmpe);
  1246. /* accept all by default. */
  1247. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  1248. }
  1249. /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
  1250. * port is known but address is not. */
  1251. static addr_policy_result_t
  1252. compare_unknown_tor_addr_to_addr_policy(uint16_t port,
  1253. const smartlist_t *policy)
  1254. {
  1255. /* We look to see if there's a definite match. If so, we return that
  1256. match's value, unless there's an intervening possible match that says
  1257. something different. */
  1258. int maybe_accept = 0, maybe_reject = 0;
  1259. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
  1260. if (tmpe->addr.family == AF_UNSPEC) {
  1261. log_warn(LD_BUG, "Policy contains an AF_UNSPEC address, which only "
  1262. "matches other AF_UNSPEC addresses.");
  1263. }
  1264. if (tmpe->prt_min <= port && port <= tmpe->prt_max) {
  1265. if (tmpe->maskbits == 0) {
  1266. /* Definitely matches, since it covers all addresses. */
  1267. if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
  1268. /* If we already hit a clause that might trigger a 'reject', than we
  1269. * can't be sure of this certain 'accept'.*/
  1270. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
  1271. ADDR_POLICY_ACCEPTED;
  1272. } else {
  1273. return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
  1274. ADDR_POLICY_REJECTED;
  1275. }
  1276. } else {
  1277. /* Might match. */
  1278. if (tmpe->policy_type == ADDR_POLICY_REJECT)
  1279. maybe_reject = 1;
  1280. else
  1281. maybe_accept = 1;
  1282. }
  1283. }
  1284. } SMARTLIST_FOREACH_END(tmpe);
  1285. /* accept all by default. */
  1286. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  1287. }
  1288. /** Decide whether a given addr:port is definitely accepted,
  1289. * definitely rejected, probably accepted, or probably rejected by a
  1290. * given policy. If <b>addr</b> is 0, we don't know the IP of the
  1291. * target address. If <b>port</b> is 0, we don't know the port of the
  1292. * target address. (At least one of <b>addr</b> and <b>port</b> must be
  1293. * provided. If you want to know whether a policy would definitely reject
  1294. * an unknown address:port, use policy_is_reject_star().)
  1295. *
  1296. * We could do better by assuming that some ranges never match typical
  1297. * addresses (127.0.0.1, and so on). But we'll try this for now.
  1298. */
  1299. MOCK_IMPL(addr_policy_result_t,
  1300. compare_tor_addr_to_addr_policy,(const tor_addr_t *addr, uint16_t port,
  1301. const smartlist_t *policy))
  1302. {
  1303. if (!policy) {
  1304. /* no policy? accept all. */
  1305. return ADDR_POLICY_ACCEPTED;
  1306. } else if (addr == NULL || tor_addr_is_null(addr)) {
  1307. if (port == 0) {
  1308. log_info(LD_BUG, "Rejecting null address with 0 port (family %d)",
  1309. addr ? tor_addr_family(addr) : -1);
  1310. return ADDR_POLICY_REJECTED;
  1311. }
  1312. return compare_unknown_tor_addr_to_addr_policy(port, policy);
  1313. } else if (port == 0) {
  1314. return compare_known_tor_addr_to_addr_policy_noport(addr, policy);
  1315. } else {
  1316. return compare_known_tor_addr_to_addr_policy(addr, port, policy);
  1317. }
  1318. }
  1319. /** Return true iff the address policy <b>a</b> covers every case that
  1320. * would be covered by <b>b</b>, so that a,b is redundant. */
  1321. static int
  1322. addr_policy_covers(addr_policy_t *a, addr_policy_t *b)
  1323. {
  1324. if (tor_addr_family(&a->addr) != tor_addr_family(&b->addr)) {
  1325. /* You can't cover a different family. */
  1326. return 0;
  1327. }
  1328. /* We can ignore accept/reject, since "accept *:80, reject *:80" reduces
  1329. * to "accept *:80". */
  1330. if (a->maskbits > b->maskbits) {
  1331. /* a has more fixed bits than b; it can't possibly cover b. */
  1332. return 0;
  1333. }
  1334. if (tor_addr_compare_masked(&a->addr, &b->addr, a->maskbits, CMP_EXACT)) {
  1335. /* There's a fixed bit in a that's set differently in b. */
  1336. return 0;
  1337. }
  1338. return (a->prt_min <= b->prt_min && a->prt_max >= b->prt_max);
  1339. }
  1340. /** Return true iff the address policies <b>a</b> and <b>b</b> intersect,
  1341. * that is, there exists an address/port that is covered by <b>a</b> that
  1342. * is also covered by <b>b</b>.
  1343. */
  1344. static int
  1345. addr_policy_intersects(addr_policy_t *a, addr_policy_t *b)
  1346. {
  1347. maskbits_t minbits;
  1348. /* All the bits we care about are those that are set in both
  1349. * netmasks. If they are equal in a and b's networkaddresses
  1350. * then the networks intersect. If there is a difference,
  1351. * then they do not. */
  1352. if (a->maskbits < b->maskbits)
  1353. minbits = a->maskbits;
  1354. else
  1355. minbits = b->maskbits;
  1356. if (tor_addr_compare_masked(&a->addr, &b->addr, minbits, CMP_EXACT))
  1357. return 0;
  1358. if (a->prt_max < b->prt_min || b->prt_max < a->prt_min)
  1359. return 0;
  1360. return 1;
  1361. }
  1362. /** Add the exit policy described by <b>more</b> to <b>policy</b>.
  1363. */
  1364. STATIC void
  1365. append_exit_policy_string(smartlist_t **policy, const char *more)
  1366. {
  1367. config_line_t tmp;
  1368. tmp.key = NULL;
  1369. tmp.value = (char*) more;
  1370. tmp.next = NULL;
  1371. if (parse_addr_policy(&tmp, policy, -1)<0) {
  1372. log_warn(LD_BUG, "Unable to parse internally generated policy %s",more);
  1373. }
  1374. }
  1375. /** Add "reject <b>addr</b>:*" to <b>dest</b>, creating the list as needed. */
  1376. void
  1377. addr_policy_append_reject_addr(smartlist_t **dest, const tor_addr_t *addr)
  1378. {
  1379. tor_assert(dest);
  1380. tor_assert(addr);
  1381. addr_policy_t p, *add;
  1382. memset(&p, 0, sizeof(p));
  1383. p.policy_type = ADDR_POLICY_REJECT;
  1384. p.maskbits = tor_addr_family(addr) == AF_INET6 ? 128 : 32;
  1385. tor_addr_copy(&p.addr, addr);
  1386. p.prt_min = 1;
  1387. p.prt_max = 65535;
  1388. add = addr_policy_get_canonical_entry(&p);
  1389. if (!*dest)
  1390. *dest = smartlist_new();
  1391. smartlist_add(*dest, add);
  1392. log_debug(LD_CONFIG, "Adding a reject ExitPolicy 'reject %s:*'",
  1393. fmt_addr(addr));
  1394. }
  1395. /* Is addr public for the purposes of rejection? */
  1396. static int
  1397. tor_addr_is_public_for_reject(const tor_addr_t *addr)
  1398. {
  1399. return (!tor_addr_is_null(addr) && !tor_addr_is_internal(addr, 0)
  1400. && !tor_addr_is_multicast(addr));
  1401. }
  1402. /* Add "reject <b>addr</b>:*" to <b>dest</b>, creating the list as needed.
  1403. * Filter the address, only adding an IPv4 reject rule if ipv4_rules
  1404. * is true, and similarly for ipv6_rules. Check each address returns true for
  1405. * tor_addr_is_public_for_reject before adding it.
  1406. */
  1407. static void
  1408. addr_policy_append_reject_addr_filter(smartlist_t **dest,
  1409. const tor_addr_t *addr,
  1410. int ipv4_rules,
  1411. int ipv6_rules)
  1412. {
  1413. tor_assert(dest);
  1414. tor_assert(addr);
  1415. /* Only reject IP addresses which are public */
  1416. if (tor_addr_is_public_for_reject(addr)) {
  1417. /* Reject IPv4 addresses and IPv6 addresses based on the filters */
  1418. int is_ipv4 = tor_addr_is_v4(addr);
  1419. if ((is_ipv4 && ipv4_rules) || (!is_ipv4 && ipv6_rules)) {
  1420. addr_policy_append_reject_addr(dest, addr);
  1421. }
  1422. }
  1423. }
  1424. /** Add "reject addr:*" to <b>dest</b>, for each addr in addrs, creating the
  1425. * list as needed. */
  1426. void
  1427. addr_policy_append_reject_addr_list(smartlist_t **dest,
  1428. const smartlist_t *addrs)
  1429. {
  1430. tor_assert(dest);
  1431. tor_assert(addrs);
  1432. SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, addr) {
  1433. addr_policy_append_reject_addr(dest, addr);
  1434. } SMARTLIST_FOREACH_END(addr);
  1435. }
  1436. /** Add "reject addr:*" to <b>dest</b>, for each addr in addrs, creating the
  1437. * list as needed. Filter using */
  1438. static void
  1439. addr_policy_append_reject_addr_list_filter(smartlist_t **dest,
  1440. const smartlist_t *addrs,
  1441. int ipv4_rules,
  1442. int ipv6_rules)
  1443. {
  1444. tor_assert(dest);
  1445. tor_assert(addrs);
  1446. SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, addr) {
  1447. addr_policy_append_reject_addr_filter(dest, addr, ipv4_rules, ipv6_rules);
  1448. } SMARTLIST_FOREACH_END(addr);
  1449. }
  1450. /** Detect and excise "dead code" from the policy *<b>dest</b>. */
  1451. static void
  1452. exit_policy_remove_redundancies(smartlist_t *dest)
  1453. {
  1454. addr_policy_t *ap, *tmp;
  1455. int i, j;
  1456. /* Step one: kill every ipv4 thing after *4:*, every IPv6 thing after *6:*
  1457. */
  1458. {
  1459. int kill_v4=0, kill_v6=0;
  1460. for (i = 0; i < smartlist_len(dest); ++i) {
  1461. sa_family_t family;
  1462. ap = smartlist_get(dest, i);
  1463. family = tor_addr_family(&ap->addr);
  1464. if ((family == AF_INET && kill_v4) ||
  1465. (family == AF_INET6 && kill_v6)) {
  1466. smartlist_del_keeporder(dest, i--);
  1467. addr_policy_free(ap);
  1468. continue;
  1469. }
  1470. if (ap->maskbits == 0 && ap->prt_min <= 1 && ap->prt_max >= 65535) {
  1471. /* This is a catch-all line -- later lines are unreachable. */
  1472. if (family == AF_INET) {
  1473. kill_v4 = 1;
  1474. } else if (family == AF_INET6) {
  1475. kill_v6 = 1;
  1476. }
  1477. }
  1478. }
  1479. }
  1480. /* Step two: for every entry, see if there's a redundant entry
  1481. * later on, and remove it. */
  1482. for (i = 0; i < smartlist_len(dest)-1; ++i) {
  1483. ap = smartlist_get(dest, i);
  1484. for (j = i+1; j < smartlist_len(dest); ++j) {
  1485. tmp = smartlist_get(dest, j);
  1486. tor_assert(j > i);
  1487. if (addr_policy_covers(ap, tmp)) {
  1488. char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
  1489. policy_write_item(p1, sizeof(p1), tmp, 0);
  1490. policy_write_item(p2, sizeof(p2), ap, 0);
  1491. log_debug(LD_CONFIG, "Removing exit policy %s (%d). It is made "
  1492. "redundant by %s (%d).", p1, j, p2, i);
  1493. smartlist_del_keeporder(dest, j--);
  1494. addr_policy_free(tmp);
  1495. }
  1496. }
  1497. }
  1498. /* Step three: for every entry A, see if there's an entry B making this one
  1499. * redundant later on. This is the case if A and B are of the same type
  1500. * (accept/reject), A is a subset of B, and there is no other entry of
  1501. * different type in between those two that intersects with A.
  1502. *
  1503. * Anybody want to double-check the logic here? XXX
  1504. */
  1505. for (i = 0; i < smartlist_len(dest)-1; ++i) {
  1506. ap = smartlist_get(dest, i);
  1507. for (j = i+1; j < smartlist_len(dest); ++j) {
  1508. // tor_assert(j > i); // j starts out at i+1; j only increases; i only
  1509. // // decreases.
  1510. tmp = smartlist_get(dest, j);
  1511. if (ap->policy_type != tmp->policy_type) {
  1512. if (addr_policy_intersects(ap, tmp))
  1513. break;
  1514. } else { /* policy_types are equal. */
  1515. if (addr_policy_covers(tmp, ap)) {
  1516. char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
  1517. policy_write_item(p1, sizeof(p1), ap, 0);
  1518. policy_write_item(p2, sizeof(p2), tmp, 0);
  1519. log_debug(LD_CONFIG, "Removing exit policy %s. It is already "
  1520. "covered by %s.", p1, p2);
  1521. smartlist_del_keeporder(dest, i--);
  1522. addr_policy_free(ap);
  1523. break;
  1524. }
  1525. }
  1526. }
  1527. }
  1528. }
  1529. /** Reject private helper for policies_parse_exit_policy_internal: rejects
  1530. * publicly routable addresses on this exit relay.
  1531. *
  1532. * Add reject entries to the linked list *<b>dest</b>:
  1533. * <ul>
  1534. * <li>if configured_addresses is non-NULL, add entries that reject each
  1535. * tor_addr_t in the list as a destination.
  1536. * <li>if reject_interface_addresses is true, add entries that reject each
  1537. * public IPv4 and IPv6 address of each interface on this machine.
  1538. * <li>if reject_configured_port_addresses is true, add entries that reject
  1539. * each IPv4 and IPv6 address configured for a port.
  1540. * </ul>
  1541. *
  1542. * IPv6 entries are only added if ipv6_exit is true. (All IPv6 addresses are
  1543. * already blocked by policies_parse_exit_policy_internal if ipv6_exit is
  1544. * false.)
  1545. *
  1546. * The list in <b>dest</b> is created as needed.
  1547. */
  1548. void
  1549. policies_parse_exit_policy_reject_private(
  1550. smartlist_t **dest,
  1551. int ipv6_exit,
  1552. const smartlist_t *configured_addresses,
  1553. int reject_interface_addresses,
  1554. int reject_configured_port_addresses)
  1555. {
  1556. tor_assert(dest);
  1557. /* Reject configured addresses, if they are from public netblocks. */
  1558. if (configured_addresses) {
  1559. addr_policy_append_reject_addr_list_filter(dest, configured_addresses,
  1560. 1, ipv6_exit);
  1561. }
  1562. /* Reject configured port addresses, if they are from public netblocks. */
  1563. if (reject_configured_port_addresses) {
  1564. const smartlist_t *port_addrs = get_configured_ports();
  1565. SMARTLIST_FOREACH_BEGIN(port_addrs, port_cfg_t *, port) {
  1566. /* Only reject port IP addresses, not port unix sockets */
  1567. if (!port->is_unix_addr) {
  1568. addr_policy_append_reject_addr_filter(dest, &port->addr, 1, ipv6_exit);
  1569. }
  1570. } SMARTLIST_FOREACH_END(port);
  1571. }
  1572. /* Reject local addresses from public netblocks on any interface. */
  1573. if (reject_interface_addresses) {
  1574. smartlist_t *public_addresses = NULL;
  1575. /* Reject public IPv4 addresses on any interface */
  1576. public_addresses = get_interface_address6_list(LOG_INFO, AF_INET, 0);
  1577. addr_policy_append_reject_addr_list_filter(dest, public_addresses, 1, 0);
  1578. free_interface_address6_list(public_addresses);
  1579. /* Don't look for IPv6 addresses if we're configured as IPv4-only */
  1580. if (ipv6_exit) {
  1581. /* Reject public IPv6 addresses on any interface */
  1582. public_addresses = get_interface_address6_list(LOG_INFO, AF_INET6, 0);
  1583. addr_policy_append_reject_addr_list_filter(dest, public_addresses, 0, 1);
  1584. free_interface_address6_list(public_addresses);
  1585. }
  1586. }
  1587. /* If addresses were added multiple times, remove all but one of them. */
  1588. if (*dest) {
  1589. exit_policy_remove_redundancies(*dest);
  1590. }
  1591. }
  1592. /**
  1593. * Iterate through <b>policy</b> looking for redundant entries. Log a
  1594. * warning message with the first redundant entry, if any is found.
  1595. */
  1596. static void
  1597. policies_log_first_redundant_entry(const smartlist_t *policy)
  1598. {
  1599. int found_final_effective_entry = 0;
  1600. int first_redundant_entry = 0;
  1601. tor_assert(policy);
  1602. SMARTLIST_FOREACH_BEGIN(policy, const addr_policy_t *, p) {
  1603. sa_family_t family;
  1604. int found_ipv4_wildcard = 0, found_ipv6_wildcard = 0;
  1605. const int i = p_sl_idx;
  1606. /* Look for accept/reject *[4|6|]:* entires */
  1607. if (p->prt_min <= 1 && p->prt_max == 65535 && p->maskbits == 0) {
  1608. family = tor_addr_family(&p->addr);
  1609. /* accept/reject *:* may have already been expanded into
  1610. * accept/reject *4:*,accept/reject *6:*
  1611. * But handle both forms.
  1612. */
  1613. if (family == AF_INET || family == AF_UNSPEC) {
  1614. found_ipv4_wildcard = 1;
  1615. }
  1616. if (family == AF_INET6 || family == AF_UNSPEC) {
  1617. found_ipv6_wildcard = 1;
  1618. }
  1619. }
  1620. /* We also find accept *4:*,reject *6:* ; and
  1621. * accept *4:*,<other policies>,accept *6:* ; and similar.
  1622. * That's ok, because they make any subsequent entries redundant. */
  1623. if (found_ipv4_wildcard && found_ipv6_wildcard) {
  1624. found_final_effective_entry = 1;
  1625. /* if we're not on the final entry in the list */
  1626. if (i < smartlist_len(policy) - 1) {
  1627. first_redundant_entry = i + 1;
  1628. }
  1629. break;
  1630. }
  1631. } SMARTLIST_FOREACH_END(p);
  1632. /* Work out if there are redundant trailing entries in the policy list */
  1633. if (found_final_effective_entry && first_redundant_entry > 0) {
  1634. const addr_policy_t *p;
  1635. /* Longest possible policy is
  1636. * "accept6 ffff:ffff:..255/128:10000-65535",
  1637. * which contains a max-length IPv6 address, plus 24 characters. */
  1638. char line[TOR_ADDR_BUF_LEN + 32];
  1639. tor_assert(first_redundant_entry < smartlist_len(policy));
  1640. p = smartlist_get(policy, first_redundant_entry);
  1641. /* since we've already parsed the policy into an addr_policy_t struct,
  1642. * we might not log exactly what the user typed in */
  1643. policy_write_item(line, TOR_ADDR_BUF_LEN + 32, p, 0);
  1644. log_warn(LD_DIR, "Exit policy '%s' and all following policies are "
  1645. "redundant, as it follows accept/reject *:* rules for both "
  1646. "IPv4 and IPv6. They will be removed from the exit policy. (Use "
  1647. "accept/reject *:* as the last entry in any exit policy.)",
  1648. line);
  1649. }
  1650. }
  1651. #define DEFAULT_EXIT_POLICY \
  1652. "reject *:25,reject *:119,reject *:135-139,reject *:445," \
  1653. "reject *:563,reject *:1214,reject *:4661-4666," \
  1654. "reject *:6346-6429,reject *:6699,reject *:6881-6999,accept *:*"
  1655. /** Parse the exit policy <b>cfg</b> into the linked list *<b>dest</b>.
  1656. *
  1657. * If <b>ipv6_exit</b> is false, prepend "reject *6:*" to the policy.
  1658. *
  1659. * If <b>configured_addresses</b> contains addresses:
  1660. * - prepend entries that reject the addresses in this list. These may be the
  1661. * advertised relay addresses and/or the outbound bind addresses,
  1662. * depending on the ExitPolicyRejectPrivate and
  1663. * ExitPolicyRejectLocalInterfaces settings.
  1664. * If <b>rejectprivate</b> is true:
  1665. * - prepend "reject private:*" to the policy.
  1666. * If <b>reject_interface_addresses</b> is true:
  1667. * - prepend entries that reject publicly routable interface addresses on
  1668. * this exit relay by calling policies_parse_exit_policy_reject_private
  1669. * If <b>reject_configured_port_addresses</b> is true:
  1670. * - prepend entries that reject all configured port addresses
  1671. *
  1672. * If cfg doesn't end in an absolute accept or reject and if
  1673. * <b>add_default_policy</b> is true, add the default exit
  1674. * policy afterwards.
  1675. *
  1676. * Return -1 if we can't parse cfg, else return 0.
  1677. *
  1678. * This function is used to parse the exit policy from our torrc. For
  1679. * the functions used to parse the exit policy from a router descriptor,
  1680. * see router_add_exit_policy.
  1681. */
  1682. static int
  1683. policies_parse_exit_policy_internal(config_line_t *cfg,
  1684. smartlist_t **dest,
  1685. int ipv6_exit,
  1686. int rejectprivate,
  1687. const smartlist_t *configured_addresses,
  1688. int reject_interface_addresses,
  1689. int reject_configured_port_addresses,
  1690. int add_default_policy)
  1691. {
  1692. if (!ipv6_exit) {
  1693. append_exit_policy_string(dest, "reject *6:*");
  1694. }
  1695. if (rejectprivate) {
  1696. /* Reject IPv4 and IPv6 reserved private netblocks */
  1697. append_exit_policy_string(dest, "reject private:*");
  1698. }
  1699. /* Consider rejecting IPv4 and IPv6 advertised relay addresses, outbound bind
  1700. * addresses, publicly routable addresses, and configured port addresses
  1701. * on this exit relay */
  1702. policies_parse_exit_policy_reject_private(dest, ipv6_exit,
  1703. configured_addresses,
  1704. reject_interface_addresses,
  1705. reject_configured_port_addresses);
  1706. if (parse_addr_policy(cfg, dest, -1))
  1707. return -1;
  1708. /* Before we add the default policy and final rejects, check to see if
  1709. * there are any lines after accept *:* or reject *:*. These lines have no
  1710. * effect, and are most likely an error. */
  1711. policies_log_first_redundant_entry(*dest);
  1712. if (add_default_policy) {
  1713. append_exit_policy_string(dest, DEFAULT_EXIT_POLICY);
  1714. } else {
  1715. append_exit_policy_string(dest, "reject *4:*");
  1716. append_exit_policy_string(dest, "reject *6:*");
  1717. }
  1718. exit_policy_remove_redundancies(*dest);
  1719. return 0;
  1720. }
  1721. /** Parse exit policy in <b>cfg</b> into <b>dest</b> smartlist.
  1722. *
  1723. * Prepend an entry that rejects all IPv6 destinations unless
  1724. * <b>EXIT_POLICY_IPV6_ENABLED</b> bit is set in <b>options</b> bitmask.
  1725. *
  1726. * If <b>EXIT_POLICY_REJECT_PRIVATE</b> bit is set in <b>options</b>:
  1727. * - prepend an entry that rejects all destinations in all netblocks
  1728. * reserved for private use.
  1729. * - prepend entries that reject the advertised relay addresses in
  1730. * configured_addresses
  1731. * If <b>EXIT_POLICY_REJECT_LOCAL_INTERFACES</b> bit is set in <b>options</b>:
  1732. * - prepend entries that reject publicly routable addresses on this exit
  1733. * relay by calling policies_parse_exit_policy_internal
  1734. * - prepend entries that reject the outbound bind addresses in
  1735. * configured_addresses
  1736. * - prepend entries that reject all configured port addresses
  1737. *
  1738. * If <b>EXIT_POLICY_ADD_DEFAULT</b> bit is set in <b>options</b>, append
  1739. * default exit policy entries to <b>result</b> smartlist.
  1740. */
  1741. int
  1742. policies_parse_exit_policy(config_line_t *cfg, smartlist_t **dest,
  1743. exit_policy_parser_cfg_t options,
  1744. const smartlist_t *configured_addresses)
  1745. {
  1746. int ipv6_enabled = (options & EXIT_POLICY_IPV6_ENABLED) ? 1 : 0;
  1747. int reject_private = (options & EXIT_POLICY_REJECT_PRIVATE) ? 1 : 0;
  1748. int add_default = (options & EXIT_POLICY_ADD_DEFAULT) ? 1 : 0;
  1749. int reject_local_interfaces = (options &
  1750. EXIT_POLICY_REJECT_LOCAL_INTERFACES) ? 1 : 0;
  1751. return policies_parse_exit_policy_internal(cfg,dest,ipv6_enabled,
  1752. reject_private,
  1753. configured_addresses,
  1754. reject_local_interfaces,
  1755. reject_local_interfaces,
  1756. add_default);
  1757. }
  1758. /** Helper function that adds a copy of addr to a smartlist as long as it is
  1759. * non-NULL and not tor_addr_is_null().
  1760. *
  1761. * The caller is responsible for freeing all the tor_addr_t* in the smartlist.
  1762. */
  1763. static void
  1764. policies_copy_addr_to_smartlist(smartlist_t *addr_list, const tor_addr_t *addr)
  1765. {
  1766. if (addr && !tor_addr_is_null(addr)) {
  1767. tor_addr_t *addr_copy = tor_malloc(sizeof(tor_addr_t));
  1768. tor_addr_copy(addr_copy, addr);
  1769. smartlist_add(addr_list, addr_copy);
  1770. }
  1771. }
  1772. /** Helper function that adds ipv4h_addr to a smartlist as a tor_addr_t *,
  1773. * as long as it is not tor_addr_is_null(), by converting it to a tor_addr_t
  1774. * and passing it to policies_add_addr_to_smartlist.
  1775. *
  1776. * The caller is responsible for freeing all the tor_addr_t* in the smartlist.
  1777. */
  1778. static void
  1779. policies_copy_ipv4h_to_smartlist(smartlist_t *addr_list, uint32_t ipv4h_addr)
  1780. {
  1781. if (ipv4h_addr) {
  1782. tor_addr_t ipv4_tor_addr;
  1783. tor_addr_from_ipv4h(&ipv4_tor_addr, ipv4h_addr);
  1784. policies_copy_addr_to_smartlist(addr_list, &ipv4_tor_addr);
  1785. }
  1786. }
  1787. /** Helper function that adds copies of
  1788. * or_options->OutboundBindAddressIPv[4|6]_ to a smartlist as tor_addr_t *, as
  1789. * long as or_options is non-NULL, and the addresses are not
  1790. * tor_addr_is_null(), by passing them to policies_add_addr_to_smartlist.
  1791. *
  1792. * The caller is responsible for freeing all the tor_addr_t* in the smartlist.
  1793. */
  1794. static void
  1795. policies_copy_outbound_addresses_to_smartlist(smartlist_t *addr_list,
  1796. const or_options_t *or_options)
  1797. {
  1798. if (or_options) {
  1799. policies_copy_addr_to_smartlist(addr_list,
  1800. &or_options->OutboundBindAddressIPv4_);
  1801. policies_copy_addr_to_smartlist(addr_list,
  1802. &or_options->OutboundBindAddressIPv6_);
  1803. }
  1804. }
  1805. /** Parse <b>ExitPolicy</b> member of <b>or_options</b> into <b>result</b>
  1806. * smartlist.
  1807. * If <b>or_options->IPv6Exit</b> is false, prepend an entry that
  1808. * rejects all IPv6 destinations.
  1809. *
  1810. * If <b>or_options->ExitPolicyRejectPrivate</b> is true:
  1811. * - prepend an entry that rejects all destinations in all netblocks reserved
  1812. * for private use.
  1813. * - if local_address is non-zero, treat it as a host-order IPv4 address, and
  1814. * add it to the list of configured addresses.
  1815. * - if ipv6_local_address is non-NULL, and not the null tor_addr_t, add it
  1816. * to the list of configured addresses.
  1817. * If <b>or_options->ExitPolicyRejectLocalInterfaces</b> is true:
  1818. * - if or_options->OutboundBindAddressIPv4_ is not the null tor_addr_t, add
  1819. * it to the list of configured addresses.
  1820. * - if or_options->OutboundBindAddressIPv6_ is not the null tor_addr_t, add
  1821. * it to the list of configured addresses.
  1822. *
  1823. * If <b>or_options->BridgeRelay</b> is false, append entries of default
  1824. * Tor exit policy into <b>result</b> smartlist.
  1825. *
  1826. * If or_options->ExitRelay is false, then make our exit policy into
  1827. * "reject *:*" regardless.
  1828. */
  1829. int
  1830. policies_parse_exit_policy_from_options(const or_options_t *or_options,
  1831. uint32_t local_address,
  1832. const tor_addr_t *ipv6_local_address,
  1833. smartlist_t **result)
  1834. {
  1835. exit_policy_parser_cfg_t parser_cfg = 0;
  1836. smartlist_t *configured_addresses = NULL;
  1837. int rv = 0;
  1838. /* Short-circuit for non-exit relays */
  1839. if (or_options->ExitRelay == 0) {
  1840. append_exit_policy_string(result, "reject *4:*");
  1841. append_exit_policy_string(result, "reject *6:*");
  1842. return 0;
  1843. }
  1844. configured_addresses = smartlist_new();
  1845. /* Configure the parser */
  1846. if (or_options->IPv6Exit) {
  1847. parser_cfg |= EXIT_POLICY_IPV6_ENABLED;
  1848. }
  1849. if (or_options->ExitPolicyRejectPrivate) {
  1850. parser_cfg |= EXIT_POLICY_REJECT_PRIVATE;
  1851. }
  1852. if (!or_options->BridgeRelay) {
  1853. parser_cfg |= EXIT_POLICY_ADD_DEFAULT;
  1854. }
  1855. if (or_options->ExitPolicyRejectLocalInterfaces) {
  1856. parser_cfg |= EXIT_POLICY_REJECT_LOCAL_INTERFACES;
  1857. }
  1858. /* Copy the configured addresses into the tor_addr_t* list */
  1859. if (or_options->ExitPolicyRejectPrivate) {
  1860. policies_copy_ipv4h_to_smartlist(configured_addresses, local_address);
  1861. policies_copy_addr_to_smartlist(configured_addresses, ipv6_local_address);
  1862. }
  1863. if (or_options->ExitPolicyRejectLocalInterfaces) {
  1864. policies_copy_outbound_addresses_to_smartlist(configured_addresses,
  1865. or_options);
  1866. }
  1867. rv = policies_parse_exit_policy(or_options->ExitPolicy, result, parser_cfg,
  1868. configured_addresses);
  1869. SMARTLIST_FOREACH(configured_addresses, tor_addr_t *, a, tor_free(a));
  1870. smartlist_free(configured_addresses);
  1871. return rv;
  1872. }
  1873. /** Add "reject *:*" to the end of the policy in *<b>dest</b>, allocating
  1874. * *<b>dest</b> as needed. */
  1875. void
  1876. policies_exit_policy_append_reject_star(smartlist_t **dest)
  1877. {
  1878. append_exit_policy_string(dest, "reject *4:*");
  1879. append_exit_policy_string(dest, "reject *6:*");
  1880. }
  1881. /** Replace the exit policy of <b>node</b> with reject *:* */
  1882. void
  1883. policies_set_node_exitpolicy_to_reject_all(node_t *node)
  1884. {
  1885. node->rejects_all = 1;
  1886. }
  1887. /** Return 1 if there is at least one /8 subnet in <b>policy</b> that
  1888. * allows exiting to <b>port</b>. Otherwise, return 0. */
  1889. static int
  1890. exit_policy_is_general_exit_helper(smartlist_t *policy, int port)
  1891. {
  1892. uint32_t mask, ip, i;
  1893. /* Is this /8 rejected (1), or undecided (0)? */
  1894. char subnet_status[256];
  1895. memset(subnet_status, 0, sizeof(subnet_status));
  1896. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
  1897. if (tor_addr_family(&p->addr) != AF_INET)
  1898. continue; /* IPv4 only for now */
  1899. if (p->prt_min > port || p->prt_max < port)
  1900. continue; /* Doesn't cover our port. */
  1901. mask = 0;
  1902. tor_assert(p->maskbits <= 32);
  1903. if (p->maskbits)
  1904. mask = UINT32_MAX<<(32-p->maskbits);
  1905. ip = tor_addr_to_ipv4h(&p->addr);
  1906. /* Calculate the first and last subnet that this exit policy touches
  1907. * and set it as loop boundaries. */
  1908. for (i = ((mask & ip)>>24); i <= (~((mask & ip) ^ mask)>>24); ++i) {
  1909. tor_addr_t addr;
  1910. if (subnet_status[i] != 0)
  1911. continue; /* We already reject some part of this /8 */
  1912. tor_addr_from_ipv4h(&addr, i<<24);
  1913. if (tor_addr_is_internal(&addr, 0) &&
  1914. !get_options()->DirAllowPrivateAddresses) {
  1915. continue; /* Local or non-routable addresses */
  1916. }
  1917. if (p->policy_type == ADDR_POLICY_ACCEPT) {
  1918. if (p->maskbits > 8)
  1919. continue; /* Narrower than a /8. */
  1920. /* We found an allowed subnet of at least size /8. Done
  1921. * for this port! */
  1922. return 1;
  1923. } else if (p->policy_type == ADDR_POLICY_REJECT) {
  1924. subnet_status[i] = 1;
  1925. }
  1926. }
  1927. } SMARTLIST_FOREACH_END(p);
  1928. return 0;
  1929. }
  1930. /** Return true iff <b>ri</b> is "useful as an exit node", meaning
  1931. * it allows exit to at least one /8 address space for at least
  1932. * two of ports 80, 443, and 6667. */
  1933. int
  1934. exit_policy_is_general_exit(smartlist_t *policy)
  1935. {
  1936. static const int ports[] = { 80, 443, 6667 };
  1937. int n_allowed = 0;
  1938. int i;
  1939. if (!policy) /*XXXX disallow NULL policies? */
  1940. return 0;
  1941. for (i = 0; i < 3; ++i) {
  1942. n_allowed += exit_policy_is_general_exit_helper(policy, ports[i]);
  1943. }
  1944. return n_allowed >= 2;
  1945. }
  1946. /** Return false if <b>policy</b> might permit access to some addr:port;
  1947. * otherwise if we are certain it rejects everything, return true. If no
  1948. * part of <b>policy</b> matches, return <b>default_reject</b>.
  1949. * NULL policies are allowed, and treated as empty. */
  1950. int
  1951. policy_is_reject_star(const smartlist_t *policy, sa_family_t family,
  1952. int default_reject)
  1953. {
  1954. if (!policy)
  1955. return default_reject;
  1956. SMARTLIST_FOREACH_BEGIN(policy, const addr_policy_t *, p) {
  1957. if (p->policy_type == ADDR_POLICY_ACCEPT &&
  1958. (tor_addr_family(&p->addr) == family ||
  1959. tor_addr_family(&p->addr) == AF_UNSPEC)) {
  1960. return 0;
  1961. } else if (p->policy_type == ADDR_POLICY_REJECT &&
  1962. p->prt_min <= 1 && p->prt_max == 65535 &&
  1963. p->maskbits == 0 &&
  1964. (tor_addr_family(&p->addr) == family ||
  1965. tor_addr_family(&p->addr) == AF_UNSPEC)) {
  1966. return 1;
  1967. }
  1968. } SMARTLIST_FOREACH_END(p);
  1969. return default_reject;
  1970. }
  1971. /** Write a single address policy to the buf_len byte buffer at buf. Return
  1972. * the number of characters written, or -1 on failure. */
  1973. int
  1974. policy_write_item(char *buf, size_t buflen, const addr_policy_t *policy,
  1975. int format_for_desc)
  1976. {
  1977. size_t written = 0;
  1978. char addrbuf[TOR_ADDR_BUF_LEN];
  1979. const char *addrpart;
  1980. int result;
  1981. const int is_accept = policy->policy_type == ADDR_POLICY_ACCEPT;
  1982. const sa_family_t family = tor_addr_family(&policy->addr);
  1983. const int is_ip6 = (family == AF_INET6);
  1984. tor_addr_to_str(addrbuf, &policy->addr, sizeof(addrbuf), 1);
  1985. /* write accept/reject 1.2.3.4 */
  1986. if (policy->is_private) {
  1987. addrpart = "private";
  1988. } else if (policy->maskbits == 0) {
  1989. if (format_for_desc)
  1990. addrpart = "*";
  1991. else if (family == AF_INET6)
  1992. addrpart = "*6";
  1993. else if (family == AF_INET)
  1994. addrpart = "*4";
  1995. else
  1996. addrpart = "*";
  1997. } else {
  1998. addrpart = addrbuf;
  1999. }
  2000. result = tor_snprintf(buf, buflen, "%s%s %s",
  2001. is_accept ? "accept" : "reject",
  2002. (is_ip6&&format_for_desc)?"6":"",
  2003. addrpart);
  2004. if (result < 0)
  2005. return -1;
  2006. written += strlen(buf);
  2007. /* If the maskbits is 32 (IPv4) or 128 (IPv6) we don't need to give it. If
  2008. the mask is 0, we already wrote "*". */
  2009. if (policy->maskbits < (is_ip6?128:32) && policy->maskbits > 0) {
  2010. if (tor_snprintf(buf+written, buflen-written, "/%d", policy->maskbits)<0)
  2011. return -1;
  2012. written += strlen(buf+written);
  2013. }
  2014. if (policy->prt_min <= 1 && policy->prt_max == 65535) {
  2015. /* There is no port set; write ":*" */
  2016. if (written+4 > buflen)
  2017. return -1;
  2018. strlcat(buf+written, ":*", buflen-written);
  2019. written += 2;
  2020. } else if (policy->prt_min == policy->prt_max) {
  2021. /* There is only one port; write ":80". */
  2022. result = tor_snprintf(buf+written, buflen-written, ":%d", policy->prt_min);
  2023. if (result<0)
  2024. return -1;
  2025. written += result;
  2026. } else {
  2027. /* There is a range of ports; write ":79-80". */
  2028. result = tor_snprintf(buf+written, buflen-written, ":%d-%d",
  2029. policy->prt_min, policy->prt_max);
  2030. if (result<0)
  2031. return -1;
  2032. written += result;
  2033. }
  2034. if (written < buflen)
  2035. buf[written] = '\0';
  2036. else
  2037. return -1;
  2038. return (int)written;
  2039. }
  2040. /** Create a new exit policy summary, initially only with a single
  2041. * port 1-64k item */
  2042. /* XXXX This entire thing will do most stuff in O(N^2), or worse. Use an
  2043. * RB-tree if that turns out to matter. */
  2044. static smartlist_t *
  2045. policy_summary_create(void)
  2046. {
  2047. smartlist_t *summary;
  2048. policy_summary_item_t* item;
  2049. item = tor_malloc_zero(sizeof(policy_summary_item_t));
  2050. item->prt_min = 1;
  2051. item->prt_max = 65535;
  2052. item->reject_count = 0;
  2053. item->accepted = 0;
  2054. summary = smartlist_new();
  2055. smartlist_add(summary, item);
  2056. return summary;
  2057. }
  2058. /** Split the summary item in <b>item</b> at the port <b>new_starts</b>.
  2059. * The current item is changed to end at new-starts - 1, the new item
  2060. * copies reject_count and accepted from the old item,
  2061. * starts at new_starts and ends at the port where the original item
  2062. * previously ended.
  2063. */
  2064. static policy_summary_item_t*
  2065. policy_summary_item_split(policy_summary_item_t* old, uint16_t new_starts)
  2066. {
  2067. policy_summary_item_t* new;
  2068. new = tor_malloc_zero(sizeof(policy_summary_item_t));
  2069. new->prt_min = new_starts;
  2070. new->prt_max = old->prt_max;
  2071. new->reject_count = old->reject_count;
  2072. new->accepted = old->accepted;
  2073. old->prt_max = new_starts-1;
  2074. tor_assert(old->prt_min <= old->prt_max);
  2075. tor_assert(new->prt_min <= new->prt_max);
  2076. return new;
  2077. }
  2078. /* XXXX Nick says I'm going to hell for this. If he feels charitably towards
  2079. * my immortal soul, he can clean it up himself. */
  2080. #define AT(x) ((policy_summary_item_t*)smartlist_get(summary, x))
  2081. #define REJECT_CUTOFF_COUNT (1<<25)
  2082. /** Split an exit policy summary so that prt_min and prt_max
  2083. * fall at exactly the start and end of an item respectively.
  2084. */
  2085. static int
  2086. policy_summary_split(smartlist_t *summary,
  2087. uint16_t prt_min, uint16_t prt_max)
  2088. {
  2089. int start_at_index;
  2090. int i = 0;
  2091. while (AT(i)->prt_max < prt_min)
  2092. i++;
  2093. if (AT(i)->prt_min != prt_min) {
  2094. policy_summary_item_t* new_item;
  2095. new_item = policy_summary_item_split(AT(i), prt_min);
  2096. smartlist_insert(summary, i+1, new_item);
  2097. i++;
  2098. }
  2099. start_at_index = i;
  2100. while (AT(i)->prt_max < prt_max)
  2101. i++;
  2102. if (AT(i)->prt_max != prt_max) {
  2103. policy_summary_item_t* new_item;
  2104. new_item = policy_summary_item_split(AT(i), prt_max+1);
  2105. smartlist_insert(summary, i+1, new_item);
  2106. }
  2107. return start_at_index;
  2108. }
  2109. /** Mark port ranges as accepted if they are below the reject_count */
  2110. static void
  2111. policy_summary_accept(smartlist_t *summary,
  2112. uint16_t prt_min, uint16_t prt_max)
  2113. {
  2114. int i = policy_summary_split(summary, prt_min, prt_max);
  2115. while (i < smartlist_len(summary) &&
  2116. AT(i)->prt_max <= prt_max) {
  2117. if (!AT(i)->accepted &&
  2118. AT(i)->reject_count <= REJECT_CUTOFF_COUNT)
  2119. AT(i)->accepted = 1;
  2120. i++;
  2121. }
  2122. tor_assert(i < smartlist_len(summary) || prt_max==65535);
  2123. }
  2124. /** Count the number of addresses in a network with prefixlen maskbits
  2125. * against the given portrange. */
  2126. static void
  2127. policy_summary_reject(smartlist_t *summary,
  2128. maskbits_t maskbits,
  2129. uint16_t prt_min, uint16_t prt_max)
  2130. {
  2131. int i = policy_summary_split(summary, prt_min, prt_max);
  2132. /* XXX: ipv4 specific */
  2133. uint64_t count = (U64_LITERAL(1) << (32-maskbits));
  2134. while (i < smartlist_len(summary) &&
  2135. AT(i)->prt_max <= prt_max) {
  2136. AT(i)->reject_count += count;
  2137. i++;
  2138. }
  2139. tor_assert(i < smartlist_len(summary) || prt_max==65535);
  2140. }
  2141. /** Add a single exit policy item to our summary:
  2142. *
  2143. * If it is an accept, ignore it unless it is for all IP addresses
  2144. * ("*", i.e. its prefixlen/maskbits is 0). Otherwise call
  2145. * policy_summary_accept().
  2146. *
  2147. * If it is a reject, ignore it if it is about one of the private
  2148. * networks. Otherwise call policy_summary_reject().
  2149. */
  2150. static void
  2151. policy_summary_add_item(smartlist_t *summary, addr_policy_t *p)
  2152. {
  2153. if (p->policy_type == ADDR_POLICY_ACCEPT) {
  2154. if (p->maskbits == 0) {
  2155. policy_summary_accept(summary, p->prt_min, p->prt_max);
  2156. }
  2157. } else if (p->policy_type == ADDR_POLICY_REJECT) {
  2158. int is_private = 0;
  2159. int i;
  2160. for (i = 0; private_nets[i]; ++i) {
  2161. tor_addr_t addr;
  2162. maskbits_t maskbits;
  2163. if (tor_addr_parse_mask_ports(private_nets[i], 0, &addr,
  2164. &maskbits, NULL, NULL)<0) {
  2165. tor_assert(0);
  2166. }
  2167. if (tor_addr_compare(&p->addr, &addr, CMP_EXACT) == 0 &&
  2168. p->maskbits == maskbits) {
  2169. is_private = 1;
  2170. break;
  2171. }
  2172. }
  2173. if (!is_private) {
  2174. policy_summary_reject(summary, p->maskbits, p->prt_min, p->prt_max);
  2175. }
  2176. } else
  2177. tor_assert(0);
  2178. }
  2179. /** Create a string representing a summary for an exit policy.
  2180. * The summary will either be an "accept" plus a comma-separated list of port
  2181. * ranges or a "reject" plus port-ranges, depending on which is shorter.
  2182. *
  2183. * If no exits are allowed at all then "reject 1-65535" is returned. If no
  2184. * ports are blocked instead of "reject " we return "accept 1-65535". (These
  2185. * are an exception to the shorter-representation-wins rule).
  2186. */
  2187. char *
  2188. policy_summarize(smartlist_t *policy, sa_family_t family)
  2189. {
  2190. smartlist_t *summary = policy_summary_create();
  2191. smartlist_t *accepts, *rejects;
  2192. int i, last, start_prt;
  2193. size_t accepts_len, rejects_len;
  2194. char *accepts_str = NULL, *rejects_str = NULL, *shorter_str, *result;
  2195. const char *prefix;
  2196. tor_assert(policy);
  2197. /* Create the summary list */
  2198. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
  2199. sa_family_t f = tor_addr_family(&p->addr);
  2200. if (f != AF_INET && f != AF_INET6) {
  2201. log_warn(LD_BUG, "Weird family when summarizing address policy");
  2202. }
  2203. if (f != family)
  2204. continue;
  2205. /* XXXX-ipv6 More family work is needed */
  2206. policy_summary_add_item(summary, p);
  2207. } SMARTLIST_FOREACH_END(p);
  2208. /* Now create two lists of strings, one for accepted and one
  2209. * for rejected ports. We take care to merge ranges so that
  2210. * we avoid getting stuff like "1-4,5-9,10", instead we want
  2211. * "1-10"
  2212. */
  2213. i = 0;
  2214. start_prt = 1;
  2215. accepts = smartlist_new();
  2216. rejects = smartlist_new();
  2217. while (1) {
  2218. last = i == smartlist_len(summary)-1;
  2219. if (last ||
  2220. AT(i)->accepted != AT(i+1)->accepted) {
  2221. char buf[POLICY_BUF_LEN];
  2222. if (start_prt == AT(i)->prt_max)
  2223. tor_snprintf(buf, sizeof(buf), "%d", start_prt);
  2224. else
  2225. tor_snprintf(buf, sizeof(buf), "%d-%d", start_prt, AT(i)->prt_max);
  2226. if (AT(i)->accepted)
  2227. smartlist_add(accepts, tor_strdup(buf));
  2228. else
  2229. smartlist_add(rejects, tor_strdup(buf));
  2230. if (last)
  2231. break;
  2232. start_prt = AT(i+1)->prt_min;
  2233. };
  2234. i++;
  2235. };
  2236. /* Figure out which of the two stringlists will be shorter and use
  2237. * that to build the result
  2238. */
  2239. if (smartlist_len(accepts) == 0) { /* no exits at all */
  2240. result = tor_strdup("reject 1-65535");
  2241. goto cleanup;
  2242. }
  2243. if (smartlist_len(rejects) == 0) { /* no rejects at all */
  2244. result = tor_strdup("accept 1-65535");
  2245. goto cleanup;
  2246. }
  2247. accepts_str = smartlist_join_strings(accepts, ",", 0, &accepts_len);
  2248. rejects_str = smartlist_join_strings(rejects, ",", 0, &rejects_len);
  2249. if (rejects_len > MAX_EXITPOLICY_SUMMARY_LEN-strlen("reject")-1 &&
  2250. accepts_len > MAX_EXITPOLICY_SUMMARY_LEN-strlen("accept")-1) {
  2251. char *c;
  2252. shorter_str = accepts_str;
  2253. prefix = "accept";
  2254. c = shorter_str + (MAX_EXITPOLICY_SUMMARY_LEN-strlen(prefix)-1);
  2255. while (*c != ',' && c >= shorter_str)
  2256. c--;
  2257. tor_assert(c >= shorter_str);
  2258. tor_assert(*c == ',');
  2259. *c = '\0';
  2260. } else if (rejects_len < accepts_len) {
  2261. shorter_str = rejects_str;
  2262. prefix = "reject";
  2263. } else {
  2264. shorter_str = accepts_str;
  2265. prefix = "accept";
  2266. }
  2267. tor_asprintf(&result, "%s %s", prefix, shorter_str);
  2268. cleanup:
  2269. /* cleanup */
  2270. SMARTLIST_FOREACH(summary, policy_summary_item_t *, s, tor_free(s));
  2271. smartlist_free(summary);
  2272. tor_free(accepts_str);
  2273. SMARTLIST_FOREACH(accepts, char *, s, tor_free(s));
  2274. smartlist_free(accepts);
  2275. tor_free(rejects_str);
  2276. SMARTLIST_FOREACH(rejects, char *, s, tor_free(s));
  2277. smartlist_free(rejects);
  2278. return result;
  2279. }
  2280. /** Convert a summarized policy string into a short_policy_t. Return NULL
  2281. * if the string is not well-formed. */
  2282. short_policy_t *
  2283. parse_short_policy(const char *summary)
  2284. {
  2285. const char *orig_summary = summary;
  2286. short_policy_t *result;
  2287. int is_accept;
  2288. int n_entries;
  2289. short_policy_entry_t entries[MAX_EXITPOLICY_SUMMARY_LEN]; /* overkill */
  2290. const char *next;
  2291. if (!strcmpstart(summary, "accept ")) {
  2292. is_accept = 1;
  2293. summary += strlen("accept ");
  2294. } else if (!strcmpstart(summary, "reject ")) {
  2295. is_accept = 0;
  2296. summary += strlen("reject ");
  2297. } else {
  2298. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Unrecognized policy summary keyword");
  2299. return NULL;
  2300. }
  2301. n_entries = 0;
  2302. for ( ; *summary; summary = next) {
  2303. const char *comma = strchr(summary, ',');
  2304. unsigned low, high;
  2305. char dummy;
  2306. char ent_buf[32];
  2307. size_t len;
  2308. next = comma ? comma+1 : strchr(summary, '\0');
  2309. len = comma ? (size_t)(comma - summary) : strlen(summary);
  2310. if (n_entries == MAX_EXITPOLICY_SUMMARY_LEN) {
  2311. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Impossibly long policy summary %s",
  2312. escaped(orig_summary));
  2313. return NULL;
  2314. }
  2315. if (! TOR_ISDIGIT(*summary) || len > (sizeof(ent_buf)-1)) {
  2316. /* unrecognized entry format. skip it. */
  2317. continue;
  2318. }
  2319. if (len < 1) {
  2320. /* empty; skip it. */
  2321. /* XXX This happens to be unreachable, since if len==0, then *summary is
  2322. * ',' or '\0', and the TOR_ISDIGIT test above would have failed. */
  2323. continue;
  2324. }
  2325. memcpy(ent_buf, summary, len);
  2326. ent_buf[len] = '\0';
  2327. if (tor_sscanf(ent_buf, "%u-%u%c", &low, &high, &dummy) == 2) {
  2328. if (low<1 || low>65535 || high<1 || high>65535 || low>high) {
  2329. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  2330. "Found bad entry in policy summary %s", escaped(orig_summary));
  2331. return NULL;
  2332. }
  2333. } else if (tor_sscanf(ent_buf, "%u%c", &low, &dummy) == 1) {
  2334. if (low<1 || low>65535) {
  2335. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  2336. "Found bad entry in policy summary %s", escaped(orig_summary));
  2337. return NULL;
  2338. }
  2339. high = low;
  2340. } else {
  2341. log_fn(LOG_PROTOCOL_WARN, LD_DIR,"Found bad entry in policy summary %s",
  2342. escaped(orig_summary));
  2343. return NULL;
  2344. }
  2345. entries[n_entries].min_port = low;
  2346. entries[n_entries].max_port = high;
  2347. n_entries++;
  2348. }
  2349. if (n_entries == 0) {
  2350. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  2351. "Found no port-range entries in summary %s", escaped(orig_summary));
  2352. return NULL;
  2353. }
  2354. {
  2355. size_t size = STRUCT_OFFSET(short_policy_t, entries) +
  2356. sizeof(short_policy_entry_t)*(n_entries);
  2357. result = tor_malloc_zero(size);
  2358. tor_assert( (char*)&result->entries[n_entries-1] < ((char*)result)+size);
  2359. }
  2360. result->is_accept = is_accept;
  2361. result->n_entries = n_entries;
  2362. memcpy(result->entries, entries, sizeof(short_policy_entry_t)*n_entries);
  2363. return result;
  2364. }
  2365. /** Write <b>policy</b> back out into a string. Used only for unit tests
  2366. * currently. */
  2367. char *
  2368. write_short_policy(const short_policy_t *policy)
  2369. {
  2370. int i;
  2371. char *answer;
  2372. smartlist_t *sl = smartlist_new();
  2373. smartlist_add_asprintf(sl, "%s", policy->is_accept ? "accept " : "reject ");
  2374. for (i=0; i < policy->n_entries; i++) {
  2375. const short_policy_entry_t *e = &policy->entries[i];
  2376. if (e->min_port == e->max_port) {
  2377. smartlist_add_asprintf(sl, "%d", e->min_port);
  2378. } else {
  2379. smartlist_add_asprintf(sl, "%d-%d", e->min_port, e->max_port);
  2380. }
  2381. if (i < policy->n_entries-1)
  2382. smartlist_add(sl, tor_strdup(","));
  2383. }
  2384. answer = smartlist_join_strings(sl, "", 0, NULL);
  2385. SMARTLIST_FOREACH(sl, char *, a, tor_free(a));
  2386. smartlist_free(sl);
  2387. return answer;
  2388. }
  2389. /** Release all storage held in <b>policy</b>. */
  2390. void
  2391. short_policy_free(short_policy_t *policy)
  2392. {
  2393. tor_free(policy);
  2394. }
  2395. /** See whether the <b>addr</b>:<b>port</b> address is likely to be accepted
  2396. * or rejected by the summarized policy <b>policy</b>. Return values are as
  2397. * for compare_tor_addr_to_addr_policy. Unlike the regular addr_policy
  2398. * functions, requires the <b>port</b> be specified. */
  2399. addr_policy_result_t
  2400. compare_tor_addr_to_short_policy(const tor_addr_t *addr, uint16_t port,
  2401. const short_policy_t *policy)
  2402. {
  2403. int i;
  2404. int found_match = 0;
  2405. int accept_;
  2406. tor_assert(port != 0);
  2407. if (addr && tor_addr_is_null(addr))
  2408. addr = NULL; /* Unspec means 'no address at all,' in this context. */
  2409. if (addr && get_options()->ClientRejectInternalAddresses &&
  2410. (tor_addr_is_internal(addr, 0) || tor_addr_is_loopback(addr)))
  2411. return ADDR_POLICY_REJECTED;
  2412. for (i=0; i < policy->n_entries; ++i) {
  2413. const short_policy_entry_t *e = &policy->entries[i];
  2414. if (e->min_port <= port && port <= e->max_port) {
  2415. found_match = 1;
  2416. break;
  2417. }
  2418. }
  2419. if (found_match)
  2420. accept_ = policy->is_accept;
  2421. else
  2422. accept_ = ! policy->is_accept;
  2423. /* ???? are these right? -NM */
  2424. /* We should be sure not to return ADDR_POLICY_ACCEPTED in the accept
  2425. * case here, because it would cause clients to believe that the node
  2426. * allows exit enclaving. Trying it anyway would open up a cool attack
  2427. * where the node refuses due to exitpolicy, the client reacts in
  2428. * surprise by rewriting the node's exitpolicy to reject *:*, and then
  2429. * an adversary targets users by causing them to attempt such connections
  2430. * to 98% of the exits.
  2431. *
  2432. * Once microdescriptors can handle addresses in special cases (e.g. if
  2433. * we ever solve ticket 1774), we can provide certainty here. -RD */
  2434. if (accept_)
  2435. return ADDR_POLICY_PROBABLY_ACCEPTED;
  2436. else
  2437. return ADDR_POLICY_REJECTED;
  2438. }
  2439. /** Return true iff <b>policy</b> seems reject all ports */
  2440. int
  2441. short_policy_is_reject_star(const short_policy_t *policy)
  2442. {
  2443. /* This doesn't need to be as much on the lookout as policy_is_reject_star,
  2444. * since policy summaries are from the consensus or from consensus
  2445. * microdescs.
  2446. */
  2447. tor_assert(policy);
  2448. /* Check for an exact match of "reject 1-65535". */
  2449. return (policy->is_accept == 0 && policy->n_entries == 1 &&
  2450. policy->entries[0].min_port == 1 &&
  2451. policy->entries[0].max_port == 65535);
  2452. }
  2453. /** Decide whether addr:port is probably or definitely accepted or rejected by
  2454. * <b>node</b>. See compare_tor_addr_to_addr_policy for details on addr/port
  2455. * interpretation. */
  2456. addr_policy_result_t
  2457. compare_tor_addr_to_node_policy(const tor_addr_t *addr, uint16_t port,
  2458. const node_t *node)
  2459. {
  2460. if (node->rejects_all)
  2461. return ADDR_POLICY_REJECTED;
  2462. if (addr && tor_addr_family(addr) == AF_INET6) {
  2463. const short_policy_t *p = NULL;
  2464. if (node->ri)
  2465. p = node->ri->ipv6_exit_policy;
  2466. else if (node->md)
  2467. p = node->md->ipv6_exit_policy;
  2468. if (p)
  2469. return compare_tor_addr_to_short_policy(addr, port, p);
  2470. else
  2471. return ADDR_POLICY_REJECTED;
  2472. }
  2473. if (node->ri) {
  2474. return compare_tor_addr_to_addr_policy(addr, port, node->ri->exit_policy);
  2475. } else if (node->md) {
  2476. if (node->md->exit_policy == NULL)
  2477. return ADDR_POLICY_REJECTED;
  2478. else
  2479. return compare_tor_addr_to_short_policy(addr, port,
  2480. node->md->exit_policy);
  2481. } else {
  2482. return ADDR_POLICY_PROBABLY_REJECTED;
  2483. }
  2484. }
  2485. /**
  2486. * Given <b>policy_list</b>, a list of addr_policy_t, produce a string
  2487. * representation of the list.
  2488. * If <b>include_ipv4</b> is true, include IPv4 entries.
  2489. * If <b>include_ipv6</b> is true, include IPv6 entries.
  2490. */
  2491. char *
  2492. policy_dump_to_string(const smartlist_t *policy_list,
  2493. int include_ipv4,
  2494. int include_ipv6)
  2495. {
  2496. smartlist_t *policy_string_list;
  2497. char *policy_string = NULL;
  2498. policy_string_list = smartlist_new();
  2499. SMARTLIST_FOREACH_BEGIN(policy_list, addr_policy_t *, tmpe) {
  2500. char *pbuf;
  2501. int bytes_written_to_pbuf;
  2502. if ((tor_addr_family(&tmpe->addr) == AF_INET6) && (!include_ipv6)) {
  2503. continue; /* Don't include IPv6 parts of address policy */
  2504. }
  2505. if ((tor_addr_family(&tmpe->addr) == AF_INET) && (!include_ipv4)) {
  2506. continue; /* Don't include IPv4 parts of address policy */
  2507. }
  2508. pbuf = tor_malloc(POLICY_BUF_LEN);
  2509. bytes_written_to_pbuf = policy_write_item(pbuf,POLICY_BUF_LEN, tmpe, 1);
  2510. if (bytes_written_to_pbuf < 0) {
  2511. log_warn(LD_BUG, "policy_dump_to_string ran out of room!");
  2512. tor_free(pbuf);
  2513. goto done;
  2514. }
  2515. smartlist_add(policy_string_list,pbuf);
  2516. } SMARTLIST_FOREACH_END(tmpe);
  2517. policy_string = smartlist_join_strings(policy_string_list, "\n", 0, NULL);
  2518. done:
  2519. SMARTLIST_FOREACH(policy_string_list, char *, str, tor_free(str));
  2520. smartlist_free(policy_string_list);
  2521. return policy_string;
  2522. }
  2523. /** Implementation for GETINFO control command: knows the answer for questions
  2524. * about "exit-policy/..." */
  2525. int
  2526. getinfo_helper_policies(control_connection_t *conn,
  2527. const char *question, char **answer,
  2528. const char **errmsg)
  2529. {
  2530. (void) conn;
  2531. (void) errmsg;
  2532. if (!strcmp(question, "exit-policy/default")) {
  2533. *answer = tor_strdup(DEFAULT_EXIT_POLICY);
  2534. } else if (!strcmp(question, "exit-policy/reject-private/default")) {
  2535. smartlist_t *private_policy_strings;
  2536. const char **priv = private_nets;
  2537. private_policy_strings = smartlist_new();
  2538. while (*priv != NULL) {
  2539. /* IPv6 addresses are in "[]" and contain ":",
  2540. * IPv4 addresses are not in "[]" and contain "." */
  2541. smartlist_add_asprintf(private_policy_strings, "reject %s:*", *priv);
  2542. priv++;
  2543. }
  2544. *answer = smartlist_join_strings(private_policy_strings,
  2545. ",", 0, NULL);
  2546. SMARTLIST_FOREACH(private_policy_strings, char *, str, tor_free(str));
  2547. smartlist_free(private_policy_strings);
  2548. } else if (!strcmp(question, "exit-policy/reject-private/relay")) {
  2549. const or_options_t *options = get_options();
  2550. const routerinfo_t *me = router_get_my_routerinfo();
  2551. if (!me) {
  2552. *errmsg = "router_get_my_routerinfo returned NULL";
  2553. return -1;
  2554. }
  2555. if (!options->ExitPolicyRejectPrivate &&
  2556. !options->ExitPolicyRejectLocalInterfaces) {
  2557. *answer = tor_strdup("");
  2558. return 0;
  2559. }
  2560. smartlist_t *private_policy_list = smartlist_new();
  2561. smartlist_t *configured_addresses = smartlist_new();
  2562. /* Copy the configured addresses into the tor_addr_t* list */
  2563. if (options->ExitPolicyRejectPrivate) {
  2564. policies_copy_ipv4h_to_smartlist(configured_addresses, me->addr);
  2565. policies_copy_addr_to_smartlist(configured_addresses, &me->ipv6_addr);
  2566. }
  2567. if (options->ExitPolicyRejectLocalInterfaces) {
  2568. policies_copy_outbound_addresses_to_smartlist(configured_addresses,
  2569. options);
  2570. }
  2571. policies_parse_exit_policy_reject_private(
  2572. &private_policy_list,
  2573. options->IPv6Exit,
  2574. configured_addresses,
  2575. options->ExitPolicyRejectLocalInterfaces,
  2576. options->ExitPolicyRejectLocalInterfaces);
  2577. *answer = policy_dump_to_string(private_policy_list, 1, 1);
  2578. addr_policy_list_free(private_policy_list);
  2579. SMARTLIST_FOREACH(configured_addresses, tor_addr_t *, a, tor_free(a));
  2580. smartlist_free(configured_addresses);
  2581. } else if (!strcmpstart(question, "exit-policy/")) {
  2582. const routerinfo_t *me = router_get_my_routerinfo();
  2583. int include_ipv4 = 0;
  2584. int include_ipv6 = 0;
  2585. if (!strcmp(question, "exit-policy/ipv4")) {
  2586. include_ipv4 = 1;
  2587. } else if (!strcmp(question, "exit-policy/ipv6")) {
  2588. include_ipv6 = 1;
  2589. } else if (!strcmp(question, "exit-policy/full")) {
  2590. include_ipv4 = include_ipv6 = 1;
  2591. } else {
  2592. return 0; /* No such key. */
  2593. }
  2594. if (!me) {
  2595. *errmsg = "router_get_my_routerinfo returned NULL";
  2596. return -1;
  2597. }
  2598. *answer = router_dump_exit_policy_to_string(me,include_ipv4,include_ipv6);
  2599. }
  2600. return 0;
  2601. }
  2602. /** Release all storage held by <b>p</b>. */
  2603. void
  2604. addr_policy_list_free(smartlist_t *lst)
  2605. {
  2606. if (!lst)
  2607. return;
  2608. SMARTLIST_FOREACH(lst, addr_policy_t *, policy, addr_policy_free(policy));
  2609. smartlist_free(lst);
  2610. }
  2611. /** Release all storage held by <b>p</b>. */
  2612. void
  2613. addr_policy_free(addr_policy_t *p)
  2614. {
  2615. if (!p)
  2616. return;
  2617. if (--p->refcnt <= 0) {
  2618. if (p->is_canonical) {
  2619. policy_map_ent_t search, *found;
  2620. search.policy = p;
  2621. found = HT_REMOVE(policy_map, &policy_root, &search);
  2622. if (found) {
  2623. tor_assert(p == found->policy);
  2624. tor_free(found);
  2625. }
  2626. }
  2627. tor_free(p);
  2628. }
  2629. }
  2630. /** Release all storage held by policy variables. */
  2631. void
  2632. policies_free_all(void)
  2633. {
  2634. addr_policy_list_free(reachable_or_addr_policy);
  2635. reachable_or_addr_policy = NULL;
  2636. addr_policy_list_free(reachable_dir_addr_policy);
  2637. reachable_dir_addr_policy = NULL;
  2638. addr_policy_list_free(socks_policy);
  2639. socks_policy = NULL;
  2640. addr_policy_list_free(dir_policy);
  2641. dir_policy = NULL;
  2642. addr_policy_list_free(authdir_reject_policy);
  2643. authdir_reject_policy = NULL;
  2644. addr_policy_list_free(authdir_invalid_policy);
  2645. authdir_invalid_policy = NULL;
  2646. addr_policy_list_free(authdir_badexit_policy);
  2647. authdir_badexit_policy = NULL;
  2648. if (!HT_EMPTY(&policy_root)) {
  2649. policy_map_ent_t **ent;
  2650. int n = 0;
  2651. char buf[POLICY_BUF_LEN];
  2652. log_warn(LD_MM, "Still had %d address policies cached at shutdown.",
  2653. (int)HT_SIZE(&policy_root));
  2654. /* Note the first 10 cached policies to try to figure out where they
  2655. * might be coming from. */
  2656. HT_FOREACH(ent, policy_map, &policy_root) {
  2657. if (++n > 10)
  2658. break;
  2659. if (policy_write_item(buf, sizeof(buf), (*ent)->policy, 0) >= 0)
  2660. log_warn(LD_MM," %d [%d]: %s", n, (*ent)->policy->refcnt, buf);
  2661. }
  2662. }
  2663. HT_CLEAR(policy_map, &policy_root);
  2664. }