routerparse.c 205 KB

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