routerparse.c 197 KB

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