routerparse.c 193 KB

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