policies.c 104 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040
  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. tor_addr_make_null(&ap->addr, AF_UNSPEC);
  775. ap->port = 0;
  776. return 0;
  777. }
  778. }
  779. /** Like fascist_firewall_choose_address_base(), but takes a host-order IPv4
  780. * address as the first parameter. */
  781. static int
  782. fascist_firewall_choose_address_ipv4h(uint32_t ipv4h_addr,
  783. uint16_t ipv4_orport,
  784. uint16_t ipv4_dirport,
  785. const tor_addr_t *ipv6_addr,
  786. uint16_t ipv6_orport,
  787. uint16_t ipv6_dirport,
  788. firewall_connection_t fw_connection,
  789. int pref_only,
  790. int pref_ipv6,
  791. tor_addr_port_t* ap)
  792. {
  793. tor_addr_t ipv4_addr;
  794. tor_addr_from_ipv4h(&ipv4_addr, ipv4h_addr);
  795. return fascist_firewall_choose_address_base(&ipv4_addr, ipv4_orport,
  796. ipv4_dirport, ipv6_addr,
  797. ipv6_orport, ipv6_dirport,
  798. fw_connection, pref_only,
  799. pref_ipv6, ap);
  800. }
  801. /** Like fascist_firewall_choose_address_base(), but takes <b>rs</b>.
  802. * Consults the corresponding node, then falls back to rs if node is NULL.
  803. * This should only happen when there's no valid consensus, and rs doesn't
  804. * correspond to a bridge client's bridge.
  805. */
  806. int
  807. fascist_firewall_choose_address_rs(const routerstatus_t *rs,
  808. firewall_connection_t fw_connection,
  809. int pref_only, tor_addr_port_t* ap)
  810. {
  811. if (!rs) {
  812. return 0;
  813. }
  814. tor_assert(ap);
  815. const node_t *node = node_get_by_id(rs->identity_digest);
  816. if (node) {
  817. return fascist_firewall_choose_address_node(node, fw_connection, pref_only,
  818. ap);
  819. } else {
  820. /* There's no node-specific IPv6 preference, so use the generic IPv6
  821. * preference instead. */
  822. const or_options_t *options = get_options();
  823. int pref_ipv6 = (fw_connection == FIREWALL_OR_CONNECTION
  824. ? fascist_firewall_prefer_ipv6_orport(options)
  825. : fascist_firewall_prefer_ipv6_dirport(options));
  826. /* Assume IPv4 and IPv6 DirPorts are the same.
  827. * Assume the IPv6 OR and Dir addresses are the same. */
  828. return fascist_firewall_choose_address_ipv4h(rs->addr,
  829. rs->or_port,
  830. rs->dir_port,
  831. &rs->ipv6_addr,
  832. rs->ipv6_orport,
  833. rs->dir_port,
  834. fw_connection,
  835. pref_only,
  836. pref_ipv6,
  837. ap);
  838. }
  839. }
  840. /** Like fascist_firewall_choose_address_base(), but takes <b>node</b>, and
  841. * looks up the node's IPv6 preference rather than taking an argument
  842. * for pref_ipv6. */
  843. int
  844. fascist_firewall_choose_address_node(const node_t *node,
  845. firewall_connection_t fw_connection,
  846. int pref_only, tor_addr_port_t *ap)
  847. {
  848. if (!node) {
  849. return 0;
  850. }
  851. node_assert_ok(node);
  852. const int pref_ipv6_node = (fw_connection == FIREWALL_OR_CONNECTION
  853. ? node_ipv6_or_preferred(node)
  854. : node_ipv6_dir_preferred(node));
  855. tor_addr_port_t ipv4_or_ap;
  856. node_get_prim_orport(node, &ipv4_or_ap);
  857. tor_addr_port_t ipv4_dir_ap;
  858. node_get_prim_dirport(node, &ipv4_dir_ap);
  859. tor_addr_port_t ipv6_or_ap;
  860. node_get_pref_ipv6_orport(node, &ipv6_or_ap);
  861. tor_addr_port_t ipv6_dir_ap;
  862. node_get_pref_ipv6_dirport(node, &ipv6_dir_ap);
  863. /* Assume the IPv6 OR and Dir addresses are the same. */
  864. return fascist_firewall_choose_address_base(&ipv4_or_ap.addr,
  865. ipv4_or_ap.port,
  866. ipv4_dir_ap.port,
  867. &ipv6_or_ap.addr,
  868. ipv6_or_ap.port,
  869. ipv6_dir_ap.port,
  870. fw_connection,
  871. pref_only,
  872. pref_ipv6_node,
  873. ap);
  874. }
  875. /** Like fascist_firewall_choose_address_rs(), but takes <b>ds</b>. */
  876. int
  877. fascist_firewall_choose_address_dir_server(const dir_server_t *ds,
  878. firewall_connection_t fw_connection,
  879. int pref_only,
  880. tor_addr_port_t *ap)
  881. {
  882. if (!ds) {
  883. return 0;
  884. }
  885. /* A dir_server_t always has a fake_status. As long as it has the same
  886. * addresses/ports in both fake_status and dir_server_t, this works fine.
  887. * (See #17867.)
  888. * This function relies on fascist_firewall_choose_address_rs looking up the
  889. * node if it can, because that will get the latest info for the relay. */
  890. return fascist_firewall_choose_address_rs(&ds->fake_status, fw_connection,
  891. pref_only, ap);
  892. }
  893. /** Return 1 if <b>addr</b> is permitted to connect to our dir port,
  894. * based on <b>dir_policy</b>. Else return 0.
  895. */
  896. int
  897. dir_policy_permits_address(const tor_addr_t *addr)
  898. {
  899. return addr_policy_permits_tor_addr(addr, 1, dir_policy);
  900. }
  901. /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
  902. * based on <b>socks_policy</b>. Else return 0.
  903. */
  904. int
  905. socks_policy_permits_address(const tor_addr_t *addr)
  906. {
  907. return addr_policy_permits_tor_addr(addr, 1, socks_policy);
  908. }
  909. /** Return true iff the address <b>addr</b> is in a country listed in the
  910. * case-insensitive list of country codes <b>cc_list</b>. */
  911. static int
  912. addr_is_in_cc_list(uint32_t addr, const smartlist_t *cc_list)
  913. {
  914. country_t country;
  915. const char *name;
  916. tor_addr_t tar;
  917. if (!cc_list)
  918. return 0;
  919. /* XXXXipv6 */
  920. tor_addr_from_ipv4h(&tar, addr);
  921. country = geoip_get_country_by_addr(&tar);
  922. name = geoip_get_country_name(country);
  923. return smartlist_contains_string_case(cc_list, name);
  924. }
  925. /** Return 1 if <b>addr</b>:<b>port</b> is permitted to publish to our
  926. * directory, based on <b>authdir_reject_policy</b>. Else return 0.
  927. */
  928. int
  929. authdir_policy_permits_address(uint32_t addr, uint16_t port)
  930. {
  931. if (! addr_policy_permits_address(addr, port, authdir_reject_policy))
  932. return 0;
  933. return !addr_is_in_cc_list(addr, get_options()->AuthDirRejectCCs);
  934. }
  935. /** Return 1 if <b>addr</b>:<b>port</b> is considered valid in our
  936. * directory, based on <b>authdir_invalid_policy</b>. Else return 0.
  937. */
  938. int
  939. authdir_policy_valid_address(uint32_t addr, uint16_t port)
  940. {
  941. if (! addr_policy_permits_address(addr, port, authdir_invalid_policy))
  942. return 0;
  943. return !addr_is_in_cc_list(addr, get_options()->AuthDirInvalidCCs);
  944. }
  945. /** Return 1 if <b>addr</b>:<b>port</b> should be marked as a bad exit,
  946. * based on <b>authdir_badexit_policy</b>. Else return 0.
  947. */
  948. int
  949. authdir_policy_badexit_address(uint32_t addr, uint16_t port)
  950. {
  951. if (! addr_policy_permits_address(addr, port, authdir_badexit_policy))
  952. return 1;
  953. return addr_is_in_cc_list(addr, get_options()->AuthDirBadExitCCs);
  954. }
  955. #define REJECT(arg) \
  956. STMT_BEGIN *msg = tor_strdup(arg); goto err; STMT_END
  957. /** Config helper: If there's any problem with the policy configuration
  958. * options in <b>options</b>, return -1 and set <b>msg</b> to a newly
  959. * allocated description of the error. Else return 0. */
  960. int
  961. validate_addr_policies(const or_options_t *options, char **msg)
  962. {
  963. /* XXXX Maybe merge this into parse_policies_from_options, to make sure
  964. * that the two can't go out of sync. */
  965. smartlist_t *addr_policy=NULL;
  966. *msg = NULL;
  967. if (policies_parse_exit_policy_from_options(options,0,NULL,&addr_policy)) {
  968. REJECT("Error in ExitPolicy entry.");
  969. }
  970. static int warned_about_exitrelay = 0;
  971. const int exitrelay_setting_is_auto = options->ExitRelay == -1;
  972. const int policy_accepts_something =
  973. ! (policy_is_reject_star(addr_policy, AF_INET, 1) &&
  974. policy_is_reject_star(addr_policy, AF_INET6, 1));
  975. if (server_mode(options) &&
  976. ! warned_about_exitrelay &&
  977. exitrelay_setting_is_auto &&
  978. policy_accepts_something) {
  979. /* Policy accepts something */
  980. warned_about_exitrelay = 1;
  981. log_warn(LD_CONFIG,
  982. "Tor is running as an exit relay%s. If you did not want this "
  983. "behavior, please set the ExitRelay option to 0. If you do "
  984. "want to run an exit Relay, please set the ExitRelay option "
  985. "to 1 to disable this warning, and for forward compatibility.",
  986. options->ExitPolicy == NULL ?
  987. " with the default exit policy" : "");
  988. if (options->ExitPolicy == NULL) {
  989. log_warn(LD_CONFIG,
  990. "In a future version of Tor, ExitRelay 0 may become the "
  991. "default when no ExitPolicy is given.");
  992. }
  993. }
  994. /* The rest of these calls *append* to addr_policy. So don't actually
  995. * use the results for anything other than checking if they parse! */
  996. if (parse_addr_policy(options->DirPolicy, &addr_policy, -1))
  997. REJECT("Error in DirPolicy entry.");
  998. if (parse_addr_policy(options->SocksPolicy, &addr_policy, -1))
  999. REJECT("Error in SocksPolicy entry.");
  1000. if (parse_addr_policy(options->AuthDirReject, &addr_policy,
  1001. ADDR_POLICY_REJECT))
  1002. REJECT("Error in AuthDirReject entry.");
  1003. if (parse_addr_policy(options->AuthDirInvalid, &addr_policy,
  1004. ADDR_POLICY_REJECT))
  1005. REJECT("Error in AuthDirInvalid entry.");
  1006. if (parse_addr_policy(options->AuthDirBadExit, &addr_policy,
  1007. ADDR_POLICY_REJECT))
  1008. REJECT("Error in AuthDirBadExit entry.");
  1009. if (parse_addr_policy(options->ReachableAddresses, &addr_policy,
  1010. ADDR_POLICY_ACCEPT))
  1011. REJECT("Error in ReachableAddresses entry.");
  1012. if (parse_addr_policy(options->ReachableORAddresses, &addr_policy,
  1013. ADDR_POLICY_ACCEPT))
  1014. REJECT("Error in ReachableORAddresses entry.");
  1015. if (parse_addr_policy(options->ReachableDirAddresses, &addr_policy,
  1016. ADDR_POLICY_ACCEPT))
  1017. REJECT("Error in ReachableDirAddresses entry.");
  1018. err:
  1019. addr_policy_list_free(addr_policy);
  1020. return *msg ? -1 : 0;
  1021. #undef REJECT
  1022. }
  1023. /** Parse <b>string</b> in the same way that the exit policy
  1024. * is parsed, and put the processed version in *<b>policy</b>.
  1025. * Ignore port specifiers.
  1026. */
  1027. static int
  1028. load_policy_from_option(config_line_t *config, const char *option_name,
  1029. smartlist_t **policy,
  1030. int assume_action)
  1031. {
  1032. int r;
  1033. int killed_any_ports = 0;
  1034. addr_policy_list_free(*policy);
  1035. *policy = NULL;
  1036. r = parse_addr_policy(config, policy, assume_action);
  1037. if (r < 0) {
  1038. return -1;
  1039. }
  1040. if (*policy) {
  1041. SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, n) {
  1042. /* ports aren't used in these. */
  1043. if (n->prt_min > 1 || n->prt_max != 65535) {
  1044. addr_policy_t newp, *c;
  1045. memcpy(&newp, n, sizeof(newp));
  1046. newp.prt_min = 1;
  1047. newp.prt_max = 65535;
  1048. newp.is_canonical = 0;
  1049. c = addr_policy_get_canonical_entry(&newp);
  1050. SMARTLIST_REPLACE_CURRENT(*policy, n, c);
  1051. addr_policy_free(n);
  1052. killed_any_ports = 1;
  1053. }
  1054. } SMARTLIST_FOREACH_END(n);
  1055. }
  1056. if (killed_any_ports) {
  1057. log_warn(LD_CONFIG, "Ignoring ports in %s option.", option_name);
  1058. }
  1059. return 0;
  1060. }
  1061. /** Set all policies based on <b>options</b>, which should have been validated
  1062. * first by validate_addr_policies. */
  1063. int
  1064. policies_parse_from_options(const or_options_t *options)
  1065. {
  1066. int ret = 0;
  1067. if (load_policy_from_option(options->SocksPolicy, "SocksPolicy",
  1068. &socks_policy, -1) < 0)
  1069. ret = -1;
  1070. if (load_policy_from_option(options->DirPolicy, "DirPolicy",
  1071. &dir_policy, -1) < 0)
  1072. ret = -1;
  1073. if (load_policy_from_option(options->AuthDirReject, "AuthDirReject",
  1074. &authdir_reject_policy, ADDR_POLICY_REJECT) < 0)
  1075. ret = -1;
  1076. if (load_policy_from_option(options->AuthDirInvalid, "AuthDirInvalid",
  1077. &authdir_invalid_policy, ADDR_POLICY_REJECT) < 0)
  1078. ret = -1;
  1079. if (load_policy_from_option(options->AuthDirBadExit, "AuthDirBadExit",
  1080. &authdir_badexit_policy, ADDR_POLICY_REJECT) < 0)
  1081. ret = -1;
  1082. if (parse_reachable_addresses() < 0)
  1083. ret = -1;
  1084. return ret;
  1085. }
  1086. /** Compare two provided address policy items, and renturn -1, 0, or 1
  1087. * if the first is less than, equal to, or greater than the second. */
  1088. static int
  1089. single_addr_policy_eq(const addr_policy_t *a, const addr_policy_t *b)
  1090. {
  1091. int r;
  1092. #define CMP_FIELD(field) do { \
  1093. if (a->field != b->field) { \
  1094. return 0; \
  1095. } \
  1096. } while (0)
  1097. CMP_FIELD(policy_type);
  1098. CMP_FIELD(is_private);
  1099. /* refcnt and is_canonical are irrelevant to equality,
  1100. * they are hash table implementation details */
  1101. if ((r=tor_addr_compare(&a->addr, &b->addr, CMP_EXACT)))
  1102. return 0;
  1103. CMP_FIELD(maskbits);
  1104. CMP_FIELD(prt_min);
  1105. CMP_FIELD(prt_max);
  1106. #undef CMP_FIELD
  1107. return 1;
  1108. }
  1109. /** As single_addr_policy_eq, but compare every element of two policies.
  1110. */
  1111. int
  1112. addr_policies_eq(const smartlist_t *a, const smartlist_t *b)
  1113. {
  1114. int i;
  1115. int len_a = a ? smartlist_len(a) : 0;
  1116. int len_b = b ? smartlist_len(b) : 0;
  1117. if (len_a != len_b)
  1118. return 0;
  1119. for (i = 0; i < len_a; ++i) {
  1120. if (! single_addr_policy_eq(smartlist_get(a, i), smartlist_get(b, i)))
  1121. return 0;
  1122. }
  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 single_addr_policy_eq(a->policy, b->policy);
  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(single_addr_policy_eq(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 IPV4_BITS (32)
  2082. /* Every IPv4 address is counted as one rejection */
  2083. #define REJECT_CUTOFF_SCALE_IPV4 (0)
  2084. /* Ports are rejected in an IPv4 summary if they are rejected in more than two
  2085. * IPv4 /8 address blocks */
  2086. #define REJECT_CUTOFF_COUNT_IPV4 (U64_LITERAL(1) << \
  2087. (IPV4_BITS - REJECT_CUTOFF_SCALE_IPV4 - 7))
  2088. #define IPV6_BITS (128)
  2089. /* IPv6 /64s are counted as one rejection, anything smaller is ignored */
  2090. #define REJECT_CUTOFF_SCALE_IPV6 (64)
  2091. /* Ports are rejected in an IPv6 summary if they are rejected in more than one
  2092. * IPv6 /16 address block.
  2093. * This is rougly equivalent to the IPv4 cutoff, as only five IPv6 /12s (and
  2094. * some scattered smaller blocks) have been allocated to the RIRs.
  2095. * Network providers are typically allocated one or more IPv6 /32s.
  2096. */
  2097. #define REJECT_CUTOFF_COUNT_IPV6 (U64_LITERAL(1) << \
  2098. (IPV6_BITS - REJECT_CUTOFF_SCALE_IPV6 - 16))
  2099. /** Split an exit policy summary so that prt_min and prt_max
  2100. * fall at exactly the start and end of an item respectively.
  2101. */
  2102. static int
  2103. policy_summary_split(smartlist_t *summary,
  2104. uint16_t prt_min, uint16_t prt_max)
  2105. {
  2106. int start_at_index;
  2107. int i = 0;
  2108. while (AT(i)->prt_max < prt_min)
  2109. i++;
  2110. if (AT(i)->prt_min != prt_min) {
  2111. policy_summary_item_t* new_item;
  2112. new_item = policy_summary_item_split(AT(i), prt_min);
  2113. smartlist_insert(summary, i+1, new_item);
  2114. i++;
  2115. }
  2116. start_at_index = i;
  2117. while (AT(i)->prt_max < prt_max)
  2118. i++;
  2119. if (AT(i)->prt_max != prt_max) {
  2120. policy_summary_item_t* new_item;
  2121. new_item = policy_summary_item_split(AT(i), prt_max+1);
  2122. smartlist_insert(summary, i+1, new_item);
  2123. }
  2124. return start_at_index;
  2125. }
  2126. /** Mark port ranges as accepted if they are below the reject_count for family
  2127. */
  2128. static void
  2129. policy_summary_accept(smartlist_t *summary,
  2130. uint16_t prt_min, uint16_t prt_max,
  2131. sa_family_t family)
  2132. {
  2133. tor_assert_nonfatal_once(family == AF_INET || family == AF_INET6);
  2134. uint64_t family_reject_count = ((family == AF_INET) ?
  2135. REJECT_CUTOFF_COUNT_IPV4 :
  2136. REJECT_CUTOFF_COUNT_IPV6);
  2137. int i = policy_summary_split(summary, prt_min, prt_max);
  2138. while (i < smartlist_len(summary) &&
  2139. AT(i)->prt_max <= prt_max) {
  2140. if (!AT(i)->accepted &&
  2141. AT(i)->reject_count <= family_reject_count)
  2142. AT(i)->accepted = 1;
  2143. i++;
  2144. }
  2145. tor_assert(i < smartlist_len(summary) || prt_max==65535);
  2146. }
  2147. /** Count the number of addresses in a network in family with prefixlen
  2148. * maskbits against the given portrange. */
  2149. static void
  2150. policy_summary_reject(smartlist_t *summary,
  2151. maskbits_t maskbits,
  2152. uint16_t prt_min, uint16_t prt_max,
  2153. sa_family_t family)
  2154. {
  2155. tor_assert_nonfatal_once(family == AF_INET || family == AF_INET6);
  2156. int i = policy_summary_split(summary, prt_min, prt_max);
  2157. /* The length of a single address mask */
  2158. int addrbits = (family == AF_INET) ? IPV4_BITS : IPV6_BITS;
  2159. tor_assert_nonfatal_once(addrbits >= maskbits);
  2160. /* We divide IPv6 address counts by (1 << scale) to keep them in a uint64_t
  2161. */
  2162. int scale = ((family == AF_INET) ?
  2163. REJECT_CUTOFF_SCALE_IPV4 :
  2164. REJECT_CUTOFF_SCALE_IPV6);
  2165. tor_assert_nonfatal_once(addrbits >= scale);
  2166. if (maskbits > (addrbits - scale)) {
  2167. tor_assert_nonfatal_once(family == AF_INET6);
  2168. /* The address range is so small, we'd need billions of them to reach the
  2169. * rejection limit. So we ignore this range in the reject count. */
  2170. return;
  2171. }
  2172. uint64_t count = 0;
  2173. if (addrbits - scale - maskbits >= 64) {
  2174. tor_assert_nonfatal_once(family == AF_INET6);
  2175. /* The address range is so large, it's an automatic rejection for all ports
  2176. * in the range. */
  2177. count = UINT64_MAX;
  2178. } else {
  2179. count = (U64_LITERAL(1) << (addrbits - scale - maskbits));
  2180. }
  2181. tor_assert_nonfatal_once(count > 0);
  2182. while (i < smartlist_len(summary) &&
  2183. AT(i)->prt_max <= prt_max) {
  2184. if (AT(i)->reject_count <= UINT64_MAX - count) {
  2185. AT(i)->reject_count += count;
  2186. } else {
  2187. /* IPv4 would require a 4-billion address redundant policy to get here,
  2188. * but IPv6 just needs to have ::/0 */
  2189. if (family == AF_INET) {
  2190. tor_assert_nonfatal_unreached_once();
  2191. }
  2192. /* If we do get here, use saturating arithmetic */
  2193. AT(i)->reject_count = UINT64_MAX;
  2194. }
  2195. i++;
  2196. }
  2197. tor_assert(i < smartlist_len(summary) || prt_max==65535);
  2198. }
  2199. /** Add a single exit policy item to our summary:
  2200. *
  2201. * If it is an accept, ignore it unless it is for all IP addresses
  2202. * ("*", i.e. its prefixlen/maskbits is 0). Otherwise call
  2203. * policy_summary_accept().
  2204. *
  2205. * If it is a reject, ignore it if it is about one of the private
  2206. * networks. Otherwise call policy_summary_reject().
  2207. */
  2208. static void
  2209. policy_summary_add_item(smartlist_t *summary, addr_policy_t *p)
  2210. {
  2211. if (p->policy_type == ADDR_POLICY_ACCEPT) {
  2212. if (p->maskbits == 0) {
  2213. policy_summary_accept(summary, p->prt_min, p->prt_max, p->addr.family);
  2214. }
  2215. } else if (p->policy_type == ADDR_POLICY_REJECT) {
  2216. int is_private = 0;
  2217. int i;
  2218. for (i = 0; private_nets[i]; ++i) {
  2219. tor_addr_t addr;
  2220. maskbits_t maskbits;
  2221. if (tor_addr_parse_mask_ports(private_nets[i], 0, &addr,
  2222. &maskbits, NULL, NULL)<0) {
  2223. tor_assert(0);
  2224. }
  2225. if (tor_addr_compare(&p->addr, &addr, CMP_EXACT) == 0 &&
  2226. p->maskbits == maskbits) {
  2227. is_private = 1;
  2228. break;
  2229. }
  2230. }
  2231. if (!is_private) {
  2232. policy_summary_reject(summary, p->maskbits, p->prt_min, p->prt_max,
  2233. p->addr.family);
  2234. }
  2235. } else
  2236. tor_assert(0);
  2237. }
  2238. /** Create a string representing a summary for an exit policy.
  2239. * The summary will either be an "accept" plus a comma-separated list of port
  2240. * ranges or a "reject" plus port-ranges, depending on which is shorter.
  2241. *
  2242. * If no exits are allowed at all then "reject 1-65535" is returned. If no
  2243. * ports are blocked instead of "reject " we return "accept 1-65535". (These
  2244. * are an exception to the shorter-representation-wins rule).
  2245. */
  2246. char *
  2247. policy_summarize(smartlist_t *policy, sa_family_t family)
  2248. {
  2249. smartlist_t *summary = policy_summary_create();
  2250. smartlist_t *accepts, *rejects;
  2251. int i, last, start_prt;
  2252. size_t accepts_len, rejects_len;
  2253. char *accepts_str = NULL, *rejects_str = NULL, *shorter_str, *result;
  2254. const char *prefix;
  2255. tor_assert(policy);
  2256. /* Create the summary list */
  2257. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
  2258. sa_family_t f = tor_addr_family(&p->addr);
  2259. if (f != AF_INET && f != AF_INET6) {
  2260. log_warn(LD_BUG, "Weird family when summarizing address policy");
  2261. }
  2262. if (f != family)
  2263. continue;
  2264. policy_summary_add_item(summary, p);
  2265. } SMARTLIST_FOREACH_END(p);
  2266. /* Now create two lists of strings, one for accepted and one
  2267. * for rejected ports. We take care to merge ranges so that
  2268. * we avoid getting stuff like "1-4,5-9,10", instead we want
  2269. * "1-10"
  2270. */
  2271. i = 0;
  2272. start_prt = 1;
  2273. accepts = smartlist_new();
  2274. rejects = smartlist_new();
  2275. while (1) {
  2276. last = i == smartlist_len(summary)-1;
  2277. if (last ||
  2278. AT(i)->accepted != AT(i+1)->accepted) {
  2279. char buf[POLICY_BUF_LEN];
  2280. if (start_prt == AT(i)->prt_max)
  2281. tor_snprintf(buf, sizeof(buf), "%d", start_prt);
  2282. else
  2283. tor_snprintf(buf, sizeof(buf), "%d-%d", start_prt, AT(i)->prt_max);
  2284. if (AT(i)->accepted)
  2285. smartlist_add(accepts, tor_strdup(buf));
  2286. else
  2287. smartlist_add(rejects, tor_strdup(buf));
  2288. if (last)
  2289. break;
  2290. start_prt = AT(i+1)->prt_min;
  2291. };
  2292. i++;
  2293. };
  2294. /* Figure out which of the two stringlists will be shorter and use
  2295. * that to build the result
  2296. */
  2297. if (smartlist_len(accepts) == 0) { /* no exits at all */
  2298. result = tor_strdup("reject 1-65535");
  2299. goto cleanup;
  2300. }
  2301. if (smartlist_len(rejects) == 0) { /* no rejects at all */
  2302. result = tor_strdup("accept 1-65535");
  2303. goto cleanup;
  2304. }
  2305. accepts_str = smartlist_join_strings(accepts, ",", 0, &accepts_len);
  2306. rejects_str = smartlist_join_strings(rejects, ",", 0, &rejects_len);
  2307. if (rejects_len > MAX_EXITPOLICY_SUMMARY_LEN-strlen("reject")-1 &&
  2308. accepts_len > MAX_EXITPOLICY_SUMMARY_LEN-strlen("accept")-1) {
  2309. char *c;
  2310. shorter_str = accepts_str;
  2311. prefix = "accept";
  2312. c = shorter_str + (MAX_EXITPOLICY_SUMMARY_LEN-strlen(prefix)-1);
  2313. while (*c != ',' && c >= shorter_str)
  2314. c--;
  2315. tor_assert(c >= shorter_str);
  2316. tor_assert(*c == ',');
  2317. *c = '\0';
  2318. } else if (rejects_len < accepts_len) {
  2319. shorter_str = rejects_str;
  2320. prefix = "reject";
  2321. } else {
  2322. shorter_str = accepts_str;
  2323. prefix = "accept";
  2324. }
  2325. tor_asprintf(&result, "%s %s", prefix, shorter_str);
  2326. cleanup:
  2327. /* cleanup */
  2328. SMARTLIST_FOREACH(summary, policy_summary_item_t *, s, tor_free(s));
  2329. smartlist_free(summary);
  2330. tor_free(accepts_str);
  2331. SMARTLIST_FOREACH(accepts, char *, s, tor_free(s));
  2332. smartlist_free(accepts);
  2333. tor_free(rejects_str);
  2334. SMARTLIST_FOREACH(rejects, char *, s, tor_free(s));
  2335. smartlist_free(rejects);
  2336. return result;
  2337. }
  2338. /** Convert a summarized policy string into a short_policy_t. Return NULL
  2339. * if the string is not well-formed. */
  2340. short_policy_t *
  2341. parse_short_policy(const char *summary)
  2342. {
  2343. const char *orig_summary = summary;
  2344. short_policy_t *result;
  2345. int is_accept;
  2346. int n_entries;
  2347. short_policy_entry_t entries[MAX_EXITPOLICY_SUMMARY_LEN]; /* overkill */
  2348. const char *next;
  2349. if (!strcmpstart(summary, "accept ")) {
  2350. is_accept = 1;
  2351. summary += strlen("accept ");
  2352. } else if (!strcmpstart(summary, "reject ")) {
  2353. is_accept = 0;
  2354. summary += strlen("reject ");
  2355. } else {
  2356. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Unrecognized policy summary keyword");
  2357. return NULL;
  2358. }
  2359. n_entries = 0;
  2360. for ( ; *summary; summary = next) {
  2361. const char *comma = strchr(summary, ',');
  2362. unsigned low, high;
  2363. char dummy;
  2364. char ent_buf[32];
  2365. size_t len;
  2366. next = comma ? comma+1 : strchr(summary, '\0');
  2367. len = comma ? (size_t)(comma - summary) : strlen(summary);
  2368. if (n_entries == MAX_EXITPOLICY_SUMMARY_LEN) {
  2369. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Impossibly long policy summary %s",
  2370. escaped(orig_summary));
  2371. return NULL;
  2372. }
  2373. if (! TOR_ISDIGIT(*summary) || len > (sizeof(ent_buf)-1)) {
  2374. /* unrecognized entry format. skip it. */
  2375. continue;
  2376. }
  2377. if (len < 1) {
  2378. /* empty; skip it. */
  2379. /* XXX This happens to be unreachable, since if len==0, then *summary is
  2380. * ',' or '\0', and the TOR_ISDIGIT test above would have failed. */
  2381. continue;
  2382. }
  2383. memcpy(ent_buf, summary, len);
  2384. ent_buf[len] = '\0';
  2385. if (tor_sscanf(ent_buf, "%u-%u%c", &low, &high, &dummy) == 2) {
  2386. if (low<1 || low>65535 || high<1 || high>65535 || low>high) {
  2387. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  2388. "Found bad entry in policy summary %s", escaped(orig_summary));
  2389. return NULL;
  2390. }
  2391. } else if (tor_sscanf(ent_buf, "%u%c", &low, &dummy) == 1) {
  2392. if (low<1 || low>65535) {
  2393. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  2394. "Found bad entry in policy summary %s", escaped(orig_summary));
  2395. return NULL;
  2396. }
  2397. high = low;
  2398. } else {
  2399. log_fn(LOG_PROTOCOL_WARN, LD_DIR,"Found bad entry in policy summary %s",
  2400. escaped(orig_summary));
  2401. return NULL;
  2402. }
  2403. entries[n_entries].min_port = low;
  2404. entries[n_entries].max_port = high;
  2405. n_entries++;
  2406. }
  2407. if (n_entries == 0) {
  2408. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  2409. "Found no port-range entries in summary %s", escaped(orig_summary));
  2410. return NULL;
  2411. }
  2412. {
  2413. size_t size = STRUCT_OFFSET(short_policy_t, entries) +
  2414. sizeof(short_policy_entry_t)*(n_entries);
  2415. result = tor_malloc_zero(size);
  2416. tor_assert( (char*)&result->entries[n_entries-1] < ((char*)result)+size);
  2417. }
  2418. result->is_accept = is_accept;
  2419. result->n_entries = n_entries;
  2420. memcpy(result->entries, entries, sizeof(short_policy_entry_t)*n_entries);
  2421. return result;
  2422. }
  2423. /** Write <b>policy</b> back out into a string. */
  2424. char *
  2425. write_short_policy(const short_policy_t *policy)
  2426. {
  2427. int i;
  2428. char *answer;
  2429. smartlist_t *sl = smartlist_new();
  2430. smartlist_add_asprintf(sl, "%s", policy->is_accept ? "accept " : "reject ");
  2431. for (i=0; i < policy->n_entries; i++) {
  2432. const short_policy_entry_t *e = &policy->entries[i];
  2433. if (e->min_port == e->max_port) {
  2434. smartlist_add_asprintf(sl, "%d", e->min_port);
  2435. } else {
  2436. smartlist_add_asprintf(sl, "%d-%d", e->min_port, e->max_port);
  2437. }
  2438. if (i < policy->n_entries-1)
  2439. smartlist_add(sl, tor_strdup(","));
  2440. }
  2441. answer = smartlist_join_strings(sl, "", 0, NULL);
  2442. SMARTLIST_FOREACH(sl, char *, a, tor_free(a));
  2443. smartlist_free(sl);
  2444. return answer;
  2445. }
  2446. /** Release all storage held in <b>policy</b>. */
  2447. void
  2448. short_policy_free(short_policy_t *policy)
  2449. {
  2450. tor_free(policy);
  2451. }
  2452. /** See whether the <b>addr</b>:<b>port</b> address is likely to be accepted
  2453. * or rejected by the summarized policy <b>policy</b>. Return values are as
  2454. * for compare_tor_addr_to_addr_policy. Unlike the regular addr_policy
  2455. * functions, requires the <b>port</b> be specified. */
  2456. addr_policy_result_t
  2457. compare_tor_addr_to_short_policy(const tor_addr_t *addr, uint16_t port,
  2458. const short_policy_t *policy)
  2459. {
  2460. int i;
  2461. int found_match = 0;
  2462. int accept_;
  2463. tor_assert(port != 0);
  2464. if (addr && tor_addr_is_null(addr))
  2465. addr = NULL; /* Unspec means 'no address at all,' in this context. */
  2466. if (addr && get_options()->ClientRejectInternalAddresses &&
  2467. (tor_addr_is_internal(addr, 0) || tor_addr_is_loopback(addr)))
  2468. return ADDR_POLICY_REJECTED;
  2469. for (i=0; i < policy->n_entries; ++i) {
  2470. const short_policy_entry_t *e = &policy->entries[i];
  2471. if (e->min_port <= port && port <= e->max_port) {
  2472. found_match = 1;
  2473. break;
  2474. }
  2475. }
  2476. if (found_match)
  2477. accept_ = policy->is_accept;
  2478. else
  2479. accept_ = ! policy->is_accept;
  2480. /* ???? are these right? -NM */
  2481. /* We should be sure not to return ADDR_POLICY_ACCEPTED in the accept
  2482. * case here, because it would cause clients to believe that the node
  2483. * allows exit enclaving. Trying it anyway would open up a cool attack
  2484. * where the node refuses due to exitpolicy, the client reacts in
  2485. * surprise by rewriting the node's exitpolicy to reject *:*, and then
  2486. * an adversary targets users by causing them to attempt such connections
  2487. * to 98% of the exits.
  2488. *
  2489. * Once microdescriptors can handle addresses in special cases (e.g. if
  2490. * we ever solve ticket 1774), we can provide certainty here. -RD */
  2491. if (accept_)
  2492. return ADDR_POLICY_PROBABLY_ACCEPTED;
  2493. else
  2494. return ADDR_POLICY_REJECTED;
  2495. }
  2496. /** Return true iff <b>policy</b> seems reject all ports */
  2497. int
  2498. short_policy_is_reject_star(const short_policy_t *policy)
  2499. {
  2500. /* This doesn't need to be as much on the lookout as policy_is_reject_star,
  2501. * since policy summaries are from the consensus or from consensus
  2502. * microdescs.
  2503. */
  2504. tor_assert(policy);
  2505. /* Check for an exact match of "reject 1-65535". */
  2506. return (policy->is_accept == 0 && policy->n_entries == 1 &&
  2507. policy->entries[0].min_port == 1 &&
  2508. policy->entries[0].max_port == 65535);
  2509. }
  2510. /** Decide whether addr:port is probably or definitely accepted or rejected by
  2511. * <b>node</b>. See compare_tor_addr_to_addr_policy for details on addr/port
  2512. * interpretation. */
  2513. addr_policy_result_t
  2514. compare_tor_addr_to_node_policy(const tor_addr_t *addr, uint16_t port,
  2515. const node_t *node)
  2516. {
  2517. if (node->rejects_all)
  2518. return ADDR_POLICY_REJECTED;
  2519. if (addr && tor_addr_family(addr) == AF_INET6) {
  2520. const short_policy_t *p = NULL;
  2521. if (node->ri)
  2522. p = node->ri->ipv6_exit_policy;
  2523. else if (node->md)
  2524. p = node->md->ipv6_exit_policy;
  2525. if (p)
  2526. return compare_tor_addr_to_short_policy(addr, port, p);
  2527. else
  2528. return ADDR_POLICY_REJECTED;
  2529. }
  2530. if (node->ri) {
  2531. return compare_tor_addr_to_addr_policy(addr, port, node->ri->exit_policy);
  2532. } else if (node->md) {
  2533. if (node->md->exit_policy == NULL)
  2534. return ADDR_POLICY_REJECTED;
  2535. else
  2536. return compare_tor_addr_to_short_policy(addr, port,
  2537. node->md->exit_policy);
  2538. } else {
  2539. return ADDR_POLICY_PROBABLY_REJECTED;
  2540. }
  2541. }
  2542. /**
  2543. * Given <b>policy_list</b>, a list of addr_policy_t, produce a string
  2544. * representation of the list.
  2545. * If <b>include_ipv4</b> is true, include IPv4 entries.
  2546. * If <b>include_ipv6</b> is true, include IPv6 entries.
  2547. */
  2548. char *
  2549. policy_dump_to_string(const smartlist_t *policy_list,
  2550. int include_ipv4,
  2551. int include_ipv6)
  2552. {
  2553. smartlist_t *policy_string_list;
  2554. char *policy_string = NULL;
  2555. policy_string_list = smartlist_new();
  2556. SMARTLIST_FOREACH_BEGIN(policy_list, addr_policy_t *, tmpe) {
  2557. char *pbuf;
  2558. int bytes_written_to_pbuf;
  2559. if ((tor_addr_family(&tmpe->addr) == AF_INET6) && (!include_ipv6)) {
  2560. continue; /* Don't include IPv6 parts of address policy */
  2561. }
  2562. if ((tor_addr_family(&tmpe->addr) == AF_INET) && (!include_ipv4)) {
  2563. continue; /* Don't include IPv4 parts of address policy */
  2564. }
  2565. pbuf = tor_malloc(POLICY_BUF_LEN);
  2566. bytes_written_to_pbuf = policy_write_item(pbuf,POLICY_BUF_LEN, tmpe, 1);
  2567. if (bytes_written_to_pbuf < 0) {
  2568. log_warn(LD_BUG, "policy_dump_to_string ran out of room!");
  2569. tor_free(pbuf);
  2570. goto done;
  2571. }
  2572. smartlist_add(policy_string_list,pbuf);
  2573. } SMARTLIST_FOREACH_END(tmpe);
  2574. policy_string = smartlist_join_strings(policy_string_list, "\n", 0, NULL);
  2575. done:
  2576. SMARTLIST_FOREACH(policy_string_list, char *, str, tor_free(str));
  2577. smartlist_free(policy_string_list);
  2578. return policy_string;
  2579. }
  2580. /** Implementation for GETINFO control command: knows the answer for questions
  2581. * about "exit-policy/..." */
  2582. int
  2583. getinfo_helper_policies(control_connection_t *conn,
  2584. const char *question, char **answer,
  2585. const char **errmsg)
  2586. {
  2587. (void) conn;
  2588. (void) errmsg;
  2589. if (!strcmp(question, "exit-policy/default")) {
  2590. *answer = tor_strdup(DEFAULT_EXIT_POLICY);
  2591. } else if (!strcmp(question, "exit-policy/reject-private/default")) {
  2592. smartlist_t *private_policy_strings;
  2593. const char **priv = private_nets;
  2594. private_policy_strings = smartlist_new();
  2595. while (*priv != NULL) {
  2596. /* IPv6 addresses are in "[]" and contain ":",
  2597. * IPv4 addresses are not in "[]" and contain "." */
  2598. smartlist_add_asprintf(private_policy_strings, "reject %s:*", *priv);
  2599. priv++;
  2600. }
  2601. *answer = smartlist_join_strings(private_policy_strings,
  2602. ",", 0, NULL);
  2603. SMARTLIST_FOREACH(private_policy_strings, char *, str, tor_free(str));
  2604. smartlist_free(private_policy_strings);
  2605. } else if (!strcmp(question, "exit-policy/reject-private/relay")) {
  2606. const or_options_t *options = get_options();
  2607. const routerinfo_t *me = router_get_my_routerinfo();
  2608. if (!me) {
  2609. *errmsg = "router_get_my_routerinfo returned NULL";
  2610. return -1;
  2611. }
  2612. if (!options->ExitPolicyRejectPrivate &&
  2613. !options->ExitPolicyRejectLocalInterfaces) {
  2614. *answer = tor_strdup("");
  2615. return 0;
  2616. }
  2617. smartlist_t *private_policy_list = smartlist_new();
  2618. smartlist_t *configured_addresses = smartlist_new();
  2619. /* Copy the configured addresses into the tor_addr_t* list */
  2620. if (options->ExitPolicyRejectPrivate) {
  2621. policies_copy_ipv4h_to_smartlist(configured_addresses, me->addr);
  2622. policies_copy_addr_to_smartlist(configured_addresses, &me->ipv6_addr);
  2623. }
  2624. if (options->ExitPolicyRejectLocalInterfaces) {
  2625. policies_copy_outbound_addresses_to_smartlist(configured_addresses,
  2626. options);
  2627. }
  2628. policies_parse_exit_policy_reject_private(
  2629. &private_policy_list,
  2630. options->IPv6Exit,
  2631. configured_addresses,
  2632. options->ExitPolicyRejectLocalInterfaces,
  2633. options->ExitPolicyRejectLocalInterfaces);
  2634. *answer = policy_dump_to_string(private_policy_list, 1, 1);
  2635. addr_policy_list_free(private_policy_list);
  2636. SMARTLIST_FOREACH(configured_addresses, tor_addr_t *, a, tor_free(a));
  2637. smartlist_free(configured_addresses);
  2638. } else if (!strcmpstart(question, "exit-policy/")) {
  2639. const routerinfo_t *me = router_get_my_routerinfo();
  2640. int include_ipv4 = 0;
  2641. int include_ipv6 = 0;
  2642. if (!strcmp(question, "exit-policy/ipv4")) {
  2643. include_ipv4 = 1;
  2644. } else if (!strcmp(question, "exit-policy/ipv6")) {
  2645. include_ipv6 = 1;
  2646. } else if (!strcmp(question, "exit-policy/full")) {
  2647. include_ipv4 = include_ipv6 = 1;
  2648. } else {
  2649. return 0; /* No such key. */
  2650. }
  2651. if (!me) {
  2652. *errmsg = "router_get_my_routerinfo returned NULL";
  2653. return -1;
  2654. }
  2655. *answer = router_dump_exit_policy_to_string(me,include_ipv4,include_ipv6);
  2656. }
  2657. return 0;
  2658. }
  2659. /** Release all storage held by <b>p</b>. */
  2660. void
  2661. addr_policy_list_free(smartlist_t *lst)
  2662. {
  2663. if (!lst)
  2664. return;
  2665. SMARTLIST_FOREACH(lst, addr_policy_t *, policy, addr_policy_free(policy));
  2666. smartlist_free(lst);
  2667. }
  2668. /** Release all storage held by <b>p</b>. */
  2669. void
  2670. addr_policy_free(addr_policy_t *p)
  2671. {
  2672. if (!p)
  2673. return;
  2674. if (--p->refcnt <= 0) {
  2675. if (p->is_canonical) {
  2676. policy_map_ent_t search, *found;
  2677. search.policy = p;
  2678. found = HT_REMOVE(policy_map, &policy_root, &search);
  2679. if (found) {
  2680. tor_assert(p == found->policy);
  2681. tor_free(found);
  2682. }
  2683. }
  2684. tor_free(p);
  2685. }
  2686. }
  2687. /** Release all storage held by policy variables. */
  2688. void
  2689. policies_free_all(void)
  2690. {
  2691. addr_policy_list_free(reachable_or_addr_policy);
  2692. reachable_or_addr_policy = NULL;
  2693. addr_policy_list_free(reachable_dir_addr_policy);
  2694. reachable_dir_addr_policy = NULL;
  2695. addr_policy_list_free(socks_policy);
  2696. socks_policy = NULL;
  2697. addr_policy_list_free(dir_policy);
  2698. dir_policy = NULL;
  2699. addr_policy_list_free(authdir_reject_policy);
  2700. authdir_reject_policy = NULL;
  2701. addr_policy_list_free(authdir_invalid_policy);
  2702. authdir_invalid_policy = NULL;
  2703. addr_policy_list_free(authdir_badexit_policy);
  2704. authdir_badexit_policy = NULL;
  2705. if (!HT_EMPTY(&policy_root)) {
  2706. policy_map_ent_t **ent;
  2707. int n = 0;
  2708. char buf[POLICY_BUF_LEN];
  2709. log_warn(LD_MM, "Still had %d address policies cached at shutdown.",
  2710. (int)HT_SIZE(&policy_root));
  2711. /* Note the first 10 cached policies to try to figure out where they
  2712. * might be coming from. */
  2713. HT_FOREACH(ent, policy_map, &policy_root) {
  2714. if (++n > 10)
  2715. break;
  2716. if (policy_write_item(buf, sizeof(buf), (*ent)->policy, 0) >= 0)
  2717. log_warn(LD_MM," %d [%d]: %s", n, (*ent)->policy->refcnt, buf);
  2718. }
  2719. }
  2720. HT_CLEAR(policy_map, &policy_root);
  2721. }