routerparse.c 167 KB

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