routerparse.c 211 KB

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