routerparse.c 177 KB

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