routerparse.c 195 KB

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