routerparse.c 174 KB

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