routerparse.c 168 KB

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