routerparse.c 196 KB

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