routerparse.c 168 KB

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