routerparse.c 151 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file routerparse.c
  8. * \brief Code to parse and validate router descriptors, consenus directories,
  9. * and similar objects.
  10. *
  11. * The objects parsed by this module use a common text-based metaformat,
  12. * documented in dir-spec.txt in torspec.git. This module is itself divided
  13. * into two major kinds of function: code to handle the metaformat, and code
  14. * to convert from particular instances of the metaformat into the
  15. * objects that Tor uses.
  16. *
  17. * The generic parsing code works by calling a table-based tokenizer on the
  18. * input string. Each token corresponds to a single line with a token, plus
  19. * optional arguments on that line, plus an optional base-64 encoded object
  20. * after that line. Each token has a definition in a table of token_rule_t
  21. * entries that describes how many arguments it can take, whether it takes an
  22. * object, how many times it may appear, whether it must appear first, and so
  23. * on.
  24. *
  25. * The tokenizer function tokenize_string() converts its string input into a
  26. * smartlist full of instances of directory_token_t, according to a provided
  27. * table of token_rule_t.
  28. *
  29. * The generic parts of this module additionally include functions for
  30. * finding the start and end of signed information inside a signed object, and
  31. * computing the digest that will be signed.
  32. *
  33. * There are also functions for saving objects to disk that have caused
  34. * parsing to fail.
  35. *
  36. * The specific parts of this module describe conversions between
  37. * particular lists of directory_token_t and particular objects. The
  38. * kinds of objects that can be parsed here are:
  39. * <ul>
  40. * <li>router descriptors (managed from routerlist.c)
  41. * <li>extra-info documents (managed from routerlist.c)
  42. * <li>microdescriptors (managed from microdesc.c)
  43. * <li>vote and consensus networkstatus documents, and the routerstatus_t
  44. * objects that they comprise (managed from networkstatus.c)
  45. * <li>detached-signature objects used by authorities for gathering
  46. * signatures on the networkstatus consensus (managed from dirvote.c)
  47. * <li>authority key certificates (managed from routerlist.c)
  48. * <li>hidden service descriptors (managed from rendcommon.c and rendcache.c)
  49. * </ul>
  50. **/
  51. #define ROUTERPARSE_PRIVATE
  52. #include "core/or/or.h"
  53. #include "app/config/config.h"
  54. #include "core/or/circuitstats.h"
  55. #include "core/or/policies.h"
  56. #include "core/or/protover.h"
  57. #include "feature/client/entrynodes.h"
  58. #include "feature/dirauth/shared_random.h"
  59. #include "feature/dircommon/voting_schedule.h"
  60. #include "feature/dirparse/parsecommon.h"
  61. #include "feature/dirparse/routerparse.h"
  62. #include "feature/hs_common/shared_random_client.h"
  63. #include "feature/nodelist/authcert.h"
  64. #include "feature/nodelist/describe.h"
  65. #include "feature/nodelist/microdesc.h"
  66. #include "feature/nodelist/networkstatus.h"
  67. #include "feature/nodelist/nickname.h"
  68. #include "feature/nodelist/routerinfo.h"
  69. #include "feature/nodelist/routerlist.h"
  70. #include "feature/nodelist/torcert.h"
  71. #include "feature/relay/router.h"
  72. #include "feature/relay/routerkeys.h"
  73. #include "feature/rend/rendcommon.h"
  74. #include "feature/stats/rephist.h"
  75. #include "lib/crypt_ops/crypto_format.h"
  76. #include "lib/crypt_ops/crypto_util.h"
  77. #include "lib/memarea/memarea.h"
  78. #include "lib/sandbox/sandbox.h"
  79. #include "feature/dirparse/authcert_parse.h"
  80. #include "feature/dirparse/sigcommon.h"
  81. #include "feature/dirparse/unparseable.h"
  82. #include "feature/dirauth/dirvote.h"
  83. #include "core/or/addr_policy_st.h"
  84. #include "feature/nodelist/authority_cert_st.h"
  85. #include "feature/nodelist/document_signature_st.h"
  86. #include "core/or/extend_info_st.h"
  87. #include "feature/nodelist/extrainfo_st.h"
  88. #include "feature/nodelist/microdesc_st.h"
  89. #include "feature/nodelist/networkstatus_st.h"
  90. #include "feature/nodelist/networkstatus_voter_info_st.h"
  91. #include "feature/dirauth/ns_detached_signatures_st.h"
  92. #include "feature/rend/rend_authorized_client_st.h"
  93. #include "feature/rend/rend_intro_point_st.h"
  94. #include "feature/rend/rend_service_descriptor_st.h"
  95. #include "feature/nodelist/routerinfo_st.h"
  96. #include "feature/nodelist/routerlist_st.h"
  97. #include "core/or/tor_version_st.h"
  98. #include "feature/dirauth/vote_microdesc_hash_st.h"
  99. #include "feature/nodelist/vote_routerstatus_st.h"
  100. #include "lib/container/bloomfilt.h"
  101. #undef log
  102. #include <math.h>
  103. /****************************************************************************/
  104. /** List of tokens recognized in router descriptors */
  105. static token_rule_t routerdesc_token_table[] = {
  106. T0N("reject", K_REJECT, ARGS, NO_OBJ ),
  107. T0N("accept", K_ACCEPT, ARGS, NO_OBJ ),
  108. T0N("reject6", K_REJECT6, ARGS, NO_OBJ ),
  109. T0N("accept6", K_ACCEPT6, ARGS, NO_OBJ ),
  110. T1_START( "router", K_ROUTER, GE(5), NO_OBJ ),
  111. T01("ipv6-policy", K_IPV6_POLICY, CONCAT_ARGS, NO_OBJ),
  112. T1( "signing-key", K_SIGNING_KEY, NO_ARGS, NEED_KEY_1024 ),
  113. T1( "onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY_1024 ),
  114. T01("ntor-onion-key", K_ONION_KEY_NTOR, GE(1), NO_OBJ ),
  115. T1_END( "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ ),
  116. T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  117. T01("uptime", K_UPTIME, GE(1), NO_OBJ ),
  118. T01("fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  119. T01("hibernating", K_HIBERNATING, GE(1), NO_OBJ ),
  120. T01("platform", K_PLATFORM, CONCAT_ARGS, NO_OBJ ),
  121. T01("proto", K_PROTO, CONCAT_ARGS, NO_OBJ ),
  122. T01("contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  123. T01("read-history", K_READ_HISTORY, ARGS, NO_OBJ ),
  124. T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
  125. T01("extra-info-digest", K_EXTRA_INFO_DIGEST, GE(1), NO_OBJ ),
  126. T01("hidden-service-dir", K_HIDDEN_SERVICE_DIR, NO_ARGS, NO_OBJ ),
  127. T01("identity-ed25519", K_IDENTITY_ED25519, NO_ARGS, NEED_OBJ ),
  128. T01("master-key-ed25519", K_MASTER_KEY_ED25519, GE(1), NO_OBJ ),
  129. T01("router-sig-ed25519", K_ROUTER_SIG_ED25519, GE(1), NO_OBJ ),
  130. T01("onion-key-crosscert", K_ONION_KEY_CROSSCERT, NO_ARGS, NEED_OBJ ),
  131. T01("ntor-onion-key-crosscert", K_NTOR_ONION_KEY_CROSSCERT,
  132. EQ(1), NEED_OBJ ),
  133. T01("allow-single-hop-exits",K_ALLOW_SINGLE_HOP_EXITS, NO_ARGS, NO_OBJ ),
  134. T01("family", K_FAMILY, ARGS, NO_OBJ ),
  135. T01("caches-extra-info", K_CACHES_EXTRA_INFO, NO_ARGS, NO_OBJ ),
  136. T0N("or-address", K_OR_ADDRESS, GE(1), NO_OBJ ),
  137. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  138. T1( "bandwidth", K_BANDWIDTH, GE(3), NO_OBJ ),
  139. A01("@purpose", A_PURPOSE, GE(1), NO_OBJ ),
  140. T01("tunnelled-dir-server",K_DIR_TUNNELLED, NO_ARGS, NO_OBJ ),
  141. END_OF_TABLE
  142. };
  143. /** List of tokens recognized in extra-info documents. */
  144. static token_rule_t extrainfo_token_table[] = {
  145. T1_END( "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ ),
  146. T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  147. T01("identity-ed25519", K_IDENTITY_ED25519, NO_ARGS, NEED_OBJ ),
  148. T01("router-sig-ed25519", K_ROUTER_SIG_ED25519, GE(1), NO_OBJ ),
  149. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  150. T01("read-history", K_READ_HISTORY, ARGS, NO_OBJ ),
  151. T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
  152. T01("dirreq-stats-end", K_DIRREQ_END, ARGS, NO_OBJ ),
  153. T01("dirreq-v2-ips", K_DIRREQ_V2_IPS, ARGS, NO_OBJ ),
  154. T01("dirreq-v3-ips", K_DIRREQ_V3_IPS, ARGS, NO_OBJ ),
  155. T01("dirreq-v2-reqs", K_DIRREQ_V2_REQS, ARGS, NO_OBJ ),
  156. T01("dirreq-v3-reqs", K_DIRREQ_V3_REQS, ARGS, NO_OBJ ),
  157. T01("dirreq-v2-share", K_DIRREQ_V2_SHARE, ARGS, NO_OBJ ),
  158. T01("dirreq-v3-share", K_DIRREQ_V3_SHARE, ARGS, NO_OBJ ),
  159. T01("dirreq-v2-resp", K_DIRREQ_V2_RESP, ARGS, NO_OBJ ),
  160. T01("dirreq-v3-resp", K_DIRREQ_V3_RESP, ARGS, NO_OBJ ),
  161. T01("dirreq-v2-direct-dl", K_DIRREQ_V2_DIR, ARGS, NO_OBJ ),
  162. T01("dirreq-v3-direct-dl", K_DIRREQ_V3_DIR, ARGS, NO_OBJ ),
  163. T01("dirreq-v2-tunneled-dl", K_DIRREQ_V2_TUN, ARGS, NO_OBJ ),
  164. T01("dirreq-v3-tunneled-dl", K_DIRREQ_V3_TUN, ARGS, NO_OBJ ),
  165. T01("entry-stats-end", K_ENTRY_END, ARGS, NO_OBJ ),
  166. T01("entry-ips", K_ENTRY_IPS, ARGS, NO_OBJ ),
  167. T01("cell-stats-end", K_CELL_END, ARGS, NO_OBJ ),
  168. T01("cell-processed-cells", K_CELL_PROCESSED, ARGS, NO_OBJ ),
  169. T01("cell-queued-cells", K_CELL_QUEUED, ARGS, NO_OBJ ),
  170. T01("cell-time-in-queue", K_CELL_TIME, ARGS, NO_OBJ ),
  171. T01("cell-circuits-per-decile", K_CELL_CIRCS, ARGS, NO_OBJ ),
  172. T01("exit-stats-end", K_EXIT_END, ARGS, NO_OBJ ),
  173. T01("exit-kibibytes-written", K_EXIT_WRITTEN, ARGS, NO_OBJ ),
  174. T01("exit-kibibytes-read", K_EXIT_READ, ARGS, NO_OBJ ),
  175. T01("exit-streams-opened", K_EXIT_OPENED, ARGS, NO_OBJ ),
  176. T1_START( "extra-info", K_EXTRA_INFO, GE(2), NO_OBJ ),
  177. END_OF_TABLE
  178. };
  179. /** List of tokens recognized in the body part of v3 networkstatus
  180. * documents. */
  181. static token_rule_t rtrstatus_token_table[] = {
  182. T01("p", K_P, CONCAT_ARGS, NO_OBJ ),
  183. T1( "r", K_R, GE(7), NO_OBJ ),
  184. T0N("a", K_A, GE(1), NO_OBJ ),
  185. T1( "s", K_S, ARGS, NO_OBJ ),
  186. T01("v", K_V, CONCAT_ARGS, NO_OBJ ),
  187. T01("w", K_W, ARGS, NO_OBJ ),
  188. T0N("m", K_M, CONCAT_ARGS, NO_OBJ ),
  189. T0N("id", K_ID, GE(2), NO_OBJ ),
  190. T01("pr", K_PROTO, CONCAT_ARGS, NO_OBJ ),
  191. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  192. END_OF_TABLE
  193. };
  194. /** List of tokens recognized in rendezvous service descriptors */
  195. static token_rule_t desc_token_table[] = {
  196. T1_START("rendezvous-service-descriptor", R_RENDEZVOUS_SERVICE_DESCRIPTOR,
  197. EQ(1), NO_OBJ),
  198. T1("version", R_VERSION, EQ(1), NO_OBJ),
  199. T1("permanent-key", R_PERMANENT_KEY, NO_ARGS, NEED_KEY_1024),
  200. T1("secret-id-part", R_SECRET_ID_PART, EQ(1), NO_OBJ),
  201. T1("publication-time", R_PUBLICATION_TIME, CONCAT_ARGS, NO_OBJ),
  202. T1("protocol-versions", R_PROTOCOL_VERSIONS, EQ(1), NO_OBJ),
  203. T01("introduction-points", R_INTRODUCTION_POINTS, NO_ARGS, NEED_OBJ),
  204. T1_END("signature", R_SIGNATURE, NO_ARGS, NEED_OBJ),
  205. END_OF_TABLE
  206. };
  207. /** List of tokens recognized in the (encrypted) list of introduction points of
  208. * rendezvous service descriptors */
  209. static token_rule_t ipo_token_table[] = {
  210. T1_START("introduction-point", R_IPO_IDENTIFIER, EQ(1), NO_OBJ),
  211. T1("ip-address", R_IPO_IP_ADDRESS, EQ(1), NO_OBJ),
  212. T1("onion-port", R_IPO_ONION_PORT, EQ(1), NO_OBJ),
  213. T1("onion-key", R_IPO_ONION_KEY, NO_ARGS, NEED_KEY_1024),
  214. T1("service-key", R_IPO_SERVICE_KEY, NO_ARGS, NEED_KEY_1024),
  215. END_OF_TABLE
  216. };
  217. /** List of tokens recognized in the (possibly encrypted) list of introduction
  218. * points of rendezvous service descriptors */
  219. static token_rule_t client_keys_token_table[] = {
  220. T1_START("client-name", C_CLIENT_NAME, CONCAT_ARGS, NO_OBJ),
  221. T1("descriptor-cookie", C_DESCRIPTOR_COOKIE, EQ(1), NO_OBJ),
  222. T01("client-key", C_CLIENT_KEY, NO_ARGS, NEED_SKEY_1024),
  223. END_OF_TABLE
  224. };
  225. /** List of tokens recognized in V3 networkstatus votes. */
  226. static token_rule_t networkstatus_token_table[] = {
  227. T1_START("network-status-version", K_NETWORK_STATUS_VERSION,
  228. GE(1), NO_OBJ ),
  229. T1("vote-status", K_VOTE_STATUS, GE(1), NO_OBJ ),
  230. T1("published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  231. T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
  232. T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
  233. T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
  234. T1("voting-delay", K_VOTING_DELAY, GE(2), NO_OBJ ),
  235. T1("known-flags", K_KNOWN_FLAGS, ARGS, NO_OBJ ),
  236. T01("params", K_PARAMS, ARGS, NO_OBJ ),
  237. T( "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  238. T01("signing-ed25519", K_SIGNING_CERT_ED, NO_ARGS , NEED_OBJ ),
  239. T01("shared-rand-participate",K_SR_FLAG, NO_ARGS, NO_OBJ ),
  240. T0N("shared-rand-commit", K_COMMIT, GE(3), NO_OBJ ),
  241. T01("shared-rand-previous-value", K_PREVIOUS_SRV,EQ(2), NO_OBJ ),
  242. T01("shared-rand-current-value", K_CURRENT_SRV, EQ(2), NO_OBJ ),
  243. T0N("package", K_PACKAGE, CONCAT_ARGS, NO_OBJ ),
  244. T01("recommended-client-protocols", K_RECOMMENDED_CLIENT_PROTOCOLS,
  245. CONCAT_ARGS, NO_OBJ ),
  246. T01("recommended-relay-protocols", K_RECOMMENDED_RELAY_PROTOCOLS,
  247. CONCAT_ARGS, NO_OBJ ),
  248. T01("required-client-protocols", K_REQUIRED_CLIENT_PROTOCOLS,
  249. CONCAT_ARGS, NO_OBJ ),
  250. T01("required-relay-protocols", K_REQUIRED_RELAY_PROTOCOLS,
  251. CONCAT_ARGS, NO_OBJ ),
  252. #include "feature/dirparse/authcert_members.i"
  253. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  254. T1( "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  255. T1( "dir-source", K_DIR_SOURCE, GE(6), NO_OBJ ),
  256. T01("legacy-dir-key", K_LEGACY_DIR_KEY, GE(1), NO_OBJ ),
  257. T1( "known-flags", K_KNOWN_FLAGS, CONCAT_ARGS, NO_OBJ ),
  258. T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  259. T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  260. T1( "consensus-methods", K_CONSENSUS_METHODS, GE(1), NO_OBJ ),
  261. END_OF_TABLE
  262. };
  263. /** List of tokens recognized in V3 networkstatus consensuses. */
  264. static token_rule_t networkstatus_consensus_token_table[] = {
  265. T1_START("network-status-version", K_NETWORK_STATUS_VERSION,
  266. GE(1), NO_OBJ ),
  267. T1("vote-status", K_VOTE_STATUS, GE(1), NO_OBJ ),
  268. T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
  269. T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
  270. T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
  271. T1("voting-delay", K_VOTING_DELAY, GE(2), NO_OBJ ),
  272. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  273. T1N("dir-source", K_DIR_SOURCE, GE(6), NO_OBJ ),
  274. T1N("contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  275. T1N("vote-digest", K_VOTE_DIGEST, GE(1), NO_OBJ ),
  276. T1( "known-flags", K_KNOWN_FLAGS, CONCAT_ARGS, NO_OBJ ),
  277. T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  278. T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  279. T01("consensus-method", K_CONSENSUS_METHOD, EQ(1), NO_OBJ),
  280. T01("params", K_PARAMS, ARGS, NO_OBJ ),
  281. T01("shared-rand-previous-value", K_PREVIOUS_SRV, EQ(2), NO_OBJ ),
  282. T01("shared-rand-current-value", K_CURRENT_SRV, EQ(2), NO_OBJ ),
  283. T01("recommended-client-protocols", K_RECOMMENDED_CLIENT_PROTOCOLS,
  284. CONCAT_ARGS, NO_OBJ ),
  285. T01("recommended-relay-protocols", K_RECOMMENDED_RELAY_PROTOCOLS,
  286. CONCAT_ARGS, NO_OBJ ),
  287. T01("required-client-protocols", K_REQUIRED_CLIENT_PROTOCOLS,
  288. CONCAT_ARGS, NO_OBJ ),
  289. T01("required-relay-protocols", K_REQUIRED_RELAY_PROTOCOLS,
  290. CONCAT_ARGS, NO_OBJ ),
  291. END_OF_TABLE
  292. };
  293. /** List of tokens recognized in the footer of v1 directory footers. */
  294. static token_rule_t networkstatus_vote_footer_token_table[] = {
  295. T01("directory-footer", K_DIRECTORY_FOOTER, NO_ARGS, NO_OBJ ),
  296. T01("bandwidth-weights", K_BW_WEIGHTS, ARGS, NO_OBJ ),
  297. T( "directory-signature", K_DIRECTORY_SIGNATURE, GE(2), NEED_OBJ ),
  298. END_OF_TABLE
  299. };
  300. /** List of tokens recognized in detached networkstatus signature documents. */
  301. static token_rule_t networkstatus_detached_signature_token_table[] = {
  302. T1_START("consensus-digest", K_CONSENSUS_DIGEST, GE(1), NO_OBJ ),
  303. T("additional-digest", K_ADDITIONAL_DIGEST,GE(3), NO_OBJ ),
  304. T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
  305. T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
  306. T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
  307. T("additional-signature", K_ADDITIONAL_SIGNATURE, GE(4), NEED_OBJ ),
  308. T1N("directory-signature", K_DIRECTORY_SIGNATURE, GE(2), NEED_OBJ ),
  309. END_OF_TABLE
  310. };
  311. /** List of tokens recognized in microdescriptors */
  312. static token_rule_t microdesc_token_table[] = {
  313. T1_START("onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY_1024),
  314. T01("ntor-onion-key", K_ONION_KEY_NTOR, GE(1), NO_OBJ ),
  315. T0N("id", K_ID, GE(2), NO_OBJ ),
  316. T0N("a", K_A, GE(1), NO_OBJ ),
  317. T01("family", K_FAMILY, ARGS, NO_OBJ ),
  318. T01("p", K_P, CONCAT_ARGS, NO_OBJ ),
  319. T01("p6", K_P6, CONCAT_ARGS, NO_OBJ ),
  320. A01("@last-listed", A_LAST_LISTED, CONCAT_ARGS, NO_OBJ ),
  321. END_OF_TABLE
  322. };
  323. #undef T
  324. /* static function prototypes */
  325. static int router_add_exit_policy(routerinfo_t *router,directory_token_t *tok);
  326. static addr_policy_t *router_parse_addr_policy(directory_token_t *tok,
  327. unsigned fmt_flags);
  328. static addr_policy_t *router_parse_addr_policy_private(directory_token_t *tok);
  329. static smartlist_t *find_all_exitpolicy(smartlist_t *s);
  330. /** Set <b>digest</b> to the SHA-1 digest of the hash of the directory in
  331. * <b>s</b>. Return 0 on success, -1 on failure.
  332. */
  333. int
  334. router_get_dir_hash(const char *s, char *digest)
  335. {
  336. return router_get_hash_impl(s, strlen(s), digest,
  337. "signed-directory","\ndirectory-signature",'\n',
  338. DIGEST_SHA1);
  339. }
  340. /** Set <b>digest</b> to the SHA-1 digest of the hash of the first router in
  341. * <b>s</b>. Return 0 on success, -1 on failure.
  342. */
  343. int
  344. router_get_router_hash(const char *s, size_t s_len, char *digest)
  345. {
  346. return router_get_hash_impl(s, s_len, digest,
  347. "router ","\nrouter-signature", '\n',
  348. DIGEST_SHA1);
  349. }
  350. /** Try to find the start and end of the signed portion of a networkstatus
  351. * document in <b>s</b>. On success, set <b>start_out</b> to the first
  352. * character of the document, and <b>end_out</b> to a position one after the
  353. * final character of the signed document, and return 0. On failure, return
  354. * -1. */
  355. int
  356. router_get_networkstatus_v3_signed_boundaries(const char *s,
  357. const char **start_out,
  358. const char **end_out)
  359. {
  360. return router_get_hash_impl_helper(s, strlen(s),
  361. "network-status-version",
  362. "\ndirectory-signature",
  363. ' ', LOG_INFO,
  364. start_out, end_out);
  365. }
  366. /** Set <b>digest_out</b> to the SHA3-256 digest of the signed portion of the
  367. * networkstatus vote in <b>s</b> -- or of the entirety of <b>s</b> if no
  368. * signed portion can be identified. Return 0 on success, -1 on failure. */
  369. int
  370. router_get_networkstatus_v3_sha3_as_signed(uint8_t *digest_out,
  371. const char *s)
  372. {
  373. const char *start, *end;
  374. if (router_get_networkstatus_v3_signed_boundaries(s, &start, &end) < 0) {
  375. start = s;
  376. end = s + strlen(s);
  377. }
  378. tor_assert(start);
  379. tor_assert(end);
  380. return crypto_digest256((char*)digest_out, start, end-start,
  381. DIGEST_SHA3_256);
  382. }
  383. /** Set <b>digests</b> to all the digests of the consensus document in
  384. * <b>s</b> */
  385. int
  386. router_get_networkstatus_v3_hashes(const char *s, common_digests_t *digests)
  387. {
  388. return router_get_hashes_impl(s,strlen(s),digests,
  389. "network-status-version",
  390. "\ndirectory-signature",
  391. ' ');
  392. }
  393. /** Set <b>digest</b> to the SHA-1 digest of the hash of the <b>s_len</b>-byte
  394. * extrainfo string at <b>s</b>. Return 0 on success, -1 on failure. */
  395. int
  396. router_get_extrainfo_hash(const char *s, size_t s_len, char *digest)
  397. {
  398. return router_get_hash_impl(s, s_len, digest, "extra-info",
  399. "\nrouter-signature",'\n', DIGEST_SHA1);
  400. }
  401. /** Helper: move *<b>s_ptr</b> ahead to the next router, the next extra-info,
  402. * or to the first of the annotations proceeding the next router or
  403. * extra-info---whichever comes first. Set <b>is_extrainfo_out</b> to true if
  404. * we found an extrainfo, or false if found a router. Do not scan beyond
  405. * <b>eos</b>. Return -1 if we found nothing; 0 if we found something. */
  406. static int
  407. find_start_of_next_router_or_extrainfo(const char **s_ptr,
  408. const char *eos,
  409. int *is_extrainfo_out)
  410. {
  411. const char *annotations = NULL;
  412. const char *s = *s_ptr;
  413. s = eat_whitespace_eos(s, eos);
  414. while (s < eos-32) { /* 32 gives enough room for a the first keyword. */
  415. /* We're at the start of a line. */
  416. tor_assert(*s != '\n');
  417. if (*s == '@' && !annotations) {
  418. annotations = s;
  419. } else if (*s == 'r' && !strcmpstart(s, "router ")) {
  420. *s_ptr = annotations ? annotations : s;
  421. *is_extrainfo_out = 0;
  422. return 0;
  423. } else if (*s == 'e' && !strcmpstart(s, "extra-info ")) {
  424. *s_ptr = annotations ? annotations : s;
  425. *is_extrainfo_out = 1;
  426. return 0;
  427. }
  428. if (!(s = memchr(s+1, '\n', eos-(s+1))))
  429. break;
  430. s = eat_whitespace_eos(s, eos);
  431. }
  432. return -1;
  433. }
  434. /** Given a string *<b>s</b> containing a concatenated sequence of router
  435. * descriptors (or extra-info documents if <b>want_extrainfo</b> is set),
  436. * parses them and stores the result in <b>dest</b>. All routers are marked
  437. * running and valid. Advances *s to a point immediately following the last
  438. * router entry. Ignore any trailing router entries that are not complete.
  439. *
  440. * If <b>saved_location</b> isn't SAVED_IN_CACHE, make a local copy of each
  441. * descriptor in the signed_descriptor_body field of each routerinfo_t. If it
  442. * isn't SAVED_NOWHERE, remember the offset of each descriptor.
  443. *
  444. * Returns 0 on success and -1 on failure. Adds a digest to
  445. * <b>invalid_digests_out</b> for every entry that was unparseable or
  446. * invalid. (This may cause duplicate entries.)
  447. */
  448. int
  449. router_parse_list_from_string(const char **s, const char *eos,
  450. smartlist_t *dest,
  451. saved_location_t saved_location,
  452. int want_extrainfo,
  453. int allow_annotations,
  454. const char *prepend_annotations,
  455. smartlist_t *invalid_digests_out)
  456. {
  457. routerinfo_t *router;
  458. extrainfo_t *extrainfo;
  459. signed_descriptor_t *signed_desc = NULL;
  460. void *elt;
  461. const char *end, *start;
  462. int have_extrainfo;
  463. tor_assert(s);
  464. tor_assert(*s);
  465. tor_assert(dest);
  466. start = *s;
  467. if (!eos)
  468. eos = *s + strlen(*s);
  469. tor_assert(eos >= *s);
  470. while (1) {
  471. char raw_digest[DIGEST_LEN];
  472. int have_raw_digest = 0;
  473. int dl_again = 0;
  474. if (find_start_of_next_router_or_extrainfo(s, eos, &have_extrainfo) < 0)
  475. break;
  476. end = tor_memstr(*s, eos-*s, "\nrouter-signature");
  477. if (end)
  478. end = tor_memstr(end, eos-end, "\n-----END SIGNATURE-----\n");
  479. if (end)
  480. end += strlen("\n-----END SIGNATURE-----\n");
  481. if (!end)
  482. break;
  483. elt = NULL;
  484. if (have_extrainfo && want_extrainfo) {
  485. routerlist_t *rl = router_get_routerlist();
  486. have_raw_digest = router_get_extrainfo_hash(*s, end-*s, raw_digest) == 0;
  487. extrainfo = extrainfo_parse_entry_from_string(*s, end,
  488. saved_location != SAVED_IN_CACHE,
  489. rl->identity_map, &dl_again);
  490. if (extrainfo) {
  491. signed_desc = &extrainfo->cache_info;
  492. elt = extrainfo;
  493. }
  494. } else if (!have_extrainfo && !want_extrainfo) {
  495. have_raw_digest = router_get_router_hash(*s, end-*s, raw_digest) == 0;
  496. router = router_parse_entry_from_string(*s, end,
  497. saved_location != SAVED_IN_CACHE,
  498. allow_annotations,
  499. prepend_annotations, &dl_again);
  500. if (router) {
  501. log_debug(LD_DIR, "Read router '%s', purpose '%s'",
  502. router_describe(router),
  503. router_purpose_to_string(router->purpose));
  504. signed_desc = &router->cache_info;
  505. elt = router;
  506. }
  507. }
  508. if (! elt && ! dl_again && have_raw_digest && invalid_digests_out) {
  509. smartlist_add(invalid_digests_out, tor_memdup(raw_digest, DIGEST_LEN));
  510. }
  511. if (!elt) {
  512. *s = end;
  513. continue;
  514. }
  515. if (saved_location != SAVED_NOWHERE) {
  516. tor_assert(signed_desc);
  517. signed_desc->saved_location = saved_location;
  518. signed_desc->saved_offset = *s - start;
  519. }
  520. *s = end;
  521. smartlist_add(dest, elt);
  522. }
  523. return 0;
  524. }
  525. /* For debugging: define to count every descriptor digest we've seen so we
  526. * know if we need to try harder to avoid duplicate verifies. */
  527. #undef COUNT_DISTINCT_DIGESTS
  528. #ifdef COUNT_DISTINCT_DIGESTS
  529. static digestmap_t *verified_digests = NULL;
  530. #endif
  531. /** Log the total count of the number of distinct router digests we've ever
  532. * verified. When compared to the number of times we've verified routerdesc
  533. * signatures <i>in toto</i>, this will tell us if we're doing too much
  534. * multiple-verification. */
  535. void
  536. dump_distinct_digest_count(int severity)
  537. {
  538. #ifdef COUNT_DISTINCT_DIGESTS
  539. if (!verified_digests)
  540. verified_digests = digestmap_new();
  541. tor_log(severity, LD_GENERAL, "%d *distinct* router digests verified",
  542. digestmap_size(verified_digests));
  543. #else /* !(defined(COUNT_DISTINCT_DIGESTS)) */
  544. (void)severity; /* suppress "unused parameter" warning */
  545. #endif /* defined(COUNT_DISTINCT_DIGESTS) */
  546. }
  547. /** Try to find an IPv6 OR port in <b>list</b> of directory_token_t's
  548. * with at least one argument (use GE(1) in setup). If found, store
  549. * address and port number to <b>addr_out</b> and
  550. * <b>port_out</b>. Return number of OR ports found. */
  551. static int
  552. find_single_ipv6_orport(const smartlist_t *list,
  553. tor_addr_t *addr_out,
  554. uint16_t *port_out)
  555. {
  556. int ret = 0;
  557. tor_assert(list != NULL);
  558. tor_assert(addr_out != NULL);
  559. tor_assert(port_out != NULL);
  560. SMARTLIST_FOREACH_BEGIN(list, directory_token_t *, t) {
  561. tor_addr_t a;
  562. maskbits_t bits;
  563. uint16_t port_min, port_max;
  564. tor_assert(t->n_args >= 1);
  565. /* XXXX Prop186 the full spec allows much more than this. */
  566. if (tor_addr_parse_mask_ports(t->args[0], 0,
  567. &a, &bits, &port_min,
  568. &port_max) == AF_INET6 &&
  569. bits == 128 &&
  570. port_min == port_max) {
  571. /* Okay, this is one we can understand. Use it and ignore
  572. any potential more addresses in list. */
  573. tor_addr_copy(addr_out, &a);
  574. *port_out = port_min;
  575. ret = 1;
  576. break;
  577. }
  578. } SMARTLIST_FOREACH_END(t);
  579. return ret;
  580. }
  581. /** Helper function: reads a single router entry from *<b>s</b> ...
  582. * *<b>end</b>. Mallocs a new router and returns it if all goes well, else
  583. * returns NULL. If <b>cache_copy</b> is true, duplicate the contents of
  584. * s through end into the signed_descriptor_body of the resulting
  585. * routerinfo_t.
  586. *
  587. * If <b>end</b> is NULL, <b>s</b> must be properly NUL-terminated.
  588. *
  589. * If <b>allow_annotations</b>, it's okay to encounter annotations in <b>s</b>
  590. * before the router; if it's false, reject the router if it's annotated. If
  591. * <b>prepend_annotations</b> is set, it should contain some annotations:
  592. * append them to the front of the router before parsing it, and keep them
  593. * around when caching the router.
  594. *
  595. * Only one of allow_annotations and prepend_annotations may be set.
  596. *
  597. * If <b>can_dl_again_out</b> is provided, set *<b>can_dl_again_out</b> to 1
  598. * if it's okay to try to download a descriptor with this same digest again,
  599. * and 0 if it isn't. (It might not be okay to download it again if part of
  600. * the part covered by the digest is invalid.)
  601. */
  602. routerinfo_t *
  603. router_parse_entry_from_string(const char *s, const char *end,
  604. int cache_copy, int allow_annotations,
  605. const char *prepend_annotations,
  606. int *can_dl_again_out)
  607. {
  608. routerinfo_t *router = NULL;
  609. char digest[128];
  610. smartlist_t *tokens = NULL, *exit_policy_tokens = NULL;
  611. directory_token_t *tok;
  612. struct in_addr in;
  613. const char *start_of_annotations, *cp, *s_dup = s;
  614. size_t prepend_len = prepend_annotations ? strlen(prepend_annotations) : 0;
  615. int ok = 1;
  616. memarea_t *area = NULL;
  617. tor_cert_t *ntor_cc_cert = NULL;
  618. /* Do not set this to '1' until we have parsed everything that we intend to
  619. * parse that's covered by the hash. */
  620. int can_dl_again = 0;
  621. crypto_pk_t *rsa_pubkey = NULL;
  622. tor_assert(!allow_annotations || !prepend_annotations);
  623. if (!end) {
  624. end = s + strlen(s);
  625. }
  626. /* point 'end' to a point immediately after the final newline. */
  627. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  628. --end;
  629. area = memarea_new();
  630. tokens = smartlist_new();
  631. if (prepend_annotations) {
  632. if (tokenize_string(area,prepend_annotations,NULL,tokens,
  633. routerdesc_token_table,TS_NOCHECK)) {
  634. log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
  635. goto err;
  636. }
  637. }
  638. start_of_annotations = s;
  639. cp = tor_memstr(s, end-s, "\nrouter ");
  640. if (!cp) {
  641. if (end-s < 7 || strcmpstart(s, "router ")) {
  642. log_warn(LD_DIR, "No router keyword found.");
  643. goto err;
  644. }
  645. } else {
  646. s = cp+1;
  647. }
  648. if (start_of_annotations != s) { /* We have annotations */
  649. if (allow_annotations) {
  650. if (tokenize_string(area,start_of_annotations,s,tokens,
  651. routerdesc_token_table,TS_NOCHECK)) {
  652. log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
  653. goto err;
  654. }
  655. } else {
  656. log_warn(LD_DIR, "Found unexpected annotations on router descriptor not "
  657. "loaded from disk. Dropping it.");
  658. goto err;
  659. }
  660. }
  661. if (router_get_router_hash(s, end - s, digest) < 0) {
  662. log_warn(LD_DIR, "Couldn't compute router hash.");
  663. goto err;
  664. }
  665. {
  666. int flags = 0;
  667. if (allow_annotations)
  668. flags |= TS_ANNOTATIONS_OK;
  669. if (prepend_annotations)
  670. flags |= TS_ANNOTATIONS_OK|TS_NO_NEW_ANNOTATIONS;
  671. if (tokenize_string(area,s,end,tokens,routerdesc_token_table, flags)) {
  672. log_warn(LD_DIR, "Error tokenizing router descriptor.");
  673. goto err;
  674. }
  675. }
  676. if (smartlist_len(tokens) < 2) {
  677. log_warn(LD_DIR, "Impossibly short router descriptor.");
  678. goto err;
  679. }
  680. tok = find_by_keyword(tokens, K_ROUTER);
  681. const int router_token_pos = smartlist_pos(tokens, tok);
  682. tor_assert(tok->n_args >= 5);
  683. router = tor_malloc_zero(sizeof(routerinfo_t));
  684. router->cert_expiration_time = TIME_MAX;
  685. router->cache_info.routerlist_index = -1;
  686. router->cache_info.annotations_len = s-start_of_annotations + prepend_len;
  687. router->cache_info.signed_descriptor_len = end-s;
  688. if (cache_copy) {
  689. size_t len = router->cache_info.signed_descriptor_len +
  690. router->cache_info.annotations_len;
  691. char *signed_body =
  692. router->cache_info.signed_descriptor_body = tor_malloc(len+1);
  693. if (prepend_annotations) {
  694. memcpy(signed_body, prepend_annotations, prepend_len);
  695. signed_body += prepend_len;
  696. }
  697. /* This assertion will always succeed.
  698. * len == signed_desc_len + annotations_len
  699. * == end-s + s-start_of_annotations + prepend_len
  700. * == end-start_of_annotations + prepend_len
  701. * We already wrote prepend_len bytes into the buffer; now we're
  702. * writing end-start_of_annotations -NM. */
  703. tor_assert(signed_body+(end-start_of_annotations) ==
  704. router->cache_info.signed_descriptor_body+len);
  705. memcpy(signed_body, start_of_annotations, end-start_of_annotations);
  706. router->cache_info.signed_descriptor_body[len] = '\0';
  707. tor_assert(strlen(router->cache_info.signed_descriptor_body) == len);
  708. }
  709. memcpy(router->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  710. router->nickname = tor_strdup(tok->args[0]);
  711. if (!is_legal_nickname(router->nickname)) {
  712. log_warn(LD_DIR,"Router nickname is invalid");
  713. goto err;
  714. }
  715. if (!tor_inet_aton(tok->args[1], &in)) {
  716. log_warn(LD_DIR,"Router address is not an IP address.");
  717. goto err;
  718. }
  719. router->addr = ntohl(in.s_addr);
  720. router->or_port =
  721. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,&ok,NULL);
  722. if (!ok) {
  723. log_warn(LD_DIR,"Invalid OR port %s", escaped(tok->args[2]));
  724. goto err;
  725. }
  726. router->dir_port =
  727. (uint16_t) tor_parse_long(tok->args[4],10,0,65535,&ok,NULL);
  728. if (!ok) {
  729. log_warn(LD_DIR,"Invalid dir port %s", escaped(tok->args[4]));
  730. goto err;
  731. }
  732. tok = find_by_keyword(tokens, K_BANDWIDTH);
  733. tor_assert(tok->n_args >= 3);
  734. router->bandwidthrate = (int)
  735. tor_parse_long(tok->args[0],10,1,INT_MAX,&ok,NULL);
  736. if (!ok) {
  737. log_warn(LD_DIR, "bandwidthrate %s unreadable or 0. Failing.",
  738. escaped(tok->args[0]));
  739. goto err;
  740. }
  741. router->bandwidthburst =
  742. (int) tor_parse_long(tok->args[1],10,0,INT_MAX,&ok,NULL);
  743. if (!ok) {
  744. log_warn(LD_DIR, "Invalid bandwidthburst %s", escaped(tok->args[1]));
  745. goto err;
  746. }
  747. router->bandwidthcapacity = (int)
  748. tor_parse_long(tok->args[2],10,0,INT_MAX,&ok,NULL);
  749. if (!ok) {
  750. log_warn(LD_DIR, "Invalid bandwidthcapacity %s", escaped(tok->args[1]));
  751. goto err;
  752. }
  753. if ((tok = find_opt_by_keyword(tokens, A_PURPOSE))) {
  754. tor_assert(tok->n_args);
  755. router->purpose = router_purpose_from_string(tok->args[0]);
  756. } else {
  757. router->purpose = ROUTER_PURPOSE_GENERAL;
  758. }
  759. router->cache_info.send_unencrypted =
  760. (router->purpose == ROUTER_PURPOSE_GENERAL) ? 1 : 0;
  761. if ((tok = find_opt_by_keyword(tokens, K_UPTIME))) {
  762. tor_assert(tok->n_args >= 1);
  763. router->uptime = tor_parse_long(tok->args[0],10,0,LONG_MAX,&ok,NULL);
  764. if (!ok) {
  765. log_warn(LD_DIR, "Invalid uptime %s", escaped(tok->args[0]));
  766. goto err;
  767. }
  768. }
  769. if ((tok = find_opt_by_keyword(tokens, K_HIBERNATING))) {
  770. tor_assert(tok->n_args >= 1);
  771. router->is_hibernating
  772. = (tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL) != 0);
  773. }
  774. tok = find_by_keyword(tokens, K_PUBLISHED);
  775. tor_assert(tok->n_args == 1);
  776. if (parse_iso_time(tok->args[0], &router->cache_info.published_on) < 0)
  777. goto err;
  778. tok = find_by_keyword(tokens, K_ONION_KEY);
  779. if (!crypto_pk_public_exponent_ok(tok->key)) {
  780. log_warn(LD_DIR,
  781. "Relay's onion key had invalid exponent.");
  782. goto err;
  783. }
  784. router_set_rsa_onion_pkey(tok->key, &router->onion_pkey,
  785. &router->onion_pkey_len);
  786. crypto_pk_free(tok->key);
  787. if ((tok = find_opt_by_keyword(tokens, K_ONION_KEY_NTOR))) {
  788. curve25519_public_key_t k;
  789. tor_assert(tok->n_args >= 1);
  790. if (curve25519_public_from_base64(&k, tok->args[0]) < 0) {
  791. log_warn(LD_DIR, "Bogus ntor-onion-key in routerinfo");
  792. goto err;
  793. }
  794. router->onion_curve25519_pkey =
  795. tor_memdup(&k, sizeof(curve25519_public_key_t));
  796. }
  797. tok = find_by_keyword(tokens, K_SIGNING_KEY);
  798. router->identity_pkey = tok->key;
  799. tok->key = NULL; /* Prevent free */
  800. if (crypto_pk_get_digest(router->identity_pkey,
  801. router->cache_info.identity_digest)) {
  802. log_warn(LD_DIR, "Couldn't calculate key digest"); goto err;
  803. }
  804. {
  805. directory_token_t *ed_sig_tok, *ed_cert_tok, *cc_tap_tok, *cc_ntor_tok,
  806. *master_key_tok;
  807. ed_sig_tok = find_opt_by_keyword(tokens, K_ROUTER_SIG_ED25519);
  808. ed_cert_tok = find_opt_by_keyword(tokens, K_IDENTITY_ED25519);
  809. master_key_tok = find_opt_by_keyword(tokens, K_MASTER_KEY_ED25519);
  810. cc_tap_tok = find_opt_by_keyword(tokens, K_ONION_KEY_CROSSCERT);
  811. cc_ntor_tok = find_opt_by_keyword(tokens, K_NTOR_ONION_KEY_CROSSCERT);
  812. int n_ed_toks = !!ed_sig_tok + !!ed_cert_tok +
  813. !!cc_tap_tok + !!cc_ntor_tok;
  814. if ((n_ed_toks != 0 && n_ed_toks != 4) ||
  815. (n_ed_toks == 4 && !router->onion_curve25519_pkey)) {
  816. log_warn(LD_DIR, "Router descriptor with only partial ed25519/"
  817. "cross-certification support");
  818. goto err;
  819. }
  820. if (master_key_tok && !ed_sig_tok) {
  821. log_warn(LD_DIR, "Router descriptor has ed25519 master key but no "
  822. "certificate");
  823. goto err;
  824. }
  825. if (ed_sig_tok) {
  826. tor_assert(ed_cert_tok && cc_tap_tok && cc_ntor_tok);
  827. const int ed_cert_token_pos = smartlist_pos(tokens, ed_cert_tok);
  828. if (ed_cert_token_pos == -1 || router_token_pos == -1 ||
  829. (ed_cert_token_pos != router_token_pos + 1 &&
  830. ed_cert_token_pos != router_token_pos - 1)) {
  831. log_warn(LD_DIR, "Ed25519 certificate in wrong position");
  832. goto err;
  833. }
  834. if (ed_sig_tok != smartlist_get(tokens, smartlist_len(tokens)-2)) {
  835. log_warn(LD_DIR, "Ed25519 signature in wrong position");
  836. goto err;
  837. }
  838. if (strcmp(ed_cert_tok->object_type, "ED25519 CERT")) {
  839. log_warn(LD_DIR, "Wrong object type on identity-ed25519 in decriptor");
  840. goto err;
  841. }
  842. if (strcmp(cc_ntor_tok->object_type, "ED25519 CERT")) {
  843. log_warn(LD_DIR, "Wrong object type on ntor-onion-key-crosscert "
  844. "in decriptor");
  845. goto err;
  846. }
  847. if (strcmp(cc_tap_tok->object_type, "CROSSCERT")) {
  848. log_warn(LD_DIR, "Wrong object type on onion-key-crosscert "
  849. "in decriptor");
  850. goto err;
  851. }
  852. if (strcmp(cc_ntor_tok->args[0], "0") &&
  853. strcmp(cc_ntor_tok->args[0], "1")) {
  854. log_warn(LD_DIR, "Bad sign bit on ntor-onion-key-crosscert");
  855. goto err;
  856. }
  857. int ntor_cc_sign_bit = !strcmp(cc_ntor_tok->args[0], "1");
  858. uint8_t d256[DIGEST256_LEN];
  859. const char *signed_start, *signed_end;
  860. tor_cert_t *cert = tor_cert_parse(
  861. (const uint8_t*)ed_cert_tok->object_body,
  862. ed_cert_tok->object_size);
  863. if (! cert) {
  864. log_warn(LD_DIR, "Couldn't parse ed25519 cert");
  865. goto err;
  866. }
  867. /* makes sure it gets freed. */
  868. router->cache_info.signing_key_cert = cert;
  869. if (cert->cert_type != CERT_TYPE_ID_SIGNING ||
  870. ! cert->signing_key_included) {
  871. log_warn(LD_DIR, "Invalid form for ed25519 cert");
  872. goto err;
  873. }
  874. if (master_key_tok) {
  875. /* This token is optional, but if it's present, it must match
  876. * the signature in the signing cert, or supplant it. */
  877. tor_assert(master_key_tok->n_args >= 1);
  878. ed25519_public_key_t pkey;
  879. if (ed25519_public_from_base64(&pkey, master_key_tok->args[0])<0) {
  880. log_warn(LD_DIR, "Can't parse ed25519 master key");
  881. goto err;
  882. }
  883. if (fast_memneq(&cert->signing_key.pubkey,
  884. pkey.pubkey, ED25519_PUBKEY_LEN)) {
  885. log_warn(LD_DIR, "Ed25519 master key does not match "
  886. "key in certificate");
  887. goto err;
  888. }
  889. }
  890. ntor_cc_cert = tor_cert_parse((const uint8_t*)cc_ntor_tok->object_body,
  891. cc_ntor_tok->object_size);
  892. if (!ntor_cc_cert) {
  893. log_warn(LD_DIR, "Couldn't parse ntor-onion-key-crosscert cert");
  894. goto err;
  895. }
  896. if (ntor_cc_cert->cert_type != CERT_TYPE_ONION_ID ||
  897. ! ed25519_pubkey_eq(&ntor_cc_cert->signed_key, &cert->signing_key)) {
  898. log_warn(LD_DIR, "Invalid contents for ntor-onion-key-crosscert cert");
  899. goto err;
  900. }
  901. ed25519_public_key_t ntor_cc_pk;
  902. if (ed25519_public_key_from_curve25519_public_key(&ntor_cc_pk,
  903. router->onion_curve25519_pkey,
  904. ntor_cc_sign_bit)<0) {
  905. log_warn(LD_DIR, "Error converting onion key to ed25519");
  906. goto err;
  907. }
  908. if (router_get_hash_impl_helper(s, end-s, "router ",
  909. "\nrouter-sig-ed25519",
  910. ' ', LOG_WARN,
  911. &signed_start, &signed_end) < 0) {
  912. log_warn(LD_DIR, "Can't find ed25519-signed portion of descriptor");
  913. goto err;
  914. }
  915. crypto_digest_t *d = crypto_digest256_new(DIGEST_SHA256);
  916. crypto_digest_add_bytes(d, ED_DESC_SIGNATURE_PREFIX,
  917. strlen(ED_DESC_SIGNATURE_PREFIX));
  918. crypto_digest_add_bytes(d, signed_start, signed_end-signed_start);
  919. crypto_digest_get_digest(d, (char*)d256, sizeof(d256));
  920. crypto_digest_free(d);
  921. ed25519_checkable_t check[3];
  922. int check_ok[3];
  923. time_t expires = TIME_MAX;
  924. if (tor_cert_get_checkable_sig(&check[0], cert, NULL, &expires) < 0) {
  925. log_err(LD_BUG, "Couldn't create 'checkable' for cert.");
  926. goto err;
  927. }
  928. if (tor_cert_get_checkable_sig(&check[1],
  929. ntor_cc_cert, &ntor_cc_pk, &expires) < 0) {
  930. log_err(LD_BUG, "Couldn't create 'checkable' for ntor_cc_cert.");
  931. goto err;
  932. }
  933. if (ed25519_signature_from_base64(&check[2].signature,
  934. ed_sig_tok->args[0])<0) {
  935. log_warn(LD_DIR, "Couldn't decode ed25519 signature");
  936. goto err;
  937. }
  938. check[2].pubkey = &cert->signed_key;
  939. check[2].msg = d256;
  940. check[2].len = DIGEST256_LEN;
  941. if (ed25519_checksig_batch(check_ok, check, 3) < 0) {
  942. log_warn(LD_DIR, "Incorrect ed25519 signature(s)");
  943. goto err;
  944. }
  945. rsa_pubkey = router_get_rsa_onion_pkey(router->onion_pkey,
  946. router->onion_pkey_len);
  947. if (check_tap_onion_key_crosscert(
  948. (const uint8_t*)cc_tap_tok->object_body,
  949. (int)cc_tap_tok->object_size,
  950. rsa_pubkey,
  951. &cert->signing_key,
  952. (const uint8_t*)router->cache_info.identity_digest)<0) {
  953. log_warn(LD_DIR, "Incorrect TAP cross-verification");
  954. goto err;
  955. }
  956. /* We check this before adding it to the routerlist. */
  957. router->cert_expiration_time = expires;
  958. }
  959. }
  960. if ((tok = find_opt_by_keyword(tokens, K_FINGERPRINT))) {
  961. /* If there's a fingerprint line, it must match the identity digest. */
  962. char d[DIGEST_LEN];
  963. tor_assert(tok->n_args == 1);
  964. tor_strstrip(tok->args[0], " ");
  965. if (base16_decode(d, DIGEST_LEN,
  966. tok->args[0], strlen(tok->args[0])) != DIGEST_LEN) {
  967. log_warn(LD_DIR, "Couldn't decode router fingerprint %s",
  968. escaped(tok->args[0]));
  969. goto err;
  970. }
  971. if (tor_memneq(d,router->cache_info.identity_digest, DIGEST_LEN)) {
  972. log_warn(LD_DIR, "Fingerprint '%s' does not match identity digest.",
  973. tok->args[0]);
  974. goto err;
  975. }
  976. }
  977. {
  978. const char *version = NULL, *protocols = NULL;
  979. if ((tok = find_opt_by_keyword(tokens, K_PLATFORM))) {
  980. router->platform = tor_strdup(tok->args[0]);
  981. version = tok->args[0];
  982. }
  983. if ((tok = find_opt_by_keyword(tokens, K_PROTO))) {
  984. router->protocol_list = tor_strdup(tok->args[0]);
  985. protocols = tok->args[0];
  986. }
  987. summarize_protover_flags(&router->pv, protocols, version);
  988. }
  989. if ((tok = find_opt_by_keyword(tokens, K_CONTACT))) {
  990. router->contact_info = tor_strdup(tok->args[0]);
  991. }
  992. if (find_opt_by_keyword(tokens, K_REJECT6) ||
  993. find_opt_by_keyword(tokens, K_ACCEPT6)) {
  994. log_warn(LD_DIR, "Rejecting router with reject6/accept6 line: they crash "
  995. "older Tors.");
  996. goto err;
  997. }
  998. {
  999. smartlist_t *or_addresses = find_all_by_keyword(tokens, K_OR_ADDRESS);
  1000. if (or_addresses) {
  1001. find_single_ipv6_orport(or_addresses, &router->ipv6_addr,
  1002. &router->ipv6_orport);
  1003. smartlist_free(or_addresses);
  1004. }
  1005. }
  1006. exit_policy_tokens = find_all_exitpolicy(tokens);
  1007. if (!smartlist_len(exit_policy_tokens)) {
  1008. log_warn(LD_DIR, "No exit policy tokens in descriptor.");
  1009. goto err;
  1010. }
  1011. SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
  1012. if (router_add_exit_policy(router,t)<0) {
  1013. log_warn(LD_DIR,"Error in exit policy");
  1014. goto err;
  1015. });
  1016. policy_expand_private(&router->exit_policy);
  1017. if ((tok = find_opt_by_keyword(tokens, K_IPV6_POLICY)) && tok->n_args) {
  1018. router->ipv6_exit_policy = parse_short_policy(tok->args[0]);
  1019. if (! router->ipv6_exit_policy) {
  1020. log_warn(LD_DIR , "Error in ipv6-policy %s", escaped(tok->args[0]));
  1021. goto err;
  1022. }
  1023. }
  1024. if (policy_is_reject_star(router->exit_policy, AF_INET, 1) &&
  1025. (!router->ipv6_exit_policy ||
  1026. short_policy_is_reject_star(router->ipv6_exit_policy)))
  1027. router->policy_is_reject_star = 1;
  1028. if ((tok = find_opt_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
  1029. int i;
  1030. router->declared_family = smartlist_new();
  1031. for (i=0;i<tok->n_args;++i) {
  1032. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  1033. log_warn(LD_DIR, "Illegal nickname %s in family line",
  1034. escaped(tok->args[i]));
  1035. goto err;
  1036. }
  1037. smartlist_add_strdup(router->declared_family, tok->args[i]);
  1038. }
  1039. }
  1040. if (find_opt_by_keyword(tokens, K_CACHES_EXTRA_INFO))
  1041. router->caches_extra_info = 1;
  1042. if (find_opt_by_keyword(tokens, K_ALLOW_SINGLE_HOP_EXITS))
  1043. router->allow_single_hop_exits = 1;
  1044. if ((tok = find_opt_by_keyword(tokens, K_EXTRA_INFO_DIGEST))) {
  1045. tor_assert(tok->n_args >= 1);
  1046. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  1047. if (base16_decode(router->cache_info.extra_info_digest, DIGEST_LEN,
  1048. tok->args[0], HEX_DIGEST_LEN) != DIGEST_LEN) {
  1049. log_warn(LD_DIR,"Invalid extra info digest");
  1050. }
  1051. } else {
  1052. log_warn(LD_DIR, "Invalid extra info digest %s", escaped(tok->args[0]));
  1053. }
  1054. if (tok->n_args >= 2) {
  1055. if (digest256_from_base64(router->cache_info.extra_info_digest256,
  1056. tok->args[1]) < 0) {
  1057. log_warn(LD_DIR, "Invalid extra info digest256 %s",
  1058. escaped(tok->args[1]));
  1059. }
  1060. }
  1061. }
  1062. if (find_opt_by_keyword(tokens, K_HIDDEN_SERVICE_DIR)) {
  1063. router->wants_to_be_hs_dir = 1;
  1064. }
  1065. /* This router accepts tunnelled directory requests via begindir if it has
  1066. * an open dirport or it included "tunnelled-dir-server". */
  1067. if (find_opt_by_keyword(tokens, K_DIR_TUNNELLED) || router->dir_port > 0) {
  1068. router->supports_tunnelled_dir_requests = 1;
  1069. }
  1070. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1071. #ifdef COUNT_DISTINCT_DIGESTS
  1072. if (!verified_digests)
  1073. verified_digests = digestmap_new();
  1074. digestmap_set(verified_digests, signed_digest, (void*)(uintptr_t)1);
  1075. #endif
  1076. if (!router->or_port) {
  1077. log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
  1078. goto err;
  1079. }
  1080. /* We've checked everything that's covered by the hash. */
  1081. can_dl_again = 1;
  1082. if (check_signature_token(digest, DIGEST_LEN, tok, router->identity_pkey, 0,
  1083. "router descriptor") < 0)
  1084. goto err;
  1085. if (!router->platform) {
  1086. router->platform = tor_strdup("<unknown>");
  1087. }
  1088. goto done;
  1089. err:
  1090. dump_desc(s_dup, "router descriptor");
  1091. routerinfo_free(router);
  1092. router = NULL;
  1093. done:
  1094. crypto_pk_free(rsa_pubkey);
  1095. tor_cert_free(ntor_cc_cert);
  1096. if (tokens) {
  1097. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1098. smartlist_free(tokens);
  1099. }
  1100. smartlist_free(exit_policy_tokens);
  1101. if (area) {
  1102. DUMP_AREA(area, "routerinfo");
  1103. memarea_drop_all(area);
  1104. }
  1105. if (can_dl_again_out)
  1106. *can_dl_again_out = can_dl_again;
  1107. return router;
  1108. }
  1109. /** Parse a single extrainfo entry from the string <b>s</b>, ending at
  1110. * <b>end</b>. (If <b>end</b> is NULL, parse up to the end of <b>s</b>.) If
  1111. * <b>cache_copy</b> is true, make a copy of the extra-info document in the
  1112. * cache_info fields of the result. If <b>routermap</b> is provided, use it
  1113. * as a map from router identity to routerinfo_t when looking up signing keys.
  1114. *
  1115. * If <b>can_dl_again_out</b> is provided, set *<b>can_dl_again_out</b> to 1
  1116. * if it's okay to try to download an extrainfo with this same digest again,
  1117. * and 0 if it isn't. (It might not be okay to download it again if part of
  1118. * the part covered by the digest is invalid.)
  1119. */
  1120. extrainfo_t *
  1121. extrainfo_parse_entry_from_string(const char *s, const char *end,
  1122. int cache_copy, struct digest_ri_map_t *routermap,
  1123. int *can_dl_again_out)
  1124. {
  1125. extrainfo_t *extrainfo = NULL;
  1126. char digest[128];
  1127. smartlist_t *tokens = NULL;
  1128. directory_token_t *tok;
  1129. crypto_pk_t *key = NULL;
  1130. routerinfo_t *router = NULL;
  1131. memarea_t *area = NULL;
  1132. const char *s_dup = s;
  1133. /* Do not set this to '1' until we have parsed everything that we intend to
  1134. * parse that's covered by the hash. */
  1135. int can_dl_again = 0;
  1136. if (BUG(s == NULL))
  1137. return NULL;
  1138. if (!end) {
  1139. end = s + strlen(s);
  1140. }
  1141. /* point 'end' to a point immediately after the final newline. */
  1142. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  1143. --end;
  1144. if (router_get_extrainfo_hash(s, end-s, digest) < 0) {
  1145. log_warn(LD_DIR, "Couldn't compute router hash.");
  1146. goto err;
  1147. }
  1148. tokens = smartlist_new();
  1149. area = memarea_new();
  1150. if (tokenize_string(area,s,end,tokens,extrainfo_token_table,0)) {
  1151. log_warn(LD_DIR, "Error tokenizing extra-info document.");
  1152. goto err;
  1153. }
  1154. if (smartlist_len(tokens) < 2) {
  1155. log_warn(LD_DIR, "Impossibly short extra-info document.");
  1156. goto err;
  1157. }
  1158. /* XXXX Accept this in position 1 too, and ed identity in position 0. */
  1159. tok = smartlist_get(tokens,0);
  1160. if (tok->tp != K_EXTRA_INFO) {
  1161. log_warn(LD_DIR,"Entry does not start with \"extra-info\"");
  1162. goto err;
  1163. }
  1164. extrainfo = tor_malloc_zero(sizeof(extrainfo_t));
  1165. extrainfo->cache_info.is_extrainfo = 1;
  1166. if (cache_copy)
  1167. extrainfo->cache_info.signed_descriptor_body = tor_memdup_nulterm(s,end-s);
  1168. extrainfo->cache_info.signed_descriptor_len = end-s;
  1169. memcpy(extrainfo->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1170. crypto_digest256((char*)extrainfo->digest256, s, end-s, DIGEST_SHA256);
  1171. tor_assert(tok->n_args >= 2);
  1172. if (!is_legal_nickname(tok->args[0])) {
  1173. log_warn(LD_DIR,"Bad nickname %s on \"extra-info\"",escaped(tok->args[0]));
  1174. goto err;
  1175. }
  1176. strlcpy(extrainfo->nickname, tok->args[0], sizeof(extrainfo->nickname));
  1177. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  1178. base16_decode(extrainfo->cache_info.identity_digest, DIGEST_LEN,
  1179. tok->args[1], HEX_DIGEST_LEN) != DIGEST_LEN) {
  1180. log_warn(LD_DIR,"Invalid fingerprint %s on \"extra-info\"",
  1181. escaped(tok->args[1]));
  1182. goto err;
  1183. }
  1184. tok = find_by_keyword(tokens, K_PUBLISHED);
  1185. if (parse_iso_time(tok->args[0], &extrainfo->cache_info.published_on)) {
  1186. log_warn(LD_DIR,"Invalid published time %s on \"extra-info\"",
  1187. escaped(tok->args[0]));
  1188. goto err;
  1189. }
  1190. {
  1191. directory_token_t *ed_sig_tok, *ed_cert_tok;
  1192. ed_sig_tok = find_opt_by_keyword(tokens, K_ROUTER_SIG_ED25519);
  1193. ed_cert_tok = find_opt_by_keyword(tokens, K_IDENTITY_ED25519);
  1194. int n_ed_toks = !!ed_sig_tok + !!ed_cert_tok;
  1195. if (n_ed_toks != 0 && n_ed_toks != 2) {
  1196. log_warn(LD_DIR, "Router descriptor with only partial ed25519/"
  1197. "cross-certification support");
  1198. goto err;
  1199. }
  1200. if (ed_sig_tok) {
  1201. tor_assert(ed_cert_tok);
  1202. const int ed_cert_token_pos = smartlist_pos(tokens, ed_cert_tok);
  1203. if (ed_cert_token_pos != 1) {
  1204. /* Accept this in position 0 XXXX */
  1205. log_warn(LD_DIR, "Ed25519 certificate in wrong position");
  1206. goto err;
  1207. }
  1208. if (ed_sig_tok != smartlist_get(tokens, smartlist_len(tokens)-2)) {
  1209. log_warn(LD_DIR, "Ed25519 signature in wrong position");
  1210. goto err;
  1211. }
  1212. if (strcmp(ed_cert_tok->object_type, "ED25519 CERT")) {
  1213. log_warn(LD_DIR, "Wrong object type on identity-ed25519 in decriptor");
  1214. goto err;
  1215. }
  1216. uint8_t d256[DIGEST256_LEN];
  1217. const char *signed_start, *signed_end;
  1218. tor_cert_t *cert = tor_cert_parse(
  1219. (const uint8_t*)ed_cert_tok->object_body,
  1220. ed_cert_tok->object_size);
  1221. if (! cert) {
  1222. log_warn(LD_DIR, "Couldn't parse ed25519 cert");
  1223. goto err;
  1224. }
  1225. /* makes sure it gets freed. */
  1226. extrainfo->cache_info.signing_key_cert = cert;
  1227. if (cert->cert_type != CERT_TYPE_ID_SIGNING ||
  1228. ! cert->signing_key_included) {
  1229. log_warn(LD_DIR, "Invalid form for ed25519 cert");
  1230. goto err;
  1231. }
  1232. if (router_get_hash_impl_helper(s, end-s, "extra-info ",
  1233. "\nrouter-sig-ed25519",
  1234. ' ', LOG_WARN,
  1235. &signed_start, &signed_end) < 0) {
  1236. log_warn(LD_DIR, "Can't find ed25519-signed portion of extrainfo");
  1237. goto err;
  1238. }
  1239. crypto_digest_t *d = crypto_digest256_new(DIGEST_SHA256);
  1240. crypto_digest_add_bytes(d, ED_DESC_SIGNATURE_PREFIX,
  1241. strlen(ED_DESC_SIGNATURE_PREFIX));
  1242. crypto_digest_add_bytes(d, signed_start, signed_end-signed_start);
  1243. crypto_digest_get_digest(d, (char*)d256, sizeof(d256));
  1244. crypto_digest_free(d);
  1245. ed25519_checkable_t check[2];
  1246. int check_ok[2];
  1247. if (tor_cert_get_checkable_sig(&check[0], cert, NULL, NULL) < 0) {
  1248. log_err(LD_BUG, "Couldn't create 'checkable' for cert.");
  1249. goto err;
  1250. }
  1251. if (ed25519_signature_from_base64(&check[1].signature,
  1252. ed_sig_tok->args[0])<0) {
  1253. log_warn(LD_DIR, "Couldn't decode ed25519 signature");
  1254. goto err;
  1255. }
  1256. check[1].pubkey = &cert->signed_key;
  1257. check[1].msg = d256;
  1258. check[1].len = DIGEST256_LEN;
  1259. if (ed25519_checksig_batch(check_ok, check, 2) < 0) {
  1260. log_warn(LD_DIR, "Incorrect ed25519 signature(s)");
  1261. goto err;
  1262. }
  1263. /* We don't check the certificate expiration time: checking that it
  1264. * matches the cert in the router descriptor is adequate. */
  1265. }
  1266. }
  1267. /* We've checked everything that's covered by the hash. */
  1268. can_dl_again = 1;
  1269. if (routermap &&
  1270. (router = digestmap_get((digestmap_t*)routermap,
  1271. extrainfo->cache_info.identity_digest))) {
  1272. key = router->identity_pkey;
  1273. }
  1274. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1275. if (strcmp(tok->object_type, "SIGNATURE") ||
  1276. tok->object_size < 128 || tok->object_size > 512) {
  1277. log_warn(LD_DIR, "Bad object type or length on extra-info signature");
  1278. goto err;
  1279. }
  1280. if (key) {
  1281. if (check_signature_token(digest, DIGEST_LEN, tok, key, 0,
  1282. "extra-info") < 0)
  1283. goto err;
  1284. if (router)
  1285. extrainfo->cache_info.send_unencrypted =
  1286. router->cache_info.send_unencrypted;
  1287. } else {
  1288. extrainfo->pending_sig = tor_memdup(tok->object_body,
  1289. tok->object_size);
  1290. extrainfo->pending_sig_len = tok->object_size;
  1291. }
  1292. goto done;
  1293. err:
  1294. dump_desc(s_dup, "extra-info descriptor");
  1295. extrainfo_free(extrainfo);
  1296. extrainfo = NULL;
  1297. done:
  1298. if (tokens) {
  1299. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1300. smartlist_free(tokens);
  1301. }
  1302. if (area) {
  1303. DUMP_AREA(area, "extrainfo");
  1304. memarea_drop_all(area);
  1305. }
  1306. if (can_dl_again_out)
  1307. *can_dl_again_out = can_dl_again;
  1308. return extrainfo;
  1309. }
  1310. /** Helper: given a string <b>s</b>, return the start of the next router-status
  1311. * object (starting with "r " at the start of a line). If none is found,
  1312. * return the start of the directory footer, or the next directory signature.
  1313. * If none is found, return the end of the string. */
  1314. static inline const char *
  1315. find_start_of_next_routerstatus(const char *s)
  1316. {
  1317. const char *eos, *footer, *sig;
  1318. if ((eos = strstr(s, "\nr ")))
  1319. ++eos;
  1320. else
  1321. eos = s + strlen(s);
  1322. footer = tor_memstr(s, eos-s, "\ndirectory-footer");
  1323. sig = tor_memstr(s, eos-s, "\ndirectory-signature");
  1324. if (footer && sig)
  1325. return MIN(footer, sig) + 1;
  1326. else if (footer)
  1327. return footer+1;
  1328. else if (sig)
  1329. return sig+1;
  1330. else
  1331. return eos;
  1332. }
  1333. /** Parse the GuardFraction string from a consensus or vote.
  1334. *
  1335. * If <b>vote</b> or <b>vote_rs</b> are set the document getting
  1336. * parsed is a vote routerstatus. Otherwise it's a consensus. This is
  1337. * the same semantic as in routerstatus_parse_entry_from_string(). */
  1338. STATIC int
  1339. routerstatus_parse_guardfraction(const char *guardfraction_str,
  1340. networkstatus_t *vote,
  1341. vote_routerstatus_t *vote_rs,
  1342. routerstatus_t *rs)
  1343. {
  1344. int ok;
  1345. const char *end_of_header = NULL;
  1346. int is_consensus = !vote_rs;
  1347. uint32_t guardfraction;
  1348. tor_assert(bool_eq(vote, vote_rs));
  1349. /* If this info comes from a consensus, but we should't apply
  1350. guardfraction, just exit. */
  1351. if (is_consensus && !should_apply_guardfraction(NULL)) {
  1352. return 0;
  1353. }
  1354. end_of_header = strchr(guardfraction_str, '=');
  1355. if (!end_of_header) {
  1356. return -1;
  1357. }
  1358. guardfraction = (uint32_t)tor_parse_ulong(end_of_header+1,
  1359. 10, 0, 100, &ok, NULL);
  1360. if (!ok) {
  1361. log_warn(LD_DIR, "Invalid GuardFraction %s", escaped(guardfraction_str));
  1362. return -1;
  1363. }
  1364. log_debug(LD_GENERAL, "[*] Parsed %s guardfraction '%s' for '%s'.",
  1365. is_consensus ? "consensus" : "vote",
  1366. guardfraction_str, rs->nickname);
  1367. if (!is_consensus) { /* We are parsing a vote */
  1368. vote_rs->status.guardfraction_percentage = guardfraction;
  1369. vote_rs->status.has_guardfraction = 1;
  1370. } else {
  1371. /* We are parsing a consensus. Only apply guardfraction to guards. */
  1372. if (rs->is_possible_guard) {
  1373. rs->guardfraction_percentage = guardfraction;
  1374. rs->has_guardfraction = 1;
  1375. } else {
  1376. log_warn(LD_BUG, "Got GuardFraction for non-guard %s. "
  1377. "This is not supposed to happen. Not applying. ", rs->nickname);
  1378. }
  1379. }
  1380. return 0;
  1381. }
  1382. /** Summarize the protocols listed in <b>protocols</b> into <b>out</b>,
  1383. * falling back or correcting them based on <b>version</b> as appropriate.
  1384. */
  1385. STATIC void
  1386. summarize_protover_flags(protover_summary_flags_t *out,
  1387. const char *protocols,
  1388. const char *version)
  1389. {
  1390. tor_assert(out);
  1391. memset(out, 0, sizeof(*out));
  1392. if (protocols) {
  1393. out->protocols_known = 1;
  1394. out->supports_extend2_cells =
  1395. protocol_list_supports_protocol(protocols, PRT_RELAY, 2);
  1396. out->supports_ed25519_link_handshake_compat =
  1397. protocol_list_supports_protocol(protocols, PRT_LINKAUTH, 3);
  1398. out->supports_ed25519_link_handshake_any =
  1399. protocol_list_supports_protocol_or_later(protocols, PRT_LINKAUTH, 3);
  1400. out->supports_ed25519_hs_intro =
  1401. protocol_list_supports_protocol(protocols, PRT_HSINTRO, 4);
  1402. out->supports_v3_hsdir =
  1403. protocol_list_supports_protocol(protocols, PRT_HSDIR,
  1404. PROTOVER_HSDIR_V3);
  1405. out->supports_v3_rendezvous_point =
  1406. protocol_list_supports_protocol(protocols, PRT_HSREND,
  1407. PROTOVER_HS_RENDEZVOUS_POINT_V3);
  1408. }
  1409. if (version && !strcmpstart(version, "Tor ")) {
  1410. if (!out->protocols_known) {
  1411. /* The version is a "Tor" version, and where there is no
  1412. * list of protocol versions that we should be looking at instead. */
  1413. out->supports_extend2_cells =
  1414. tor_version_as_new_as(version, "0.2.4.8-alpha");
  1415. out->protocols_known = 1;
  1416. } else {
  1417. /* Bug #22447 forces us to filter on this version. */
  1418. if (!tor_version_as_new_as(version, "0.3.0.8")) {
  1419. out->supports_v3_hsdir = 0;
  1420. }
  1421. }
  1422. }
  1423. }
  1424. /** Given a string at *<b>s</b>, containing a routerstatus object, and an
  1425. * empty smartlist at <b>tokens</b>, parse and return the first router status
  1426. * object in the string, and advance *<b>s</b> to just after the end of the
  1427. * router status. Return NULL and advance *<b>s</b> on error.
  1428. *
  1429. * If <b>vote</b> and <b>vote_rs</b> are provided, don't allocate a fresh
  1430. * routerstatus but use <b>vote_rs</b> instead.
  1431. *
  1432. * If <b>consensus_method</b> is nonzero, this routerstatus is part of a
  1433. * consensus, and we should parse it according to the method used to
  1434. * make that consensus.
  1435. *
  1436. * Parse according to the syntax used by the consensus flavor <b>flav</b>.
  1437. **/
  1438. STATIC routerstatus_t *
  1439. routerstatus_parse_entry_from_string(memarea_t *area,
  1440. const char **s, smartlist_t *tokens,
  1441. networkstatus_t *vote,
  1442. vote_routerstatus_t *vote_rs,
  1443. int consensus_method,
  1444. consensus_flavor_t flav)
  1445. {
  1446. const char *eos, *s_dup = *s;
  1447. routerstatus_t *rs = NULL;
  1448. directory_token_t *tok;
  1449. char timebuf[ISO_TIME_LEN+1];
  1450. struct in_addr in;
  1451. int offset = 0;
  1452. tor_assert(tokens);
  1453. tor_assert(bool_eq(vote, vote_rs));
  1454. if (!consensus_method)
  1455. flav = FLAV_NS;
  1456. tor_assert(flav == FLAV_NS || flav == FLAV_MICRODESC);
  1457. eos = find_start_of_next_routerstatus(*s);
  1458. if (tokenize_string(area,*s, eos, tokens, rtrstatus_token_table,0)) {
  1459. log_warn(LD_DIR, "Error tokenizing router status");
  1460. goto err;
  1461. }
  1462. if (smartlist_len(tokens) < 1) {
  1463. log_warn(LD_DIR, "Impossibly short router status");
  1464. goto err;
  1465. }
  1466. tok = find_by_keyword(tokens, K_R);
  1467. tor_assert(tok->n_args >= 7); /* guaranteed by GE(7) in K_R setup */
  1468. if (flav == FLAV_NS) {
  1469. if (tok->n_args < 8) {
  1470. log_warn(LD_DIR, "Too few arguments to r");
  1471. goto err;
  1472. }
  1473. } else if (flav == FLAV_MICRODESC) {
  1474. offset = -1; /* There is no descriptor digest in an md consensus r line */
  1475. }
  1476. if (vote_rs) {
  1477. rs = &vote_rs->status;
  1478. } else {
  1479. rs = tor_malloc_zero(sizeof(routerstatus_t));
  1480. }
  1481. if (!is_legal_nickname(tok->args[0])) {
  1482. log_warn(LD_DIR,
  1483. "Invalid nickname %s in router status; skipping.",
  1484. escaped(tok->args[0]));
  1485. goto err;
  1486. }
  1487. strlcpy(rs->nickname, tok->args[0], sizeof(rs->nickname));
  1488. if (digest_from_base64(rs->identity_digest, tok->args[1])) {
  1489. log_warn(LD_DIR, "Error decoding identity digest %s",
  1490. escaped(tok->args[1]));
  1491. goto err;
  1492. }
  1493. if (flav == FLAV_NS) {
  1494. if (digest_from_base64(rs->descriptor_digest, tok->args[2])) {
  1495. log_warn(LD_DIR, "Error decoding descriptor digest %s",
  1496. escaped(tok->args[2]));
  1497. goto err;
  1498. }
  1499. }
  1500. if (tor_snprintf(timebuf, sizeof(timebuf), "%s %s",
  1501. tok->args[3+offset], tok->args[4+offset]) < 0 ||
  1502. parse_iso_time(timebuf, &rs->published_on)<0) {
  1503. log_warn(LD_DIR, "Error parsing time '%s %s' [%d %d]",
  1504. tok->args[3+offset], tok->args[4+offset],
  1505. offset, (int)flav);
  1506. goto err;
  1507. }
  1508. if (tor_inet_aton(tok->args[5+offset], &in) == 0) {
  1509. log_warn(LD_DIR, "Error parsing router address in network-status %s",
  1510. escaped(tok->args[5+offset]));
  1511. goto err;
  1512. }
  1513. rs->addr = ntohl(in.s_addr);
  1514. rs->or_port = (uint16_t) tor_parse_long(tok->args[6+offset],
  1515. 10,0,65535,NULL,NULL);
  1516. rs->dir_port = (uint16_t) tor_parse_long(tok->args[7+offset],
  1517. 10,0,65535,NULL,NULL);
  1518. {
  1519. smartlist_t *a_lines = find_all_by_keyword(tokens, K_A);
  1520. if (a_lines) {
  1521. find_single_ipv6_orport(a_lines, &rs->ipv6_addr, &rs->ipv6_orport);
  1522. smartlist_free(a_lines);
  1523. }
  1524. }
  1525. tok = find_opt_by_keyword(tokens, K_S);
  1526. if (tok && vote) {
  1527. int i;
  1528. vote_rs->flags = 0;
  1529. for (i=0; i < tok->n_args; ++i) {
  1530. int p = smartlist_string_pos(vote->known_flags, tok->args[i]);
  1531. if (p >= 0) {
  1532. vote_rs->flags |= (UINT64_C(1)<<p);
  1533. } else {
  1534. log_warn(LD_DIR, "Flags line had a flag %s not listed in known_flags.",
  1535. escaped(tok->args[i]));
  1536. goto err;
  1537. }
  1538. }
  1539. } else if (tok) {
  1540. /* This is a consensus, not a vote. */
  1541. int i;
  1542. for (i=0; i < tok->n_args; ++i) {
  1543. if (!strcmp(tok->args[i], "Exit"))
  1544. rs->is_exit = 1;
  1545. else if (!strcmp(tok->args[i], "Stable"))
  1546. rs->is_stable = 1;
  1547. else if (!strcmp(tok->args[i], "Fast"))
  1548. rs->is_fast = 1;
  1549. else if (!strcmp(tok->args[i], "Running"))
  1550. rs->is_flagged_running = 1;
  1551. else if (!strcmp(tok->args[i], "Named"))
  1552. rs->is_named = 1;
  1553. else if (!strcmp(tok->args[i], "Valid"))
  1554. rs->is_valid = 1;
  1555. else if (!strcmp(tok->args[i], "Guard"))
  1556. rs->is_possible_guard = 1;
  1557. else if (!strcmp(tok->args[i], "BadExit"))
  1558. rs->is_bad_exit = 1;
  1559. else if (!strcmp(tok->args[i], "Authority"))
  1560. rs->is_authority = 1;
  1561. else if (!strcmp(tok->args[i], "Unnamed") &&
  1562. consensus_method >= 2) {
  1563. /* Unnamed is computed right by consensus method 2 and later. */
  1564. rs->is_unnamed = 1;
  1565. } else if (!strcmp(tok->args[i], "HSDir")) {
  1566. rs->is_hs_dir = 1;
  1567. } else if (!strcmp(tok->args[i], "V2Dir")) {
  1568. rs->is_v2_dir = 1;
  1569. }
  1570. }
  1571. /* These are implied true by having been included in a consensus made
  1572. * with a given method */
  1573. rs->is_flagged_running = 1; /* Starting with consensus method 4. */
  1574. rs->is_valid = 1; /* Starting with consensus method 24. */
  1575. }
  1576. {
  1577. const char *protocols = NULL, *version = NULL;
  1578. if ((tok = find_opt_by_keyword(tokens, K_PROTO))) {
  1579. tor_assert(tok->n_args == 1);
  1580. protocols = tok->args[0];
  1581. }
  1582. if ((tok = find_opt_by_keyword(tokens, K_V))) {
  1583. tor_assert(tok->n_args == 1);
  1584. version = tok->args[0];
  1585. if (vote_rs) {
  1586. vote_rs->version = tor_strdup(tok->args[0]);
  1587. }
  1588. }
  1589. summarize_protover_flags(&rs->pv, protocols, version);
  1590. }
  1591. /* handle weighting/bandwidth info */
  1592. if ((tok = find_opt_by_keyword(tokens, K_W))) {
  1593. int i;
  1594. for (i=0; i < tok->n_args; ++i) {
  1595. if (!strcmpstart(tok->args[i], "Bandwidth=")) {
  1596. int ok;
  1597. rs->bandwidth_kb =
  1598. (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
  1599. 10, 0, UINT32_MAX,
  1600. &ok, NULL);
  1601. if (!ok) {
  1602. log_warn(LD_DIR, "Invalid Bandwidth %s", escaped(tok->args[i]));
  1603. goto err;
  1604. }
  1605. rs->has_bandwidth = 1;
  1606. } else if (!strcmpstart(tok->args[i], "Measured=") && vote_rs) {
  1607. int ok;
  1608. vote_rs->measured_bw_kb =
  1609. (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
  1610. 10, 0, UINT32_MAX, &ok, NULL);
  1611. if (!ok) {
  1612. log_warn(LD_DIR, "Invalid Measured Bandwidth %s",
  1613. escaped(tok->args[i]));
  1614. goto err;
  1615. }
  1616. vote_rs->has_measured_bw = 1;
  1617. vote->has_measured_bws = 1;
  1618. } else if (!strcmpstart(tok->args[i], "Unmeasured=1")) {
  1619. rs->bw_is_unmeasured = 1;
  1620. } else if (!strcmpstart(tok->args[i], "GuardFraction=")) {
  1621. if (routerstatus_parse_guardfraction(tok->args[i],
  1622. vote, vote_rs, rs) < 0) {
  1623. goto err;
  1624. }
  1625. }
  1626. }
  1627. }
  1628. /* parse exit policy summaries */
  1629. if ((tok = find_opt_by_keyword(tokens, K_P))) {
  1630. tor_assert(tok->n_args == 1);
  1631. if (strcmpstart(tok->args[0], "accept ") &&
  1632. strcmpstart(tok->args[0], "reject ")) {
  1633. log_warn(LD_DIR, "Unknown exit policy summary type %s.",
  1634. escaped(tok->args[0]));
  1635. goto err;
  1636. }
  1637. /* XXX weasel: parse this into ports and represent them somehow smart,
  1638. * maybe not here but somewhere on if we need it for the client.
  1639. * we should still parse it here to check it's valid tho.
  1640. */
  1641. rs->exitsummary = tor_strdup(tok->args[0]);
  1642. rs->has_exitsummary = 1;
  1643. }
  1644. if (vote_rs) {
  1645. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, t) {
  1646. if (t->tp == K_M && t->n_args) {
  1647. vote_microdesc_hash_t *line =
  1648. tor_malloc(sizeof(vote_microdesc_hash_t));
  1649. line->next = vote_rs->microdesc;
  1650. line->microdesc_hash_line = tor_strdup(t->args[0]);
  1651. vote_rs->microdesc = line;
  1652. }
  1653. if (t->tp == K_ID) {
  1654. tor_assert(t->n_args >= 2);
  1655. if (!strcmp(t->args[0], "ed25519")) {
  1656. vote_rs->has_ed25519_listing = 1;
  1657. if (strcmp(t->args[1], "none") &&
  1658. digest256_from_base64((char*)vote_rs->ed25519_id,
  1659. t->args[1])<0) {
  1660. log_warn(LD_DIR, "Bogus ed25519 key in networkstatus vote");
  1661. goto err;
  1662. }
  1663. }
  1664. }
  1665. if (t->tp == K_PROTO) {
  1666. tor_assert(t->n_args == 1);
  1667. vote_rs->protocols = tor_strdup(t->args[0]);
  1668. }
  1669. } SMARTLIST_FOREACH_END(t);
  1670. } else if (flav == FLAV_MICRODESC) {
  1671. tok = find_opt_by_keyword(tokens, K_M);
  1672. if (tok) {
  1673. tor_assert(tok->n_args);
  1674. if (digest256_from_base64(rs->descriptor_digest, tok->args[0])) {
  1675. log_warn(LD_DIR, "Error decoding microdescriptor digest %s",
  1676. escaped(tok->args[0]));
  1677. goto err;
  1678. }
  1679. } else {
  1680. log_info(LD_BUG, "Found an entry in networkstatus with no "
  1681. "microdescriptor digest. (Router %s ($%s) at %s:%d.)",
  1682. rs->nickname, hex_str(rs->identity_digest, DIGEST_LEN),
  1683. fmt_addr32(rs->addr), rs->or_port);
  1684. }
  1685. }
  1686. if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME))
  1687. rs->is_named = 0;
  1688. goto done;
  1689. err:
  1690. dump_desc(s_dup, "routerstatus entry");
  1691. if (rs && !vote_rs)
  1692. routerstatus_free(rs);
  1693. rs = NULL;
  1694. done:
  1695. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1696. smartlist_clear(tokens);
  1697. if (area) {
  1698. DUMP_AREA(area, "routerstatus entry");
  1699. memarea_clear(area);
  1700. }
  1701. *s = eos;
  1702. return rs;
  1703. }
  1704. int
  1705. compare_vote_routerstatus_entries(const void **_a, const void **_b)
  1706. {
  1707. const vote_routerstatus_t *a = *_a, *b = *_b;
  1708. return fast_memcmp(a->status.identity_digest, b->status.identity_digest,
  1709. DIGEST_LEN);
  1710. }
  1711. /** Verify the bandwidth weights of a network status document */
  1712. int
  1713. networkstatus_verify_bw_weights(networkstatus_t *ns, int consensus_method)
  1714. {
  1715. int64_t G=0, M=0, E=0, D=0, T=0;
  1716. double Wgg, Wgm, Wgd, Wmg, Wmm, Wme, Wmd, Weg, Wem, Wee, Wed;
  1717. double Gtotal=0, Mtotal=0, Etotal=0;
  1718. const char *casename = NULL;
  1719. int valid = 1;
  1720. (void) consensus_method;
  1721. const int64_t weight_scale = networkstatus_get_weight_scale_param(ns);
  1722. tor_assert(weight_scale >= 1);
  1723. Wgg = networkstatus_get_bw_weight(ns, "Wgg", -1);
  1724. Wgm = networkstatus_get_bw_weight(ns, "Wgm", -1);
  1725. Wgd = networkstatus_get_bw_weight(ns, "Wgd", -1);
  1726. Wmg = networkstatus_get_bw_weight(ns, "Wmg", -1);
  1727. Wmm = networkstatus_get_bw_weight(ns, "Wmm", -1);
  1728. Wme = networkstatus_get_bw_weight(ns, "Wme", -1);
  1729. Wmd = networkstatus_get_bw_weight(ns, "Wmd", -1);
  1730. Weg = networkstatus_get_bw_weight(ns, "Weg", -1);
  1731. Wem = networkstatus_get_bw_weight(ns, "Wem", -1);
  1732. Wee = networkstatus_get_bw_weight(ns, "Wee", -1);
  1733. Wed = networkstatus_get_bw_weight(ns, "Wed", -1);
  1734. if (Wgg<0 || Wgm<0 || Wgd<0 || Wmg<0 || Wmm<0 || Wme<0 || Wmd<0 || Weg<0
  1735. || Wem<0 || Wee<0 || Wed<0) {
  1736. log_warn(LD_BUG, "No bandwidth weights produced in consensus!");
  1737. return 0;
  1738. }
  1739. // First, sanity check basic summing properties that hold for all cases
  1740. // We use > 1 as the check for these because they are computed as integers.
  1741. // Sometimes there are rounding errors.
  1742. if (fabs(Wmm - weight_scale) > 1) {
  1743. log_warn(LD_BUG, "Wmm=%f != %"PRId64,
  1744. Wmm, (weight_scale));
  1745. valid = 0;
  1746. }
  1747. if (fabs(Wem - Wee) > 1) {
  1748. log_warn(LD_BUG, "Wem=%f != Wee=%f", Wem, Wee);
  1749. valid = 0;
  1750. }
  1751. if (fabs(Wgm - Wgg) > 1) {
  1752. log_warn(LD_BUG, "Wgm=%f != Wgg=%f", Wgm, Wgg);
  1753. valid = 0;
  1754. }
  1755. if (fabs(Weg - Wed) > 1) {
  1756. log_warn(LD_BUG, "Wed=%f != Weg=%f", Wed, Weg);
  1757. valid = 0;
  1758. }
  1759. if (fabs(Wgg + Wmg - weight_scale) > 0.001*weight_scale) {
  1760. log_warn(LD_BUG, "Wgg=%f != %"PRId64" - Wmg=%f", Wgg,
  1761. (weight_scale), Wmg);
  1762. valid = 0;
  1763. }
  1764. if (fabs(Wee + Wme - weight_scale) > 0.001*weight_scale) {
  1765. log_warn(LD_BUG, "Wee=%f != %"PRId64" - Wme=%f", Wee,
  1766. (weight_scale), Wme);
  1767. valid = 0;
  1768. }
  1769. if (fabs(Wgd + Wmd + Wed - weight_scale) > 0.001*weight_scale) {
  1770. log_warn(LD_BUG, "Wgd=%f + Wmd=%f + Wed=%f != %"PRId64,
  1771. Wgd, Wmd, Wed, (weight_scale));
  1772. valid = 0;
  1773. }
  1774. Wgg /= weight_scale;
  1775. Wgm /= weight_scale; (void) Wgm; // unused from here on.
  1776. Wgd /= weight_scale;
  1777. Wmg /= weight_scale;
  1778. Wmm /= weight_scale;
  1779. Wme /= weight_scale;
  1780. Wmd /= weight_scale;
  1781. Weg /= weight_scale; (void) Weg; // unused from here on.
  1782. Wem /= weight_scale; (void) Wem; // unused from here on.
  1783. Wee /= weight_scale;
  1784. Wed /= weight_scale;
  1785. // Then, gather G, M, E, D, T to determine case
  1786. SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) {
  1787. int is_exit = 0;
  1788. /* Bug #2203: Don't count bad exits as exits for balancing */
  1789. is_exit = rs->is_exit && !rs->is_bad_exit;
  1790. if (rs->has_bandwidth) {
  1791. T += rs->bandwidth_kb;
  1792. if (is_exit && rs->is_possible_guard) {
  1793. D += rs->bandwidth_kb;
  1794. Gtotal += Wgd*rs->bandwidth_kb;
  1795. Mtotal += Wmd*rs->bandwidth_kb;
  1796. Etotal += Wed*rs->bandwidth_kb;
  1797. } else if (is_exit) {
  1798. E += rs->bandwidth_kb;
  1799. Mtotal += Wme*rs->bandwidth_kb;
  1800. Etotal += Wee*rs->bandwidth_kb;
  1801. } else if (rs->is_possible_guard) {
  1802. G += rs->bandwidth_kb;
  1803. Gtotal += Wgg*rs->bandwidth_kb;
  1804. Mtotal += Wmg*rs->bandwidth_kb;
  1805. } else {
  1806. M += rs->bandwidth_kb;
  1807. Mtotal += Wmm*rs->bandwidth_kb;
  1808. }
  1809. } else {
  1810. log_warn(LD_BUG, "Missing consensus bandwidth for router %s",
  1811. routerstatus_describe(rs));
  1812. }
  1813. } SMARTLIST_FOREACH_END(rs);
  1814. // Finally, check equality conditions depending upon case 1, 2 or 3
  1815. // Full equality cases: 1, 3b
  1816. // Partial equality cases: 2b (E=G), 3a (M=E)
  1817. // Fully unknown: 2a
  1818. if (3*E >= T && 3*G >= T) {
  1819. // Case 1: Neither are scarce
  1820. casename = "Case 1";
  1821. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  1822. log_warn(LD_DIR,
  1823. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  1824. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  1825. " T=%"PRId64". "
  1826. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1827. casename, Etotal, Mtotal,
  1828. (G), (M), (E),
  1829. (D), (T),
  1830. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1831. valid = 0;
  1832. }
  1833. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  1834. log_warn(LD_DIR,
  1835. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  1836. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  1837. " T=%"PRId64". "
  1838. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1839. casename, Etotal, Gtotal,
  1840. (G), (M), (E),
  1841. (D), (T),
  1842. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1843. valid = 0;
  1844. }
  1845. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  1846. log_warn(LD_DIR,
  1847. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  1848. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  1849. " T=%"PRId64". "
  1850. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1851. casename, Mtotal, Gtotal,
  1852. (G), (M), (E),
  1853. (D), (T),
  1854. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1855. valid = 0;
  1856. }
  1857. } else if (3*E < T && 3*G < T) {
  1858. int64_t R = MIN(E, G);
  1859. int64_t S = MAX(E, G);
  1860. /*
  1861. * Case 2: Both Guards and Exits are scarce
  1862. * Balance D between E and G, depending upon
  1863. * D capacity and scarcity. Devote no extra
  1864. * bandwidth to middle nodes.
  1865. */
  1866. if (R+D < S) { // Subcase a
  1867. double Rtotal, Stotal;
  1868. if (E < G) {
  1869. Rtotal = Etotal;
  1870. Stotal = Gtotal;
  1871. } else {
  1872. Rtotal = Gtotal;
  1873. Stotal = Etotal;
  1874. }
  1875. casename = "Case 2a";
  1876. // Rtotal < Stotal
  1877. if (Rtotal > Stotal) {
  1878. log_warn(LD_DIR,
  1879. "Bw Weight Failure for %s: Rtotal %f > Stotal %f. "
  1880. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  1881. " T=%"PRId64". "
  1882. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1883. casename, Rtotal, Stotal,
  1884. (G), (M), (E),
  1885. (D), (T),
  1886. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1887. valid = 0;
  1888. }
  1889. // Rtotal < T/3
  1890. if (3*Rtotal > T) {
  1891. log_warn(LD_DIR,
  1892. "Bw Weight Failure for %s: 3*Rtotal %f > T "
  1893. "%"PRId64". G=%"PRId64" M=%"PRId64" E=%"PRId64
  1894. " D=%"PRId64" T=%"PRId64". "
  1895. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1896. casename, Rtotal*3, (T),
  1897. (G), (M), (E),
  1898. (D), (T),
  1899. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1900. valid = 0;
  1901. }
  1902. // Stotal < T/3
  1903. if (3*Stotal > T) {
  1904. log_warn(LD_DIR,
  1905. "Bw Weight Failure for %s: 3*Stotal %f > T "
  1906. "%"PRId64". G=%"PRId64" M=%"PRId64" E=%"PRId64
  1907. " D=%"PRId64" T=%"PRId64". "
  1908. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1909. casename, Stotal*3, (T),
  1910. (G), (M), (E),
  1911. (D), (T),
  1912. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1913. valid = 0;
  1914. }
  1915. // Mtotal > T/3
  1916. if (3*Mtotal < T) {
  1917. log_warn(LD_DIR,
  1918. "Bw Weight Failure for %s: 3*Mtotal %f < T "
  1919. "%"PRId64". "
  1920. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  1921. " T=%"PRId64". "
  1922. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1923. casename, Mtotal*3, (T),
  1924. (G), (M), (E),
  1925. (D), (T),
  1926. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1927. valid = 0;
  1928. }
  1929. } else { // Subcase b: R+D > S
  1930. casename = "Case 2b";
  1931. /* Check the rare-M redirect case. */
  1932. if (D != 0 && 3*M < T) {
  1933. casename = "Case 2b (balanced)";
  1934. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  1935. log_warn(LD_DIR,
  1936. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  1937. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  1938. " T=%"PRId64". "
  1939. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1940. casename, Etotal, Mtotal,
  1941. (G), (M), (E),
  1942. (D), (T),
  1943. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1944. valid = 0;
  1945. }
  1946. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  1947. log_warn(LD_DIR,
  1948. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  1949. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  1950. " T=%"PRId64". "
  1951. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1952. casename, Etotal, Gtotal,
  1953. (G), (M), (E),
  1954. (D), (T),
  1955. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1956. valid = 0;
  1957. }
  1958. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  1959. log_warn(LD_DIR,
  1960. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  1961. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  1962. " T=%"PRId64". "
  1963. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1964. casename, Mtotal, Gtotal,
  1965. (G), (M), (E),
  1966. (D), (T),
  1967. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1968. valid = 0;
  1969. }
  1970. } else {
  1971. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  1972. log_warn(LD_DIR,
  1973. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  1974. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  1975. " T=%"PRId64". "
  1976. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  1977. casename, Etotal, Gtotal,
  1978. (G), (M), (E),
  1979. (D), (T),
  1980. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  1981. valid = 0;
  1982. }
  1983. }
  1984. }
  1985. } else { // if (E < T/3 || G < T/3) {
  1986. int64_t S = MIN(E, G);
  1987. int64_t NS = MAX(E, G);
  1988. if (3*(S+D) < T) { // Subcase a:
  1989. double Stotal;
  1990. double NStotal;
  1991. if (G < E) {
  1992. casename = "Case 3a (G scarce)";
  1993. Stotal = Gtotal;
  1994. NStotal = Etotal;
  1995. } else { // if (G >= E) {
  1996. casename = "Case 3a (E scarce)";
  1997. NStotal = Gtotal;
  1998. Stotal = Etotal;
  1999. }
  2000. // Stotal < T/3
  2001. if (3*Stotal > T) {
  2002. log_warn(LD_DIR,
  2003. "Bw Weight Failure for %s: 3*Stotal %f > T "
  2004. "%"PRId64". G=%"PRId64" M=%"PRId64" E=%"PRId64
  2005. " D=%"PRId64" T=%"PRId64". "
  2006. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2007. casename, Stotal*3, (T),
  2008. (G), (M), (E),
  2009. (D), (T),
  2010. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2011. valid = 0;
  2012. }
  2013. if (NS >= M) {
  2014. if (fabs(NStotal-Mtotal) > 0.01*MAX(NStotal,Mtotal)) {
  2015. log_warn(LD_DIR,
  2016. "Bw Weight Failure for %s: NStotal %f != Mtotal %f. "
  2017. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  2018. " T=%"PRId64". "
  2019. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2020. casename, NStotal, Mtotal,
  2021. (G), (M), (E),
  2022. (D), (T),
  2023. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2024. valid = 0;
  2025. }
  2026. } else {
  2027. // if NS < M, NStotal > T/3 because only one of G or E is scarce
  2028. if (3*NStotal < T) {
  2029. log_warn(LD_DIR,
  2030. "Bw Weight Failure for %s: 3*NStotal %f < T "
  2031. "%"PRId64". G=%"PRId64" M=%"PRId64
  2032. " E=%"PRId64" D=%"PRId64" T=%"PRId64". "
  2033. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2034. casename, NStotal*3, (T),
  2035. (G), (M), (E),
  2036. (D), (T),
  2037. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2038. valid = 0;
  2039. }
  2040. }
  2041. } else { // Subcase b: S+D >= T/3
  2042. casename = "Case 3b";
  2043. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  2044. log_warn(LD_DIR,
  2045. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  2046. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  2047. " T=%"PRId64". "
  2048. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2049. casename, Etotal, Mtotal,
  2050. (G), (M), (E),
  2051. (D), (T),
  2052. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2053. valid = 0;
  2054. }
  2055. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2056. log_warn(LD_DIR,
  2057. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2058. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  2059. " T=%"PRId64". "
  2060. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2061. casename, Etotal, Gtotal,
  2062. (G), (M), (E),
  2063. (D), (T),
  2064. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2065. valid = 0;
  2066. }
  2067. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  2068. log_warn(LD_DIR,
  2069. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  2070. "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
  2071. " T=%"PRId64". "
  2072. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2073. casename, Mtotal, Gtotal,
  2074. (G), (M), (E),
  2075. (D), (T),
  2076. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2077. valid = 0;
  2078. }
  2079. }
  2080. }
  2081. if (valid)
  2082. log_notice(LD_DIR, "Bandwidth-weight %s is verified and valid.",
  2083. casename);
  2084. return valid;
  2085. }
  2086. /** Check if a shared random value of type <b>srv_type</b> is in
  2087. * <b>tokens</b>. If there is, parse it and set it to <b>srv_out</b>. Return
  2088. * -1 on failure, 0 on success. The resulting srv is allocated on the heap and
  2089. * it's the responsibility of the caller to free it. */
  2090. static int
  2091. extract_one_srv(smartlist_t *tokens, directory_keyword srv_type,
  2092. sr_srv_t **srv_out)
  2093. {
  2094. int ret = -1;
  2095. directory_token_t *tok;
  2096. sr_srv_t *srv = NULL;
  2097. smartlist_t *chunks;
  2098. tor_assert(tokens);
  2099. chunks = smartlist_new();
  2100. tok = find_opt_by_keyword(tokens, srv_type);
  2101. if (!tok) {
  2102. /* That's fine, no SRV is allowed. */
  2103. ret = 0;
  2104. goto end;
  2105. }
  2106. for (int i = 0; i < tok->n_args; i++) {
  2107. smartlist_add(chunks, tok->args[i]);
  2108. }
  2109. srv = sr_parse_srv(chunks);
  2110. if (srv == NULL) {
  2111. log_warn(LD_DIR, "SR: Unparseable SRV %s", escaped(tok->object_body));
  2112. goto end;
  2113. }
  2114. /* All is good. */
  2115. *srv_out = srv;
  2116. ret = 0;
  2117. end:
  2118. smartlist_free(chunks);
  2119. return ret;
  2120. }
  2121. /** Extract any shared random values found in <b>tokens</b> and place them in
  2122. * the networkstatus <b>ns</b>. */
  2123. static void
  2124. extract_shared_random_srvs(networkstatus_t *ns, smartlist_t *tokens)
  2125. {
  2126. const char *voter_identity;
  2127. networkstatus_voter_info_t *voter;
  2128. tor_assert(ns);
  2129. tor_assert(tokens);
  2130. /* Can be only one of them else code flow. */
  2131. tor_assert(ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_CONSENSUS);
  2132. if (ns->type == NS_TYPE_VOTE) {
  2133. voter = smartlist_get(ns->voters, 0);
  2134. tor_assert(voter);
  2135. voter_identity = hex_str(voter->identity_digest,
  2136. sizeof(voter->identity_digest));
  2137. } else {
  2138. /* Consensus has multiple voters so no specific voter. */
  2139. voter_identity = "consensus";
  2140. }
  2141. /* We extract both, and on error everything is stopped because it means
  2142. * the vote is malformed for the shared random value(s). */
  2143. if (extract_one_srv(tokens, K_PREVIOUS_SRV, &ns->sr_info.previous_srv) < 0) {
  2144. log_warn(LD_DIR, "SR: Unable to parse previous SRV from %s",
  2145. voter_identity);
  2146. /* Maybe we have a chance with the current SRV so let's try it anyway. */
  2147. }
  2148. if (extract_one_srv(tokens, K_CURRENT_SRV, &ns->sr_info.current_srv) < 0) {
  2149. log_warn(LD_DIR, "SR: Unable to parse current SRV from %s",
  2150. voter_identity);
  2151. }
  2152. }
  2153. /** Parse a v3 networkstatus vote, opinion, or consensus (depending on
  2154. * ns_type), from <b>s</b>, and return the result. Return NULL on failure. */
  2155. networkstatus_t *
  2156. networkstatus_parse_vote_from_string(const char *s, const char **eos_out,
  2157. networkstatus_type_t ns_type)
  2158. {
  2159. smartlist_t *tokens = smartlist_new();
  2160. smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;
  2161. networkstatus_voter_info_t *voter = NULL;
  2162. networkstatus_t *ns = NULL;
  2163. common_digests_t ns_digests;
  2164. uint8_t sha3_as_signed[DIGEST256_LEN];
  2165. const char *cert, *end_of_header, *end_of_footer, *s_dup = s;
  2166. directory_token_t *tok;
  2167. struct in_addr in;
  2168. int i, inorder, n_signatures = 0;
  2169. memarea_t *area = NULL, *rs_area = NULL;
  2170. consensus_flavor_t flav = FLAV_NS;
  2171. char *last_kwd=NULL;
  2172. tor_assert(s);
  2173. if (eos_out)
  2174. *eos_out = NULL;
  2175. if (router_get_networkstatus_v3_hashes(s, &ns_digests) ||
  2176. router_get_networkstatus_v3_sha3_as_signed(sha3_as_signed, s)<0) {
  2177. log_warn(LD_DIR, "Unable to compute digest of network-status");
  2178. goto err;
  2179. }
  2180. area = memarea_new();
  2181. end_of_header = find_start_of_next_routerstatus(s);
  2182. if (tokenize_string(area, s, end_of_header, tokens,
  2183. (ns_type == NS_TYPE_CONSENSUS) ?
  2184. networkstatus_consensus_token_table :
  2185. networkstatus_token_table, 0)) {
  2186. log_warn(LD_DIR, "Error tokenizing network-status header");
  2187. goto err;
  2188. }
  2189. ns = tor_malloc_zero(sizeof(networkstatus_t));
  2190. memcpy(&ns->digests, &ns_digests, sizeof(ns_digests));
  2191. memcpy(&ns->digest_sha3_as_signed, sha3_as_signed, sizeof(sha3_as_signed));
  2192. tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
  2193. tor_assert(tok);
  2194. if (tok->n_args > 1) {
  2195. int flavor = networkstatus_parse_flavor_name(tok->args[1]);
  2196. if (flavor < 0) {
  2197. log_warn(LD_DIR, "Can't parse document with unknown flavor %s",
  2198. escaped(tok->args[1]));
  2199. goto err;
  2200. }
  2201. ns->flavor = flav = flavor;
  2202. }
  2203. if (flav != FLAV_NS && ns_type != NS_TYPE_CONSENSUS) {
  2204. log_warn(LD_DIR, "Flavor found on non-consensus networkstatus.");
  2205. goto err;
  2206. }
  2207. if (ns_type != NS_TYPE_CONSENSUS) {
  2208. const char *end_of_cert = NULL;
  2209. if (!(cert = strstr(s, "\ndir-key-certificate-version")))
  2210. goto err;
  2211. ++cert;
  2212. ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);
  2213. if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)
  2214. goto err;
  2215. }
  2216. tok = find_by_keyword(tokens, K_VOTE_STATUS);
  2217. tor_assert(tok->n_args);
  2218. if (!strcmp(tok->args[0], "vote")) {
  2219. ns->type = NS_TYPE_VOTE;
  2220. } else if (!strcmp(tok->args[0], "consensus")) {
  2221. ns->type = NS_TYPE_CONSENSUS;
  2222. } else if (!strcmp(tok->args[0], "opinion")) {
  2223. ns->type = NS_TYPE_OPINION;
  2224. } else {
  2225. log_warn(LD_DIR, "Unrecognized vote status %s in network-status",
  2226. escaped(tok->args[0]));
  2227. goto err;
  2228. }
  2229. if (ns_type != ns->type) {
  2230. log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus.");
  2231. goto err;
  2232. }
  2233. if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
  2234. tok = find_by_keyword(tokens, K_PUBLISHED);
  2235. if (parse_iso_time(tok->args[0], &ns->published))
  2236. goto err;
  2237. ns->supported_methods = smartlist_new();
  2238. tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHODS);
  2239. if (tok) {
  2240. for (i=0; i < tok->n_args; ++i)
  2241. smartlist_add_strdup(ns->supported_methods, tok->args[i]);
  2242. } else {
  2243. smartlist_add_strdup(ns->supported_methods, "1");
  2244. }
  2245. } else {
  2246. tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHOD);
  2247. if (tok) {
  2248. int num_ok;
  2249. ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX,
  2250. &num_ok, NULL);
  2251. if (!num_ok)
  2252. goto err;
  2253. } else {
  2254. ns->consensus_method = 1;
  2255. }
  2256. }
  2257. if ((tok = find_opt_by_keyword(tokens, K_RECOMMENDED_CLIENT_PROTOCOLS)))
  2258. ns->recommended_client_protocols = tor_strdup(tok->args[0]);
  2259. if ((tok = find_opt_by_keyword(tokens, K_RECOMMENDED_RELAY_PROTOCOLS)))
  2260. ns->recommended_relay_protocols = tor_strdup(tok->args[0]);
  2261. if ((tok = find_opt_by_keyword(tokens, K_REQUIRED_CLIENT_PROTOCOLS)))
  2262. ns->required_client_protocols = tor_strdup(tok->args[0]);
  2263. if ((tok = find_opt_by_keyword(tokens, K_REQUIRED_RELAY_PROTOCOLS)))
  2264. ns->required_relay_protocols = tor_strdup(tok->args[0]);
  2265. tok = find_by_keyword(tokens, K_VALID_AFTER);
  2266. if (parse_iso_time(tok->args[0], &ns->valid_after))
  2267. goto err;
  2268. tok = find_by_keyword(tokens, K_FRESH_UNTIL);
  2269. if (parse_iso_time(tok->args[0], &ns->fresh_until))
  2270. goto err;
  2271. tok = find_by_keyword(tokens, K_VALID_UNTIL);
  2272. if (parse_iso_time(tok->args[0], &ns->valid_until))
  2273. goto err;
  2274. tok = find_by_keyword(tokens, K_VOTING_DELAY);
  2275. tor_assert(tok->n_args >= 2);
  2276. {
  2277. int ok;
  2278. ns->vote_seconds =
  2279. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);
  2280. if (!ok)
  2281. goto err;
  2282. ns->dist_seconds =
  2283. (int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL);
  2284. if (!ok)
  2285. goto err;
  2286. }
  2287. if (ns->valid_after +
  2288. (get_options()->TestingTorNetwork ?
  2289. MIN_VOTE_INTERVAL_TESTING : MIN_VOTE_INTERVAL) > ns->fresh_until) {
  2290. log_warn(LD_DIR, "Vote/consensus freshness interval is too short");
  2291. goto err;
  2292. }
  2293. if (ns->valid_after +
  2294. (get_options()->TestingTorNetwork ?
  2295. MIN_VOTE_INTERVAL_TESTING : MIN_VOTE_INTERVAL)*2 > ns->valid_until) {
  2296. log_warn(LD_DIR, "Vote/consensus liveness interval is too short");
  2297. goto err;
  2298. }
  2299. if (ns->vote_seconds < MIN_VOTE_SECONDS) {
  2300. log_warn(LD_DIR, "Vote seconds is too short");
  2301. goto err;
  2302. }
  2303. if (ns->dist_seconds < MIN_DIST_SECONDS) {
  2304. log_warn(LD_DIR, "Dist seconds is too short");
  2305. goto err;
  2306. }
  2307. if ((tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  2308. ns->client_versions = tor_strdup(tok->args[0]);
  2309. }
  2310. if ((tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS))) {
  2311. ns->server_versions = tor_strdup(tok->args[0]);
  2312. }
  2313. {
  2314. smartlist_t *package_lst = find_all_by_keyword(tokens, K_PACKAGE);
  2315. ns->package_lines = smartlist_new();
  2316. if (package_lst) {
  2317. SMARTLIST_FOREACH(package_lst, directory_token_t *, t,
  2318. smartlist_add_strdup(ns->package_lines, t->args[0]));
  2319. }
  2320. smartlist_free(package_lst);
  2321. }
  2322. tok = find_by_keyword(tokens, K_KNOWN_FLAGS);
  2323. ns->known_flags = smartlist_new();
  2324. inorder = 1;
  2325. for (i = 0; i < tok->n_args; ++i) {
  2326. smartlist_add_strdup(ns->known_flags, tok->args[i]);
  2327. if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) {
  2328. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  2329. inorder = 0;
  2330. }
  2331. }
  2332. if (!inorder) {
  2333. log_warn(LD_DIR, "known-flags not in order");
  2334. goto err;
  2335. }
  2336. if (ns->type != NS_TYPE_CONSENSUS &&
  2337. smartlist_len(ns->known_flags) > MAX_KNOWN_FLAGS_IN_VOTE) {
  2338. /* If we allowed more than 64 flags in votes, then parsing them would make
  2339. * us invoke undefined behavior whenever we used 1<<flagnum to do a
  2340. * bit-shift. This is only for votes and opinions: consensus users don't
  2341. * care about flags they don't recognize, and so don't build a bitfield
  2342. * for them. */
  2343. log_warn(LD_DIR, "Too many known-flags in consensus vote or opinion");
  2344. goto err;
  2345. }
  2346. tok = find_opt_by_keyword(tokens, K_PARAMS);
  2347. if (tok) {
  2348. int any_dups = 0;
  2349. inorder = 1;
  2350. ns->net_params = smartlist_new();
  2351. for (i = 0; i < tok->n_args; ++i) {
  2352. int ok=0;
  2353. char *eq = strchr(tok->args[i], '=');
  2354. size_t eq_pos;
  2355. if (!eq) {
  2356. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  2357. goto err;
  2358. }
  2359. eq_pos = eq-tok->args[i];
  2360. tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
  2361. if (!ok) {
  2362. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  2363. goto err;
  2364. }
  2365. if (i > 0 && strcmp(tok->args[i-1], tok->args[i]) >= 0) {
  2366. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  2367. inorder = 0;
  2368. }
  2369. if (last_kwd && eq_pos == strlen(last_kwd) &&
  2370. fast_memeq(last_kwd, tok->args[i], eq_pos)) {
  2371. log_warn(LD_DIR, "Duplicate value for %s parameter",
  2372. escaped(tok->args[i]));
  2373. any_dups = 1;
  2374. }
  2375. tor_free(last_kwd);
  2376. last_kwd = tor_strndup(tok->args[i], eq_pos);
  2377. smartlist_add_strdup(ns->net_params, tok->args[i]);
  2378. }
  2379. if (!inorder) {
  2380. log_warn(LD_DIR, "params not in order");
  2381. goto err;
  2382. }
  2383. if (any_dups) {
  2384. log_warn(LD_DIR, "Duplicate in parameters");
  2385. goto err;
  2386. }
  2387. }
  2388. ns->voters = smartlist_new();
  2389. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  2390. tok = _tok;
  2391. if (tok->tp == K_DIR_SOURCE) {
  2392. tor_assert(tok->n_args >= 6);
  2393. if (voter)
  2394. smartlist_add(ns->voters, voter);
  2395. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  2396. voter->sigs = smartlist_new();
  2397. if (ns->type != NS_TYPE_CONSENSUS)
  2398. memcpy(voter->vote_digest, ns_digests.d[DIGEST_SHA1], DIGEST_LEN);
  2399. voter->nickname = tor_strdup(tok->args[0]);
  2400. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  2401. base16_decode(voter->identity_digest, sizeof(voter->identity_digest),
  2402. tok->args[1], HEX_DIGEST_LEN)
  2403. != sizeof(voter->identity_digest)) {
  2404. log_warn(LD_DIR, "Error decoding identity digest %s in "
  2405. "network-status document.", escaped(tok->args[1]));
  2406. goto err;
  2407. }
  2408. if (ns->type != NS_TYPE_CONSENSUS &&
  2409. tor_memneq(ns->cert->cache_info.identity_digest,
  2410. voter->identity_digest, DIGEST_LEN)) {
  2411. log_warn(LD_DIR,"Mismatch between identities in certificate and vote");
  2412. goto err;
  2413. }
  2414. if (ns->type != NS_TYPE_CONSENSUS) {
  2415. if (authority_cert_is_blacklisted(ns->cert)) {
  2416. log_warn(LD_DIR, "Rejecting vote signature made with blacklisted "
  2417. "signing key %s",
  2418. hex_str(ns->cert->signing_key_digest, DIGEST_LEN));
  2419. goto err;
  2420. }
  2421. }
  2422. voter->address = tor_strdup(tok->args[2]);
  2423. if (!tor_inet_aton(tok->args[3], &in)) {
  2424. log_warn(LD_DIR, "Error decoding IP address %s in network-status.",
  2425. escaped(tok->args[3]));
  2426. goto err;
  2427. }
  2428. voter->addr = ntohl(in.s_addr);
  2429. int ok;
  2430. voter->dir_port = (uint16_t)
  2431. tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);
  2432. if (!ok)
  2433. goto err;
  2434. voter->or_port = (uint16_t)
  2435. tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);
  2436. if (!ok)
  2437. goto err;
  2438. } else if (tok->tp == K_CONTACT) {
  2439. if (!voter || voter->contact) {
  2440. log_warn(LD_DIR, "contact element is out of place.");
  2441. goto err;
  2442. }
  2443. voter->contact = tor_strdup(tok->args[0]);
  2444. } else if (tok->tp == K_VOTE_DIGEST) {
  2445. tor_assert(ns->type == NS_TYPE_CONSENSUS);
  2446. tor_assert(tok->n_args >= 1);
  2447. if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {
  2448. log_warn(LD_DIR, "vote-digest element is out of place.");
  2449. goto err;
  2450. }
  2451. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  2452. base16_decode(voter->vote_digest, sizeof(voter->vote_digest),
  2453. tok->args[0], HEX_DIGEST_LEN)
  2454. != sizeof(voter->vote_digest)) {
  2455. log_warn(LD_DIR, "Error decoding vote digest %s in "
  2456. "network-status consensus.", escaped(tok->args[0]));
  2457. goto err;
  2458. }
  2459. }
  2460. } SMARTLIST_FOREACH_END(_tok);
  2461. if (voter) {
  2462. smartlist_add(ns->voters, voter);
  2463. voter = NULL;
  2464. }
  2465. if (smartlist_len(ns->voters) == 0) {
  2466. log_warn(LD_DIR, "Missing dir-source elements in a networkstatus.");
  2467. goto err;
  2468. } else if (ns->type != NS_TYPE_CONSENSUS && smartlist_len(ns->voters) != 1) {
  2469. log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus.");
  2470. goto err;
  2471. }
  2472. if (ns->type != NS_TYPE_CONSENSUS &&
  2473. (tok = find_opt_by_keyword(tokens, K_LEGACY_DIR_KEY))) {
  2474. int bad = 1;
  2475. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  2476. networkstatus_voter_info_t *voter_0 = smartlist_get(ns->voters, 0);
  2477. if (base16_decode(voter_0->legacy_id_digest, DIGEST_LEN,
  2478. tok->args[0], HEX_DIGEST_LEN) != DIGEST_LEN)
  2479. bad = 1;
  2480. else
  2481. bad = 0;
  2482. }
  2483. if (bad) {
  2484. log_warn(LD_DIR, "Invalid legacy key digest %s on vote.",
  2485. escaped(tok->args[0]));
  2486. }
  2487. }
  2488. /* If this is a vote document, check if information about the shared
  2489. randomness protocol is included, and extract it. */
  2490. if (ns->type == NS_TYPE_VOTE) {
  2491. dirvote_parse_sr_commits(ns, tokens);
  2492. }
  2493. /* For both a vote and consensus, extract the shared random values. */
  2494. if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_CONSENSUS) {
  2495. extract_shared_random_srvs(ns, tokens);
  2496. }
  2497. /* Parse routerstatus lines. */
  2498. rs_tokens = smartlist_new();
  2499. rs_area = memarea_new();
  2500. s = end_of_header;
  2501. ns->routerstatus_list = smartlist_new();
  2502. while (!strcmpstart(s, "r ")) {
  2503. if (ns->type != NS_TYPE_CONSENSUS) {
  2504. vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  2505. if (routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, ns,
  2506. rs, 0, 0)) {
  2507. smartlist_add(ns->routerstatus_list, rs);
  2508. } else {
  2509. vote_routerstatus_free(rs);
  2510. }
  2511. } else {
  2512. routerstatus_t *rs;
  2513. if ((rs = routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens,
  2514. NULL, NULL,
  2515. ns->consensus_method,
  2516. flav))) {
  2517. /* Use exponential-backoff scheduling when downloading microdescs */
  2518. smartlist_add(ns->routerstatus_list, rs);
  2519. }
  2520. }
  2521. }
  2522. for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {
  2523. routerstatus_t *rs1, *rs2;
  2524. if (ns->type != NS_TYPE_CONSENSUS) {
  2525. vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);
  2526. vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);
  2527. rs1 = &a->status; rs2 = &b->status;
  2528. } else {
  2529. rs1 = smartlist_get(ns->routerstatus_list, i-1);
  2530. rs2 = smartlist_get(ns->routerstatus_list, i);
  2531. }
  2532. if (fast_memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN)
  2533. >= 0) {
  2534. log_warn(LD_DIR, "Networkstatus entries not sorted by identity digest");
  2535. goto err;
  2536. }
  2537. }
  2538. if (ns_type != NS_TYPE_CONSENSUS) {
  2539. digest256map_t *ed_id_map = digest256map_new();
  2540. SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, vote_routerstatus_t *,
  2541. vrs) {
  2542. if (! vrs->has_ed25519_listing ||
  2543. tor_mem_is_zero((const char *)vrs->ed25519_id, DIGEST256_LEN))
  2544. continue;
  2545. if (digest256map_get(ed_id_map, vrs->ed25519_id) != NULL) {
  2546. log_warn(LD_DIR, "Vote networkstatus ed25519 identities were not "
  2547. "unique");
  2548. digest256map_free(ed_id_map, NULL);
  2549. goto err;
  2550. }
  2551. digest256map_set(ed_id_map, vrs->ed25519_id, (void*)1);
  2552. } SMARTLIST_FOREACH_END(vrs);
  2553. digest256map_free(ed_id_map, NULL);
  2554. }
  2555. /* Parse footer; check signature. */
  2556. footer_tokens = smartlist_new();
  2557. if ((end_of_footer = strstr(s, "\nnetwork-status-version ")))
  2558. ++end_of_footer;
  2559. else
  2560. end_of_footer = s + strlen(s);
  2561. if (tokenize_string(area,s, end_of_footer, footer_tokens,
  2562. networkstatus_vote_footer_token_table, 0)) {
  2563. log_warn(LD_DIR, "Error tokenizing network-status vote footer.");
  2564. goto err;
  2565. }
  2566. {
  2567. int found_sig = 0;
  2568. SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
  2569. tok = _tok;
  2570. if (tok->tp == K_DIRECTORY_SIGNATURE)
  2571. found_sig = 1;
  2572. else if (found_sig) {
  2573. log_warn(LD_DIR, "Extraneous token after first directory-signature");
  2574. goto err;
  2575. }
  2576. } SMARTLIST_FOREACH_END(_tok);
  2577. }
  2578. if ((tok = find_opt_by_keyword(footer_tokens, K_DIRECTORY_FOOTER))) {
  2579. if (tok != smartlist_get(footer_tokens, 0)) {
  2580. log_warn(LD_DIR, "Misplaced directory-footer token");
  2581. goto err;
  2582. }
  2583. }
  2584. tok = find_opt_by_keyword(footer_tokens, K_BW_WEIGHTS);
  2585. if (tok) {
  2586. ns->weight_params = smartlist_new();
  2587. for (i = 0; i < tok->n_args; ++i) {
  2588. int ok=0;
  2589. char *eq = strchr(tok->args[i], '=');
  2590. if (!eq) {
  2591. log_warn(LD_DIR, "Bad element '%s' in weight params",
  2592. escaped(tok->args[i]));
  2593. goto err;
  2594. }
  2595. tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
  2596. if (!ok) {
  2597. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  2598. goto err;
  2599. }
  2600. smartlist_add_strdup(ns->weight_params, tok->args[i]);
  2601. }
  2602. }
  2603. SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
  2604. char declared_identity[DIGEST_LEN];
  2605. networkstatus_voter_info_t *v;
  2606. document_signature_t *sig;
  2607. const char *id_hexdigest = NULL;
  2608. const char *sk_hexdigest = NULL;
  2609. digest_algorithm_t alg = DIGEST_SHA1;
  2610. tok = _tok;
  2611. if (tok->tp != K_DIRECTORY_SIGNATURE)
  2612. continue;
  2613. tor_assert(tok->n_args >= 2);
  2614. if (tok->n_args == 2) {
  2615. id_hexdigest = tok->args[0];
  2616. sk_hexdigest = tok->args[1];
  2617. } else {
  2618. const char *algname = tok->args[0];
  2619. int a;
  2620. id_hexdigest = tok->args[1];
  2621. sk_hexdigest = tok->args[2];
  2622. a = crypto_digest_algorithm_parse_name(algname);
  2623. if (a<0) {
  2624. log_warn(LD_DIR, "Unknown digest algorithm %s; skipping",
  2625. escaped(algname));
  2626. continue;
  2627. }
  2628. alg = a;
  2629. }
  2630. if (!tok->object_type ||
  2631. strcmp(tok->object_type, "SIGNATURE") ||
  2632. tok->object_size < 128 || tok->object_size > 512) {
  2633. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  2634. goto err;
  2635. }
  2636. if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
  2637. base16_decode(declared_identity, sizeof(declared_identity),
  2638. id_hexdigest, HEX_DIGEST_LEN)
  2639. != sizeof(declared_identity)) {
  2640. log_warn(LD_DIR, "Error decoding declared identity %s in "
  2641. "network-status document.", escaped(id_hexdigest));
  2642. goto err;
  2643. }
  2644. if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {
  2645. log_warn(LD_DIR, "ID on signature on network-status document does "
  2646. "not match any declared directory source.");
  2647. goto err;
  2648. }
  2649. sig = tor_malloc_zero(sizeof(document_signature_t));
  2650. memcpy(sig->identity_digest, v->identity_digest, DIGEST_LEN);
  2651. sig->alg = alg;
  2652. if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
  2653. base16_decode(sig->signing_key_digest, sizeof(sig->signing_key_digest),
  2654. sk_hexdigest, HEX_DIGEST_LEN)
  2655. != sizeof(sig->signing_key_digest)) {
  2656. log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
  2657. "network-status document.", escaped(sk_hexdigest));
  2658. tor_free(sig);
  2659. goto err;
  2660. }
  2661. if (ns->type != NS_TYPE_CONSENSUS) {
  2662. if (tor_memneq(declared_identity, ns->cert->cache_info.identity_digest,
  2663. DIGEST_LEN)) {
  2664. log_warn(LD_DIR, "Digest mismatch between declared and actual on "
  2665. "network-status vote.");
  2666. tor_free(sig);
  2667. goto err;
  2668. }
  2669. }
  2670. if (networkstatus_get_voter_sig_by_alg(v, sig->alg)) {
  2671. /* We already parsed a vote with this algorithm from this voter. Use the
  2672. first one. */
  2673. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "We received a networkstatus "
  2674. "that contains two signatures from the same voter with the same "
  2675. "algorithm. Ignoring the second signature.");
  2676. tor_free(sig);
  2677. continue;
  2678. }
  2679. if (ns->type != NS_TYPE_CONSENSUS) {
  2680. if (check_signature_token(ns_digests.d[DIGEST_SHA1], DIGEST_LEN,
  2681. tok, ns->cert->signing_key, 0,
  2682. "network-status document")) {
  2683. tor_free(sig);
  2684. goto err;
  2685. }
  2686. sig->good_signature = 1;
  2687. } else {
  2688. if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
  2689. tor_free(sig);
  2690. goto err;
  2691. }
  2692. sig->signature = tor_memdup(tok->object_body, tok->object_size);
  2693. sig->signature_len = (int) tok->object_size;
  2694. }
  2695. smartlist_add(v->sigs, sig);
  2696. ++n_signatures;
  2697. } SMARTLIST_FOREACH_END(_tok);
  2698. if (! n_signatures) {
  2699. log_warn(LD_DIR, "No signatures on networkstatus document.");
  2700. goto err;
  2701. } else if (ns->type == NS_TYPE_VOTE && n_signatures != 1) {
  2702. log_warn(LD_DIR, "Received more than one signature on a "
  2703. "network-status vote.");
  2704. goto err;
  2705. }
  2706. if (eos_out)
  2707. *eos_out = end_of_footer;
  2708. goto done;
  2709. err:
  2710. dump_desc(s_dup, "v3 networkstatus");
  2711. networkstatus_vote_free(ns);
  2712. ns = NULL;
  2713. done:
  2714. if (tokens) {
  2715. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2716. smartlist_free(tokens);
  2717. }
  2718. if (voter) {
  2719. if (voter->sigs) {
  2720. SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
  2721. document_signature_free(sig));
  2722. smartlist_free(voter->sigs);
  2723. }
  2724. tor_free(voter->nickname);
  2725. tor_free(voter->address);
  2726. tor_free(voter->contact);
  2727. tor_free(voter);
  2728. }
  2729. if (rs_tokens) {
  2730. SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_clear(t));
  2731. smartlist_free(rs_tokens);
  2732. }
  2733. if (footer_tokens) {
  2734. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_clear(t));
  2735. smartlist_free(footer_tokens);
  2736. }
  2737. if (area) {
  2738. DUMP_AREA(area, "v3 networkstatus");
  2739. memarea_drop_all(area);
  2740. }
  2741. if (rs_area)
  2742. memarea_drop_all(rs_area);
  2743. tor_free(last_kwd);
  2744. return ns;
  2745. }
  2746. /** Return the common_digests_t that holds the digests of the
  2747. * <b>flavor_name</b>-flavored networkstatus according to the detached
  2748. * signatures document <b>sigs</b>, allocating a new common_digests_t as
  2749. * needed. */
  2750. static common_digests_t *
  2751. detached_get_digests(ns_detached_signatures_t *sigs, const char *flavor_name)
  2752. {
  2753. common_digests_t *d = strmap_get(sigs->digests, flavor_name);
  2754. if (!d) {
  2755. d = tor_malloc_zero(sizeof(common_digests_t));
  2756. strmap_set(sigs->digests, flavor_name, d);
  2757. }
  2758. return d;
  2759. }
  2760. /** Return the list of signatures of the <b>flavor_name</b>-flavored
  2761. * networkstatus according to the detached signatures document <b>sigs</b>,
  2762. * allocating a new common_digests_t as needed. */
  2763. static smartlist_t *
  2764. detached_get_signatures(ns_detached_signatures_t *sigs,
  2765. const char *flavor_name)
  2766. {
  2767. smartlist_t *sl = strmap_get(sigs->signatures, flavor_name);
  2768. if (!sl) {
  2769. sl = smartlist_new();
  2770. strmap_set(sigs->signatures, flavor_name, sl);
  2771. }
  2772. return sl;
  2773. }
  2774. /** Parse a detached v3 networkstatus signature document between <b>s</b> and
  2775. * <b>eos</b> and return the result. Return -1 on failure. */
  2776. ns_detached_signatures_t *
  2777. networkstatus_parse_detached_signatures(const char *s, const char *eos)
  2778. {
  2779. /* XXXX there is too much duplicate shared between this function and
  2780. * networkstatus_parse_vote_from_string(). */
  2781. directory_token_t *tok;
  2782. memarea_t *area = NULL;
  2783. common_digests_t *digests;
  2784. smartlist_t *tokens = smartlist_new();
  2785. ns_detached_signatures_t *sigs =
  2786. tor_malloc_zero(sizeof(ns_detached_signatures_t));
  2787. sigs->digests = strmap_new();
  2788. sigs->signatures = strmap_new();
  2789. if (!eos)
  2790. eos = s + strlen(s);
  2791. area = memarea_new();
  2792. if (tokenize_string(area,s, eos, tokens,
  2793. networkstatus_detached_signature_token_table, 0)) {
  2794. log_warn(LD_DIR, "Error tokenizing detached networkstatus signatures");
  2795. goto err;
  2796. }
  2797. /* Grab all the digest-like tokens. */
  2798. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  2799. const char *algname;
  2800. digest_algorithm_t alg;
  2801. const char *flavor;
  2802. const char *hexdigest;
  2803. size_t expected_length, digest_length;
  2804. tok = _tok;
  2805. if (tok->tp == K_CONSENSUS_DIGEST) {
  2806. algname = "sha1";
  2807. alg = DIGEST_SHA1;
  2808. flavor = "ns";
  2809. hexdigest = tok->args[0];
  2810. } else if (tok->tp == K_ADDITIONAL_DIGEST) {
  2811. int a = crypto_digest_algorithm_parse_name(tok->args[1]);
  2812. if (a<0) {
  2813. log_warn(LD_DIR, "Unrecognized algorithm name %s", tok->args[0]);
  2814. continue;
  2815. }
  2816. alg = (digest_algorithm_t) a;
  2817. flavor = tok->args[0];
  2818. algname = tok->args[1];
  2819. hexdigest = tok->args[2];
  2820. } else {
  2821. continue;
  2822. }
  2823. digest_length = crypto_digest_algorithm_get_length(alg);
  2824. expected_length = digest_length * 2; /* hex encoding */
  2825. if (strlen(hexdigest) != expected_length) {
  2826. log_warn(LD_DIR, "Wrong length on consensus-digest in detached "
  2827. "networkstatus signatures");
  2828. goto err;
  2829. }
  2830. digests = detached_get_digests(sigs, flavor);
  2831. tor_assert(digests);
  2832. if (!tor_mem_is_zero(digests->d[alg], digest_length)) {
  2833. log_warn(LD_DIR, "Multiple digests for %s with %s on detached "
  2834. "signatures document", flavor, algname);
  2835. continue;
  2836. }
  2837. if (base16_decode(digests->d[alg], digest_length,
  2838. hexdigest, strlen(hexdigest)) != (int) digest_length) {
  2839. log_warn(LD_DIR, "Bad encoding on consensus-digest in detached "
  2840. "networkstatus signatures");
  2841. goto err;
  2842. }
  2843. } SMARTLIST_FOREACH_END(_tok);
  2844. tok = find_by_keyword(tokens, K_VALID_AFTER);
  2845. if (parse_iso_time(tok->args[0], &sigs->valid_after)) {
  2846. log_warn(LD_DIR, "Bad valid-after in detached networkstatus signatures");
  2847. goto err;
  2848. }
  2849. tok = find_by_keyword(tokens, K_FRESH_UNTIL);
  2850. if (parse_iso_time(tok->args[0], &sigs->fresh_until)) {
  2851. log_warn(LD_DIR, "Bad fresh-until in detached networkstatus signatures");
  2852. goto err;
  2853. }
  2854. tok = find_by_keyword(tokens, K_VALID_UNTIL);
  2855. if (parse_iso_time(tok->args[0], &sigs->valid_until)) {
  2856. log_warn(LD_DIR, "Bad valid-until in detached networkstatus signatures");
  2857. goto err;
  2858. }
  2859. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  2860. const char *id_hexdigest;
  2861. const char *sk_hexdigest;
  2862. const char *algname;
  2863. const char *flavor;
  2864. digest_algorithm_t alg;
  2865. char id_digest[DIGEST_LEN];
  2866. char sk_digest[DIGEST_LEN];
  2867. smartlist_t *siglist;
  2868. document_signature_t *sig;
  2869. int is_duplicate;
  2870. tok = _tok;
  2871. if (tok->tp == K_DIRECTORY_SIGNATURE) {
  2872. tor_assert(tok->n_args >= 2);
  2873. flavor = "ns";
  2874. algname = "sha1";
  2875. id_hexdigest = tok->args[0];
  2876. sk_hexdigest = tok->args[1];
  2877. } else if (tok->tp == K_ADDITIONAL_SIGNATURE) {
  2878. tor_assert(tok->n_args >= 4);
  2879. flavor = tok->args[0];
  2880. algname = tok->args[1];
  2881. id_hexdigest = tok->args[2];
  2882. sk_hexdigest = tok->args[3];
  2883. } else {
  2884. continue;
  2885. }
  2886. {
  2887. int a = crypto_digest_algorithm_parse_name(algname);
  2888. if (a<0) {
  2889. log_warn(LD_DIR, "Unrecognized algorithm name %s", algname);
  2890. continue;
  2891. }
  2892. alg = (digest_algorithm_t) a;
  2893. }
  2894. if (!tok->object_type ||
  2895. strcmp(tok->object_type, "SIGNATURE") ||
  2896. tok->object_size < 128 || tok->object_size > 512) {
  2897. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  2898. goto err;
  2899. }
  2900. if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
  2901. base16_decode(id_digest, sizeof(id_digest),
  2902. id_hexdigest, HEX_DIGEST_LEN) != sizeof(id_digest)) {
  2903. log_warn(LD_DIR, "Error decoding declared identity %s in "
  2904. "network-status vote.", escaped(id_hexdigest));
  2905. goto err;
  2906. }
  2907. if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
  2908. base16_decode(sk_digest, sizeof(sk_digest),
  2909. sk_hexdigest, HEX_DIGEST_LEN) != sizeof(sk_digest)) {
  2910. log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
  2911. "network-status vote.", escaped(sk_hexdigest));
  2912. goto err;
  2913. }
  2914. siglist = detached_get_signatures(sigs, flavor);
  2915. is_duplicate = 0;
  2916. SMARTLIST_FOREACH(siglist, document_signature_t *, dsig, {
  2917. if (dsig->alg == alg &&
  2918. tor_memeq(id_digest, dsig->identity_digest, DIGEST_LEN) &&
  2919. tor_memeq(sk_digest, dsig->signing_key_digest, DIGEST_LEN)) {
  2920. is_duplicate = 1;
  2921. }
  2922. });
  2923. if (is_duplicate) {
  2924. log_warn(LD_DIR, "Two signatures with identical keys and algorithm "
  2925. "found.");
  2926. continue;
  2927. }
  2928. sig = tor_malloc_zero(sizeof(document_signature_t));
  2929. sig->alg = alg;
  2930. memcpy(sig->identity_digest, id_digest, DIGEST_LEN);
  2931. memcpy(sig->signing_key_digest, sk_digest, DIGEST_LEN);
  2932. if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
  2933. tor_free(sig);
  2934. goto err;
  2935. }
  2936. sig->signature = tor_memdup(tok->object_body, tok->object_size);
  2937. sig->signature_len = (int) tok->object_size;
  2938. smartlist_add(siglist, sig);
  2939. } SMARTLIST_FOREACH_END(_tok);
  2940. goto done;
  2941. err:
  2942. ns_detached_signatures_free(sigs);
  2943. sigs = NULL;
  2944. done:
  2945. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2946. smartlist_free(tokens);
  2947. if (area) {
  2948. DUMP_AREA(area, "detached signatures");
  2949. memarea_drop_all(area);
  2950. }
  2951. return sigs;
  2952. }
  2953. /** Parse the addr policy in the string <b>s</b> and return it. If
  2954. * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
  2955. * ADDR_POLICY_REJECT) for items that specify no action.
  2956. *
  2957. * Returns NULL on policy errors.
  2958. *
  2959. * Set *<b>malformed_list</b> to true if the entire policy list should be
  2960. * discarded. Otherwise, set it to false, and only this item should be ignored
  2961. * on error - the rest of the policy list can continue to be processed and
  2962. * used.
  2963. *
  2964. * The addr_policy_t returned by this function can have its address set to
  2965. * AF_UNSPEC for '*'. Use policy_expand_unspec() to turn this into a pair
  2966. * of AF_INET and AF_INET6 items.
  2967. */
  2968. MOCK_IMPL(addr_policy_t *,
  2969. router_parse_addr_policy_item_from_string,(const char *s, int assume_action,
  2970. int *malformed_list))
  2971. {
  2972. directory_token_t *tok = NULL;
  2973. const char *cp, *eos;
  2974. /* Longest possible policy is
  2975. * "accept6 [ffff:ffff:..255]/128:10000-65535",
  2976. * which contains a max-length IPv6 address, plus 26 characters.
  2977. * But note that there can be an arbitrary amount of space between the
  2978. * accept and the address:mask/port element.
  2979. * We don't need to multiply TOR_ADDR_BUF_LEN by 2, as there is only one
  2980. * IPv6 address. But making the buffer shorter might cause valid long lines,
  2981. * which parsed in previous versions, to fail to parse in new versions.
  2982. * (These lines would have to have excessive amounts of whitespace.) */
  2983. char line[TOR_ADDR_BUF_LEN*2 + 32];
  2984. addr_policy_t *r;
  2985. memarea_t *area = NULL;
  2986. tor_assert(malformed_list);
  2987. *malformed_list = 0;
  2988. s = eat_whitespace(s);
  2989. /* We can only do assume_action on []-quoted IPv6, as "a" (accept)
  2990. * and ":" (port separator) are ambiguous */
  2991. if ((*s == '*' || *s == '[' || TOR_ISDIGIT(*s)) && assume_action >= 0) {
  2992. if (tor_snprintf(line, sizeof(line), "%s %s",
  2993. assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", s)<0) {
  2994. log_warn(LD_DIR, "Policy %s is too long.", escaped(s));
  2995. return NULL;
  2996. }
  2997. cp = line;
  2998. tor_strlower(line);
  2999. } else { /* assume an already well-formed address policy line */
  3000. cp = s;
  3001. }
  3002. eos = cp + strlen(cp);
  3003. area = memarea_new();
  3004. tok = get_next_token(area, &cp, eos, routerdesc_token_table);
  3005. if (tok->tp == ERR_) {
  3006. log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
  3007. goto err;
  3008. }
  3009. if (tok->tp != K_ACCEPT && tok->tp != K_ACCEPT6 &&
  3010. tok->tp != K_REJECT && tok->tp != K_REJECT6) {
  3011. log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
  3012. goto err;
  3013. }
  3014. /* Use the extended interpretation of accept/reject *,
  3015. * expanding it into an IPv4 wildcard and an IPv6 wildcard.
  3016. * Also permit *4 and *6 for IPv4 and IPv6 only wildcards. */
  3017. r = router_parse_addr_policy(tok, TAPMP_EXTENDED_STAR);
  3018. if (!r) {
  3019. goto err;
  3020. }
  3021. /* Ensure that accept6/reject6 fields are followed by IPv6 addresses.
  3022. * AF_UNSPEC addresses are only permitted on the accept/reject field type.
  3023. * Unlike descriptors, torrcs exit policy accept/reject can be followed by
  3024. * either an IPv4 or IPv6 address. */
  3025. if ((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  3026. tor_addr_family(&r->addr) != AF_INET6) {
  3027. /* This is a non-fatal error, just ignore this one entry. */
  3028. *malformed_list = 0;
  3029. log_warn(LD_DIR, "IPv4 address '%s' with accept6/reject6 field type in "
  3030. "exit policy. Ignoring, but continuing to parse rules. (Use "
  3031. "accept/reject with IPv4 addresses.)",
  3032. tok->n_args == 1 ? tok->args[0] : "");
  3033. addr_policy_free(r);
  3034. r = NULL;
  3035. goto done;
  3036. }
  3037. goto done;
  3038. err:
  3039. *malformed_list = 1;
  3040. r = NULL;
  3041. done:
  3042. token_clear(tok);
  3043. if (area) {
  3044. DUMP_AREA(area, "policy item");
  3045. memarea_drop_all(area);
  3046. }
  3047. return r;
  3048. }
  3049. /** Add an exit policy stored in the token <b>tok</b> to the router info in
  3050. * <b>router</b>. Return 0 on success, -1 on failure. */
  3051. static int
  3052. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
  3053. {
  3054. addr_policy_t *newe;
  3055. /* Use the standard interpretation of accept/reject *, an IPv4 wildcard. */
  3056. newe = router_parse_addr_policy(tok, 0);
  3057. if (!newe)
  3058. return -1;
  3059. if (! router->exit_policy)
  3060. router->exit_policy = smartlist_new();
  3061. /* Ensure that in descriptors, accept/reject fields are followed by
  3062. * IPv4 addresses, and accept6/reject6 fields are followed by
  3063. * IPv6 addresses. Unlike torrcs, descriptor exit policies do not permit
  3064. * accept/reject followed by IPv6. */
  3065. if (((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  3066. tor_addr_family(&newe->addr) == AF_INET)
  3067. ||
  3068. ((tok->tp == K_ACCEPT || tok->tp == K_REJECT) &&
  3069. tor_addr_family(&newe->addr) == AF_INET6)) {
  3070. /* There's nothing the user can do about other relays' descriptors,
  3071. * so we don't provide usage advice here. */
  3072. log_warn(LD_DIR, "Mismatch between field type and address type in exit "
  3073. "policy '%s'. Discarding entire router descriptor.",
  3074. tok->n_args == 1 ? tok->args[0] : "");
  3075. addr_policy_free(newe);
  3076. return -1;
  3077. }
  3078. smartlist_add(router->exit_policy, newe);
  3079. return 0;
  3080. }
  3081. /** Given a K_ACCEPT[6] or K_REJECT[6] token and a router, create and return
  3082. * a new exit_policy_t corresponding to the token. If TAPMP_EXTENDED_STAR
  3083. * is set in fmt_flags, K_ACCEPT6 and K_REJECT6 tokens followed by *
  3084. * expand to IPv6-only policies, otherwise they expand to IPv4 and IPv6
  3085. * policies */
  3086. static addr_policy_t *
  3087. router_parse_addr_policy(directory_token_t *tok, unsigned fmt_flags)
  3088. {
  3089. addr_policy_t newe;
  3090. char *arg;
  3091. tor_assert(tok->tp == K_REJECT || tok->tp == K_REJECT6 ||
  3092. tok->tp == K_ACCEPT || tok->tp == K_ACCEPT6);
  3093. if (tok->n_args != 1)
  3094. return NULL;
  3095. arg = tok->args[0];
  3096. if (!strcmpstart(arg,"private"))
  3097. return router_parse_addr_policy_private(tok);
  3098. memset(&newe, 0, sizeof(newe));
  3099. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  3100. newe.policy_type = ADDR_POLICY_REJECT;
  3101. else
  3102. newe.policy_type = ADDR_POLICY_ACCEPT;
  3103. /* accept6/reject6 * produces an IPv6 wildcard address only.
  3104. * (accept/reject * produces rules for IPv4 and IPv6 wildcard addresses.) */
  3105. if ((fmt_flags & TAPMP_EXTENDED_STAR)
  3106. && (tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6)) {
  3107. fmt_flags |= TAPMP_STAR_IPV6_ONLY;
  3108. }
  3109. if (tor_addr_parse_mask_ports(arg, fmt_flags, &newe.addr, &newe.maskbits,
  3110. &newe.prt_min, &newe.prt_max) < 0) {
  3111. log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
  3112. return NULL;
  3113. }
  3114. return addr_policy_get_canonical_entry(&newe);
  3115. }
  3116. /** Parse an exit policy line of the format "accept[6]/reject[6] private:...".
  3117. * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
  3118. * router descriptors until earlier versions are obsolete.
  3119. *
  3120. * accept/reject and accept6/reject6 private all produce rules for both
  3121. * IPv4 and IPv6 addresses.
  3122. */
  3123. static addr_policy_t *
  3124. router_parse_addr_policy_private(directory_token_t *tok)
  3125. {
  3126. const char *arg;
  3127. uint16_t port_min, port_max;
  3128. addr_policy_t result;
  3129. arg = tok->args[0];
  3130. if (strcmpstart(arg, "private"))
  3131. return NULL;
  3132. arg += strlen("private");
  3133. arg = (char*) eat_whitespace(arg);
  3134. if (!arg || *arg != ':')
  3135. return NULL;
  3136. if (parse_port_range(arg+1, &port_min, &port_max)<0)
  3137. return NULL;
  3138. memset(&result, 0, sizeof(result));
  3139. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  3140. result.policy_type = ADDR_POLICY_REJECT;
  3141. else
  3142. result.policy_type = ADDR_POLICY_ACCEPT;
  3143. result.is_private = 1;
  3144. result.prt_min = port_min;
  3145. result.prt_max = port_max;
  3146. if (tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) {
  3147. log_warn(LD_GENERAL,
  3148. "'%s' expands into rules which apply to all private IPv4 and "
  3149. "IPv6 addresses. (Use accept/reject private:* for IPv4 and "
  3150. "IPv6.)", tok->n_args == 1 ? tok->args[0] : "");
  3151. }
  3152. return addr_policy_get_canonical_entry(&result);
  3153. }
  3154. /** Log and exit if <b>t</b> is malformed */
  3155. void
  3156. assert_addr_policy_ok(smartlist_t *lst)
  3157. {
  3158. if (!lst) return;
  3159. SMARTLIST_FOREACH(lst, addr_policy_t *, t, {
  3160. tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
  3161. t->policy_type == ADDR_POLICY_ACCEPT);
  3162. tor_assert(t->prt_min <= t->prt_max);
  3163. });
  3164. }
  3165. /** Return a newly allocated smartlist of all accept or reject tokens in
  3166. * <b>s</b>.
  3167. */
  3168. static smartlist_t *
  3169. find_all_exitpolicy(smartlist_t *s)
  3170. {
  3171. smartlist_t *out = smartlist_new();
  3172. SMARTLIST_FOREACH(s, directory_token_t *, t,
  3173. if (t->tp == K_ACCEPT || t->tp == K_ACCEPT6 ||
  3174. t->tp == K_REJECT || t->tp == K_REJECT6)
  3175. smartlist_add(out,t));
  3176. return out;
  3177. }
  3178. /** Assuming that s starts with a microdesc, return the start of the
  3179. * *NEXT* one. Return NULL on "not found." */
  3180. static const char *
  3181. find_start_of_next_microdesc(const char *s, const char *eos)
  3182. {
  3183. int started_with_annotations;
  3184. s = eat_whitespace_eos(s, eos);
  3185. if (!s)
  3186. return NULL;
  3187. #define CHECK_LENGTH() STMT_BEGIN \
  3188. if (s+32 > eos) \
  3189. return NULL; \
  3190. STMT_END
  3191. #define NEXT_LINE() STMT_BEGIN \
  3192. s = memchr(s, '\n', eos-s); \
  3193. if (!s || s+1 >= eos) \
  3194. return NULL; \
  3195. s++; \
  3196. STMT_END
  3197. CHECK_LENGTH();
  3198. started_with_annotations = (*s == '@');
  3199. if (started_with_annotations) {
  3200. /* Start by advancing to the first non-annotation line. */
  3201. while (*s == '@')
  3202. NEXT_LINE();
  3203. }
  3204. CHECK_LENGTH();
  3205. /* Now we should be pointed at an onion-key line. If we are, then skip
  3206. * it. */
  3207. if (!strcmpstart(s, "onion-key"))
  3208. NEXT_LINE();
  3209. /* Okay, now we're pointed at the first line of the microdescriptor which is
  3210. not an annotation or onion-key. The next line that _is_ an annotation or
  3211. onion-key is the start of the next microdescriptor. */
  3212. while (s+32 < eos) {
  3213. if (*s == '@' || !strcmpstart(s, "onion-key"))
  3214. return s;
  3215. NEXT_LINE();
  3216. }
  3217. return NULL;
  3218. #undef CHECK_LENGTH
  3219. #undef NEXT_LINE
  3220. }
  3221. /** Parse as many microdescriptors as are found from the string starting at
  3222. * <b>s</b> and ending at <b>eos</b>. If allow_annotations is set, read any
  3223. * annotations we recognize and ignore ones we don't.
  3224. *
  3225. * If <b>saved_location</b> isn't SAVED_IN_CACHE, make a local copy of each
  3226. * descriptor in the body field of each microdesc_t.
  3227. *
  3228. * Return all newly parsed microdescriptors in a newly allocated
  3229. * smartlist_t. If <b>invalid_disgests_out</b> is provided, add a SHA256
  3230. * microdesc digest to it for every microdesc that we found to be badly
  3231. * formed. (This may cause duplicates) */
  3232. smartlist_t *
  3233. microdescs_parse_from_string(const char *s, const char *eos,
  3234. int allow_annotations,
  3235. saved_location_t where,
  3236. smartlist_t *invalid_digests_out)
  3237. {
  3238. smartlist_t *tokens;
  3239. smartlist_t *result;
  3240. microdesc_t *md = NULL;
  3241. memarea_t *area;
  3242. const char *start = s;
  3243. const char *start_of_next_microdesc;
  3244. int flags = allow_annotations ? TS_ANNOTATIONS_OK : 0;
  3245. const int copy_body = (where != SAVED_IN_CACHE);
  3246. directory_token_t *tok;
  3247. if (!eos)
  3248. eos = s + strlen(s);
  3249. s = eat_whitespace_eos(s, eos);
  3250. area = memarea_new();
  3251. result = smartlist_new();
  3252. tokens = smartlist_new();
  3253. while (s < eos) {
  3254. int okay = 0;
  3255. start_of_next_microdesc = find_start_of_next_microdesc(s, eos);
  3256. if (!start_of_next_microdesc)
  3257. start_of_next_microdesc = eos;
  3258. md = tor_malloc_zero(sizeof(microdesc_t));
  3259. {
  3260. const char *cp = tor_memstr(s, start_of_next_microdesc-s,
  3261. "onion-key");
  3262. const int no_onion_key = (cp == NULL);
  3263. if (no_onion_key) {
  3264. cp = s; /* So that we have *some* junk to put in the body */
  3265. }
  3266. md->bodylen = start_of_next_microdesc - cp;
  3267. md->saved_location = where;
  3268. if (copy_body)
  3269. md->body = tor_memdup_nulterm(cp, md->bodylen);
  3270. else
  3271. md->body = (char*)cp;
  3272. md->off = cp - start;
  3273. crypto_digest256(md->digest, md->body, md->bodylen, DIGEST_SHA256);
  3274. if (no_onion_key) {
  3275. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Malformed or truncated descriptor");
  3276. goto next;
  3277. }
  3278. }
  3279. if (tokenize_string(area, s, start_of_next_microdesc, tokens,
  3280. microdesc_token_table, flags)) {
  3281. log_warn(LD_DIR, "Unparseable microdescriptor");
  3282. goto next;
  3283. }
  3284. if ((tok = find_opt_by_keyword(tokens, A_LAST_LISTED))) {
  3285. if (parse_iso_time(tok->args[0], &md->last_listed)) {
  3286. log_warn(LD_DIR, "Bad last-listed time in microdescriptor");
  3287. goto next;
  3288. }
  3289. }
  3290. tok = find_by_keyword(tokens, K_ONION_KEY);
  3291. if (!crypto_pk_public_exponent_ok(tok->key)) {
  3292. log_warn(LD_DIR,
  3293. "Relay's onion key had invalid exponent.");
  3294. goto next;
  3295. }
  3296. router_set_rsa_onion_pkey(tok->key, &md->onion_pkey,
  3297. &md->onion_pkey_len);
  3298. crypto_pk_free(tok->key);
  3299. if ((tok = find_opt_by_keyword(tokens, K_ONION_KEY_NTOR))) {
  3300. curve25519_public_key_t k;
  3301. tor_assert(tok->n_args >= 1);
  3302. if (curve25519_public_from_base64(&k, tok->args[0]) < 0) {
  3303. log_warn(LD_DIR, "Bogus ntor-onion-key in microdesc");
  3304. goto next;
  3305. }
  3306. md->onion_curve25519_pkey =
  3307. tor_memdup(&k, sizeof(curve25519_public_key_t));
  3308. }
  3309. smartlist_t *id_lines = find_all_by_keyword(tokens, K_ID);
  3310. if (id_lines) {
  3311. SMARTLIST_FOREACH_BEGIN(id_lines, directory_token_t *, t) {
  3312. tor_assert(t->n_args >= 2);
  3313. if (!strcmp(t->args[0], "ed25519")) {
  3314. if (md->ed25519_identity_pkey) {
  3315. log_warn(LD_DIR, "Extra ed25519 key in microdesc");
  3316. smartlist_free(id_lines);
  3317. goto next;
  3318. }
  3319. ed25519_public_key_t k;
  3320. if (ed25519_public_from_base64(&k, t->args[1])<0) {
  3321. log_warn(LD_DIR, "Bogus ed25519 key in microdesc");
  3322. smartlist_free(id_lines);
  3323. goto next;
  3324. }
  3325. md->ed25519_identity_pkey = tor_memdup(&k, sizeof(k));
  3326. }
  3327. } SMARTLIST_FOREACH_END(t);
  3328. smartlist_free(id_lines);
  3329. }
  3330. {
  3331. smartlist_t *a_lines = find_all_by_keyword(tokens, K_A);
  3332. if (a_lines) {
  3333. find_single_ipv6_orport(a_lines, &md->ipv6_addr, &md->ipv6_orport);
  3334. smartlist_free(a_lines);
  3335. }
  3336. }
  3337. if ((tok = find_opt_by_keyword(tokens, K_FAMILY))) {
  3338. int i;
  3339. md->family = smartlist_new();
  3340. for (i=0;i<tok->n_args;++i) {
  3341. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  3342. log_warn(LD_DIR, "Illegal nickname %s in family line",
  3343. escaped(tok->args[i]));
  3344. goto next;
  3345. }
  3346. smartlist_add_strdup(md->family, tok->args[i]);
  3347. }
  3348. }
  3349. if ((tok = find_opt_by_keyword(tokens, K_P))) {
  3350. md->exit_policy = parse_short_policy(tok->args[0]);
  3351. }
  3352. if ((tok = find_opt_by_keyword(tokens, K_P6))) {
  3353. md->ipv6_exit_policy = parse_short_policy(tok->args[0]);
  3354. }
  3355. smartlist_add(result, md);
  3356. okay = 1;
  3357. md = NULL;
  3358. next:
  3359. if (! okay && invalid_digests_out) {
  3360. smartlist_add(invalid_digests_out,
  3361. tor_memdup(md->digest, DIGEST256_LEN));
  3362. }
  3363. microdesc_free(md);
  3364. md = NULL;
  3365. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  3366. memarea_clear(area);
  3367. smartlist_clear(tokens);
  3368. s = start_of_next_microdesc;
  3369. }
  3370. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  3371. memarea_drop_all(area);
  3372. smartlist_free(tokens);
  3373. return result;
  3374. }
  3375. /** Parse and validate the ASCII-encoded v2 descriptor in <b>desc</b>,
  3376. * write the parsed descriptor to the newly allocated *<b>parsed_out</b>, the
  3377. * binary descriptor ID of length DIGEST_LEN to <b>desc_id_out</b>, the
  3378. * encrypted introduction points to the newly allocated
  3379. * *<b>intro_points_encrypted_out</b>, their encrypted size to
  3380. * *<b>intro_points_encrypted_size_out</b>, the size of the encoded descriptor
  3381. * to *<b>encoded_size_out</b>, and a pointer to the possibly next
  3382. * descriptor to *<b>next_out</b>; return 0 for success (including validation)
  3383. * and -1 for failure.
  3384. *
  3385. * If <b>as_hsdir</b> is 1, we're parsing this as an HSDir, and we should
  3386. * be strict about time formats.
  3387. */
  3388. int
  3389. rend_parse_v2_service_descriptor(rend_service_descriptor_t **parsed_out,
  3390. char *desc_id_out,
  3391. char **intro_points_encrypted_out,
  3392. size_t *intro_points_encrypted_size_out,
  3393. size_t *encoded_size_out,
  3394. const char **next_out, const char *desc,
  3395. int as_hsdir)
  3396. {
  3397. rend_service_descriptor_t *result =
  3398. tor_malloc_zero(sizeof(rend_service_descriptor_t));
  3399. char desc_hash[DIGEST_LEN];
  3400. const char *eos;
  3401. smartlist_t *tokens = smartlist_new();
  3402. directory_token_t *tok;
  3403. char secret_id_part[DIGEST_LEN];
  3404. int i, version, num_ok=1;
  3405. smartlist_t *versions;
  3406. char public_key_hash[DIGEST_LEN];
  3407. char test_desc_id[DIGEST_LEN];
  3408. memarea_t *area = NULL;
  3409. const int strict_time_fmt = as_hsdir;
  3410. tor_assert(desc);
  3411. /* Check if desc starts correctly. */
  3412. if (strcmpstart(desc, "rendezvous-service-descriptor ")) {
  3413. log_info(LD_REND, "Descriptor does not start correctly.");
  3414. goto err;
  3415. }
  3416. /* Compute descriptor hash for later validation. */
  3417. if (router_get_hash_impl(desc, strlen(desc), desc_hash,
  3418. "rendezvous-service-descriptor ",
  3419. "\nsignature", '\n', DIGEST_SHA1) < 0) {
  3420. log_warn(LD_REND, "Couldn't compute descriptor hash.");
  3421. goto err;
  3422. }
  3423. /* Determine end of string. */
  3424. eos = strstr(desc, "\nrendezvous-service-descriptor ");
  3425. if (!eos)
  3426. eos = desc + strlen(desc);
  3427. else
  3428. eos = eos + 1;
  3429. /* Check length. */
  3430. if (eos-desc > REND_DESC_MAX_SIZE) {
  3431. /* XXXX+ If we are parsing this descriptor as a server, this
  3432. * should be a protocol warning. */
  3433. log_warn(LD_REND, "Descriptor length is %d which exceeds "
  3434. "maximum rendezvous descriptor size of %d bytes.",
  3435. (int)(eos-desc), REND_DESC_MAX_SIZE);
  3436. goto err;
  3437. }
  3438. /* Tokenize descriptor. */
  3439. area = memarea_new();
  3440. if (tokenize_string(area, desc, eos, tokens, desc_token_table, 0)) {
  3441. log_warn(LD_REND, "Error tokenizing descriptor.");
  3442. goto err;
  3443. }
  3444. /* Set next to next descriptor, if available. */
  3445. *next_out = eos;
  3446. /* Set length of encoded descriptor. */
  3447. *encoded_size_out = eos - desc;
  3448. /* Check min allowed length of token list. */
  3449. if (smartlist_len(tokens) < 7) {
  3450. log_warn(LD_REND, "Impossibly short descriptor.");
  3451. goto err;
  3452. }
  3453. /* Parse base32-encoded descriptor ID. */
  3454. tok = find_by_keyword(tokens, R_RENDEZVOUS_SERVICE_DESCRIPTOR);
  3455. tor_assert(tok == smartlist_get(tokens, 0));
  3456. tor_assert(tok->n_args == 1);
  3457. if (!rend_valid_descriptor_id(tok->args[0])) {
  3458. log_warn(LD_REND, "Invalid descriptor ID: '%s'", tok->args[0]);
  3459. goto err;
  3460. }
  3461. if (base32_decode(desc_id_out, DIGEST_LEN,
  3462. tok->args[0], REND_DESC_ID_V2_LEN_BASE32) < 0) {
  3463. log_warn(LD_REND, "Descriptor ID contains illegal characters: %s",
  3464. tok->args[0]);
  3465. goto err;
  3466. }
  3467. /* Parse descriptor version. */
  3468. tok = find_by_keyword(tokens, R_VERSION);
  3469. tor_assert(tok->n_args == 1);
  3470. result->version =
  3471. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &num_ok, NULL);
  3472. if (result->version != 2 || !num_ok) {
  3473. /* If it's <2, it shouldn't be under this format. If the number
  3474. * is greater than 2, we bumped it because we broke backward
  3475. * compatibility. See how version numbers in our other formats
  3476. * work. */
  3477. log_warn(LD_REND, "Unrecognized descriptor version: %s",
  3478. escaped(tok->args[0]));
  3479. goto err;
  3480. }
  3481. /* Parse public key. */
  3482. tok = find_by_keyword(tokens, R_PERMANENT_KEY);
  3483. result->pk = tok->key;
  3484. tok->key = NULL; /* Prevent free */
  3485. /* Parse secret ID part. */
  3486. tok = find_by_keyword(tokens, R_SECRET_ID_PART);
  3487. tor_assert(tok->n_args == 1);
  3488. if (strlen(tok->args[0]) != REND_SECRET_ID_PART_LEN_BASE32 ||
  3489. strspn(tok->args[0], BASE32_CHARS) != REND_SECRET_ID_PART_LEN_BASE32) {
  3490. log_warn(LD_REND, "Invalid secret ID part: '%s'", tok->args[0]);
  3491. goto err;
  3492. }
  3493. if (base32_decode(secret_id_part, DIGEST_LEN, tok->args[0], 32) < 0) {
  3494. log_warn(LD_REND, "Secret ID part contains illegal characters: %s",
  3495. tok->args[0]);
  3496. goto err;
  3497. }
  3498. /* Parse publication time -- up-to-date check is done when storing the
  3499. * descriptor. */
  3500. tok = find_by_keyword(tokens, R_PUBLICATION_TIME);
  3501. tor_assert(tok->n_args == 1);
  3502. if (parse_iso_time_(tok->args[0], &result->timestamp,
  3503. strict_time_fmt, 0) < 0) {
  3504. log_warn(LD_REND, "Invalid publication time: '%s'", tok->args[0]);
  3505. goto err;
  3506. }
  3507. /* Parse protocol versions. */
  3508. tok = find_by_keyword(tokens, R_PROTOCOL_VERSIONS);
  3509. tor_assert(tok->n_args == 1);
  3510. versions = smartlist_new();
  3511. smartlist_split_string(versions, tok->args[0], ",",
  3512. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3513. for (i = 0; i < smartlist_len(versions); i++) {
  3514. version = (int) tor_parse_long(smartlist_get(versions, i),
  3515. 10, 0, INT_MAX, &num_ok, NULL);
  3516. if (!num_ok) /* It's a string; let's ignore it. */
  3517. continue;
  3518. if (version >= REND_PROTOCOL_VERSION_BITMASK_WIDTH)
  3519. /* Avoid undefined left-shift behaviour. */
  3520. continue;
  3521. result->protocols |= 1 << version;
  3522. }
  3523. SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
  3524. smartlist_free(versions);
  3525. /* Parse encrypted introduction points. Don't verify. */
  3526. tok = find_opt_by_keyword(tokens, R_INTRODUCTION_POINTS);
  3527. if (tok) {
  3528. if (strcmp(tok->object_type, "MESSAGE")) {
  3529. log_warn(LD_DIR, "Bad object type: introduction points should be of "
  3530. "type MESSAGE");
  3531. goto err;
  3532. }
  3533. *intro_points_encrypted_out = tor_memdup(tok->object_body,
  3534. tok->object_size);
  3535. *intro_points_encrypted_size_out = tok->object_size;
  3536. } else {
  3537. *intro_points_encrypted_out = NULL;
  3538. *intro_points_encrypted_size_out = 0;
  3539. }
  3540. /* Parse and verify signature. */
  3541. tok = find_by_keyword(tokens, R_SIGNATURE);
  3542. if (check_signature_token(desc_hash, DIGEST_LEN, tok, result->pk, 0,
  3543. "v2 rendezvous service descriptor") < 0)
  3544. goto err;
  3545. /* Verify that descriptor ID belongs to public key and secret ID part. */
  3546. if (crypto_pk_get_digest(result->pk, public_key_hash) < 0) {
  3547. log_warn(LD_REND, "Unable to compute rend descriptor public key digest");
  3548. goto err;
  3549. }
  3550. rend_get_descriptor_id_bytes(test_desc_id, public_key_hash,
  3551. secret_id_part);
  3552. if (tor_memneq(desc_id_out, test_desc_id, DIGEST_LEN)) {
  3553. log_warn(LD_REND, "Parsed descriptor ID does not match "
  3554. "computed descriptor ID.");
  3555. goto err;
  3556. }
  3557. goto done;
  3558. err:
  3559. rend_service_descriptor_free(result);
  3560. result = NULL;
  3561. done:
  3562. if (tokens) {
  3563. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  3564. smartlist_free(tokens);
  3565. }
  3566. if (area)
  3567. memarea_drop_all(area);
  3568. *parsed_out = result;
  3569. if (result)
  3570. return 0;
  3571. return -1;
  3572. }
  3573. /** Decrypt the encrypted introduction points in <b>ipos_encrypted</b> of
  3574. * length <b>ipos_encrypted_size</b> using <b>descriptor_cookie</b> and
  3575. * write the result to a newly allocated string that is pointed to by
  3576. * <b>ipos_decrypted</b> and its length to <b>ipos_decrypted_size</b>.
  3577. * Return 0 if decryption was successful and -1 otherwise. */
  3578. int
  3579. rend_decrypt_introduction_points(char **ipos_decrypted,
  3580. size_t *ipos_decrypted_size,
  3581. const char *descriptor_cookie,
  3582. const char *ipos_encrypted,
  3583. size_t ipos_encrypted_size)
  3584. {
  3585. tor_assert(ipos_encrypted);
  3586. tor_assert(descriptor_cookie);
  3587. if (ipos_encrypted_size < 2) {
  3588. log_warn(LD_REND, "Size of encrypted introduction points is too "
  3589. "small.");
  3590. return -1;
  3591. }
  3592. if (ipos_encrypted[0] == (int)REND_BASIC_AUTH) {
  3593. char iv[CIPHER_IV_LEN], client_id[REND_BASIC_AUTH_CLIENT_ID_LEN],
  3594. session_key[CIPHER_KEY_LEN], *dec;
  3595. int declen, client_blocks;
  3596. size_t pos = 0, len, client_entries_len;
  3597. crypto_digest_t *digest;
  3598. crypto_cipher_t *cipher;
  3599. client_blocks = (int) ipos_encrypted[1];
  3600. client_entries_len = client_blocks * REND_BASIC_AUTH_CLIENT_MULTIPLE *
  3601. REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
  3602. if (ipos_encrypted_size < 2 + client_entries_len + CIPHER_IV_LEN + 1) {
  3603. log_warn(LD_REND, "Size of encrypted introduction points is too "
  3604. "small.");
  3605. return -1;
  3606. }
  3607. memcpy(iv, ipos_encrypted + 2 + client_entries_len, CIPHER_IV_LEN);
  3608. digest = crypto_digest_new();
  3609. crypto_digest_add_bytes(digest, descriptor_cookie, REND_DESC_COOKIE_LEN);
  3610. crypto_digest_add_bytes(digest, iv, CIPHER_IV_LEN);
  3611. crypto_digest_get_digest(digest, client_id,
  3612. REND_BASIC_AUTH_CLIENT_ID_LEN);
  3613. crypto_digest_free(digest);
  3614. for (pos = 2; pos < 2 + client_entries_len;
  3615. pos += REND_BASIC_AUTH_CLIENT_ENTRY_LEN) {
  3616. if (tor_memeq(ipos_encrypted + pos, client_id,
  3617. REND_BASIC_AUTH_CLIENT_ID_LEN)) {
  3618. /* Attempt to decrypt introduction points. */
  3619. cipher = crypto_cipher_new(descriptor_cookie);
  3620. if (crypto_cipher_decrypt(cipher, session_key, ipos_encrypted
  3621. + pos + REND_BASIC_AUTH_CLIENT_ID_LEN,
  3622. CIPHER_KEY_LEN) < 0) {
  3623. log_warn(LD_REND, "Could not decrypt session key for client.");
  3624. crypto_cipher_free(cipher);
  3625. return -1;
  3626. }
  3627. crypto_cipher_free(cipher);
  3628. len = ipos_encrypted_size - 2 - client_entries_len - CIPHER_IV_LEN;
  3629. dec = tor_malloc_zero(len + 1);
  3630. declen = crypto_cipher_decrypt_with_iv(session_key, dec, len,
  3631. ipos_encrypted + 2 + client_entries_len,
  3632. ipos_encrypted_size - 2 - client_entries_len);
  3633. if (declen < 0) {
  3634. log_warn(LD_REND, "Could not decrypt introduction point string.");
  3635. tor_free(dec);
  3636. return -1;
  3637. }
  3638. if (fast_memcmpstart(dec, declen, "introduction-point ")) {
  3639. log_warn(LD_REND, "Decrypted introduction points don't "
  3640. "look like we could parse them.");
  3641. tor_free(dec);
  3642. continue;
  3643. }
  3644. *ipos_decrypted = dec;
  3645. *ipos_decrypted_size = declen;
  3646. return 0;
  3647. }
  3648. }
  3649. log_warn(LD_REND, "Could not decrypt introduction points. Please "
  3650. "check your authorization for this service!");
  3651. return -1;
  3652. } else if (ipos_encrypted[0] == (int)REND_STEALTH_AUTH) {
  3653. char *dec;
  3654. int declen;
  3655. if (ipos_encrypted_size < CIPHER_IV_LEN + 2) {
  3656. log_warn(LD_REND, "Size of encrypted introduction points is too "
  3657. "small.");
  3658. return -1;
  3659. }
  3660. dec = tor_malloc_zero(ipos_encrypted_size - CIPHER_IV_LEN - 1 + 1);
  3661. declen = crypto_cipher_decrypt_with_iv(descriptor_cookie, dec,
  3662. ipos_encrypted_size -
  3663. CIPHER_IV_LEN - 1,
  3664. ipos_encrypted + 1,
  3665. ipos_encrypted_size - 1);
  3666. if (declen < 0) {
  3667. log_warn(LD_REND, "Decrypting introduction points failed!");
  3668. tor_free(dec);
  3669. return -1;
  3670. }
  3671. *ipos_decrypted = dec;
  3672. *ipos_decrypted_size = declen;
  3673. return 0;
  3674. } else {
  3675. log_warn(LD_REND, "Unknown authorization type number: %d",
  3676. ipos_encrypted[0]);
  3677. return -1;
  3678. }
  3679. }
  3680. /** Parse the encoded introduction points in <b>intro_points_encoded</b> of
  3681. * length <b>intro_points_encoded_size</b> and write the result to the
  3682. * descriptor in <b>parsed</b>; return the number of successfully parsed
  3683. * introduction points or -1 in case of a failure. */
  3684. int
  3685. rend_parse_introduction_points(rend_service_descriptor_t *parsed,
  3686. const char *intro_points_encoded,
  3687. size_t intro_points_encoded_size)
  3688. {
  3689. const char *current_ipo, *end_of_intro_points;
  3690. smartlist_t *tokens = NULL;
  3691. directory_token_t *tok;
  3692. rend_intro_point_t *intro;
  3693. extend_info_t *info;
  3694. int result, num_ok=1;
  3695. memarea_t *area = NULL;
  3696. tor_assert(parsed);
  3697. /** Function may only be invoked once. */
  3698. tor_assert(!parsed->intro_nodes);
  3699. if (!intro_points_encoded || intro_points_encoded_size == 0) {
  3700. log_warn(LD_REND, "Empty or zero size introduction point list");
  3701. goto err;
  3702. }
  3703. /* Consider one intro point after the other. */
  3704. current_ipo = intro_points_encoded;
  3705. end_of_intro_points = intro_points_encoded + intro_points_encoded_size;
  3706. tokens = smartlist_new();
  3707. parsed->intro_nodes = smartlist_new();
  3708. area = memarea_new();
  3709. while (!fast_memcmpstart(current_ipo, end_of_intro_points-current_ipo,
  3710. "introduction-point ")) {
  3711. /* Determine end of string. */
  3712. const char *eos = tor_memstr(current_ipo, end_of_intro_points-current_ipo,
  3713. "\nintroduction-point ");
  3714. if (!eos)
  3715. eos = end_of_intro_points;
  3716. else
  3717. eos = eos+1;
  3718. tor_assert(eos <= intro_points_encoded+intro_points_encoded_size);
  3719. /* Free tokens and clear token list. */
  3720. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  3721. smartlist_clear(tokens);
  3722. memarea_clear(area);
  3723. /* Tokenize string. */
  3724. if (tokenize_string(area, current_ipo, eos, tokens, ipo_token_table, 0)) {
  3725. log_warn(LD_REND, "Error tokenizing introduction point");
  3726. goto err;
  3727. }
  3728. /* Advance to next introduction point, if available. */
  3729. current_ipo = eos;
  3730. /* Check minimum allowed length of introduction point. */
  3731. if (smartlist_len(tokens) < 5) {
  3732. log_warn(LD_REND, "Impossibly short introduction point.");
  3733. goto err;
  3734. }
  3735. /* Allocate new intro point and extend info. */
  3736. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  3737. info = intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  3738. /* Parse identifier. */
  3739. tok = find_by_keyword(tokens, R_IPO_IDENTIFIER);
  3740. if (base32_decode(info->identity_digest, DIGEST_LEN,
  3741. tok->args[0], REND_INTRO_POINT_ID_LEN_BASE32) < 0) {
  3742. log_warn(LD_REND, "Identity digest contains illegal characters: %s",
  3743. tok->args[0]);
  3744. rend_intro_point_free(intro);
  3745. goto err;
  3746. }
  3747. /* Write identifier to nickname. */
  3748. info->nickname[0] = '$';
  3749. base16_encode(info->nickname + 1, sizeof(info->nickname) - 1,
  3750. info->identity_digest, DIGEST_LEN);
  3751. /* Parse IP address. */
  3752. tok = find_by_keyword(tokens, R_IPO_IP_ADDRESS);
  3753. if (tor_addr_parse(&info->addr, tok->args[0])<0) {
  3754. log_warn(LD_REND, "Could not parse introduction point address.");
  3755. rend_intro_point_free(intro);
  3756. goto err;
  3757. }
  3758. if (tor_addr_family(&info->addr) != AF_INET) {
  3759. log_warn(LD_REND, "Introduction point address was not ipv4.");
  3760. rend_intro_point_free(intro);
  3761. goto err;
  3762. }
  3763. /* Parse onion port. */
  3764. tok = find_by_keyword(tokens, R_IPO_ONION_PORT);
  3765. info->port = (uint16_t) tor_parse_long(tok->args[0],10,1,65535,
  3766. &num_ok,NULL);
  3767. if (!info->port || !num_ok) {
  3768. log_warn(LD_REND, "Introduction point onion port %s is invalid",
  3769. escaped(tok->args[0]));
  3770. rend_intro_point_free(intro);
  3771. goto err;
  3772. }
  3773. /* Parse onion key. */
  3774. tok = find_by_keyword(tokens, R_IPO_ONION_KEY);
  3775. if (!crypto_pk_public_exponent_ok(tok->key)) {
  3776. log_warn(LD_REND,
  3777. "Introduction point's onion key had invalid exponent.");
  3778. rend_intro_point_free(intro);
  3779. goto err;
  3780. }
  3781. info->onion_key = tok->key;
  3782. tok->key = NULL; /* Prevent free */
  3783. /* Parse service key. */
  3784. tok = find_by_keyword(tokens, R_IPO_SERVICE_KEY);
  3785. if (!crypto_pk_public_exponent_ok(tok->key)) {
  3786. log_warn(LD_REND,
  3787. "Introduction point key had invalid exponent.");
  3788. rend_intro_point_free(intro);
  3789. goto err;
  3790. }
  3791. intro->intro_key = tok->key;
  3792. tok->key = NULL; /* Prevent free */
  3793. /* Add extend info to list of introduction points. */
  3794. smartlist_add(parsed->intro_nodes, intro);
  3795. }
  3796. result = smartlist_len(parsed->intro_nodes);
  3797. goto done;
  3798. err:
  3799. result = -1;
  3800. done:
  3801. /* Free tokens and clear token list. */
  3802. if (tokens) {
  3803. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  3804. smartlist_free(tokens);
  3805. }
  3806. if (area)
  3807. memarea_drop_all(area);
  3808. return result;
  3809. }
  3810. /** Parse the content of a client_key file in <b>ckstr</b> and add
  3811. * rend_authorized_client_t's for each parsed client to
  3812. * <b>parsed_clients</b>. Return the number of parsed clients as result
  3813. * or -1 for failure. */
  3814. int
  3815. rend_parse_client_keys(strmap_t *parsed_clients, const char *ckstr)
  3816. {
  3817. int result = -1;
  3818. smartlist_t *tokens;
  3819. directory_token_t *tok;
  3820. const char *current_entry = NULL;
  3821. memarea_t *area = NULL;
  3822. char *err_msg = NULL;
  3823. if (!ckstr || strlen(ckstr) == 0)
  3824. return -1;
  3825. tokens = smartlist_new();
  3826. /* Begin parsing with first entry, skipping comments or whitespace at the
  3827. * beginning. */
  3828. area = memarea_new();
  3829. current_entry = eat_whitespace(ckstr);
  3830. while (!strcmpstart(current_entry, "client-name ")) {
  3831. rend_authorized_client_t *parsed_entry;
  3832. /* Determine end of string. */
  3833. const char *eos = strstr(current_entry, "\nclient-name ");
  3834. if (!eos)
  3835. eos = current_entry + strlen(current_entry);
  3836. else
  3837. eos = eos + 1;
  3838. /* Free tokens and clear token list. */
  3839. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  3840. smartlist_clear(tokens);
  3841. memarea_clear(area);
  3842. /* Tokenize string. */
  3843. if (tokenize_string(area, current_entry, eos, tokens,
  3844. client_keys_token_table, 0)) {
  3845. log_warn(LD_REND, "Error tokenizing client keys file.");
  3846. goto err;
  3847. }
  3848. /* Advance to next entry, if available. */
  3849. current_entry = eos;
  3850. /* Check minimum allowed length of token list. */
  3851. if (smartlist_len(tokens) < 2) {
  3852. log_warn(LD_REND, "Impossibly short client key entry.");
  3853. goto err;
  3854. }
  3855. /* Parse client name. */
  3856. tok = find_by_keyword(tokens, C_CLIENT_NAME);
  3857. tor_assert(tok == smartlist_get(tokens, 0));
  3858. tor_assert(tok->n_args == 1);
  3859. if (!rend_valid_client_name(tok->args[0])) {
  3860. log_warn(LD_CONFIG, "Illegal client name: %s. (Length must be "
  3861. "between 1 and %d, and valid characters are "
  3862. "[A-Za-z0-9+-_].)", tok->args[0], REND_CLIENTNAME_MAX_LEN);
  3863. goto err;
  3864. }
  3865. /* Check if client name is duplicate. */
  3866. if (strmap_get(parsed_clients, tok->args[0])) {
  3867. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains a "
  3868. "duplicate client name: '%s'. Ignoring.", tok->args[0]);
  3869. goto err;
  3870. }
  3871. parsed_entry = tor_malloc_zero(sizeof(rend_authorized_client_t));
  3872. parsed_entry->client_name = tor_strdup(tok->args[0]);
  3873. strmap_set(parsed_clients, parsed_entry->client_name, parsed_entry);
  3874. /* Parse client key. */
  3875. tok = find_opt_by_keyword(tokens, C_CLIENT_KEY);
  3876. if (tok) {
  3877. parsed_entry->client_key = tok->key;
  3878. tok->key = NULL; /* Prevent free */
  3879. }
  3880. /* Parse descriptor cookie. */
  3881. tok = find_by_keyword(tokens, C_DESCRIPTOR_COOKIE);
  3882. tor_assert(tok->n_args == 1);
  3883. if (rend_auth_decode_cookie(tok->args[0], parsed_entry->descriptor_cookie,
  3884. NULL, &err_msg) < 0) {
  3885. tor_assert(err_msg);
  3886. log_warn(LD_REND, "%s", err_msg);
  3887. tor_free(err_msg);
  3888. goto err;
  3889. }
  3890. }
  3891. result = strmap_size(parsed_clients);
  3892. goto done;
  3893. err:
  3894. result = -1;
  3895. done:
  3896. /* Free tokens and clear token list. */
  3897. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  3898. smartlist_free(tokens);
  3899. if (area)
  3900. memarea_drop_all(area);
  3901. return result;
  3902. }
  3903. /** Called on startup; right now we just handle scanning the unparseable
  3904. * descriptor dumps, but hang anything else we might need to do in the
  3905. * future here as well.
  3906. */
  3907. void
  3908. routerparse_init(void)
  3909. {
  3910. /*
  3911. * Check both if the sandbox is active and whether it's configured; no
  3912. * point in loading all that if we won't be able to use it after the
  3913. * sandbox becomes active.
  3914. */
  3915. if (!(sandbox_is_active() || get_options()->Sandbox)) {
  3916. dump_desc_init();
  3917. }
  3918. }
  3919. /** Clean up all data structures used by routerparse.c at exit */
  3920. void
  3921. routerparse_free_all(void)
  3922. {
  3923. dump_desc_fifo_cleanup();
  3924. }