routerparse.c 176 KB

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