routerparse.c 196 KB

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