routerparse.c 217 KB

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