routerparse.c 196 KB

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