routerparse.c 210 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202
  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. time_t expires = TIME_MAX;
  1829. if (tor_cert_get_checkable_sig(&check[0], cert, NULL, &expires) < 0) {
  1830. log_err(LD_BUG, "Couldn't create 'checkable' for cert.");
  1831. goto err;
  1832. }
  1833. if (tor_cert_get_checkable_sig(&check[1],
  1834. ntor_cc_cert, &ntor_cc_pk, &expires) < 0) {
  1835. log_err(LD_BUG, "Couldn't create 'checkable' for ntor_cc_cert.");
  1836. goto err;
  1837. }
  1838. if (ed25519_signature_from_base64(&check[2].signature,
  1839. ed_sig_tok->args[0])<0) {
  1840. log_warn(LD_DIR, "Couldn't decode ed25519 signature");
  1841. goto err;
  1842. }
  1843. check[2].pubkey = &cert->signed_key;
  1844. check[2].msg = d256;
  1845. check[2].len = DIGEST256_LEN;
  1846. if (ed25519_checksig_batch(check_ok, check, 3) < 0) {
  1847. log_warn(LD_DIR, "Incorrect ed25519 signature(s)");
  1848. goto err;
  1849. }
  1850. if (check_tap_onion_key_crosscert(
  1851. (const uint8_t*)cc_tap_tok->object_body,
  1852. (int)cc_tap_tok->object_size,
  1853. router->onion_pkey,
  1854. &cert->signing_key,
  1855. (const uint8_t*)router->cache_info.identity_digest)<0) {
  1856. log_warn(LD_DIR, "Incorrect TAP cross-verification");
  1857. goto err;
  1858. }
  1859. /* We check this before adding it to the routerlist. */
  1860. router->cert_expiration_time = expires;
  1861. }
  1862. }
  1863. if ((tok = find_opt_by_keyword(tokens, K_FINGERPRINT))) {
  1864. /* If there's a fingerprint line, it must match the identity digest. */
  1865. char d[DIGEST_LEN];
  1866. tor_assert(tok->n_args == 1);
  1867. tor_strstrip(tok->args[0], " ");
  1868. if (base16_decode(d, DIGEST_LEN,
  1869. tok->args[0], strlen(tok->args[0])) != DIGEST_LEN) {
  1870. log_warn(LD_DIR, "Couldn't decode router fingerprint %s",
  1871. escaped(tok->args[0]));
  1872. goto err;
  1873. }
  1874. if (tor_memneq(d,router->cache_info.identity_digest, DIGEST_LEN)) {
  1875. log_warn(LD_DIR, "Fingerprint '%s' does not match identity digest.",
  1876. tok->args[0]);
  1877. goto err;
  1878. }
  1879. }
  1880. if ((tok = find_opt_by_keyword(tokens, K_PLATFORM))) {
  1881. router->platform = tor_strdup(tok->args[0]);
  1882. }
  1883. if ((tok = find_opt_by_keyword(tokens, K_CONTACT))) {
  1884. router->contact_info = tor_strdup(tok->args[0]);
  1885. }
  1886. if (find_opt_by_keyword(tokens, K_REJECT6) ||
  1887. find_opt_by_keyword(tokens, K_ACCEPT6)) {
  1888. log_warn(LD_DIR, "Rejecting router with reject6/accept6 line: they crash "
  1889. "older Tors.");
  1890. goto err;
  1891. }
  1892. {
  1893. smartlist_t *or_addresses = find_all_by_keyword(tokens, K_OR_ADDRESS);
  1894. if (or_addresses) {
  1895. find_single_ipv6_orport(or_addresses, &router->ipv6_addr,
  1896. &router->ipv6_orport);
  1897. smartlist_free(or_addresses);
  1898. }
  1899. }
  1900. exit_policy_tokens = find_all_exitpolicy(tokens);
  1901. if (!smartlist_len(exit_policy_tokens)) {
  1902. log_warn(LD_DIR, "No exit policy tokens in descriptor.");
  1903. goto err;
  1904. }
  1905. SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
  1906. if (router_add_exit_policy(router,t)<0) {
  1907. log_warn(LD_DIR,"Error in exit policy");
  1908. goto err;
  1909. });
  1910. policy_expand_private(&router->exit_policy);
  1911. if ((tok = find_opt_by_keyword(tokens, K_IPV6_POLICY)) && tok->n_args) {
  1912. router->ipv6_exit_policy = parse_short_policy(tok->args[0]);
  1913. if (! router->ipv6_exit_policy) {
  1914. log_warn(LD_DIR , "Error in ipv6-policy %s", escaped(tok->args[0]));
  1915. goto err;
  1916. }
  1917. }
  1918. if (policy_is_reject_star(router->exit_policy, AF_INET) &&
  1919. (!router->ipv6_exit_policy ||
  1920. short_policy_is_reject_star(router->ipv6_exit_policy)))
  1921. router->policy_is_reject_star = 1;
  1922. if ((tok = find_opt_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
  1923. int i;
  1924. router->declared_family = smartlist_new();
  1925. for (i=0;i<tok->n_args;++i) {
  1926. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  1927. log_warn(LD_DIR, "Illegal nickname %s in family line",
  1928. escaped(tok->args[i]));
  1929. goto err;
  1930. }
  1931. smartlist_add(router->declared_family, tor_strdup(tok->args[i]));
  1932. }
  1933. }
  1934. if (find_opt_by_keyword(tokens, K_CACHES_EXTRA_INFO))
  1935. router->caches_extra_info = 1;
  1936. if (find_opt_by_keyword(tokens, K_ALLOW_SINGLE_HOP_EXITS))
  1937. router->allow_single_hop_exits = 1;
  1938. if ((tok = find_opt_by_keyword(tokens, K_EXTRA_INFO_DIGEST))) {
  1939. tor_assert(tok->n_args >= 1);
  1940. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  1941. if (base16_decode(router->cache_info.extra_info_digest, DIGEST_LEN,
  1942. tok->args[0], HEX_DIGEST_LEN) != DIGEST_LEN) {
  1943. log_warn(LD_DIR,"Invalid extra info digest");
  1944. }
  1945. } else {
  1946. log_warn(LD_DIR, "Invalid extra info digest %s", escaped(tok->args[0]));
  1947. }
  1948. if (tok->n_args >= 2) {
  1949. if (digest256_from_base64(router->cache_info.extra_info_digest256,
  1950. tok->args[1]) < 0) {
  1951. log_warn(LD_DIR, "Invalid extra info digest256 %s",
  1952. escaped(tok->args[1]));
  1953. }
  1954. }
  1955. }
  1956. if (find_opt_by_keyword(tokens, K_HIDDEN_SERVICE_DIR)) {
  1957. router->wants_to_be_hs_dir = 1;
  1958. }
  1959. /* This router accepts tunnelled directory requests via begindir if it has
  1960. * an open dirport or it included "tunnelled-dir-server". */
  1961. if (find_opt_by_keyword(tokens, K_DIR_TUNNELLED) || router->dir_port > 0) {
  1962. router->supports_tunnelled_dir_requests = 1;
  1963. }
  1964. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1965. note_crypto_pk_op(VERIFY_RTR);
  1966. #ifdef COUNT_DISTINCT_DIGESTS
  1967. if (!verified_digests)
  1968. verified_digests = digestmap_new();
  1969. digestmap_set(verified_digests, signed_digest, (void*)(uintptr_t)1);
  1970. #endif
  1971. if (!router->or_port) {
  1972. log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
  1973. goto err;
  1974. }
  1975. /* We've checked everything that's covered by the hash. */
  1976. can_dl_again = 1;
  1977. if (check_signature_token(digest, DIGEST_LEN, tok, router->identity_pkey, 0,
  1978. "router descriptor") < 0)
  1979. goto err;
  1980. if (!router->platform) {
  1981. router->platform = tor_strdup("<unknown>");
  1982. }
  1983. goto done;
  1984. err:
  1985. dump_desc(s_dup, "router descriptor");
  1986. routerinfo_free(router);
  1987. router = NULL;
  1988. done:
  1989. tor_cert_free(ntor_cc_cert);
  1990. if (tokens) {
  1991. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1992. smartlist_free(tokens);
  1993. }
  1994. smartlist_free(exit_policy_tokens);
  1995. if (area) {
  1996. DUMP_AREA(area, "routerinfo");
  1997. memarea_drop_all(area);
  1998. }
  1999. if (can_dl_again_out)
  2000. *can_dl_again_out = can_dl_again;
  2001. return router;
  2002. }
  2003. /** Parse a single extrainfo entry from the string <b>s</b>, ending at
  2004. * <b>end</b>. (If <b>end</b> is NULL, parse up to the end of <b>s</b>.) If
  2005. * <b>cache_copy</b> is true, make a copy of the extra-info document in the
  2006. * cache_info fields of the result. If <b>routermap</b> is provided, use it
  2007. * as a map from router identity to routerinfo_t when looking up signing keys.
  2008. *
  2009. * If <b>can_dl_again_out</b> is provided, set *<b>can_dl_again_out</b> to 1
  2010. * if it's okay to try to download an extrainfo with this same digest again,
  2011. * and 0 if it isn't. (It might not be okay to download it again if part of
  2012. * the part covered by the digest is invalid.)
  2013. */
  2014. extrainfo_t *
  2015. extrainfo_parse_entry_from_string(const char *s, const char *end,
  2016. int cache_copy, struct digest_ri_map_t *routermap,
  2017. int *can_dl_again_out)
  2018. {
  2019. extrainfo_t *extrainfo = NULL;
  2020. char digest[128];
  2021. smartlist_t *tokens = NULL;
  2022. directory_token_t *tok;
  2023. crypto_pk_t *key = NULL;
  2024. routerinfo_t *router = NULL;
  2025. memarea_t *area = NULL;
  2026. const char *s_dup = s;
  2027. /* Do not set this to '1' until we have parsed everything that we intend to
  2028. * parse that's covered by the hash. */
  2029. int can_dl_again = 0;
  2030. if (!end) {
  2031. end = s + strlen(s);
  2032. }
  2033. /* point 'end' to a point immediately after the final newline. */
  2034. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  2035. --end;
  2036. if (router_get_extrainfo_hash(s, end-s, digest) < 0) {
  2037. log_warn(LD_DIR, "Couldn't compute router hash.");
  2038. goto err;
  2039. }
  2040. tokens = smartlist_new();
  2041. area = memarea_new();
  2042. if (tokenize_string(area,s,end,tokens,extrainfo_token_table,0)) {
  2043. log_warn(LD_DIR, "Error tokenizing extra-info document.");
  2044. goto err;
  2045. }
  2046. if (smartlist_len(tokens) < 2) {
  2047. log_warn(LD_DIR, "Impossibly short extra-info document.");
  2048. goto err;
  2049. }
  2050. /* XXXX Accept this in position 1 too, and ed identity in position 0. */
  2051. tok = smartlist_get(tokens,0);
  2052. if (tok->tp != K_EXTRA_INFO) {
  2053. log_warn(LD_DIR,"Entry does not start with \"extra-info\"");
  2054. goto err;
  2055. }
  2056. extrainfo = tor_malloc_zero(sizeof(extrainfo_t));
  2057. extrainfo->cache_info.is_extrainfo = 1;
  2058. if (cache_copy)
  2059. extrainfo->cache_info.signed_descriptor_body = tor_memdup_nulterm(s,end-s);
  2060. extrainfo->cache_info.signed_descriptor_len = end-s;
  2061. memcpy(extrainfo->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  2062. crypto_digest256((char*)extrainfo->digest256, s, end-s, DIGEST_SHA256);
  2063. tor_assert(tok->n_args >= 2);
  2064. if (!is_legal_nickname(tok->args[0])) {
  2065. log_warn(LD_DIR,"Bad nickname %s on \"extra-info\"",escaped(tok->args[0]));
  2066. goto err;
  2067. }
  2068. strlcpy(extrainfo->nickname, tok->args[0], sizeof(extrainfo->nickname));
  2069. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  2070. base16_decode(extrainfo->cache_info.identity_digest, DIGEST_LEN,
  2071. tok->args[1], HEX_DIGEST_LEN) != DIGEST_LEN) {
  2072. log_warn(LD_DIR,"Invalid fingerprint %s on \"extra-info\"",
  2073. escaped(tok->args[1]));
  2074. goto err;
  2075. }
  2076. tok = find_by_keyword(tokens, K_PUBLISHED);
  2077. if (parse_iso_time(tok->args[0], &extrainfo->cache_info.published_on)) {
  2078. log_warn(LD_DIR,"Invalid published time %s on \"extra-info\"",
  2079. escaped(tok->args[0]));
  2080. goto err;
  2081. }
  2082. {
  2083. directory_token_t *ed_sig_tok, *ed_cert_tok;
  2084. ed_sig_tok = find_opt_by_keyword(tokens, K_ROUTER_SIG_ED25519);
  2085. ed_cert_tok = find_opt_by_keyword(tokens, K_IDENTITY_ED25519);
  2086. int n_ed_toks = !!ed_sig_tok + !!ed_cert_tok;
  2087. if (n_ed_toks != 0 && n_ed_toks != 2) {
  2088. log_warn(LD_DIR, "Router descriptor with only partial ed25519/"
  2089. "cross-certification support");
  2090. goto err;
  2091. }
  2092. if (ed_sig_tok) {
  2093. tor_assert(ed_cert_tok);
  2094. const int ed_cert_token_pos = smartlist_pos(tokens, ed_cert_tok);
  2095. if (ed_cert_token_pos != 1) {
  2096. /* Accept this in position 0 XXXX */
  2097. log_warn(LD_DIR, "Ed25519 certificate in wrong position");
  2098. goto err;
  2099. }
  2100. if (ed_sig_tok != smartlist_get(tokens, smartlist_len(tokens)-2)) {
  2101. log_warn(LD_DIR, "Ed25519 signature in wrong position");
  2102. goto err;
  2103. }
  2104. if (strcmp(ed_cert_tok->object_type, "ED25519 CERT")) {
  2105. log_warn(LD_DIR, "Wrong object type on identity-ed25519 in decriptor");
  2106. goto err;
  2107. }
  2108. uint8_t d256[DIGEST256_LEN];
  2109. const char *signed_start, *signed_end;
  2110. tor_cert_t *cert = tor_cert_parse(
  2111. (const uint8_t*)ed_cert_tok->object_body,
  2112. ed_cert_tok->object_size);
  2113. if (! cert) {
  2114. log_warn(LD_DIR, "Couldn't parse ed25519 cert");
  2115. goto err;
  2116. }
  2117. /* makes sure it gets freed. */
  2118. extrainfo->cache_info.signing_key_cert = cert;
  2119. if (cert->cert_type != CERT_TYPE_ID_SIGNING ||
  2120. ! cert->signing_key_included) {
  2121. log_warn(LD_DIR, "Invalid form for ed25519 cert");
  2122. goto err;
  2123. }
  2124. if (router_get_hash_impl_helper(s, end-s, "extra-info ",
  2125. "\nrouter-sig-ed25519",
  2126. ' ', &signed_start, &signed_end) < 0) {
  2127. log_warn(LD_DIR, "Can't find ed25519-signed portion of extrainfo");
  2128. goto err;
  2129. }
  2130. crypto_digest_t *d = crypto_digest256_new(DIGEST_SHA256);
  2131. crypto_digest_add_bytes(d, ED_DESC_SIGNATURE_PREFIX,
  2132. strlen(ED_DESC_SIGNATURE_PREFIX));
  2133. crypto_digest_add_bytes(d, signed_start, signed_end-signed_start);
  2134. crypto_digest_get_digest(d, (char*)d256, sizeof(d256));
  2135. crypto_digest_free(d);
  2136. ed25519_checkable_t check[2];
  2137. int check_ok[2];
  2138. if (tor_cert_get_checkable_sig(&check[0], cert, NULL, NULL) < 0) {
  2139. log_err(LD_BUG, "Couldn't create 'checkable' for cert.");
  2140. goto err;
  2141. }
  2142. if (ed25519_signature_from_base64(&check[1].signature,
  2143. ed_sig_tok->args[0])<0) {
  2144. log_warn(LD_DIR, "Couldn't decode ed25519 signature");
  2145. goto err;
  2146. }
  2147. check[1].pubkey = &cert->signed_key;
  2148. check[1].msg = d256;
  2149. check[1].len = DIGEST256_LEN;
  2150. if (ed25519_checksig_batch(check_ok, check, 2) < 0) {
  2151. log_warn(LD_DIR, "Incorrect ed25519 signature(s)");
  2152. goto err;
  2153. }
  2154. /* We don't check the certificate expiration time: checking that it
  2155. * matches the cert in the router descriptor is adequate. */
  2156. }
  2157. }
  2158. /* We've checked everything that's covered by the hash. */
  2159. can_dl_again = 1;
  2160. if (routermap &&
  2161. (router = digestmap_get((digestmap_t*)routermap,
  2162. extrainfo->cache_info.identity_digest))) {
  2163. key = router->identity_pkey;
  2164. }
  2165. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  2166. if (strcmp(tok->object_type, "SIGNATURE") ||
  2167. tok->object_size < 128 || tok->object_size > 512) {
  2168. log_warn(LD_DIR, "Bad object type or length on extra-info signature");
  2169. goto err;
  2170. }
  2171. if (key) {
  2172. note_crypto_pk_op(VERIFY_RTR);
  2173. if (check_signature_token(digest, DIGEST_LEN, tok, key, 0,
  2174. "extra-info") < 0)
  2175. goto err;
  2176. if (router)
  2177. extrainfo->cache_info.send_unencrypted =
  2178. router->cache_info.send_unencrypted;
  2179. } else {
  2180. extrainfo->pending_sig = tor_memdup(tok->object_body,
  2181. tok->object_size);
  2182. extrainfo->pending_sig_len = tok->object_size;
  2183. }
  2184. goto done;
  2185. err:
  2186. dump_desc(s_dup, "extra-info descriptor");
  2187. extrainfo_free(extrainfo);
  2188. extrainfo = NULL;
  2189. done:
  2190. if (tokens) {
  2191. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2192. smartlist_free(tokens);
  2193. }
  2194. if (area) {
  2195. DUMP_AREA(area, "extrainfo");
  2196. memarea_drop_all(area);
  2197. }
  2198. if (can_dl_again_out)
  2199. *can_dl_again_out = can_dl_again;
  2200. return extrainfo;
  2201. }
  2202. /** Parse a key certificate from <b>s</b>; point <b>end-of-string</b> to
  2203. * the first character after the certificate. */
  2204. authority_cert_t *
  2205. authority_cert_parse_from_string(const char *s, const char **end_of_string)
  2206. {
  2207. /** Reject any certificate at least this big; it is probably an overflow, an
  2208. * attack, a bug, or some other nonsense. */
  2209. #define MAX_CERT_SIZE (128*1024)
  2210. authority_cert_t *cert = NULL, *old_cert;
  2211. smartlist_t *tokens = NULL;
  2212. char digest[DIGEST_LEN];
  2213. directory_token_t *tok;
  2214. char fp_declared[DIGEST_LEN];
  2215. char *eos;
  2216. size_t len;
  2217. int found;
  2218. memarea_t *area = NULL;
  2219. const char *s_dup = s;
  2220. s = eat_whitespace(s);
  2221. eos = strstr(s, "\ndir-key-certification");
  2222. if (! eos) {
  2223. log_warn(LD_DIR, "No signature found on key certificate");
  2224. return NULL;
  2225. }
  2226. eos = strstr(eos, "\n-----END SIGNATURE-----\n");
  2227. if (! eos) {
  2228. log_warn(LD_DIR, "No end-of-signature found on key certificate");
  2229. return NULL;
  2230. }
  2231. eos = strchr(eos+2, '\n');
  2232. tor_assert(eos);
  2233. ++eos;
  2234. len = eos - s;
  2235. if (len > MAX_CERT_SIZE) {
  2236. log_warn(LD_DIR, "Certificate is far too big (at %lu bytes long); "
  2237. "rejecting", (unsigned long)len);
  2238. return NULL;
  2239. }
  2240. tokens = smartlist_new();
  2241. area = memarea_new();
  2242. if (tokenize_string(area,s, eos, tokens, dir_key_certificate_table, 0) < 0) {
  2243. log_warn(LD_DIR, "Error tokenizing key certificate");
  2244. goto err;
  2245. }
  2246. if (router_get_hash_impl(s, strlen(s), digest, "dir-key-certificate-version",
  2247. "\ndir-key-certification", '\n', DIGEST_SHA1) < 0)
  2248. goto err;
  2249. tok = smartlist_get(tokens, 0);
  2250. if (tok->tp != K_DIR_KEY_CERTIFICATE_VERSION || strcmp(tok->args[0], "3")) {
  2251. log_warn(LD_DIR,
  2252. "Key certificate does not begin with a recognized version (3).");
  2253. goto err;
  2254. }
  2255. cert = tor_malloc_zero(sizeof(authority_cert_t));
  2256. memcpy(cert->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  2257. tok = find_by_keyword(tokens, K_DIR_SIGNING_KEY);
  2258. tor_assert(tok->key);
  2259. cert->signing_key = tok->key;
  2260. tok->key = NULL;
  2261. if (crypto_pk_get_digest(cert->signing_key, cert->signing_key_digest))
  2262. goto err;
  2263. tok = find_by_keyword(tokens, K_DIR_IDENTITY_KEY);
  2264. tor_assert(tok->key);
  2265. cert->identity_key = tok->key;
  2266. tok->key = NULL;
  2267. tok = find_by_keyword(tokens, K_FINGERPRINT);
  2268. tor_assert(tok->n_args);
  2269. if (base16_decode(fp_declared, DIGEST_LEN, tok->args[0],
  2270. strlen(tok->args[0])) != DIGEST_LEN) {
  2271. log_warn(LD_DIR, "Couldn't decode key certificate fingerprint %s",
  2272. escaped(tok->args[0]));
  2273. goto err;
  2274. }
  2275. if (crypto_pk_get_digest(cert->identity_key,
  2276. cert->cache_info.identity_digest))
  2277. goto err;
  2278. if (tor_memneq(cert->cache_info.identity_digest, fp_declared, DIGEST_LEN)) {
  2279. log_warn(LD_DIR, "Digest of certificate key didn't match declared "
  2280. "fingerprint");
  2281. goto err;
  2282. }
  2283. tok = find_opt_by_keyword(tokens, K_DIR_ADDRESS);
  2284. if (tok) {
  2285. struct in_addr in;
  2286. char *address = NULL;
  2287. tor_assert(tok->n_args);
  2288. /* XXX++ use some tor_addr parse function below instead. -RD */
  2289. if (tor_addr_port_split(LOG_WARN, tok->args[0], &address,
  2290. &cert->dir_port) < 0 ||
  2291. tor_inet_aton(address, &in) == 0) {
  2292. log_warn(LD_DIR, "Couldn't parse dir-address in certificate");
  2293. tor_free(address);
  2294. goto err;
  2295. }
  2296. cert->addr = ntohl(in.s_addr);
  2297. tor_free(address);
  2298. }
  2299. tok = find_by_keyword(tokens, K_DIR_KEY_PUBLISHED);
  2300. if (parse_iso_time(tok->args[0], &cert->cache_info.published_on) < 0) {
  2301. goto err;
  2302. }
  2303. tok = find_by_keyword(tokens, K_DIR_KEY_EXPIRES);
  2304. if (parse_iso_time(tok->args[0], &cert->expires) < 0) {
  2305. goto err;
  2306. }
  2307. tok = smartlist_get(tokens, smartlist_len(tokens)-1);
  2308. if (tok->tp != K_DIR_KEY_CERTIFICATION) {
  2309. log_warn(LD_DIR, "Certificate didn't end with dir-key-certification.");
  2310. goto err;
  2311. }
  2312. /* If we already have this cert, don't bother checking the signature. */
  2313. old_cert = authority_cert_get_by_digests(
  2314. cert->cache_info.identity_digest,
  2315. cert->signing_key_digest);
  2316. found = 0;
  2317. if (old_cert) {
  2318. /* XXXX We could just compare signed_descriptor_digest, but that wouldn't
  2319. * buy us much. */
  2320. if (old_cert->cache_info.signed_descriptor_len == len &&
  2321. old_cert->cache_info.signed_descriptor_body &&
  2322. tor_memeq(s, old_cert->cache_info.signed_descriptor_body, len)) {
  2323. log_debug(LD_DIR, "We already checked the signature on this "
  2324. "certificate; no need to do so again.");
  2325. found = 1;
  2326. }
  2327. }
  2328. if (!found) {
  2329. if (check_signature_token(digest, DIGEST_LEN, tok, cert->identity_key, 0,
  2330. "key certificate")) {
  2331. goto err;
  2332. }
  2333. tok = find_by_keyword(tokens, K_DIR_KEY_CROSSCERT);
  2334. if (check_signature_token(cert->cache_info.identity_digest,
  2335. DIGEST_LEN,
  2336. tok,
  2337. cert->signing_key,
  2338. CST_NO_CHECK_OBJTYPE,
  2339. "key cross-certification")) {
  2340. goto err;
  2341. }
  2342. }
  2343. cert->cache_info.signed_descriptor_len = len;
  2344. cert->cache_info.signed_descriptor_body = tor_malloc(len+1);
  2345. memcpy(cert->cache_info.signed_descriptor_body, s, len);
  2346. cert->cache_info.signed_descriptor_body[len] = 0;
  2347. cert->cache_info.saved_location = SAVED_NOWHERE;
  2348. if (end_of_string) {
  2349. *end_of_string = eat_whitespace(eos);
  2350. }
  2351. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2352. smartlist_free(tokens);
  2353. if (area) {
  2354. DUMP_AREA(area, "authority cert");
  2355. memarea_drop_all(area);
  2356. }
  2357. return cert;
  2358. err:
  2359. dump_desc(s_dup, "authority cert");
  2360. authority_cert_free(cert);
  2361. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2362. smartlist_free(tokens);
  2363. if (area) {
  2364. DUMP_AREA(area, "authority cert");
  2365. memarea_drop_all(area);
  2366. }
  2367. return NULL;
  2368. }
  2369. /** Helper: given a string <b>s</b>, return the start of the next router-status
  2370. * object (starting with "r " at the start of a line). If none is found,
  2371. * return the start of the directory footer, or the next directory signature.
  2372. * If none is found, return the end of the string. */
  2373. static inline const char *
  2374. find_start_of_next_routerstatus(const char *s)
  2375. {
  2376. const char *eos, *footer, *sig;
  2377. if ((eos = strstr(s, "\nr ")))
  2378. ++eos;
  2379. else
  2380. eos = s + strlen(s);
  2381. footer = tor_memstr(s, eos-s, "\ndirectory-footer");
  2382. sig = tor_memstr(s, eos-s, "\ndirectory-signature");
  2383. if (footer && sig)
  2384. return MIN(footer, sig) + 1;
  2385. else if (footer)
  2386. return footer+1;
  2387. else if (sig)
  2388. return sig+1;
  2389. else
  2390. return eos;
  2391. }
  2392. /** Parse the GuardFraction string from a consensus or vote.
  2393. *
  2394. * If <b>vote</b> or <b>vote_rs</b> are set the document getting
  2395. * parsed is a vote routerstatus. Otherwise it's a consensus. This is
  2396. * the same semantic as in routerstatus_parse_entry_from_string(). */
  2397. STATIC int
  2398. routerstatus_parse_guardfraction(const char *guardfraction_str,
  2399. networkstatus_t *vote,
  2400. vote_routerstatus_t *vote_rs,
  2401. routerstatus_t *rs)
  2402. {
  2403. int ok;
  2404. const char *end_of_header = NULL;
  2405. int is_consensus = !vote_rs;
  2406. uint32_t guardfraction;
  2407. tor_assert(bool_eq(vote, vote_rs));
  2408. /* If this info comes from a consensus, but we should't apply
  2409. guardfraction, just exit. */
  2410. if (is_consensus && !should_apply_guardfraction(NULL)) {
  2411. return 0;
  2412. }
  2413. end_of_header = strchr(guardfraction_str, '=');
  2414. if (!end_of_header) {
  2415. return -1;
  2416. }
  2417. guardfraction = (uint32_t)tor_parse_ulong(end_of_header+1,
  2418. 10, 0, 100, &ok, NULL);
  2419. if (!ok) {
  2420. log_warn(LD_DIR, "Invalid GuardFraction %s", escaped(guardfraction_str));
  2421. return -1;
  2422. }
  2423. log_debug(LD_GENERAL, "[*] Parsed %s guardfraction '%s' for '%s'.",
  2424. is_consensus ? "consensus" : "vote",
  2425. guardfraction_str, rs->nickname);
  2426. if (!is_consensus) { /* We are parsing a vote */
  2427. vote_rs->status.guardfraction_percentage = guardfraction;
  2428. vote_rs->status.has_guardfraction = 1;
  2429. } else {
  2430. /* We are parsing a consensus. Only apply guardfraction to guards. */
  2431. if (rs->is_possible_guard) {
  2432. rs->guardfraction_percentage = guardfraction;
  2433. rs->has_guardfraction = 1;
  2434. } else {
  2435. log_warn(LD_BUG, "Got GuardFraction for non-guard %s. "
  2436. "This is not supposed to happen. Not applying. ", rs->nickname);
  2437. }
  2438. }
  2439. return 0;
  2440. }
  2441. /** Given a string at *<b>s</b>, containing a routerstatus object, and an
  2442. * empty smartlist at <b>tokens</b>, parse and return the first router status
  2443. * object in the string, and advance *<b>s</b> to just after the end of the
  2444. * router status. Return NULL and advance *<b>s</b> on error.
  2445. *
  2446. * If <b>vote</b> and <b>vote_rs</b> are provided, don't allocate a fresh
  2447. * routerstatus but use <b>vote_rs</b> instead.
  2448. *
  2449. * If <b>consensus_method</b> is nonzero, this routerstatus is part of a
  2450. * consensus, and we should parse it according to the method used to
  2451. * make that consensus.
  2452. *
  2453. * Parse according to the syntax used by the consensus flavor <b>flav</b>.
  2454. **/
  2455. static routerstatus_t *
  2456. routerstatus_parse_entry_from_string(memarea_t *area,
  2457. const char **s, smartlist_t *tokens,
  2458. networkstatus_t *vote,
  2459. vote_routerstatus_t *vote_rs,
  2460. int consensus_method,
  2461. consensus_flavor_t flav)
  2462. {
  2463. const char *eos, *s_dup = *s;
  2464. routerstatus_t *rs = NULL;
  2465. directory_token_t *tok;
  2466. char timebuf[ISO_TIME_LEN+1];
  2467. struct in_addr in;
  2468. int offset = 0;
  2469. tor_assert(tokens);
  2470. tor_assert(bool_eq(vote, vote_rs));
  2471. if (!consensus_method)
  2472. flav = FLAV_NS;
  2473. tor_assert(flav == FLAV_NS || flav == FLAV_MICRODESC);
  2474. eos = find_start_of_next_routerstatus(*s);
  2475. if (tokenize_string(area,*s, eos, tokens, rtrstatus_token_table,0)) {
  2476. log_warn(LD_DIR, "Error tokenizing router status");
  2477. goto err;
  2478. }
  2479. if (smartlist_len(tokens) < 1) {
  2480. log_warn(LD_DIR, "Impossibly short router status");
  2481. goto err;
  2482. }
  2483. tok = find_by_keyword(tokens, K_R);
  2484. tor_assert(tok->n_args >= 7); /* guaranteed by GE(7) in K_R setup */
  2485. if (flav == FLAV_NS) {
  2486. if (tok->n_args < 8) {
  2487. log_warn(LD_DIR, "Too few arguments to r");
  2488. goto err;
  2489. }
  2490. } else if (flav == FLAV_MICRODESC) {
  2491. offset = -1; /* There is no identity digest */
  2492. }
  2493. if (vote_rs) {
  2494. rs = &vote_rs->status;
  2495. } else {
  2496. rs = tor_malloc_zero(sizeof(routerstatus_t));
  2497. }
  2498. if (!is_legal_nickname(tok->args[0])) {
  2499. log_warn(LD_DIR,
  2500. "Invalid nickname %s in router status; skipping.",
  2501. escaped(tok->args[0]));
  2502. goto err;
  2503. }
  2504. strlcpy(rs->nickname, tok->args[0], sizeof(rs->nickname));
  2505. if (digest_from_base64(rs->identity_digest, tok->args[1])) {
  2506. log_warn(LD_DIR, "Error decoding identity digest %s",
  2507. escaped(tok->args[1]));
  2508. goto err;
  2509. }
  2510. if (flav == FLAV_NS) {
  2511. if (digest_from_base64(rs->descriptor_digest, tok->args[2])) {
  2512. log_warn(LD_DIR, "Error decoding descriptor digest %s",
  2513. escaped(tok->args[2]));
  2514. goto err;
  2515. }
  2516. }
  2517. if (tor_snprintf(timebuf, sizeof(timebuf), "%s %s",
  2518. tok->args[3+offset], tok->args[4+offset]) < 0 ||
  2519. parse_iso_time(timebuf, &rs->published_on)<0) {
  2520. log_warn(LD_DIR, "Error parsing time '%s %s' [%d %d]",
  2521. tok->args[3+offset], tok->args[4+offset],
  2522. offset, (int)flav);
  2523. goto err;
  2524. }
  2525. if (tor_inet_aton(tok->args[5+offset], &in) == 0) {
  2526. log_warn(LD_DIR, "Error parsing router address in network-status %s",
  2527. escaped(tok->args[5+offset]));
  2528. goto err;
  2529. }
  2530. rs->addr = ntohl(in.s_addr);
  2531. rs->or_port = (uint16_t) tor_parse_long(tok->args[6+offset],
  2532. 10,0,65535,NULL,NULL);
  2533. rs->dir_port = (uint16_t) tor_parse_long(tok->args[7+offset],
  2534. 10,0,65535,NULL,NULL);
  2535. {
  2536. smartlist_t *a_lines = find_all_by_keyword(tokens, K_A);
  2537. if (a_lines) {
  2538. find_single_ipv6_orport(a_lines, &rs->ipv6_addr, &rs->ipv6_orport);
  2539. smartlist_free(a_lines);
  2540. }
  2541. }
  2542. tok = find_opt_by_keyword(tokens, K_S);
  2543. if (tok && vote) {
  2544. int i;
  2545. vote_rs->flags = 0;
  2546. for (i=0; i < tok->n_args; ++i) {
  2547. int p = smartlist_string_pos(vote->known_flags, tok->args[i]);
  2548. if (p >= 0) {
  2549. vote_rs->flags |= (U64_LITERAL(1)<<p);
  2550. } else {
  2551. log_warn(LD_DIR, "Flags line had a flag %s not listed in known_flags.",
  2552. escaped(tok->args[i]));
  2553. goto err;
  2554. }
  2555. }
  2556. } else if (tok) {
  2557. int i;
  2558. for (i=0; i < tok->n_args; ++i) {
  2559. if (!strcmp(tok->args[i], "Exit"))
  2560. rs->is_exit = 1;
  2561. else if (!strcmp(tok->args[i], "Stable"))
  2562. rs->is_stable = 1;
  2563. else if (!strcmp(tok->args[i], "Fast"))
  2564. rs->is_fast = 1;
  2565. else if (!strcmp(tok->args[i], "Running"))
  2566. rs->is_flagged_running = 1;
  2567. else if (!strcmp(tok->args[i], "Named"))
  2568. rs->is_named = 1;
  2569. else if (!strcmp(tok->args[i], "Valid"))
  2570. rs->is_valid = 1;
  2571. else if (!strcmp(tok->args[i], "Guard"))
  2572. rs->is_possible_guard = 1;
  2573. else if (!strcmp(tok->args[i], "BadExit"))
  2574. rs->is_bad_exit = 1;
  2575. else if (!strcmp(tok->args[i], "Authority"))
  2576. rs->is_authority = 1;
  2577. else if (!strcmp(tok->args[i], "Unnamed") &&
  2578. consensus_method >= 2) {
  2579. /* Unnamed is computed right by consensus method 2 and later. */
  2580. rs->is_unnamed = 1;
  2581. } else if (!strcmp(tok->args[i], "HSDir")) {
  2582. rs->is_hs_dir = 1;
  2583. } else if (!strcmp(tok->args[i], "V2Dir")) {
  2584. rs->is_v2_dir = 1;
  2585. }
  2586. }
  2587. }
  2588. if ((tok = find_opt_by_keyword(tokens, K_V))) {
  2589. tor_assert(tok->n_args == 1);
  2590. rs->version_known = 1;
  2591. if (strcmpstart(tok->args[0], "Tor ")) {
  2592. } else {
  2593. rs->version_supports_extend2_cells =
  2594. tor_version_as_new_as(tok->args[0], "0.2.4.8-alpha");
  2595. }
  2596. if (vote_rs) {
  2597. vote_rs->version = tor_strdup(tok->args[0]);
  2598. }
  2599. }
  2600. /* handle weighting/bandwidth info */
  2601. if ((tok = find_opt_by_keyword(tokens, K_W))) {
  2602. int i;
  2603. for (i=0; i < tok->n_args; ++i) {
  2604. if (!strcmpstart(tok->args[i], "Bandwidth=")) {
  2605. int ok;
  2606. rs->bandwidth_kb =
  2607. (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
  2608. 10, 0, UINT32_MAX,
  2609. &ok, NULL);
  2610. if (!ok) {
  2611. log_warn(LD_DIR, "Invalid Bandwidth %s", escaped(tok->args[i]));
  2612. goto err;
  2613. }
  2614. rs->has_bandwidth = 1;
  2615. } else if (!strcmpstart(tok->args[i], "Measured=") && vote_rs) {
  2616. int ok;
  2617. vote_rs->measured_bw_kb =
  2618. (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
  2619. 10, 0, UINT32_MAX, &ok, NULL);
  2620. if (!ok) {
  2621. log_warn(LD_DIR, "Invalid Measured Bandwidth %s",
  2622. escaped(tok->args[i]));
  2623. goto err;
  2624. }
  2625. vote_rs->has_measured_bw = 1;
  2626. vote->has_measured_bws = 1;
  2627. } else if (!strcmpstart(tok->args[i], "Unmeasured=1")) {
  2628. rs->bw_is_unmeasured = 1;
  2629. } else if (!strcmpstart(tok->args[i], "GuardFraction=")) {
  2630. if (routerstatus_parse_guardfraction(tok->args[i],
  2631. vote, vote_rs, rs) < 0) {
  2632. goto err;
  2633. }
  2634. }
  2635. }
  2636. }
  2637. /* parse exit policy summaries */
  2638. if ((tok = find_opt_by_keyword(tokens, K_P))) {
  2639. tor_assert(tok->n_args == 1);
  2640. if (strcmpstart(tok->args[0], "accept ") &&
  2641. strcmpstart(tok->args[0], "reject ")) {
  2642. log_warn(LD_DIR, "Unknown exit policy summary type %s.",
  2643. escaped(tok->args[0]));
  2644. goto err;
  2645. }
  2646. /* XXX weasel: parse this into ports and represent them somehow smart,
  2647. * maybe not here but somewhere on if we need it for the client.
  2648. * we should still parse it here to check it's valid tho.
  2649. */
  2650. rs->exitsummary = tor_strdup(tok->args[0]);
  2651. rs->has_exitsummary = 1;
  2652. }
  2653. if (vote_rs) {
  2654. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, t) {
  2655. if (t->tp == K_M && t->n_args) {
  2656. vote_microdesc_hash_t *line =
  2657. tor_malloc(sizeof(vote_microdesc_hash_t));
  2658. line->next = vote_rs->microdesc;
  2659. line->microdesc_hash_line = tor_strdup(t->args[0]);
  2660. vote_rs->microdesc = line;
  2661. }
  2662. if (t->tp == K_ID) {
  2663. tor_assert(t->n_args >= 2);
  2664. if (!strcmp(t->args[0], "ed25519")) {
  2665. vote_rs->has_ed25519_listing = 1;
  2666. if (strcmp(t->args[1], "none") &&
  2667. digest256_from_base64((char*)vote_rs->ed25519_id,
  2668. t->args[1])<0) {
  2669. log_warn(LD_DIR, "Bogus ed25519 key in networkstatus vote");
  2670. goto err;
  2671. }
  2672. }
  2673. }
  2674. } SMARTLIST_FOREACH_END(t);
  2675. } else if (flav == FLAV_MICRODESC) {
  2676. tok = find_opt_by_keyword(tokens, K_M);
  2677. if (tok) {
  2678. tor_assert(tok->n_args);
  2679. if (digest256_from_base64(rs->descriptor_digest, tok->args[0])) {
  2680. log_warn(LD_DIR, "Error decoding microdescriptor digest %s",
  2681. escaped(tok->args[0]));
  2682. goto err;
  2683. }
  2684. } else {
  2685. log_info(LD_BUG, "Found an entry in networkstatus with no "
  2686. "microdescriptor digest. (Router %s ($%s) at %s:%d.)",
  2687. rs->nickname, hex_str(rs->identity_digest, DIGEST_LEN),
  2688. fmt_addr32(rs->addr), rs->or_port);
  2689. }
  2690. }
  2691. if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME))
  2692. rs->is_named = 0;
  2693. goto done;
  2694. err:
  2695. dump_desc(s_dup, "routerstatus entry");
  2696. if (rs && !vote_rs)
  2697. routerstatus_free(rs);
  2698. rs = NULL;
  2699. done:
  2700. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2701. smartlist_clear(tokens);
  2702. if (area) {
  2703. DUMP_AREA(area, "routerstatus entry");
  2704. memarea_clear(area);
  2705. }
  2706. *s = eos;
  2707. return rs;
  2708. }
  2709. int
  2710. compare_vote_routerstatus_entries(const void **_a, const void **_b)
  2711. {
  2712. const vote_routerstatus_t *a = *_a, *b = *_b;
  2713. return fast_memcmp(a->status.identity_digest, b->status.identity_digest,
  2714. DIGEST_LEN);
  2715. }
  2716. /** Verify the bandwidth weights of a network status document */
  2717. int
  2718. networkstatus_verify_bw_weights(networkstatus_t *ns, int consensus_method)
  2719. {
  2720. int64_t weight_scale;
  2721. int64_t G=0, M=0, E=0, D=0, T=0;
  2722. double Wgg, Wgm, Wgd, Wmg, Wmm, Wme, Wmd, Weg, Wem, Wee, Wed;
  2723. double Gtotal=0, Mtotal=0, Etotal=0;
  2724. const char *casename = NULL;
  2725. int valid = 1;
  2726. (void) consensus_method;
  2727. weight_scale = networkstatus_get_weight_scale_param(ns);
  2728. Wgg = networkstatus_get_bw_weight(ns, "Wgg", -1);
  2729. Wgm = networkstatus_get_bw_weight(ns, "Wgm", -1);
  2730. Wgd = networkstatus_get_bw_weight(ns, "Wgd", -1);
  2731. Wmg = networkstatus_get_bw_weight(ns, "Wmg", -1);
  2732. Wmm = networkstatus_get_bw_weight(ns, "Wmm", -1);
  2733. Wme = networkstatus_get_bw_weight(ns, "Wme", -1);
  2734. Wmd = networkstatus_get_bw_weight(ns, "Wmd", -1);
  2735. Weg = networkstatus_get_bw_weight(ns, "Weg", -1);
  2736. Wem = networkstatus_get_bw_weight(ns, "Wem", -1);
  2737. Wee = networkstatus_get_bw_weight(ns, "Wee", -1);
  2738. Wed = networkstatus_get_bw_weight(ns, "Wed", -1);
  2739. if (Wgg<0 || Wgm<0 || Wgd<0 || Wmg<0 || Wmm<0 || Wme<0 || Wmd<0 || Weg<0
  2740. || Wem<0 || Wee<0 || Wed<0) {
  2741. log_warn(LD_BUG, "No bandwidth weights produced in consensus!");
  2742. return 0;
  2743. }
  2744. // First, sanity check basic summing properties that hold for all cases
  2745. // We use > 1 as the check for these because they are computed as integers.
  2746. // Sometimes there are rounding errors.
  2747. if (fabs(Wmm - weight_scale) > 1) {
  2748. log_warn(LD_BUG, "Wmm=%f != "I64_FORMAT,
  2749. Wmm, I64_PRINTF_ARG(weight_scale));
  2750. valid = 0;
  2751. }
  2752. if (fabs(Wem - Wee) > 1) {
  2753. log_warn(LD_BUG, "Wem=%f != Wee=%f", Wem, Wee);
  2754. valid = 0;
  2755. }
  2756. if (fabs(Wgm - Wgg) > 1) {
  2757. log_warn(LD_BUG, "Wgm=%f != Wgg=%f", Wgm, Wgg);
  2758. valid = 0;
  2759. }
  2760. if (fabs(Weg - Wed) > 1) {
  2761. log_warn(LD_BUG, "Wed=%f != Weg=%f", Wed, Weg);
  2762. valid = 0;
  2763. }
  2764. if (fabs(Wgg + Wmg - weight_scale) > 0.001*weight_scale) {
  2765. log_warn(LD_BUG, "Wgg=%f != "I64_FORMAT" - Wmg=%f", Wgg,
  2766. I64_PRINTF_ARG(weight_scale), Wmg);
  2767. valid = 0;
  2768. }
  2769. if (fabs(Wee + Wme - weight_scale) > 0.001*weight_scale) {
  2770. log_warn(LD_BUG, "Wee=%f != "I64_FORMAT" - Wme=%f", Wee,
  2771. I64_PRINTF_ARG(weight_scale), Wme);
  2772. valid = 0;
  2773. }
  2774. if (fabs(Wgd + Wmd + Wed - weight_scale) > 0.001*weight_scale) {
  2775. log_warn(LD_BUG, "Wgd=%f + Wmd=%f + Wed=%f != "I64_FORMAT,
  2776. Wgd, Wmd, Wed, I64_PRINTF_ARG(weight_scale));
  2777. valid = 0;
  2778. }
  2779. Wgg /= weight_scale;
  2780. Wgm /= weight_scale;
  2781. Wgd /= weight_scale;
  2782. Wmg /= weight_scale;
  2783. Wmm /= weight_scale;
  2784. Wme /= weight_scale;
  2785. Wmd /= weight_scale;
  2786. Weg /= weight_scale;
  2787. Wem /= weight_scale;
  2788. Wee /= weight_scale;
  2789. Wed /= weight_scale;
  2790. // Then, gather G, M, E, D, T to determine case
  2791. SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) {
  2792. int is_exit = 0;
  2793. /* Bug #2203: Don't count bad exits as exits for balancing */
  2794. is_exit = rs->is_exit && !rs->is_bad_exit;
  2795. if (rs->has_bandwidth) {
  2796. T += rs->bandwidth_kb;
  2797. if (is_exit && rs->is_possible_guard) {
  2798. D += rs->bandwidth_kb;
  2799. Gtotal += Wgd*rs->bandwidth_kb;
  2800. Mtotal += Wmd*rs->bandwidth_kb;
  2801. Etotal += Wed*rs->bandwidth_kb;
  2802. } else if (is_exit) {
  2803. E += rs->bandwidth_kb;
  2804. Mtotal += Wme*rs->bandwidth_kb;
  2805. Etotal += Wee*rs->bandwidth_kb;
  2806. } else if (rs->is_possible_guard) {
  2807. G += rs->bandwidth_kb;
  2808. Gtotal += Wgg*rs->bandwidth_kb;
  2809. Mtotal += Wmg*rs->bandwidth_kb;
  2810. } else {
  2811. M += rs->bandwidth_kb;
  2812. Mtotal += Wmm*rs->bandwidth_kb;
  2813. }
  2814. } else {
  2815. log_warn(LD_BUG, "Missing consensus bandwidth for router %s",
  2816. routerstatus_describe(rs));
  2817. }
  2818. } SMARTLIST_FOREACH_END(rs);
  2819. // Finally, check equality conditions depending upon case 1, 2 or 3
  2820. // Full equality cases: 1, 3b
  2821. // Partial equality cases: 2b (E=G), 3a (M=E)
  2822. // Fully unknown: 2a
  2823. if (3*E >= T && 3*G >= T) {
  2824. // Case 1: Neither are scarce
  2825. casename = "Case 1";
  2826. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  2827. log_warn(LD_DIR,
  2828. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  2829. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2830. " T="I64_FORMAT". "
  2831. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2832. casename, Etotal, Mtotal,
  2833. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2834. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2835. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2836. valid = 0;
  2837. }
  2838. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2839. log_warn(LD_DIR,
  2840. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2841. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2842. " T="I64_FORMAT". "
  2843. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2844. casename, Etotal, Gtotal,
  2845. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2846. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2847. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2848. valid = 0;
  2849. }
  2850. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  2851. log_warn(LD_DIR,
  2852. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  2853. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2854. " T="I64_FORMAT". "
  2855. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2856. casename, Mtotal, Gtotal,
  2857. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2858. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2859. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2860. valid = 0;
  2861. }
  2862. } else if (3*E < T && 3*G < T) {
  2863. int64_t R = MIN(E, G);
  2864. int64_t S = MAX(E, G);
  2865. /*
  2866. * Case 2: Both Guards and Exits are scarce
  2867. * Balance D between E and G, depending upon
  2868. * D capacity and scarcity. Devote no extra
  2869. * bandwidth to middle nodes.
  2870. */
  2871. if (R+D < S) { // Subcase a
  2872. double Rtotal, Stotal;
  2873. if (E < G) {
  2874. Rtotal = Etotal;
  2875. Stotal = Gtotal;
  2876. } else {
  2877. Rtotal = Gtotal;
  2878. Stotal = Etotal;
  2879. }
  2880. casename = "Case 2a";
  2881. // Rtotal < Stotal
  2882. if (Rtotal > Stotal) {
  2883. log_warn(LD_DIR,
  2884. "Bw Weight Failure for %s: Rtotal %f > Stotal %f. "
  2885. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2886. " T="I64_FORMAT". "
  2887. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2888. casename, Rtotal, Stotal,
  2889. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2890. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2891. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2892. valid = 0;
  2893. }
  2894. // Rtotal < T/3
  2895. if (3*Rtotal > T) {
  2896. log_warn(LD_DIR,
  2897. "Bw Weight Failure for %s: 3*Rtotal %f > T "
  2898. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
  2899. " D="I64_FORMAT" T="I64_FORMAT". "
  2900. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2901. casename, Rtotal*3, I64_PRINTF_ARG(T),
  2902. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2903. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2904. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2905. valid = 0;
  2906. }
  2907. // Stotal < T/3
  2908. if (3*Stotal > T) {
  2909. log_warn(LD_DIR,
  2910. "Bw Weight Failure for %s: 3*Stotal %f > T "
  2911. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
  2912. " D="I64_FORMAT" T="I64_FORMAT". "
  2913. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2914. casename, Stotal*3, I64_PRINTF_ARG(T),
  2915. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2916. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2917. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2918. valid = 0;
  2919. }
  2920. // Mtotal > T/3
  2921. if (3*Mtotal < T) {
  2922. log_warn(LD_DIR,
  2923. "Bw Weight Failure for %s: 3*Mtotal %f < T "
  2924. I64_FORMAT". "
  2925. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2926. " T="I64_FORMAT". "
  2927. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2928. casename, Mtotal*3, I64_PRINTF_ARG(T),
  2929. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2930. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2931. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2932. valid = 0;
  2933. }
  2934. } else { // Subcase b: R+D > S
  2935. casename = "Case 2b";
  2936. /* Check the rare-M redirect case. */
  2937. if (D != 0 && 3*M < T) {
  2938. casename = "Case 2b (balanced)";
  2939. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  2940. log_warn(LD_DIR,
  2941. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  2942. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2943. " T="I64_FORMAT". "
  2944. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2945. casename, Etotal, Mtotal,
  2946. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2947. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2948. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2949. valid = 0;
  2950. }
  2951. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2952. log_warn(LD_DIR,
  2953. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2954. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2955. " T="I64_FORMAT". "
  2956. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2957. casename, Etotal, Gtotal,
  2958. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2959. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2960. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2961. valid = 0;
  2962. }
  2963. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  2964. log_warn(LD_DIR,
  2965. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  2966. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2967. " T="I64_FORMAT". "
  2968. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2969. casename, Mtotal, Gtotal,
  2970. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2971. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2972. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2973. valid = 0;
  2974. }
  2975. } else {
  2976. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2977. log_warn(LD_DIR,
  2978. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2979. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2980. " T="I64_FORMAT". "
  2981. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2982. casename, Etotal, Gtotal,
  2983. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2984. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2985. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2986. valid = 0;
  2987. }
  2988. }
  2989. }
  2990. } else { // if (E < T/3 || G < T/3) {
  2991. int64_t S = MIN(E, G);
  2992. int64_t NS = MAX(E, G);
  2993. if (3*(S+D) < T) { // Subcase a:
  2994. double Stotal;
  2995. double NStotal;
  2996. if (G < E) {
  2997. casename = "Case 3a (G scarce)";
  2998. Stotal = Gtotal;
  2999. NStotal = Etotal;
  3000. } else { // if (G >= E) {
  3001. casename = "Case 3a (E scarce)";
  3002. NStotal = Gtotal;
  3003. Stotal = Etotal;
  3004. }
  3005. // Stotal < T/3
  3006. if (3*Stotal > T) {
  3007. log_warn(LD_DIR,
  3008. "Bw Weight Failure for %s: 3*Stotal %f > T "
  3009. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
  3010. " D="I64_FORMAT" T="I64_FORMAT". "
  3011. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  3012. casename, Stotal*3, I64_PRINTF_ARG(T),
  3013. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  3014. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  3015. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  3016. valid = 0;
  3017. }
  3018. if (NS >= M) {
  3019. if (fabs(NStotal-Mtotal) > 0.01*MAX(NStotal,Mtotal)) {
  3020. log_warn(LD_DIR,
  3021. "Bw Weight Failure for %s: NStotal %f != Mtotal %f. "
  3022. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  3023. " T="I64_FORMAT". "
  3024. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  3025. casename, NStotal, Mtotal,
  3026. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  3027. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  3028. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  3029. valid = 0;
  3030. }
  3031. } else {
  3032. // if NS < M, NStotal > T/3 because only one of G or E is scarce
  3033. if (3*NStotal < T) {
  3034. log_warn(LD_DIR,
  3035. "Bw Weight Failure for %s: 3*NStotal %f < T "
  3036. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT
  3037. " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT". "
  3038. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  3039. casename, NStotal*3, I64_PRINTF_ARG(T),
  3040. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  3041. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  3042. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  3043. valid = 0;
  3044. }
  3045. }
  3046. } else { // Subcase b: S+D >= T/3
  3047. casename = "Case 3b";
  3048. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  3049. log_warn(LD_DIR,
  3050. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  3051. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  3052. " T="I64_FORMAT". "
  3053. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  3054. casename, Etotal, Mtotal,
  3055. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  3056. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  3057. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  3058. valid = 0;
  3059. }
  3060. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  3061. log_warn(LD_DIR,
  3062. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  3063. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  3064. " T="I64_FORMAT". "
  3065. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  3066. casename, Etotal, Gtotal,
  3067. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  3068. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  3069. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  3070. valid = 0;
  3071. }
  3072. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  3073. log_warn(LD_DIR,
  3074. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  3075. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  3076. " T="I64_FORMAT". "
  3077. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  3078. casename, Mtotal, Gtotal,
  3079. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  3080. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  3081. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  3082. valid = 0;
  3083. }
  3084. }
  3085. }
  3086. if (valid)
  3087. log_notice(LD_DIR, "Bandwidth-weight %s is verified and valid.",
  3088. casename);
  3089. return valid;
  3090. }
  3091. /** Parse and extract all SR commits from <b>tokens</b> and place them in
  3092. * <b>ns</b>. */
  3093. static void
  3094. extract_shared_random_commits(networkstatus_t *ns, smartlist_t *tokens)
  3095. {
  3096. smartlist_t *chunks = NULL;
  3097. tor_assert(ns);
  3098. tor_assert(tokens);
  3099. /* Commits are only present in a vote. */
  3100. tor_assert(ns->type == NS_TYPE_VOTE);
  3101. ns->sr_info.commits = smartlist_new();
  3102. smartlist_t *commits = find_all_by_keyword(tokens, K_COMMIT);
  3103. /* It's normal that a vote might contain no commits even if it participates
  3104. * in the SR protocol. Don't treat it as an error. */
  3105. if (commits == NULL) {
  3106. goto end;
  3107. }
  3108. /* Parse the commit. We do NO validation of number of arguments or ordering
  3109. * for forward compatibility, it's the parse commit job to inform us if it's
  3110. * supported or not. */
  3111. chunks = smartlist_new();
  3112. SMARTLIST_FOREACH_BEGIN(commits, directory_token_t *, tok) {
  3113. /* Extract all arguments and put them in the chunks list. */
  3114. for (int i = 0; i < tok->n_args; i++) {
  3115. smartlist_add(chunks, tok->args[i]);
  3116. }
  3117. sr_commit_t *commit = sr_parse_commit(chunks);
  3118. smartlist_clear(chunks);
  3119. if (commit == NULL) {
  3120. /* Get voter identity so we can warn that this dirauth vote contains
  3121. * commit we can't parse. */
  3122. networkstatus_voter_info_t *voter = smartlist_get(ns->voters, 0);
  3123. tor_assert(voter);
  3124. log_warn(LD_DIR, "SR: Unable to parse commit %s from vote of voter %s.",
  3125. escaped(tok->object_body),
  3126. hex_str(voter->identity_digest,
  3127. sizeof(voter->identity_digest)));
  3128. /* Commitment couldn't be parsed. Continue onto the next commit because
  3129. * this one could be unsupported for instance. */
  3130. continue;
  3131. }
  3132. /* Add newly created commit object to the vote. */
  3133. smartlist_add(ns->sr_info.commits, commit);
  3134. } SMARTLIST_FOREACH_END(tok);
  3135. end:
  3136. smartlist_free(chunks);
  3137. smartlist_free(commits);
  3138. }
  3139. /** Check if a shared random value of type <b>srv_type</b> is in
  3140. * <b>tokens</b>. If there is, parse it and set it to <b>srv_out</b>. Return
  3141. * -1 on failure, 0 on success. The resulting srv is allocated on the heap and
  3142. * it's the responsibility of the caller to free it. */
  3143. static int
  3144. extract_one_srv(smartlist_t *tokens, directory_keyword srv_type,
  3145. sr_srv_t **srv_out)
  3146. {
  3147. int ret = -1;
  3148. directory_token_t *tok;
  3149. sr_srv_t *srv = NULL;
  3150. smartlist_t *chunks;
  3151. tor_assert(tokens);
  3152. chunks = smartlist_new();
  3153. tok = find_opt_by_keyword(tokens, srv_type);
  3154. if (!tok) {
  3155. /* That's fine, no SRV is allowed. */
  3156. ret = 0;
  3157. goto end;
  3158. }
  3159. for (int i = 0; i < tok->n_args; i++) {
  3160. smartlist_add(chunks, tok->args[i]);
  3161. }
  3162. srv = sr_parse_srv(chunks);
  3163. if (srv == NULL) {
  3164. log_warn(LD_DIR, "SR: Unparseable SRV %s", escaped(tok->object_body));
  3165. goto end;
  3166. }
  3167. /* All is good. */
  3168. *srv_out = srv;
  3169. ret = 0;
  3170. end:
  3171. smartlist_free(chunks);
  3172. return ret;
  3173. }
  3174. /** Extract any shared random values found in <b>tokens</b> and place them in
  3175. * the networkstatus <b>ns</b>. */
  3176. static void
  3177. extract_shared_random_srvs(networkstatus_t *ns, smartlist_t *tokens)
  3178. {
  3179. const char *voter_identity;
  3180. networkstatus_voter_info_t *voter;
  3181. tor_assert(ns);
  3182. tor_assert(tokens);
  3183. /* Can be only one of them else code flow. */
  3184. tor_assert(ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_CONSENSUS);
  3185. if (ns->type == NS_TYPE_VOTE) {
  3186. voter = smartlist_get(ns->voters, 0);
  3187. tor_assert(voter);
  3188. voter_identity = hex_str(voter->identity_digest,
  3189. sizeof(voter->identity_digest));
  3190. } else {
  3191. /* Consensus has multiple voters so no specific voter. */
  3192. voter_identity = "consensus";
  3193. }
  3194. /* We extract both and on error, everything is stopped because it means
  3195. * the votes is malformed for the shared random value(s). */
  3196. if (extract_one_srv(tokens, K_PREVIOUS_SRV, &ns->sr_info.previous_srv) < 0) {
  3197. log_warn(LD_DIR, "SR: Unable to parse previous SRV from %s",
  3198. voter_identity);
  3199. /* Maybe we have a chance with the current SRV so let's try it anyway. */
  3200. }
  3201. if (extract_one_srv(tokens, K_CURRENT_SRV, &ns->sr_info.current_srv) < 0) {
  3202. log_warn(LD_DIR, "SR: Unable to parse current SRV from %s",
  3203. voter_identity);
  3204. }
  3205. }
  3206. /** Parse a v3 networkstatus vote, opinion, or consensus (depending on
  3207. * ns_type), from <b>s</b>, and return the result. Return NULL on failure. */
  3208. networkstatus_t *
  3209. networkstatus_parse_vote_from_string(const char *s, const char **eos_out,
  3210. networkstatus_type_t ns_type)
  3211. {
  3212. smartlist_t *tokens = smartlist_new();
  3213. smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;
  3214. networkstatus_voter_info_t *voter = NULL;
  3215. networkstatus_t *ns = NULL;
  3216. common_digests_t ns_digests;
  3217. const char *cert, *end_of_header, *end_of_footer, *s_dup = s;
  3218. directory_token_t *tok;
  3219. struct in_addr in;
  3220. int i, inorder, n_signatures = 0;
  3221. memarea_t *area = NULL, *rs_area = NULL;
  3222. consensus_flavor_t flav = FLAV_NS;
  3223. char *last_kwd=NULL;
  3224. tor_assert(s);
  3225. if (eos_out)
  3226. *eos_out = NULL;
  3227. if (router_get_networkstatus_v3_hashes(s, &ns_digests)) {
  3228. log_warn(LD_DIR, "Unable to compute digest of network-status");
  3229. goto err;
  3230. }
  3231. area = memarea_new();
  3232. end_of_header = find_start_of_next_routerstatus(s);
  3233. if (tokenize_string(area, s, end_of_header, tokens,
  3234. (ns_type == NS_TYPE_CONSENSUS) ?
  3235. networkstatus_consensus_token_table :
  3236. networkstatus_token_table, 0)) {
  3237. log_warn(LD_DIR, "Error tokenizing network-status header");
  3238. goto err;
  3239. }
  3240. ns = tor_malloc_zero(sizeof(networkstatus_t));
  3241. memcpy(&ns->digests, &ns_digests, sizeof(ns_digests));
  3242. tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
  3243. tor_assert(tok);
  3244. if (tok->n_args > 1) {
  3245. int flavor = networkstatus_parse_flavor_name(tok->args[1]);
  3246. if (flavor < 0) {
  3247. log_warn(LD_DIR, "Can't parse document with unknown flavor %s",
  3248. escaped(tok->args[1]));
  3249. goto err;
  3250. }
  3251. ns->flavor = flav = flavor;
  3252. }
  3253. if (flav != FLAV_NS && ns_type != NS_TYPE_CONSENSUS) {
  3254. log_warn(LD_DIR, "Flavor found on non-consensus networkstatus.");
  3255. goto err;
  3256. }
  3257. if (ns_type != NS_TYPE_CONSENSUS) {
  3258. const char *end_of_cert = NULL;
  3259. if (!(cert = strstr(s, "\ndir-key-certificate-version")))
  3260. goto err;
  3261. ++cert;
  3262. ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);
  3263. if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)
  3264. goto err;
  3265. }
  3266. tok = find_by_keyword(tokens, K_VOTE_STATUS);
  3267. tor_assert(tok->n_args);
  3268. if (!strcmp(tok->args[0], "vote")) {
  3269. ns->type = NS_TYPE_VOTE;
  3270. } else if (!strcmp(tok->args[0], "consensus")) {
  3271. ns->type = NS_TYPE_CONSENSUS;
  3272. } else if (!strcmp(tok->args[0], "opinion")) {
  3273. ns->type = NS_TYPE_OPINION;
  3274. } else {
  3275. log_warn(LD_DIR, "Unrecognized vote status %s in network-status",
  3276. escaped(tok->args[0]));
  3277. goto err;
  3278. }
  3279. if (ns_type != ns->type) {
  3280. log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus.");
  3281. goto err;
  3282. }
  3283. if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
  3284. tok = find_by_keyword(tokens, K_PUBLISHED);
  3285. if (parse_iso_time(tok->args[0], &ns->published))
  3286. goto err;
  3287. ns->supported_methods = smartlist_new();
  3288. tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHODS);
  3289. if (tok) {
  3290. for (i=0; i < tok->n_args; ++i)
  3291. smartlist_add(ns->supported_methods, tor_strdup(tok->args[i]));
  3292. } else {
  3293. smartlist_add(ns->supported_methods, tor_strdup("1"));
  3294. }
  3295. } else {
  3296. tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHOD);
  3297. if (tok) {
  3298. int num_ok;
  3299. ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX,
  3300. &num_ok, NULL);
  3301. if (!num_ok)
  3302. goto err;
  3303. } else {
  3304. ns->consensus_method = 1;
  3305. }
  3306. }
  3307. tok = find_by_keyword(tokens, K_VALID_AFTER);
  3308. if (parse_iso_time(tok->args[0], &ns->valid_after))
  3309. goto err;
  3310. tok = find_by_keyword(tokens, K_FRESH_UNTIL);
  3311. if (parse_iso_time(tok->args[0], &ns->fresh_until))
  3312. goto err;
  3313. tok = find_by_keyword(tokens, K_VALID_UNTIL);
  3314. if (parse_iso_time(tok->args[0], &ns->valid_until))
  3315. goto err;
  3316. tok = find_by_keyword(tokens, K_VOTING_DELAY);
  3317. tor_assert(tok->n_args >= 2);
  3318. {
  3319. int ok;
  3320. ns->vote_seconds =
  3321. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);
  3322. if (!ok)
  3323. goto err;
  3324. ns->dist_seconds =
  3325. (int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL);
  3326. if (!ok)
  3327. goto err;
  3328. }
  3329. if (ns->valid_after +
  3330. (get_options()->TestingTorNetwork ?
  3331. MIN_VOTE_INTERVAL_TESTING : MIN_VOTE_INTERVAL) > ns->fresh_until) {
  3332. log_warn(LD_DIR, "Vote/consensus freshness interval is too short");
  3333. goto err;
  3334. }
  3335. if (ns->valid_after +
  3336. (get_options()->TestingTorNetwork ?
  3337. MIN_VOTE_INTERVAL_TESTING : MIN_VOTE_INTERVAL)*2 > ns->valid_until) {
  3338. log_warn(LD_DIR, "Vote/consensus liveness interval is too short");
  3339. goto err;
  3340. }
  3341. if (ns->vote_seconds < MIN_VOTE_SECONDS) {
  3342. log_warn(LD_DIR, "Vote seconds is too short");
  3343. goto err;
  3344. }
  3345. if (ns->dist_seconds < MIN_DIST_SECONDS) {
  3346. log_warn(LD_DIR, "Dist seconds is too short");
  3347. goto err;
  3348. }
  3349. if ((tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  3350. ns->client_versions = tor_strdup(tok->args[0]);
  3351. }
  3352. if ((tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS))) {
  3353. ns->server_versions = tor_strdup(tok->args[0]);
  3354. }
  3355. {
  3356. smartlist_t *package_lst = find_all_by_keyword(tokens, K_PACKAGE);
  3357. ns->package_lines = smartlist_new();
  3358. if (package_lst) {
  3359. SMARTLIST_FOREACH(package_lst, directory_token_t *, t,
  3360. smartlist_add(ns->package_lines, tor_strdup(t->args[0])));
  3361. }
  3362. smartlist_free(package_lst);
  3363. }
  3364. tok = find_by_keyword(tokens, K_KNOWN_FLAGS);
  3365. ns->known_flags = smartlist_new();
  3366. inorder = 1;
  3367. for (i = 0; i < tok->n_args; ++i) {
  3368. smartlist_add(ns->known_flags, tor_strdup(tok->args[i]));
  3369. if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) {
  3370. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  3371. inorder = 0;
  3372. }
  3373. }
  3374. if (!inorder) {
  3375. log_warn(LD_DIR, "known-flags not in order");
  3376. goto err;
  3377. }
  3378. if (ns->type != NS_TYPE_CONSENSUS &&
  3379. smartlist_len(ns->known_flags) > MAX_KNOWN_FLAGS_IN_VOTE) {
  3380. /* If we allowed more than 64 flags in votes, then parsing them would make
  3381. * us invoke undefined behavior whenever we used 1<<flagnum to do a
  3382. * bit-shift. This is only for votes and opinions: consensus users don't
  3383. * care about flags they don't recognize, and so don't build a bitfield
  3384. * for them. */
  3385. log_warn(LD_DIR, "Too many known-flags in consensus vote or opinion");
  3386. goto err;
  3387. }
  3388. tok = find_opt_by_keyword(tokens, K_PARAMS);
  3389. if (tok) {
  3390. int any_dups = 0;
  3391. inorder = 1;
  3392. ns->net_params = smartlist_new();
  3393. for (i = 0; i < tok->n_args; ++i) {
  3394. int ok=0;
  3395. char *eq = strchr(tok->args[i], '=');
  3396. size_t eq_pos;
  3397. if (!eq) {
  3398. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  3399. goto err;
  3400. }
  3401. eq_pos = eq-tok->args[i];
  3402. tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
  3403. if (!ok) {
  3404. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  3405. goto err;
  3406. }
  3407. if (i > 0 && strcmp(tok->args[i-1], tok->args[i]) >= 0) {
  3408. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  3409. inorder = 0;
  3410. }
  3411. if (last_kwd && eq_pos == strlen(last_kwd) &&
  3412. fast_memeq(last_kwd, tok->args[i], eq_pos)) {
  3413. log_warn(LD_DIR, "Duplicate value for %s parameter",
  3414. escaped(tok->args[i]));
  3415. any_dups = 1;
  3416. }
  3417. tor_free(last_kwd);
  3418. last_kwd = tor_strndup(tok->args[i], eq_pos);
  3419. smartlist_add(ns->net_params, tor_strdup(tok->args[i]));
  3420. }
  3421. if (!inorder) {
  3422. log_warn(LD_DIR, "params not in order");
  3423. goto err;
  3424. }
  3425. if (any_dups) {
  3426. log_warn(LD_DIR, "Duplicate in parameters");
  3427. goto err;
  3428. }
  3429. }
  3430. ns->voters = smartlist_new();
  3431. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  3432. tok = _tok;
  3433. if (tok->tp == K_DIR_SOURCE) {
  3434. tor_assert(tok->n_args >= 6);
  3435. if (voter)
  3436. smartlist_add(ns->voters, voter);
  3437. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  3438. voter->sigs = smartlist_new();
  3439. if (ns->type != NS_TYPE_CONSENSUS)
  3440. memcpy(voter->vote_digest, ns_digests.d[DIGEST_SHA1], DIGEST_LEN);
  3441. voter->nickname = tor_strdup(tok->args[0]);
  3442. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  3443. base16_decode(voter->identity_digest, sizeof(voter->identity_digest),
  3444. tok->args[1], HEX_DIGEST_LEN)
  3445. != sizeof(voter->identity_digest)) {
  3446. log_warn(LD_DIR, "Error decoding identity digest %s in "
  3447. "network-status document.", escaped(tok->args[1]));
  3448. goto err;
  3449. }
  3450. if (ns->type != NS_TYPE_CONSENSUS &&
  3451. tor_memneq(ns->cert->cache_info.identity_digest,
  3452. voter->identity_digest, DIGEST_LEN)) {
  3453. log_warn(LD_DIR,"Mismatch between identities in certificate and vote");
  3454. goto err;
  3455. }
  3456. if (ns->type != NS_TYPE_CONSENSUS) {
  3457. if (authority_cert_is_blacklisted(ns->cert)) {
  3458. log_warn(LD_DIR, "Rejecting vote signature made with blacklisted "
  3459. "signing key %s",
  3460. hex_str(ns->cert->signing_key_digest, DIGEST_LEN));
  3461. goto err;
  3462. }
  3463. }
  3464. voter->address = tor_strdup(tok->args[2]);
  3465. if (!tor_inet_aton(tok->args[3], &in)) {
  3466. log_warn(LD_DIR, "Error decoding IP address %s in network-status.",
  3467. escaped(tok->args[3]));
  3468. goto err;
  3469. }
  3470. voter->addr = ntohl(in.s_addr);
  3471. int ok;
  3472. voter->dir_port = (uint16_t)
  3473. tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);
  3474. if (!ok)
  3475. goto err;
  3476. voter->or_port = (uint16_t)
  3477. tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);
  3478. if (!ok)
  3479. goto err;
  3480. } else if (tok->tp == K_CONTACT) {
  3481. if (!voter || voter->contact) {
  3482. log_warn(LD_DIR, "contact element is out of place.");
  3483. goto err;
  3484. }
  3485. voter->contact = tor_strdup(tok->args[0]);
  3486. } else if (tok->tp == K_VOTE_DIGEST) {
  3487. tor_assert(ns->type == NS_TYPE_CONSENSUS);
  3488. tor_assert(tok->n_args >= 1);
  3489. if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {
  3490. log_warn(LD_DIR, "vote-digest element is out of place.");
  3491. goto err;
  3492. }
  3493. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  3494. base16_decode(voter->vote_digest, sizeof(voter->vote_digest),
  3495. tok->args[0], HEX_DIGEST_LEN)
  3496. != sizeof(voter->vote_digest)) {
  3497. log_warn(LD_DIR, "Error decoding vote digest %s in "
  3498. "network-status consensus.", escaped(tok->args[0]));
  3499. goto err;
  3500. }
  3501. }
  3502. } SMARTLIST_FOREACH_END(_tok);
  3503. if (voter) {
  3504. smartlist_add(ns->voters, voter);
  3505. voter = NULL;
  3506. }
  3507. if (smartlist_len(ns->voters) == 0) {
  3508. log_warn(LD_DIR, "Missing dir-source elements in a networkstatus.");
  3509. goto err;
  3510. } else if (ns->type != NS_TYPE_CONSENSUS && smartlist_len(ns->voters) != 1) {
  3511. log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus.");
  3512. goto err;
  3513. }
  3514. if (ns->type != NS_TYPE_CONSENSUS &&
  3515. (tok = find_opt_by_keyword(tokens, K_LEGACY_DIR_KEY))) {
  3516. int bad = 1;
  3517. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  3518. networkstatus_voter_info_t *voter_0 = smartlist_get(ns->voters, 0);
  3519. if (base16_decode(voter_0->legacy_id_digest, DIGEST_LEN,
  3520. tok->args[0], HEX_DIGEST_LEN) != DIGEST_LEN)
  3521. bad = 1;
  3522. else
  3523. bad = 0;
  3524. }
  3525. if (bad) {
  3526. log_warn(LD_DIR, "Invalid legacy key digest %s on vote.",
  3527. escaped(tok->args[0]));
  3528. }
  3529. }
  3530. /* If this is a vote document, check if information about the shared
  3531. randomness protocol is included, and extract it. */
  3532. if (ns->type == NS_TYPE_VOTE) {
  3533. /* Does this authority participates in the SR protocol? */
  3534. tok = find_opt_by_keyword(tokens, K_SR_FLAG);
  3535. if (tok) {
  3536. ns->sr_info.participate = 1;
  3537. /* Get the SR commitments and reveals from the vote. */
  3538. extract_shared_random_commits(ns, tokens);
  3539. }
  3540. }
  3541. /* For both a vote and consensus, extract the shared random values. */
  3542. if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_CONSENSUS) {
  3543. extract_shared_random_srvs(ns, tokens);
  3544. }
  3545. /* Parse routerstatus lines. */
  3546. rs_tokens = smartlist_new();
  3547. rs_area = memarea_new();
  3548. s = end_of_header;
  3549. ns->routerstatus_list = smartlist_new();
  3550. while (!strcmpstart(s, "r ")) {
  3551. if (ns->type != NS_TYPE_CONSENSUS) {
  3552. vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  3553. if (routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, ns,
  3554. rs, 0, 0))
  3555. smartlist_add(ns->routerstatus_list, rs);
  3556. else {
  3557. tor_free(rs->version);
  3558. tor_free(rs);
  3559. }
  3560. } else {
  3561. routerstatus_t *rs;
  3562. if ((rs = routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens,
  3563. NULL, NULL,
  3564. ns->consensus_method,
  3565. flav))) {
  3566. /* Use exponential-backoff scheduling when downloading microdescs */
  3567. rs->dl_status.backoff = DL_SCHED_RANDOM_EXPONENTIAL;
  3568. smartlist_add(ns->routerstatus_list, rs);
  3569. }
  3570. }
  3571. }
  3572. for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {
  3573. routerstatus_t *rs1, *rs2;
  3574. if (ns->type != NS_TYPE_CONSENSUS) {
  3575. vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);
  3576. vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);
  3577. rs1 = &a->status; rs2 = &b->status;
  3578. } else {
  3579. rs1 = smartlist_get(ns->routerstatus_list, i-1);
  3580. rs2 = smartlist_get(ns->routerstatus_list, i);
  3581. }
  3582. if (fast_memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN)
  3583. >= 0) {
  3584. log_warn(LD_DIR, "Networkstatus entries not sorted by identity digest");
  3585. goto err;
  3586. }
  3587. }
  3588. if (ns_type != NS_TYPE_CONSENSUS) {
  3589. digest256map_t *ed_id_map = digest256map_new();
  3590. SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, vote_routerstatus_t *,
  3591. vrs) {
  3592. if (! vrs->has_ed25519_listing ||
  3593. tor_mem_is_zero((const char *)vrs->ed25519_id, DIGEST256_LEN))
  3594. continue;
  3595. if (digest256map_get(ed_id_map, vrs->ed25519_id) != NULL) {
  3596. log_warn(LD_DIR, "Vote networkstatus ed25519 identities were not "
  3597. "unique");
  3598. digest256map_free(ed_id_map, NULL);
  3599. goto err;
  3600. }
  3601. digest256map_set(ed_id_map, vrs->ed25519_id, (void*)1);
  3602. } SMARTLIST_FOREACH_END(vrs);
  3603. digest256map_free(ed_id_map, NULL);
  3604. }
  3605. /* Parse footer; check signature. */
  3606. footer_tokens = smartlist_new();
  3607. if ((end_of_footer = strstr(s, "\nnetwork-status-version ")))
  3608. ++end_of_footer;
  3609. else
  3610. end_of_footer = s + strlen(s);
  3611. if (tokenize_string(area,s, end_of_footer, footer_tokens,
  3612. networkstatus_vote_footer_token_table, 0)) {
  3613. log_warn(LD_DIR, "Error tokenizing network-status vote footer.");
  3614. goto err;
  3615. }
  3616. {
  3617. int found_sig = 0;
  3618. SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
  3619. tok = _tok;
  3620. if (tok->tp == K_DIRECTORY_SIGNATURE)
  3621. found_sig = 1;
  3622. else if (found_sig) {
  3623. log_warn(LD_DIR, "Extraneous token after first directory-signature");
  3624. goto err;
  3625. }
  3626. } SMARTLIST_FOREACH_END(_tok);
  3627. }
  3628. if ((tok = find_opt_by_keyword(footer_tokens, K_DIRECTORY_FOOTER))) {
  3629. if (tok != smartlist_get(footer_tokens, 0)) {
  3630. log_warn(LD_DIR, "Misplaced directory-footer token");
  3631. goto err;
  3632. }
  3633. }
  3634. tok = find_opt_by_keyword(footer_tokens, K_BW_WEIGHTS);
  3635. if (tok) {
  3636. ns->weight_params = smartlist_new();
  3637. for (i = 0; i < tok->n_args; ++i) {
  3638. int ok=0;
  3639. char *eq = strchr(tok->args[i], '=');
  3640. if (!eq) {
  3641. log_warn(LD_DIR, "Bad element '%s' in weight params",
  3642. escaped(tok->args[i]));
  3643. goto err;
  3644. }
  3645. tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
  3646. if (!ok) {
  3647. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  3648. goto err;
  3649. }
  3650. smartlist_add(ns->weight_params, tor_strdup(tok->args[i]));
  3651. }
  3652. }
  3653. SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
  3654. char declared_identity[DIGEST_LEN];
  3655. networkstatus_voter_info_t *v;
  3656. document_signature_t *sig;
  3657. const char *id_hexdigest = NULL;
  3658. const char *sk_hexdigest = NULL;
  3659. digest_algorithm_t alg = DIGEST_SHA1;
  3660. tok = _tok;
  3661. if (tok->tp != K_DIRECTORY_SIGNATURE)
  3662. continue;
  3663. tor_assert(tok->n_args >= 2);
  3664. if (tok->n_args == 2) {
  3665. id_hexdigest = tok->args[0];
  3666. sk_hexdigest = tok->args[1];
  3667. } else {
  3668. const char *algname = tok->args[0];
  3669. int a;
  3670. id_hexdigest = tok->args[1];
  3671. sk_hexdigest = tok->args[2];
  3672. a = crypto_digest_algorithm_parse_name(algname);
  3673. if (a<0) {
  3674. log_warn(LD_DIR, "Unknown digest algorithm %s; skipping",
  3675. escaped(algname));
  3676. continue;
  3677. }
  3678. alg = a;
  3679. }
  3680. if (!tok->object_type ||
  3681. strcmp(tok->object_type, "SIGNATURE") ||
  3682. tok->object_size < 128 || tok->object_size > 512) {
  3683. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  3684. goto err;
  3685. }
  3686. if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
  3687. base16_decode(declared_identity, sizeof(declared_identity),
  3688. id_hexdigest, HEX_DIGEST_LEN)
  3689. != sizeof(declared_identity)) {
  3690. log_warn(LD_DIR, "Error decoding declared identity %s in "
  3691. "network-status document.", escaped(id_hexdigest));
  3692. goto err;
  3693. }
  3694. if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {
  3695. log_warn(LD_DIR, "ID on signature on network-status document does "
  3696. "not match any declared directory source.");
  3697. goto err;
  3698. }
  3699. sig = tor_malloc_zero(sizeof(document_signature_t));
  3700. memcpy(sig->identity_digest, v->identity_digest, DIGEST_LEN);
  3701. sig->alg = alg;
  3702. if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
  3703. base16_decode(sig->signing_key_digest, sizeof(sig->signing_key_digest),
  3704. sk_hexdigest, HEX_DIGEST_LEN)
  3705. != sizeof(sig->signing_key_digest)) {
  3706. log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
  3707. "network-status document.", escaped(sk_hexdigest));
  3708. tor_free(sig);
  3709. goto err;
  3710. }
  3711. if (ns->type != NS_TYPE_CONSENSUS) {
  3712. if (tor_memneq(declared_identity, ns->cert->cache_info.identity_digest,
  3713. DIGEST_LEN)) {
  3714. log_warn(LD_DIR, "Digest mismatch between declared and actual on "
  3715. "network-status vote.");
  3716. tor_free(sig);
  3717. goto err;
  3718. }
  3719. }
  3720. if (voter_get_sig_by_algorithm(v, sig->alg)) {
  3721. /* We already parsed a vote with this algorithm from this voter. Use the
  3722. first one. */
  3723. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "We received a networkstatus "
  3724. "that contains two signatures from the same voter with the same "
  3725. "algorithm. Ignoring the second signature.");
  3726. tor_free(sig);
  3727. continue;
  3728. }
  3729. if (ns->type != NS_TYPE_CONSENSUS) {
  3730. if (check_signature_token(ns_digests.d[DIGEST_SHA1], DIGEST_LEN,
  3731. tok, ns->cert->signing_key, 0,
  3732. "network-status document")) {
  3733. tor_free(sig);
  3734. goto err;
  3735. }
  3736. sig->good_signature = 1;
  3737. } else {
  3738. if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
  3739. tor_free(sig);
  3740. goto err;
  3741. }
  3742. sig->signature = tor_memdup(tok->object_body, tok->object_size);
  3743. sig->signature_len = (int) tok->object_size;
  3744. }
  3745. smartlist_add(v->sigs, sig);
  3746. ++n_signatures;
  3747. } SMARTLIST_FOREACH_END(_tok);
  3748. if (! n_signatures) {
  3749. log_warn(LD_DIR, "No signatures on networkstatus document.");
  3750. goto err;
  3751. } else if (ns->type == NS_TYPE_VOTE && n_signatures != 1) {
  3752. log_warn(LD_DIR, "Received more than one signature on a "
  3753. "network-status vote.");
  3754. goto err;
  3755. }
  3756. if (eos_out)
  3757. *eos_out = end_of_footer;
  3758. goto done;
  3759. err:
  3760. dump_desc(s_dup, "v3 networkstatus");
  3761. networkstatus_vote_free(ns);
  3762. ns = NULL;
  3763. done:
  3764. if (tokens) {
  3765. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  3766. smartlist_free(tokens);
  3767. }
  3768. if (voter) {
  3769. if (voter->sigs) {
  3770. SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
  3771. document_signature_free(sig));
  3772. smartlist_free(voter->sigs);
  3773. }
  3774. tor_free(voter->nickname);
  3775. tor_free(voter->address);
  3776. tor_free(voter->contact);
  3777. tor_free(voter);
  3778. }
  3779. if (rs_tokens) {
  3780. SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_clear(t));
  3781. smartlist_free(rs_tokens);
  3782. }
  3783. if (footer_tokens) {
  3784. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_clear(t));
  3785. smartlist_free(footer_tokens);
  3786. }
  3787. if (area) {
  3788. DUMP_AREA(area, "v3 networkstatus");
  3789. memarea_drop_all(area);
  3790. }
  3791. if (rs_area)
  3792. memarea_drop_all(rs_area);
  3793. tor_free(last_kwd);
  3794. return ns;
  3795. }
  3796. /** Return the common_digests_t that holds the digests of the
  3797. * <b>flavor_name</b>-flavored networkstatus according to the detached
  3798. * signatures document <b>sigs</b>, allocating a new common_digests_t as
  3799. * neeeded. */
  3800. static common_digests_t *
  3801. detached_get_digests(ns_detached_signatures_t *sigs, const char *flavor_name)
  3802. {
  3803. common_digests_t *d = strmap_get(sigs->digests, flavor_name);
  3804. if (!d) {
  3805. d = tor_malloc_zero(sizeof(common_digests_t));
  3806. strmap_set(sigs->digests, flavor_name, d);
  3807. }
  3808. return d;
  3809. }
  3810. /** Return the list of signatures of the <b>flavor_name</b>-flavored
  3811. * networkstatus according to the detached signatures document <b>sigs</b>,
  3812. * allocating a new common_digests_t as neeeded. */
  3813. static smartlist_t *
  3814. detached_get_signatures(ns_detached_signatures_t *sigs,
  3815. const char *flavor_name)
  3816. {
  3817. smartlist_t *sl = strmap_get(sigs->signatures, flavor_name);
  3818. if (!sl) {
  3819. sl = smartlist_new();
  3820. strmap_set(sigs->signatures, flavor_name, sl);
  3821. }
  3822. return sl;
  3823. }
  3824. /** Parse a detached v3 networkstatus signature document between <b>s</b> and
  3825. * <b>eos</b> and return the result. Return -1 on failure. */
  3826. ns_detached_signatures_t *
  3827. networkstatus_parse_detached_signatures(const char *s, const char *eos)
  3828. {
  3829. /* XXXX there is too much duplicate shared between this function and
  3830. * networkstatus_parse_vote_from_string(). */
  3831. directory_token_t *tok;
  3832. memarea_t *area = NULL;
  3833. common_digests_t *digests;
  3834. smartlist_t *tokens = smartlist_new();
  3835. ns_detached_signatures_t *sigs =
  3836. tor_malloc_zero(sizeof(ns_detached_signatures_t));
  3837. sigs->digests = strmap_new();
  3838. sigs->signatures = strmap_new();
  3839. if (!eos)
  3840. eos = s + strlen(s);
  3841. area = memarea_new();
  3842. if (tokenize_string(area,s, eos, tokens,
  3843. networkstatus_detached_signature_token_table, 0)) {
  3844. log_warn(LD_DIR, "Error tokenizing detached networkstatus signatures");
  3845. goto err;
  3846. }
  3847. /* Grab all the digest-like tokens. */
  3848. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  3849. const char *algname;
  3850. digest_algorithm_t alg;
  3851. const char *flavor;
  3852. const char *hexdigest;
  3853. size_t expected_length, digest_length;
  3854. tok = _tok;
  3855. if (tok->tp == K_CONSENSUS_DIGEST) {
  3856. algname = "sha1";
  3857. alg = DIGEST_SHA1;
  3858. flavor = "ns";
  3859. hexdigest = tok->args[0];
  3860. } else if (tok->tp == K_ADDITIONAL_DIGEST) {
  3861. int a = crypto_digest_algorithm_parse_name(tok->args[1]);
  3862. if (a<0) {
  3863. log_warn(LD_DIR, "Unrecognized algorithm name %s", tok->args[0]);
  3864. continue;
  3865. }
  3866. alg = (digest_algorithm_t) a;
  3867. flavor = tok->args[0];
  3868. algname = tok->args[1];
  3869. hexdigest = tok->args[2];
  3870. } else {
  3871. continue;
  3872. }
  3873. digest_length = crypto_digest_algorithm_get_length(alg);
  3874. expected_length = digest_length * 2; /* hex encoding */
  3875. if (strlen(hexdigest) != expected_length) {
  3876. log_warn(LD_DIR, "Wrong length on consensus-digest in detached "
  3877. "networkstatus signatures");
  3878. goto err;
  3879. }
  3880. digests = detached_get_digests(sigs, flavor);
  3881. tor_assert(digests);
  3882. if (!tor_mem_is_zero(digests->d[alg], digest_length)) {
  3883. log_warn(LD_DIR, "Multiple digests for %s with %s on detached "
  3884. "signatures document", flavor, algname);
  3885. continue;
  3886. }
  3887. if (base16_decode(digests->d[alg], digest_length,
  3888. hexdigest, strlen(hexdigest)) != (int) digest_length) {
  3889. log_warn(LD_DIR, "Bad encoding on consensus-digest in detached "
  3890. "networkstatus signatures");
  3891. goto err;
  3892. }
  3893. } SMARTLIST_FOREACH_END(_tok);
  3894. tok = find_by_keyword(tokens, K_VALID_AFTER);
  3895. if (parse_iso_time(tok->args[0], &sigs->valid_after)) {
  3896. log_warn(LD_DIR, "Bad valid-after in detached networkstatus signatures");
  3897. goto err;
  3898. }
  3899. tok = find_by_keyword(tokens, K_FRESH_UNTIL);
  3900. if (parse_iso_time(tok->args[0], &sigs->fresh_until)) {
  3901. log_warn(LD_DIR, "Bad fresh-until in detached networkstatus signatures");
  3902. goto err;
  3903. }
  3904. tok = find_by_keyword(tokens, K_VALID_UNTIL);
  3905. if (parse_iso_time(tok->args[0], &sigs->valid_until)) {
  3906. log_warn(LD_DIR, "Bad valid-until in detached networkstatus signatures");
  3907. goto err;
  3908. }
  3909. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  3910. const char *id_hexdigest;
  3911. const char *sk_hexdigest;
  3912. const char *algname;
  3913. const char *flavor;
  3914. digest_algorithm_t alg;
  3915. char id_digest[DIGEST_LEN];
  3916. char sk_digest[DIGEST_LEN];
  3917. smartlist_t *siglist;
  3918. document_signature_t *sig;
  3919. int is_duplicate;
  3920. tok = _tok;
  3921. if (tok->tp == K_DIRECTORY_SIGNATURE) {
  3922. tor_assert(tok->n_args >= 2);
  3923. flavor = "ns";
  3924. algname = "sha1";
  3925. id_hexdigest = tok->args[0];
  3926. sk_hexdigest = tok->args[1];
  3927. } else if (tok->tp == K_ADDITIONAL_SIGNATURE) {
  3928. tor_assert(tok->n_args >= 4);
  3929. flavor = tok->args[0];
  3930. algname = tok->args[1];
  3931. id_hexdigest = tok->args[2];
  3932. sk_hexdigest = tok->args[3];
  3933. } else {
  3934. continue;
  3935. }
  3936. {
  3937. int a = crypto_digest_algorithm_parse_name(algname);
  3938. if (a<0) {
  3939. log_warn(LD_DIR, "Unrecognized algorithm name %s", algname);
  3940. continue;
  3941. }
  3942. alg = (digest_algorithm_t) a;
  3943. }
  3944. if (!tok->object_type ||
  3945. strcmp(tok->object_type, "SIGNATURE") ||
  3946. tok->object_size < 128 || tok->object_size > 512) {
  3947. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  3948. goto err;
  3949. }
  3950. if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
  3951. base16_decode(id_digest, sizeof(id_digest),
  3952. id_hexdigest, HEX_DIGEST_LEN) != sizeof(id_digest)) {
  3953. log_warn(LD_DIR, "Error decoding declared identity %s in "
  3954. "network-status vote.", escaped(id_hexdigest));
  3955. goto err;
  3956. }
  3957. if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
  3958. base16_decode(sk_digest, sizeof(sk_digest),
  3959. sk_hexdigest, HEX_DIGEST_LEN) != sizeof(sk_digest)) {
  3960. log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
  3961. "network-status vote.", escaped(sk_hexdigest));
  3962. goto err;
  3963. }
  3964. siglist = detached_get_signatures(sigs, flavor);
  3965. is_duplicate = 0;
  3966. SMARTLIST_FOREACH(siglist, document_signature_t *, dsig, {
  3967. if (dsig->alg == alg &&
  3968. tor_memeq(id_digest, dsig->identity_digest, DIGEST_LEN) &&
  3969. tor_memeq(sk_digest, dsig->signing_key_digest, DIGEST_LEN)) {
  3970. is_duplicate = 1;
  3971. }
  3972. });
  3973. if (is_duplicate) {
  3974. log_warn(LD_DIR, "Two signatures with identical keys and algorithm "
  3975. "found.");
  3976. continue;
  3977. }
  3978. sig = tor_malloc_zero(sizeof(document_signature_t));
  3979. sig->alg = alg;
  3980. memcpy(sig->identity_digest, id_digest, DIGEST_LEN);
  3981. memcpy(sig->signing_key_digest, sk_digest, DIGEST_LEN);
  3982. if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
  3983. tor_free(sig);
  3984. goto err;
  3985. }
  3986. sig->signature = tor_memdup(tok->object_body, tok->object_size);
  3987. sig->signature_len = (int) tok->object_size;
  3988. smartlist_add(siglist, sig);
  3989. } SMARTLIST_FOREACH_END(_tok);
  3990. goto done;
  3991. err:
  3992. ns_detached_signatures_free(sigs);
  3993. sigs = NULL;
  3994. done:
  3995. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  3996. smartlist_free(tokens);
  3997. if (area) {
  3998. DUMP_AREA(area, "detached signatures");
  3999. memarea_drop_all(area);
  4000. }
  4001. return sigs;
  4002. }
  4003. /** Parse the addr policy in the string <b>s</b> and return it. If
  4004. * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
  4005. * ADDR_POLICY_REJECT) for items that specify no action.
  4006. *
  4007. * Returns NULL on policy errors.
  4008. *
  4009. * Set *<b>malformed_list</b> to true if the entire policy list should be
  4010. * discarded. Otherwise, set it to false, and only this item should be ignored
  4011. * on error - the rest of the policy list can continue to be processed and
  4012. * used.
  4013. *
  4014. * The addr_policy_t returned by this function can have its address set to
  4015. * AF_UNSPEC for '*'. Use policy_expand_unspec() to turn this into a pair
  4016. * of AF_INET and AF_INET6 items.
  4017. */
  4018. MOCK_IMPL(addr_policy_t *,
  4019. router_parse_addr_policy_item_from_string,(const char *s, int assume_action,
  4020. int *malformed_list))
  4021. {
  4022. directory_token_t *tok = NULL;
  4023. const char *cp, *eos;
  4024. /* Longest possible policy is
  4025. * "accept6 [ffff:ffff:..255]/128:10000-65535",
  4026. * which contains a max-length IPv6 address, plus 26 characters.
  4027. * But note that there can be an arbitrary amount of space between the
  4028. * accept and the address:mask/port element.
  4029. * We don't need to multiply TOR_ADDR_BUF_LEN by 2, as there is only one
  4030. * IPv6 address. But making the buffer shorter might cause valid long lines,
  4031. * which parsed in previous versions, to fail to parse in new versions.
  4032. * (These lines would have to have excessive amounts of whitespace.) */
  4033. char line[TOR_ADDR_BUF_LEN*2 + 32];
  4034. addr_policy_t *r;
  4035. memarea_t *area = NULL;
  4036. tor_assert(malformed_list);
  4037. *malformed_list = 0;
  4038. s = eat_whitespace(s);
  4039. /* We can only do assume_action on []-quoted IPv6, as "a" (accept)
  4040. * and ":" (port separator) are ambiguous */
  4041. if ((*s == '*' || *s == '[' || TOR_ISDIGIT(*s)) && assume_action >= 0) {
  4042. if (tor_snprintf(line, sizeof(line), "%s %s",
  4043. assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", s)<0) {
  4044. log_warn(LD_DIR, "Policy %s is too long.", escaped(s));
  4045. return NULL;
  4046. }
  4047. cp = line;
  4048. tor_strlower(line);
  4049. } else { /* assume an already well-formed address policy line */
  4050. cp = s;
  4051. }
  4052. eos = cp + strlen(cp);
  4053. area = memarea_new();
  4054. tok = get_next_token(area, &cp, eos, routerdesc_token_table);
  4055. if (tok->tp == ERR_) {
  4056. log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
  4057. goto err;
  4058. }
  4059. if (tok->tp != K_ACCEPT && tok->tp != K_ACCEPT6 &&
  4060. tok->tp != K_REJECT && tok->tp != K_REJECT6) {
  4061. log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
  4062. goto err;
  4063. }
  4064. /* Use the extended interpretation of accept/reject *,
  4065. * expanding it into an IPv4 wildcard and an IPv6 wildcard.
  4066. * Also permit *4 and *6 for IPv4 and IPv6 only wildcards. */
  4067. r = router_parse_addr_policy(tok, TAPMP_EXTENDED_STAR);
  4068. if (!r) {
  4069. goto err;
  4070. }
  4071. /* Ensure that accept6/reject6 fields are followed by IPv6 addresses.
  4072. * AF_UNSPEC addresses are only permitted on the accept/reject field type.
  4073. * Unlike descriptors, torrcs exit policy accept/reject can be followed by
  4074. * either an IPv4 or IPv6 address. */
  4075. if ((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  4076. tor_addr_family(&r->addr) != AF_INET6) {
  4077. /* This is a non-fatal error, just ignore this one entry. */
  4078. *malformed_list = 0;
  4079. log_warn(LD_DIR, "IPv4 address '%s' with accept6/reject6 field type in "
  4080. "exit policy. Ignoring, but continuing to parse rules. (Use "
  4081. "accept/reject with IPv4 addresses.)",
  4082. tok->n_args == 1 ? tok->args[0] : "");
  4083. addr_policy_free(r);
  4084. r = NULL;
  4085. goto done;
  4086. }
  4087. goto done;
  4088. err:
  4089. *malformed_list = 1;
  4090. r = NULL;
  4091. done:
  4092. token_clear(tok);
  4093. if (area) {
  4094. DUMP_AREA(area, "policy item");
  4095. memarea_drop_all(area);
  4096. }
  4097. return r;
  4098. }
  4099. /** Add an exit policy stored in the token <b>tok</b> to the router info in
  4100. * <b>router</b>. Return 0 on success, -1 on failure. */
  4101. static int
  4102. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
  4103. {
  4104. addr_policy_t *newe;
  4105. /* Use the standard interpretation of accept/reject *, an IPv4 wildcard. */
  4106. newe = router_parse_addr_policy(tok, 0);
  4107. if (!newe)
  4108. return -1;
  4109. if (! router->exit_policy)
  4110. router->exit_policy = smartlist_new();
  4111. /* Ensure that in descriptors, accept/reject fields are followed by
  4112. * IPv4 addresses, and accept6/reject6 fields are followed by
  4113. * IPv6 addresses. Unlike torrcs, descriptor exit policies do not permit
  4114. * accept/reject followed by IPv6. */
  4115. if (((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  4116. tor_addr_family(&newe->addr) == AF_INET)
  4117. ||
  4118. ((tok->tp == K_ACCEPT || tok->tp == K_REJECT) &&
  4119. tor_addr_family(&newe->addr) == AF_INET6)) {
  4120. /* There's nothing the user can do about other relays' descriptors,
  4121. * so we don't provide usage advice here. */
  4122. log_warn(LD_DIR, "Mismatch between field type and address type in exit "
  4123. "policy '%s'. Discarding entire router descriptor.",
  4124. tok->n_args == 1 ? tok->args[0] : "");
  4125. addr_policy_free(newe);
  4126. return -1;
  4127. }
  4128. smartlist_add(router->exit_policy, newe);
  4129. return 0;
  4130. }
  4131. /** Given a K_ACCEPT[6] or K_REJECT[6] token and a router, create and return
  4132. * a new exit_policy_t corresponding to the token. If TAPMP_EXTENDED_STAR
  4133. * is set in fmt_flags, K_ACCEPT6 and K_REJECT6 tokens followed by *
  4134. * expand to IPv6-only policies, otherwise they expand to IPv4 and IPv6
  4135. * policies */
  4136. static addr_policy_t *
  4137. router_parse_addr_policy(directory_token_t *tok, unsigned fmt_flags)
  4138. {
  4139. addr_policy_t newe;
  4140. char *arg;
  4141. tor_assert(tok->tp == K_REJECT || tok->tp == K_REJECT6 ||
  4142. tok->tp == K_ACCEPT || tok->tp == K_ACCEPT6);
  4143. if (tok->n_args != 1)
  4144. return NULL;
  4145. arg = tok->args[0];
  4146. if (!strcmpstart(arg,"private"))
  4147. return router_parse_addr_policy_private(tok);
  4148. memset(&newe, 0, sizeof(newe));
  4149. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  4150. newe.policy_type = ADDR_POLICY_REJECT;
  4151. else
  4152. newe.policy_type = ADDR_POLICY_ACCEPT;
  4153. /* accept6/reject6 * produces an IPv6 wildcard address only.
  4154. * (accept/reject * produces rules for IPv4 and IPv6 wildcard addresses.) */
  4155. if ((fmt_flags & TAPMP_EXTENDED_STAR)
  4156. && (tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6)) {
  4157. fmt_flags |= TAPMP_STAR_IPV6_ONLY;
  4158. }
  4159. if (tor_addr_parse_mask_ports(arg, fmt_flags, &newe.addr, &newe.maskbits,
  4160. &newe.prt_min, &newe.prt_max) < 0) {
  4161. log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
  4162. return NULL;
  4163. }
  4164. return addr_policy_get_canonical_entry(&newe);
  4165. }
  4166. /** Parse an exit policy line of the format "accept[6]/reject[6] private:...".
  4167. * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
  4168. * router descriptors until earlier versions are obsolete.
  4169. *
  4170. * accept/reject and accept6/reject6 private all produce rules for both
  4171. * IPv4 and IPv6 addresses.
  4172. */
  4173. static addr_policy_t *
  4174. router_parse_addr_policy_private(directory_token_t *tok)
  4175. {
  4176. const char *arg;
  4177. uint16_t port_min, port_max;
  4178. addr_policy_t result;
  4179. arg = tok->args[0];
  4180. if (strcmpstart(arg, "private"))
  4181. return NULL;
  4182. arg += strlen("private");
  4183. arg = (char*) eat_whitespace(arg);
  4184. if (!arg || *arg != ':')
  4185. return NULL;
  4186. if (parse_port_range(arg+1, &port_min, &port_max)<0)
  4187. return NULL;
  4188. memset(&result, 0, sizeof(result));
  4189. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  4190. result.policy_type = ADDR_POLICY_REJECT;
  4191. else
  4192. result.policy_type = ADDR_POLICY_ACCEPT;
  4193. result.is_private = 1;
  4194. result.prt_min = port_min;
  4195. result.prt_max = port_max;
  4196. if (tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) {
  4197. log_warn(LD_GENERAL,
  4198. "'%s' expands into rules which apply to all private IPv4 and "
  4199. "IPv6 addresses. (Use accept/reject private:* for IPv4 and "
  4200. "IPv6.)", tok->n_args == 1 ? tok->args[0] : "");
  4201. }
  4202. return addr_policy_get_canonical_entry(&result);
  4203. }
  4204. /** Log and exit if <b>t</b> is malformed */
  4205. void
  4206. assert_addr_policy_ok(smartlist_t *lst)
  4207. {
  4208. if (!lst) return;
  4209. SMARTLIST_FOREACH(lst, addr_policy_t *, t, {
  4210. tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
  4211. t->policy_type == ADDR_POLICY_ACCEPT);
  4212. tor_assert(t->prt_min <= t->prt_max);
  4213. });
  4214. }
  4215. /*
  4216. * Low-level tokenizer for router descriptors and directories.
  4217. */
  4218. /** Free all resources allocated for <b>tok</b> */
  4219. static void
  4220. token_clear(directory_token_t *tok)
  4221. {
  4222. if (tok->key)
  4223. crypto_pk_free(tok->key);
  4224. }
  4225. #define ALLOC_ZERO(sz) memarea_alloc_zero(area,sz)
  4226. #define ALLOC(sz) memarea_alloc(area,sz)
  4227. #define STRDUP(str) memarea_strdup(area,str)
  4228. #define STRNDUP(str,n) memarea_strndup(area,(str),(n))
  4229. #define RET_ERR(msg) \
  4230. STMT_BEGIN \
  4231. if (tok) token_clear(tok); \
  4232. tok = ALLOC_ZERO(sizeof(directory_token_t)); \
  4233. tok->tp = ERR_; \
  4234. tok->error = STRDUP(msg); \
  4235. goto done_tokenizing; \
  4236. STMT_END
  4237. /** Helper: make sure that the token <b>tok</b> with keyword <b>kwd</b> obeys
  4238. * the object syntax of <b>o_syn</b>. Allocate all storage in <b>area</b>.
  4239. * Return <b>tok</b> on success, or a new ERR_ token if the token didn't
  4240. * conform to the syntax we wanted.
  4241. **/
  4242. static inline directory_token_t *
  4243. token_check_object(memarea_t *area, const char *kwd,
  4244. directory_token_t *tok, obj_syntax o_syn)
  4245. {
  4246. char ebuf[128];
  4247. switch (o_syn) {
  4248. case NO_OBJ:
  4249. /* No object is allowed for this token. */
  4250. if (tok->object_body) {
  4251. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected object for %s", kwd);
  4252. RET_ERR(ebuf);
  4253. }
  4254. if (tok->key) {
  4255. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected public key for %s", kwd);
  4256. RET_ERR(ebuf);
  4257. }
  4258. break;
  4259. case NEED_OBJ:
  4260. /* There must be a (non-key) object. */
  4261. if (!tok->object_body) {
  4262. tor_snprintf(ebuf, sizeof(ebuf), "Missing object for %s", kwd);
  4263. RET_ERR(ebuf);
  4264. }
  4265. break;
  4266. case NEED_KEY_1024: /* There must be a 1024-bit public key. */
  4267. case NEED_SKEY_1024: /* There must be a 1024-bit private key. */
  4268. if (tok->key && crypto_pk_num_bits(tok->key) != PK_BYTES*8) {
  4269. tor_snprintf(ebuf, sizeof(ebuf), "Wrong size on key for %s: %d bits",
  4270. kwd, crypto_pk_num_bits(tok->key));
  4271. RET_ERR(ebuf);
  4272. }
  4273. /* fall through */
  4274. case NEED_KEY: /* There must be some kind of key. */
  4275. if (!tok->key) {
  4276. tor_snprintf(ebuf, sizeof(ebuf), "Missing public key for %s", kwd);
  4277. RET_ERR(ebuf);
  4278. }
  4279. if (o_syn != NEED_SKEY_1024) {
  4280. if (crypto_pk_key_is_private(tok->key)) {
  4281. tor_snprintf(ebuf, sizeof(ebuf),
  4282. "Private key given for %s, which wants a public key", kwd);
  4283. RET_ERR(ebuf);
  4284. }
  4285. } else { /* o_syn == NEED_SKEY_1024 */
  4286. if (!crypto_pk_key_is_private(tok->key)) {
  4287. tor_snprintf(ebuf, sizeof(ebuf),
  4288. "Public key given for %s, which wants a private key", kwd);
  4289. RET_ERR(ebuf);
  4290. }
  4291. }
  4292. break;
  4293. case OBJ_OK:
  4294. /* Anything goes with this token. */
  4295. break;
  4296. }
  4297. done_tokenizing:
  4298. return tok;
  4299. }
  4300. /** Helper: parse space-separated arguments from the string <b>s</b> ending at
  4301. * <b>eol</b>, and store them in the args field of <b>tok</b>. Store the
  4302. * number of parsed elements into the n_args field of <b>tok</b>. Allocate
  4303. * all storage in <b>area</b>. Return the number of arguments parsed, or
  4304. * return -1 if there was an insanely high number of arguments. */
  4305. static inline int
  4306. get_token_arguments(memarea_t *area, directory_token_t *tok,
  4307. const char *s, const char *eol)
  4308. {
  4309. /** Largest number of arguments we'll accept to any token, ever. */
  4310. #define MAX_ARGS 512
  4311. char *mem = memarea_strndup(area, s, eol-s);
  4312. char *cp = mem;
  4313. int j = 0;
  4314. char *args[MAX_ARGS];
  4315. while (*cp) {
  4316. if (j == MAX_ARGS)
  4317. return -1;
  4318. args[j++] = cp;
  4319. cp = (char*)find_whitespace(cp);
  4320. if (!cp || !*cp)
  4321. break; /* End of the line. */
  4322. *cp++ = '\0';
  4323. cp = (char*)eat_whitespace(cp);
  4324. }
  4325. tok->n_args = j;
  4326. tok->args = memarea_memdup(area, args, j*sizeof(char*));
  4327. return j;
  4328. #undef MAX_ARGS
  4329. }
  4330. /** Helper function: read the next token from *s, advance *s to the end of the
  4331. * token, and return the parsed token. Parse *<b>s</b> according to the list
  4332. * of tokens in <b>table</b>.
  4333. */
  4334. static directory_token_t *
  4335. get_next_token(memarea_t *area,
  4336. const char **s, const char *eos, token_rule_t *table)
  4337. {
  4338. /** Reject any object at least this big; it is probably an overflow, an
  4339. * attack, a bug, or some other nonsense. */
  4340. #define MAX_UNPARSED_OBJECT_SIZE (128*1024)
  4341. /** Reject any line at least this big; it is probably an overflow, an
  4342. * attack, a bug, or some other nonsense. */
  4343. #define MAX_LINE_LENGTH (128*1024)
  4344. const char *next, *eol, *obstart;
  4345. size_t obname_len;
  4346. int i;
  4347. directory_token_t *tok;
  4348. obj_syntax o_syn = NO_OBJ;
  4349. char ebuf[128];
  4350. const char *kwd = "";
  4351. tor_assert(area);
  4352. tok = ALLOC_ZERO(sizeof(directory_token_t));
  4353. tok->tp = ERR_;
  4354. /* Set *s to first token, eol to end-of-line, next to after first token */
  4355. *s = eat_whitespace_eos(*s, eos); /* eat multi-line whitespace */
  4356. tor_assert(eos >= *s);
  4357. eol = memchr(*s, '\n', eos-*s);
  4358. if (!eol)
  4359. eol = eos;
  4360. if (eol - *s > MAX_LINE_LENGTH) {
  4361. RET_ERR("Line far too long");
  4362. }
  4363. next = find_whitespace_eos(*s, eol);
  4364. if (!strcmp_len(*s, "opt", next-*s)) {
  4365. /* Skip past an "opt" at the start of the line. */
  4366. *s = eat_whitespace_eos_no_nl(next, eol);
  4367. next = find_whitespace_eos(*s, eol);
  4368. } else if (*s == eos) { /* If no "opt", and end-of-line, line is invalid */
  4369. RET_ERR("Unexpected EOF");
  4370. }
  4371. /* Search the table for the appropriate entry. (I tried a binary search
  4372. * instead, but it wasn't any faster.) */
  4373. for (i = 0; table[i].t ; ++i) {
  4374. if (!strcmp_len(*s, table[i].t, next-*s)) {
  4375. /* We've found the keyword. */
  4376. kwd = table[i].t;
  4377. tok->tp = table[i].v;
  4378. o_syn = table[i].os;
  4379. *s = eat_whitespace_eos_no_nl(next, eol);
  4380. /* We go ahead whether there are arguments or not, so that tok->args is
  4381. * always set if we want arguments. */
  4382. if (table[i].concat_args) {
  4383. /* The keyword takes the line as a single argument */
  4384. tok->args = ALLOC(sizeof(char*));
  4385. tok->args[0] = STRNDUP(*s,eol-*s); /* Grab everything on line */
  4386. tok->n_args = 1;
  4387. } else {
  4388. /* This keyword takes multiple arguments. */
  4389. if (get_token_arguments(area, tok, *s, eol)<0) {
  4390. tor_snprintf(ebuf, sizeof(ebuf),"Far too many arguments to %s", kwd);
  4391. RET_ERR(ebuf);
  4392. }
  4393. *s = eol;
  4394. }
  4395. if (tok->n_args < table[i].min_args) {
  4396. tor_snprintf(ebuf, sizeof(ebuf), "Too few arguments to %s", kwd);
  4397. RET_ERR(ebuf);
  4398. } else if (tok->n_args > table[i].max_args) {
  4399. tor_snprintf(ebuf, sizeof(ebuf), "Too many arguments to %s", kwd);
  4400. RET_ERR(ebuf);
  4401. }
  4402. break;
  4403. }
  4404. }
  4405. if (tok->tp == ERR_) {
  4406. /* No keyword matched; call it an "K_opt" or "A_unrecognized" */
  4407. if (**s == '@')
  4408. tok->tp = A_UNKNOWN_;
  4409. else
  4410. tok->tp = K_OPT;
  4411. tok->args = ALLOC(sizeof(char*));
  4412. tok->args[0] = STRNDUP(*s, eol-*s);
  4413. tok->n_args = 1;
  4414. o_syn = OBJ_OK;
  4415. }
  4416. /* Check whether there's an object present */
  4417. *s = eat_whitespace_eos(eol, eos); /* Scan from end of first line */
  4418. tor_assert(eos >= *s);
  4419. eol = memchr(*s, '\n', eos-*s);
  4420. if (!eol || eol-*s<11 || strcmpstart(*s, "-----BEGIN ")) /* No object. */
  4421. goto check_object;
  4422. obstart = *s; /* Set obstart to start of object spec */
  4423. if (*s+16 >= eol || memchr(*s+11,'\0',eol-*s-16) || /* no short lines, */
  4424. strcmp_len(eol-5, "-----", 5) || /* nuls or invalid endings */
  4425. (eol-*s) > MAX_UNPARSED_OBJECT_SIZE) { /* name too long */
  4426. RET_ERR("Malformed object: bad begin line");
  4427. }
  4428. tok->object_type = STRNDUP(*s+11, eol-*s-16);
  4429. obname_len = eol-*s-16; /* store objname length here to avoid a strlen() */
  4430. *s = eol+1; /* Set *s to possible start of object data (could be eos) */
  4431. /* Go to the end of the object */
  4432. next = tor_memstr(*s, eos-*s, "-----END ");
  4433. if (!next) {
  4434. RET_ERR("Malformed object: missing object end line");
  4435. }
  4436. tor_assert(eos >= next);
  4437. eol = memchr(next, '\n', eos-next);
  4438. if (!eol) /* end-of-line marker, or eos if there's no '\n' */
  4439. eol = eos;
  4440. /* Validate the ending tag, which should be 9 + NAME + 5 + eol */
  4441. if ((size_t)(eol-next) != 9+obname_len+5 ||
  4442. strcmp_len(next+9, tok->object_type, obname_len) ||
  4443. strcmp_len(eol-5, "-----", 5)) {
  4444. tor_snprintf(ebuf, sizeof(ebuf), "Malformed object: mismatched end tag %s",
  4445. tok->object_type);
  4446. ebuf[sizeof(ebuf)-1] = '\0';
  4447. RET_ERR(ebuf);
  4448. }
  4449. if (next - *s > MAX_UNPARSED_OBJECT_SIZE)
  4450. RET_ERR("Couldn't parse object: missing footer or object much too big.");
  4451. if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) { /* If it's a public key */
  4452. tok->key = crypto_pk_new();
  4453. if (crypto_pk_read_public_key_from_string(tok->key, obstart, eol-obstart))
  4454. RET_ERR("Couldn't parse public key.");
  4455. } else if (!strcmp(tok->object_type, "RSA PRIVATE KEY")) { /* private key */
  4456. tok->key = crypto_pk_new();
  4457. if (crypto_pk_read_private_key_from_string(tok->key, obstart, eol-obstart))
  4458. RET_ERR("Couldn't parse private key.");
  4459. } else { /* If it's something else, try to base64-decode it */
  4460. int r;
  4461. tok->object_body = ALLOC(next-*s); /* really, this is too much RAM. */
  4462. r = base64_decode(tok->object_body, next-*s, *s, next-*s);
  4463. if (r<0)
  4464. RET_ERR("Malformed object: bad base64-encoded data");
  4465. tok->object_size = r;
  4466. }
  4467. *s = eol;
  4468. check_object:
  4469. tok = token_check_object(area, kwd, tok, o_syn);
  4470. done_tokenizing:
  4471. return tok;
  4472. #undef RET_ERR
  4473. #undef ALLOC
  4474. #undef ALLOC_ZERO
  4475. #undef STRDUP
  4476. #undef STRNDUP
  4477. }
  4478. /** Read all tokens from a string between <b>start</b> and <b>end</b>, and add
  4479. * them to <b>out</b>. Parse according to the token rules in <b>table</b>.
  4480. * Caller must free tokens in <b>out</b>. If <b>end</b> is NULL, use the
  4481. * entire string.
  4482. */
  4483. static int
  4484. tokenize_string(memarea_t *area,
  4485. const char *start, const char *end, smartlist_t *out,
  4486. token_rule_t *table, int flags)
  4487. {
  4488. const char **s;
  4489. directory_token_t *tok = NULL;
  4490. int counts[NIL_];
  4491. int i;
  4492. int first_nonannotation;
  4493. int prev_len = smartlist_len(out);
  4494. tor_assert(area);
  4495. s = &start;
  4496. if (!end) {
  4497. end = start+strlen(start);
  4498. } else {
  4499. /* it's only meaningful to check for nuls if we got an end-of-string ptr */
  4500. if (memchr(start, '\0', end-start)) {
  4501. log_warn(LD_DIR, "parse error: internal NUL character.");
  4502. return -1;
  4503. }
  4504. }
  4505. for (i = 0; i < NIL_; ++i)
  4506. counts[i] = 0;
  4507. SMARTLIST_FOREACH(out, const directory_token_t *, t, ++counts[t->tp]);
  4508. while (*s < end && (!tok || tok->tp != EOF_)) {
  4509. tok = get_next_token(area, s, end, table);
  4510. if (tok->tp == ERR_) {
  4511. log_warn(LD_DIR, "parse error: %s", tok->error);
  4512. token_clear(tok);
  4513. return -1;
  4514. }
  4515. ++counts[tok->tp];
  4516. smartlist_add(out, tok);
  4517. *s = eat_whitespace_eos(*s, end);
  4518. }
  4519. if (flags & TS_NOCHECK)
  4520. return 0;
  4521. if ((flags & TS_ANNOTATIONS_OK)) {
  4522. first_nonannotation = -1;
  4523. for (i = 0; i < smartlist_len(out); ++i) {
  4524. tok = smartlist_get(out, i);
  4525. if (tok->tp < MIN_ANNOTATION || tok->tp > MAX_ANNOTATION) {
  4526. first_nonannotation = i;
  4527. break;
  4528. }
  4529. }
  4530. if (first_nonannotation < 0) {
  4531. log_warn(LD_DIR, "parse error: item contains only annotations");
  4532. return -1;
  4533. }
  4534. for (i=first_nonannotation; i < smartlist_len(out); ++i) {
  4535. tok = smartlist_get(out, i);
  4536. if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
  4537. log_warn(LD_DIR, "parse error: Annotations mixed with keywords");
  4538. return -1;
  4539. }
  4540. }
  4541. if ((flags & TS_NO_NEW_ANNOTATIONS)) {
  4542. if (first_nonannotation != prev_len) {
  4543. log_warn(LD_DIR, "parse error: Unexpected annotations.");
  4544. return -1;
  4545. }
  4546. }
  4547. } else {
  4548. for (i=0; i < smartlist_len(out); ++i) {
  4549. tok = smartlist_get(out, i);
  4550. if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
  4551. log_warn(LD_DIR, "parse error: no annotations allowed.");
  4552. return -1;
  4553. }
  4554. }
  4555. first_nonannotation = 0;
  4556. }
  4557. for (i = 0; table[i].t; ++i) {
  4558. if (counts[table[i].v] < table[i].min_cnt) {
  4559. log_warn(LD_DIR, "Parse error: missing %s element.", table[i].t);
  4560. return -1;
  4561. }
  4562. if (counts[table[i].v] > table[i].max_cnt) {
  4563. log_warn(LD_DIR, "Parse error: too many %s elements.", table[i].t);
  4564. return -1;
  4565. }
  4566. if (table[i].pos & AT_START) {
  4567. if (smartlist_len(out) < 1 ||
  4568. (tok = smartlist_get(out, first_nonannotation))->tp != table[i].v) {
  4569. log_warn(LD_DIR, "Parse error: first item is not %s.", table[i].t);
  4570. return -1;
  4571. }
  4572. }
  4573. if (table[i].pos & AT_END) {
  4574. if (smartlist_len(out) < 1 ||
  4575. (tok = smartlist_get(out, smartlist_len(out)-1))->tp != table[i].v) {
  4576. log_warn(LD_DIR, "Parse error: last item is not %s.", table[i].t);
  4577. return -1;
  4578. }
  4579. }
  4580. }
  4581. return 0;
  4582. }
  4583. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
  4584. * NULL if no such keyword is found.
  4585. */
  4586. static directory_token_t *
  4587. find_opt_by_keyword(smartlist_t *s, directory_keyword keyword)
  4588. {
  4589. SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
  4590. return NULL;
  4591. }
  4592. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; fail
  4593. * with an assert if no such keyword is found.
  4594. */
  4595. static directory_token_t *
  4596. find_by_keyword_(smartlist_t *s, directory_keyword keyword,
  4597. const char *keyword_as_string)
  4598. {
  4599. directory_token_t *tok = find_opt_by_keyword(s, keyword);
  4600. if (PREDICT_UNLIKELY(!tok)) {
  4601. log_err(LD_BUG, "Missing %s [%d] in directory object that should have "
  4602. "been validated. Internal error.", keyword_as_string, (int)keyword);
  4603. tor_assert(tok);
  4604. }
  4605. return tok;
  4606. }
  4607. /** If there are any directory_token_t entries in <b>s</b> whose keyword is
  4608. * <b>k</b>, return a newly allocated smartlist_t containing all such entries,
  4609. * in the same order in which they occur in <b>s</b>. Otherwise return
  4610. * NULL. */
  4611. static smartlist_t *
  4612. find_all_by_keyword(smartlist_t *s, directory_keyword k)
  4613. {
  4614. smartlist_t *out = NULL;
  4615. SMARTLIST_FOREACH(s, directory_token_t *, t,
  4616. if (t->tp == k) {
  4617. if (!out)
  4618. out = smartlist_new();
  4619. smartlist_add(out, t);
  4620. });
  4621. return out;
  4622. }
  4623. /** Return a newly allocated smartlist of all accept or reject tokens in
  4624. * <b>s</b>.
  4625. */
  4626. static smartlist_t *
  4627. find_all_exitpolicy(smartlist_t *s)
  4628. {
  4629. smartlist_t *out = smartlist_new();
  4630. SMARTLIST_FOREACH(s, directory_token_t *, t,
  4631. if (t->tp == K_ACCEPT || t->tp == K_ACCEPT6 ||
  4632. t->tp == K_REJECT || t->tp == K_REJECT6)
  4633. smartlist_add(out,t));
  4634. return out;
  4635. }
  4636. /** Helper function for <b>router_get_hash_impl</b>: given <b>s</b>,
  4637. * <b>s_len</b>, <b>start_str</b>, <b>end_str</b>, and <b>end_c</b> with the
  4638. * same semantics as in that function, set *<b>start_out</b> (inclusive) and
  4639. * *<b>end_out</b> (exclusive) to the boundaries of the string to be hashed.
  4640. *
  4641. * Return 0 on success and -1 on failure.
  4642. */
  4643. static int
  4644. router_get_hash_impl_helper(const char *s, size_t s_len,
  4645. const char *start_str,
  4646. const char *end_str, char end_c,
  4647. const char **start_out, const char **end_out)
  4648. {
  4649. const char *start, *end;
  4650. start = tor_memstr(s, s_len, start_str);
  4651. if (!start) {
  4652. log_warn(LD_DIR,"couldn't find start of hashed material \"%s\"",start_str);
  4653. return -1;
  4654. }
  4655. if (start != s && *(start-1) != '\n') {
  4656. log_warn(LD_DIR,
  4657. "first occurrence of \"%s\" is not at the start of a line",
  4658. start_str);
  4659. return -1;
  4660. }
  4661. end = tor_memstr(start+strlen(start_str),
  4662. s_len - (start-s) - strlen(start_str), end_str);
  4663. if (!end) {
  4664. log_warn(LD_DIR,"couldn't find end of hashed material \"%s\"",end_str);
  4665. return -1;
  4666. }
  4667. end = memchr(end+strlen(end_str), end_c, s_len - (end-s) - strlen(end_str));
  4668. if (!end) {
  4669. log_warn(LD_DIR,"couldn't find EOL");
  4670. return -1;
  4671. }
  4672. ++end;
  4673. *start_out = start;
  4674. *end_out = end;
  4675. return 0;
  4676. }
  4677. /** Compute the digest of the substring of <b>s</b> taken from the first
  4678. * occurrence of <b>start_str</b> through the first instance of c after the
  4679. * first subsequent occurrence of <b>end_str</b>; store the 20-byte or 32-byte
  4680. * result in <b>digest</b>; return 0 on success.
  4681. *
  4682. * If no such substring exists, return -1.
  4683. */
  4684. static int
  4685. router_get_hash_impl(const char *s, size_t s_len, char *digest,
  4686. const char *start_str,
  4687. const char *end_str, char end_c,
  4688. digest_algorithm_t alg)
  4689. {
  4690. const char *start=NULL, *end=NULL;
  4691. if (router_get_hash_impl_helper(s,s_len,start_str,end_str,end_c,
  4692. &start,&end)<0)
  4693. return -1;
  4694. if (alg == DIGEST_SHA1) {
  4695. if (crypto_digest(digest, start, end-start)) {
  4696. log_warn(LD_BUG,"couldn't compute digest");
  4697. return -1;
  4698. }
  4699. } else {
  4700. if (crypto_digest256(digest, start, end-start, alg)) {
  4701. log_warn(LD_BUG,"couldn't compute digest");
  4702. return -1;
  4703. }
  4704. }
  4705. return 0;
  4706. }
  4707. /** As router_get_hash_impl, but compute all hashes. */
  4708. static int
  4709. router_get_hashes_impl(const char *s, size_t s_len, common_digests_t *digests,
  4710. const char *start_str,
  4711. const char *end_str, char end_c)
  4712. {
  4713. const char *start=NULL, *end=NULL;
  4714. if (router_get_hash_impl_helper(s,s_len,start_str,end_str,end_c,
  4715. &start,&end)<0)
  4716. return -1;
  4717. if (crypto_common_digests(digests, start, end-start)) {
  4718. log_warn(LD_BUG,"couldn't compute digests");
  4719. return -1;
  4720. }
  4721. return 0;
  4722. }
  4723. /** Assuming that s starts with a microdesc, return the start of the
  4724. * *NEXT* one. Return NULL on "not found." */
  4725. static const char *
  4726. find_start_of_next_microdesc(const char *s, const char *eos)
  4727. {
  4728. int started_with_annotations;
  4729. s = eat_whitespace_eos(s, eos);
  4730. if (!s)
  4731. return NULL;
  4732. #define CHECK_LENGTH() STMT_BEGIN \
  4733. if (s+32 > eos) \
  4734. return NULL; \
  4735. STMT_END
  4736. #define NEXT_LINE() STMT_BEGIN \
  4737. s = memchr(s, '\n', eos-s); \
  4738. if (!s || s+1 >= eos) \
  4739. return NULL; \
  4740. s++; \
  4741. STMT_END
  4742. CHECK_LENGTH();
  4743. started_with_annotations = (*s == '@');
  4744. if (started_with_annotations) {
  4745. /* Start by advancing to the first non-annotation line. */
  4746. while (*s == '@')
  4747. NEXT_LINE();
  4748. }
  4749. CHECK_LENGTH();
  4750. /* Now we should be pointed at an onion-key line. If we are, then skip
  4751. * it. */
  4752. if (!strcmpstart(s, "onion-key"))
  4753. NEXT_LINE();
  4754. /* Okay, now we're pointed at the first line of the microdescriptor which is
  4755. not an annotation or onion-key. The next line that _is_ an annotation or
  4756. onion-key is the start of the next microdescriptor. */
  4757. while (s+32 < eos) {
  4758. if (*s == '@' || !strcmpstart(s, "onion-key"))
  4759. return s;
  4760. NEXT_LINE();
  4761. }
  4762. return NULL;
  4763. #undef CHECK_LENGTH
  4764. #undef NEXT_LINE
  4765. }
  4766. /** Parse as many microdescriptors as are found from the string starting at
  4767. * <b>s</b> and ending at <b>eos</b>. If allow_annotations is set, read any
  4768. * annotations we recognize and ignore ones we don't.
  4769. *
  4770. * If <b>saved_location</b> isn't SAVED_IN_CACHE, make a local copy of each
  4771. * descriptor in the body field of each microdesc_t.
  4772. *
  4773. * Return all newly parsed microdescriptors in a newly allocated
  4774. * smartlist_t. If <b>invalid_disgests_out</b> is provided, add a SHA256
  4775. * microdesc digest to it for every microdesc that we found to be badly
  4776. * formed. (This may cause duplicates) */
  4777. smartlist_t *
  4778. microdescs_parse_from_string(const char *s, const char *eos,
  4779. int allow_annotations,
  4780. saved_location_t where,
  4781. smartlist_t *invalid_digests_out)
  4782. {
  4783. smartlist_t *tokens;
  4784. smartlist_t *result;
  4785. microdesc_t *md = NULL;
  4786. memarea_t *area;
  4787. const char *start = s;
  4788. const char *start_of_next_microdesc;
  4789. int flags = allow_annotations ? TS_ANNOTATIONS_OK : 0;
  4790. const int copy_body = (where != SAVED_IN_CACHE);
  4791. directory_token_t *tok;
  4792. if (!eos)
  4793. eos = s + strlen(s);
  4794. s = eat_whitespace_eos(s, eos);
  4795. area = memarea_new();
  4796. result = smartlist_new();
  4797. tokens = smartlist_new();
  4798. while (s < eos) {
  4799. int okay = 0;
  4800. start_of_next_microdesc = find_start_of_next_microdesc(s, eos);
  4801. if (!start_of_next_microdesc)
  4802. start_of_next_microdesc = eos;
  4803. md = tor_malloc_zero(sizeof(microdesc_t));
  4804. {
  4805. const char *cp = tor_memstr(s, start_of_next_microdesc-s,
  4806. "onion-key");
  4807. const int no_onion_key = (cp == NULL);
  4808. if (no_onion_key) {
  4809. cp = s; /* So that we have *some* junk to put in the body */
  4810. }
  4811. md->bodylen = start_of_next_microdesc - cp;
  4812. md->saved_location = where;
  4813. if (copy_body)
  4814. md->body = tor_memdup_nulterm(cp, md->bodylen);
  4815. else
  4816. md->body = (char*)cp;
  4817. md->off = cp - start;
  4818. crypto_digest256(md->digest, md->body, md->bodylen, DIGEST_SHA256);
  4819. if (no_onion_key) {
  4820. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Malformed or truncated descriptor");
  4821. goto next;
  4822. }
  4823. }
  4824. if (tokenize_string(area, s, start_of_next_microdesc, tokens,
  4825. microdesc_token_table, flags)) {
  4826. log_warn(LD_DIR, "Unparseable microdescriptor");
  4827. goto next;
  4828. }
  4829. if ((tok = find_opt_by_keyword(tokens, A_LAST_LISTED))) {
  4830. if (parse_iso_time(tok->args[0], &md->last_listed)) {
  4831. log_warn(LD_DIR, "Bad last-listed time in microdescriptor");
  4832. goto next;
  4833. }
  4834. }
  4835. tok = find_by_keyword(tokens, K_ONION_KEY);
  4836. if (!crypto_pk_public_exponent_ok(tok->key)) {
  4837. log_warn(LD_DIR,
  4838. "Relay's onion key had invalid exponent.");
  4839. goto next;
  4840. }
  4841. md->onion_pkey = tok->key;
  4842. tok->key = NULL;
  4843. if ((tok = find_opt_by_keyword(tokens, K_ONION_KEY_NTOR))) {
  4844. curve25519_public_key_t k;
  4845. tor_assert(tok->n_args >= 1);
  4846. if (curve25519_public_from_base64(&k, tok->args[0]) < 0) {
  4847. log_warn(LD_DIR, "Bogus ntor-onion-key in microdesc");
  4848. goto next;
  4849. }
  4850. md->onion_curve25519_pkey =
  4851. tor_memdup(&k, sizeof(curve25519_public_key_t));
  4852. }
  4853. smartlist_t *id_lines = find_all_by_keyword(tokens, K_ID);
  4854. if (id_lines) {
  4855. SMARTLIST_FOREACH_BEGIN(id_lines, directory_token_t *, t) {
  4856. tor_assert(t->n_args >= 2);
  4857. if (!strcmp(t->args[0], "ed25519")) {
  4858. if (md->ed25519_identity_pkey) {
  4859. log_warn(LD_DIR, "Extra ed25519 key in microdesc");
  4860. goto next;
  4861. }
  4862. ed25519_public_key_t k;
  4863. if (ed25519_public_from_base64(&k, t->args[1])<0) {
  4864. log_warn(LD_DIR, "Bogus ed25519 key in microdesc");
  4865. goto next;
  4866. }
  4867. md->ed25519_identity_pkey = tor_memdup(&k, sizeof(k));
  4868. }
  4869. } SMARTLIST_FOREACH_END(t);
  4870. smartlist_free(id_lines);
  4871. }
  4872. {
  4873. smartlist_t *a_lines = find_all_by_keyword(tokens, K_A);
  4874. if (a_lines) {
  4875. find_single_ipv6_orport(a_lines, &md->ipv6_addr, &md->ipv6_orport);
  4876. smartlist_free(a_lines);
  4877. }
  4878. }
  4879. if ((tok = find_opt_by_keyword(tokens, K_FAMILY))) {
  4880. int i;
  4881. md->family = smartlist_new();
  4882. for (i=0;i<tok->n_args;++i) {
  4883. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  4884. log_warn(LD_DIR, "Illegal nickname %s in family line",
  4885. escaped(tok->args[i]));
  4886. goto next;
  4887. }
  4888. smartlist_add(md->family, tor_strdup(tok->args[i]));
  4889. }
  4890. }
  4891. if ((tok = find_opt_by_keyword(tokens, K_P))) {
  4892. md->exit_policy = parse_short_policy(tok->args[0]);
  4893. }
  4894. if ((tok = find_opt_by_keyword(tokens, K_P6))) {
  4895. md->ipv6_exit_policy = parse_short_policy(tok->args[0]);
  4896. }
  4897. smartlist_add(result, md);
  4898. okay = 1;
  4899. md = NULL;
  4900. next:
  4901. if (! okay && invalid_digests_out) {
  4902. smartlist_add(invalid_digests_out,
  4903. tor_memdup(md->digest, DIGEST256_LEN));
  4904. }
  4905. microdesc_free(md);
  4906. md = NULL;
  4907. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4908. memarea_clear(area);
  4909. smartlist_clear(tokens);
  4910. s = start_of_next_microdesc;
  4911. }
  4912. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4913. memarea_drop_all(area);
  4914. smartlist_free(tokens);
  4915. return result;
  4916. }
  4917. /** Parse the Tor version of the platform string <b>platform</b>,
  4918. * and compare it to the version in <b>cutoff</b>. Return 1 if
  4919. * the router is at least as new as the cutoff, else return 0.
  4920. */
  4921. int
  4922. tor_version_as_new_as(const char *platform, const char *cutoff)
  4923. {
  4924. tor_version_t cutoff_version, router_version;
  4925. char *s, *s2, *start;
  4926. char tmp[128];
  4927. tor_assert(platform);
  4928. if (tor_version_parse(cutoff, &cutoff_version)<0) {
  4929. log_warn(LD_BUG,"cutoff version '%s' unparseable.",cutoff);
  4930. return 0;
  4931. }
  4932. if (strcmpstart(platform,"Tor ")) /* nonstandard Tor; be safe and say yes */
  4933. return 1;
  4934. start = (char *)eat_whitespace(platform+3);
  4935. if (!*start) return 0;
  4936. s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
  4937. s2 = (char*)eat_whitespace(s);
  4938. if (!strcmpstart(s2, "(r") || !strcmpstart(s2, "(git-"))
  4939. s = (char*)find_whitespace(s2);
  4940. if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
  4941. return 0;
  4942. strlcpy(tmp, start, s-start+1);
  4943. if (tor_version_parse(tmp, &router_version)<0) {
  4944. log_info(LD_DIR,"Router version '%s' unparseable.",tmp);
  4945. return 1; /* be safe and say yes */
  4946. }
  4947. /* Here's why we don't need to do any special handling for svn revisions:
  4948. * - If neither has an svn revision, we're fine.
  4949. * - If the router doesn't have an svn revision, we can't assume that it
  4950. * is "at least" any svn revision, so we need to return 0.
  4951. * - If the target version doesn't have an svn revision, any svn revision
  4952. * (or none at all) is good enough, so return 1.
  4953. * - If both target and router have an svn revision, we compare them.
  4954. */
  4955. return tor_version_compare(&router_version, &cutoff_version) >= 0;
  4956. }
  4957. /** Parse a tor version from <b>s</b>, and store the result in <b>out</b>.
  4958. * Return 0 on success, -1 on failure. */
  4959. int
  4960. tor_version_parse(const char *s, tor_version_t *out)
  4961. {
  4962. char *eos=NULL;
  4963. const char *cp=NULL;
  4964. /* Format is:
  4965. * "Tor " ? NUM dot NUM [ dot NUM [ ( pre | rc | dot ) NUM ] ] [ - tag ]
  4966. */
  4967. tor_assert(s);
  4968. tor_assert(out);
  4969. memset(out, 0, sizeof(tor_version_t));
  4970. out->status = VER_RELEASE;
  4971. if (!strcasecmpstart(s, "Tor "))
  4972. s += 4;
  4973. cp = s;
  4974. #define NUMBER(m) \
  4975. do { \
  4976. out->m = (int)strtol(cp, &eos, 10); \
  4977. if (!eos || eos == cp) \
  4978. return -1; \
  4979. cp = eos; \
  4980. } while (0)
  4981. #define DOT() \
  4982. do { \
  4983. if (*cp != '.') \
  4984. return -1; \
  4985. ++cp; \
  4986. } while (0)
  4987. NUMBER(major);
  4988. DOT();
  4989. NUMBER(minor);
  4990. if (*cp == 0)
  4991. return 0;
  4992. else if (*cp == '-')
  4993. goto status_tag;
  4994. DOT();
  4995. NUMBER(micro);
  4996. /* Get status */
  4997. if (*cp == 0) {
  4998. return 0;
  4999. } else if (*cp == '.') {
  5000. ++cp;
  5001. } else if (*cp == '-') {
  5002. goto status_tag;
  5003. } else if (0==strncmp(cp, "pre", 3)) {
  5004. out->status = VER_PRE;
  5005. cp += 3;
  5006. } else if (0==strncmp(cp, "rc", 2)) {
  5007. out->status = VER_RC;
  5008. cp += 2;
  5009. } else {
  5010. return -1;
  5011. }
  5012. NUMBER(patchlevel);
  5013. status_tag:
  5014. /* Get status tag. */
  5015. if (*cp == '-' || *cp == '.')
  5016. ++cp;
  5017. eos = (char*) find_whitespace(cp);
  5018. if (eos-cp >= (int)sizeof(out->status_tag))
  5019. strlcpy(out->status_tag, cp, sizeof(out->status_tag));
  5020. else {
  5021. memcpy(out->status_tag, cp, eos-cp);
  5022. out->status_tag[eos-cp] = 0;
  5023. }
  5024. cp = eat_whitespace(eos);
  5025. if (!strcmpstart(cp, "(r")) {
  5026. cp += 2;
  5027. out->svn_revision = (int) strtol(cp,&eos,10);
  5028. } else if (!strcmpstart(cp, "(git-")) {
  5029. char *close_paren = strchr(cp, ')');
  5030. int hexlen;
  5031. char digest[DIGEST_LEN];
  5032. if (! close_paren)
  5033. return -1;
  5034. cp += 5;
  5035. if (close_paren-cp > HEX_DIGEST_LEN)
  5036. return -1;
  5037. hexlen = (int)(close_paren-cp);
  5038. memwipe(digest, 0, sizeof(digest));
  5039. if ( hexlen == 0 || (hexlen % 2) == 1)
  5040. return -1;
  5041. if (base16_decode(digest, hexlen/2, cp, hexlen) != hexlen/2)
  5042. return -1;
  5043. memcpy(out->git_tag, digest, hexlen/2);
  5044. out->git_tag_len = hexlen/2;
  5045. }
  5046. return 0;
  5047. #undef NUMBER
  5048. #undef DOT
  5049. }
  5050. /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
  5051. * b. */
  5052. int
  5053. tor_version_compare(tor_version_t *a, tor_version_t *b)
  5054. {
  5055. int i;
  5056. tor_assert(a);
  5057. tor_assert(b);
  5058. if ((i = a->major - b->major))
  5059. return i;
  5060. else if ((i = a->minor - b->minor))
  5061. return i;
  5062. else if ((i = a->micro - b->micro))
  5063. return i;
  5064. else if ((i = a->status - b->status))
  5065. return i;
  5066. else if ((i = a->patchlevel - b->patchlevel))
  5067. return i;
  5068. else if ((i = strcmp(a->status_tag, b->status_tag)))
  5069. return i;
  5070. else if ((i = a->svn_revision - b->svn_revision))
  5071. return i;
  5072. else if ((i = a->git_tag_len - b->git_tag_len))
  5073. return i;
  5074. else if (a->git_tag_len)
  5075. return fast_memcmp(a->git_tag, b->git_tag, a->git_tag_len);
  5076. else
  5077. return 0;
  5078. }
  5079. /** Return true iff versions <b>a</b> and <b>b</b> belong to the same series.
  5080. */
  5081. int
  5082. tor_version_same_series(tor_version_t *a, tor_version_t *b)
  5083. {
  5084. tor_assert(a);
  5085. tor_assert(b);
  5086. return ((a->major == b->major) &&
  5087. (a->minor == b->minor) &&
  5088. (a->micro == b->micro));
  5089. }
  5090. /** Helper: Given pointers to two strings describing tor versions, return -1
  5091. * if _a precedes _b, 1 if _b precedes _a, and 0 if they are equivalent.
  5092. * Used to sort a list of versions. */
  5093. static int
  5094. compare_tor_version_str_ptr_(const void **_a, const void **_b)
  5095. {
  5096. const char *a = *_a, *b = *_b;
  5097. int ca, cb;
  5098. tor_version_t va, vb;
  5099. ca = tor_version_parse(a, &va);
  5100. cb = tor_version_parse(b, &vb);
  5101. /* If they both parse, compare them. */
  5102. if (!ca && !cb)
  5103. return tor_version_compare(&va,&vb);
  5104. /* If one parses, it comes first. */
  5105. if (!ca && cb)
  5106. return -1;
  5107. if (ca && !cb)
  5108. return 1;
  5109. /* If neither parses, compare strings. Also, the directory server admin
  5110. ** needs to be smacked upside the head. But Tor is tolerant and gentle. */
  5111. return strcmp(a,b);
  5112. }
  5113. /** Sort a list of string-representations of versions in ascending order. */
  5114. void
  5115. sort_version_list(smartlist_t *versions, int remove_duplicates)
  5116. {
  5117. smartlist_sort(versions, compare_tor_version_str_ptr_);
  5118. if (remove_duplicates)
  5119. smartlist_uniq(versions, compare_tor_version_str_ptr_, tor_free_);
  5120. }
  5121. /** Parse and validate the ASCII-encoded v2 descriptor in <b>desc</b>,
  5122. * write the parsed descriptor to the newly allocated *<b>parsed_out</b>, the
  5123. * binary descriptor ID of length DIGEST_LEN to <b>desc_id_out</b>, the
  5124. * encrypted introduction points to the newly allocated
  5125. * *<b>intro_points_encrypted_out</b>, their encrypted size to
  5126. * *<b>intro_points_encrypted_size_out</b>, the size of the encoded descriptor
  5127. * to *<b>encoded_size_out</b>, and a pointer to the possibly next
  5128. * descriptor to *<b>next_out</b>; return 0 for success (including validation)
  5129. * and -1 for failure.
  5130. *
  5131. * If <b>as_hsdir</b> is 1, we're parsing this as an HSDir, and we should
  5132. * be strict about time formats.
  5133. */
  5134. int
  5135. rend_parse_v2_service_descriptor(rend_service_descriptor_t **parsed_out,
  5136. char *desc_id_out,
  5137. char **intro_points_encrypted_out,
  5138. size_t *intro_points_encrypted_size_out,
  5139. size_t *encoded_size_out,
  5140. const char **next_out, const char *desc,
  5141. int as_hsdir)
  5142. {
  5143. rend_service_descriptor_t *result =
  5144. tor_malloc_zero(sizeof(rend_service_descriptor_t));
  5145. char desc_hash[DIGEST_LEN];
  5146. const char *eos;
  5147. smartlist_t *tokens = smartlist_new();
  5148. directory_token_t *tok;
  5149. char secret_id_part[DIGEST_LEN];
  5150. int i, version, num_ok=1;
  5151. smartlist_t *versions;
  5152. char public_key_hash[DIGEST_LEN];
  5153. char test_desc_id[DIGEST_LEN];
  5154. memarea_t *area = NULL;
  5155. const int strict_time_fmt = as_hsdir;
  5156. tor_assert(desc);
  5157. /* Check if desc starts correctly. */
  5158. if (strncmp(desc, "rendezvous-service-descriptor ",
  5159. strlen("rendezvous-service-descriptor "))) {
  5160. log_info(LD_REND, "Descriptor does not start correctly.");
  5161. goto err;
  5162. }
  5163. /* Compute descriptor hash for later validation. */
  5164. if (router_get_hash_impl(desc, strlen(desc), desc_hash,
  5165. "rendezvous-service-descriptor ",
  5166. "\nsignature", '\n', DIGEST_SHA1) < 0) {
  5167. log_warn(LD_REND, "Couldn't compute descriptor hash.");
  5168. goto err;
  5169. }
  5170. /* Determine end of string. */
  5171. eos = strstr(desc, "\nrendezvous-service-descriptor ");
  5172. if (!eos)
  5173. eos = desc + strlen(desc);
  5174. else
  5175. eos = eos + 1;
  5176. /* Check length. */
  5177. if (eos-desc > REND_DESC_MAX_SIZE) {
  5178. /* XXXX+ If we are parsing this descriptor as a server, this
  5179. * should be a protocol warning. */
  5180. log_warn(LD_REND, "Descriptor length is %d which exceeds "
  5181. "maximum rendezvous descriptor size of %d bytes.",
  5182. (int)(eos-desc), REND_DESC_MAX_SIZE);
  5183. goto err;
  5184. }
  5185. /* Tokenize descriptor. */
  5186. area = memarea_new();
  5187. if (tokenize_string(area, desc, eos, tokens, desc_token_table, 0)) {
  5188. log_warn(LD_REND, "Error tokenizing descriptor.");
  5189. goto err;
  5190. }
  5191. /* Set next to next descriptor, if available. */
  5192. *next_out = eos;
  5193. /* Set length of encoded descriptor. */
  5194. *encoded_size_out = eos - desc;
  5195. /* Check min allowed length of token list. */
  5196. if (smartlist_len(tokens) < 7) {
  5197. log_warn(LD_REND, "Impossibly short descriptor.");
  5198. goto err;
  5199. }
  5200. /* Parse base32-encoded descriptor ID. */
  5201. tok = find_by_keyword(tokens, R_RENDEZVOUS_SERVICE_DESCRIPTOR);
  5202. tor_assert(tok == smartlist_get(tokens, 0));
  5203. tor_assert(tok->n_args == 1);
  5204. if (!rend_valid_descriptor_id(tok->args[0])) {
  5205. log_warn(LD_REND, "Invalid descriptor ID: '%s'", tok->args[0]);
  5206. goto err;
  5207. }
  5208. if (base32_decode(desc_id_out, DIGEST_LEN,
  5209. tok->args[0], REND_DESC_ID_V2_LEN_BASE32) < 0) {
  5210. log_warn(LD_REND, "Descriptor ID contains illegal characters: %s",
  5211. tok->args[0]);
  5212. goto err;
  5213. }
  5214. /* Parse descriptor version. */
  5215. tok = find_by_keyword(tokens, R_VERSION);
  5216. tor_assert(tok->n_args == 1);
  5217. result->version =
  5218. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &num_ok, NULL);
  5219. if (result->version != 2 || !num_ok) {
  5220. /* If it's <2, it shouldn't be under this format. If the number
  5221. * is greater than 2, we bumped it because we broke backward
  5222. * compatibility. See how version numbers in our other formats
  5223. * work. */
  5224. log_warn(LD_REND, "Unrecognized descriptor version: %s",
  5225. escaped(tok->args[0]));
  5226. goto err;
  5227. }
  5228. /* Parse public key. */
  5229. tok = find_by_keyword(tokens, R_PERMANENT_KEY);
  5230. result->pk = tok->key;
  5231. tok->key = NULL; /* Prevent free */
  5232. /* Parse secret ID part. */
  5233. tok = find_by_keyword(tokens, R_SECRET_ID_PART);
  5234. tor_assert(tok->n_args == 1);
  5235. if (strlen(tok->args[0]) != REND_SECRET_ID_PART_LEN_BASE32 ||
  5236. strspn(tok->args[0], BASE32_CHARS) != REND_SECRET_ID_PART_LEN_BASE32) {
  5237. log_warn(LD_REND, "Invalid secret ID part: '%s'", tok->args[0]);
  5238. goto err;
  5239. }
  5240. if (base32_decode(secret_id_part, DIGEST_LEN, tok->args[0], 32) < 0) {
  5241. log_warn(LD_REND, "Secret ID part contains illegal characters: %s",
  5242. tok->args[0]);
  5243. goto err;
  5244. }
  5245. /* Parse publication time -- up-to-date check is done when storing the
  5246. * descriptor. */
  5247. tok = find_by_keyword(tokens, R_PUBLICATION_TIME);
  5248. tor_assert(tok->n_args == 1);
  5249. if (parse_iso_time_(tok->args[0], &result->timestamp, strict_time_fmt) < 0) {
  5250. log_warn(LD_REND, "Invalid publication time: '%s'", tok->args[0]);
  5251. goto err;
  5252. }
  5253. /* Parse protocol versions. */
  5254. tok = find_by_keyword(tokens, R_PROTOCOL_VERSIONS);
  5255. tor_assert(tok->n_args == 1);
  5256. versions = smartlist_new();
  5257. smartlist_split_string(versions, tok->args[0], ",",
  5258. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  5259. for (i = 0; i < smartlist_len(versions); i++) {
  5260. version = (int) tor_parse_long(smartlist_get(versions, i),
  5261. 10, 0, INT_MAX, &num_ok, NULL);
  5262. if (!num_ok) /* It's a string; let's ignore it. */
  5263. continue;
  5264. if (version >= REND_PROTOCOL_VERSION_BITMASK_WIDTH)
  5265. /* Avoid undefined left-shift behaviour. */
  5266. continue;
  5267. result->protocols |= 1 << version;
  5268. }
  5269. SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
  5270. smartlist_free(versions);
  5271. /* Parse encrypted introduction points. Don't verify. */
  5272. tok = find_opt_by_keyword(tokens, R_INTRODUCTION_POINTS);
  5273. if (tok) {
  5274. if (strcmp(tok->object_type, "MESSAGE")) {
  5275. log_warn(LD_DIR, "Bad object type: introduction points should be of "
  5276. "type MESSAGE");
  5277. goto err;
  5278. }
  5279. *intro_points_encrypted_out = tor_memdup(tok->object_body,
  5280. tok->object_size);
  5281. *intro_points_encrypted_size_out = tok->object_size;
  5282. } else {
  5283. *intro_points_encrypted_out = NULL;
  5284. *intro_points_encrypted_size_out = 0;
  5285. }
  5286. /* Parse and verify signature. */
  5287. tok = find_by_keyword(tokens, R_SIGNATURE);
  5288. note_crypto_pk_op(VERIFY_RTR);
  5289. if (check_signature_token(desc_hash, DIGEST_LEN, tok, result->pk, 0,
  5290. "v2 rendezvous service descriptor") < 0)
  5291. goto err;
  5292. /* Verify that descriptor ID belongs to public key and secret ID part. */
  5293. crypto_pk_get_digest(result->pk, public_key_hash);
  5294. rend_get_descriptor_id_bytes(test_desc_id, public_key_hash,
  5295. secret_id_part);
  5296. if (tor_memneq(desc_id_out, test_desc_id, DIGEST_LEN)) {
  5297. log_warn(LD_REND, "Parsed descriptor ID does not match "
  5298. "computed descriptor ID.");
  5299. goto err;
  5300. }
  5301. goto done;
  5302. err:
  5303. rend_service_descriptor_free(result);
  5304. result = NULL;
  5305. done:
  5306. if (tokens) {
  5307. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  5308. smartlist_free(tokens);
  5309. }
  5310. if (area)
  5311. memarea_drop_all(area);
  5312. *parsed_out = result;
  5313. if (result)
  5314. return 0;
  5315. return -1;
  5316. }
  5317. /** Decrypt the encrypted introduction points in <b>ipos_encrypted</b> of
  5318. * length <b>ipos_encrypted_size</b> using <b>descriptor_cookie</b> and
  5319. * write the result to a newly allocated string that is pointed to by
  5320. * <b>ipos_decrypted</b> and its length to <b>ipos_decrypted_size</b>.
  5321. * Return 0 if decryption was successful and -1 otherwise. */
  5322. int
  5323. rend_decrypt_introduction_points(char **ipos_decrypted,
  5324. size_t *ipos_decrypted_size,
  5325. const char *descriptor_cookie,
  5326. const char *ipos_encrypted,
  5327. size_t ipos_encrypted_size)
  5328. {
  5329. tor_assert(ipos_encrypted);
  5330. tor_assert(descriptor_cookie);
  5331. if (ipos_encrypted_size < 2) {
  5332. log_warn(LD_REND, "Size of encrypted introduction points is too "
  5333. "small.");
  5334. return -1;
  5335. }
  5336. if (ipos_encrypted[0] == (int)REND_BASIC_AUTH) {
  5337. char iv[CIPHER_IV_LEN], client_id[REND_BASIC_AUTH_CLIENT_ID_LEN],
  5338. session_key[CIPHER_KEY_LEN], *dec;
  5339. int declen, client_blocks;
  5340. size_t pos = 0, len, client_entries_len;
  5341. crypto_digest_t *digest;
  5342. crypto_cipher_t *cipher;
  5343. client_blocks = (int) ipos_encrypted[1];
  5344. client_entries_len = client_blocks * REND_BASIC_AUTH_CLIENT_MULTIPLE *
  5345. REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
  5346. if (ipos_encrypted_size < 2 + client_entries_len + CIPHER_IV_LEN + 1) {
  5347. log_warn(LD_REND, "Size of encrypted introduction points is too "
  5348. "small.");
  5349. return -1;
  5350. }
  5351. memcpy(iv, ipos_encrypted + 2 + client_entries_len, CIPHER_IV_LEN);
  5352. digest = crypto_digest_new();
  5353. crypto_digest_add_bytes(digest, descriptor_cookie, REND_DESC_COOKIE_LEN);
  5354. crypto_digest_add_bytes(digest, iv, CIPHER_IV_LEN);
  5355. crypto_digest_get_digest(digest, client_id,
  5356. REND_BASIC_AUTH_CLIENT_ID_LEN);
  5357. crypto_digest_free(digest);
  5358. for (pos = 2; pos < 2 + client_entries_len;
  5359. pos += REND_BASIC_AUTH_CLIENT_ENTRY_LEN) {
  5360. if (tor_memeq(ipos_encrypted + pos, client_id,
  5361. REND_BASIC_AUTH_CLIENT_ID_LEN)) {
  5362. /* Attempt to decrypt introduction points. */
  5363. cipher = crypto_cipher_new(descriptor_cookie);
  5364. if (crypto_cipher_decrypt(cipher, session_key, ipos_encrypted
  5365. + pos + REND_BASIC_AUTH_CLIENT_ID_LEN,
  5366. CIPHER_KEY_LEN) < 0) {
  5367. log_warn(LD_REND, "Could not decrypt session key for client.");
  5368. crypto_cipher_free(cipher);
  5369. return -1;
  5370. }
  5371. crypto_cipher_free(cipher);
  5372. len = ipos_encrypted_size - 2 - client_entries_len - CIPHER_IV_LEN;
  5373. dec = tor_malloc(len);
  5374. declen = crypto_cipher_decrypt_with_iv(session_key, dec, len,
  5375. ipos_encrypted + 2 + client_entries_len,
  5376. ipos_encrypted_size - 2 - client_entries_len);
  5377. if (declen < 0) {
  5378. log_warn(LD_REND, "Could not decrypt introduction point string.");
  5379. tor_free(dec);
  5380. return -1;
  5381. }
  5382. if (fast_memcmpstart(dec, declen, "introduction-point ")) {
  5383. log_warn(LD_REND, "Decrypted introduction points don't "
  5384. "look like we could parse them.");
  5385. tor_free(dec);
  5386. continue;
  5387. }
  5388. *ipos_decrypted = dec;
  5389. *ipos_decrypted_size = declen;
  5390. return 0;
  5391. }
  5392. }
  5393. log_warn(LD_REND, "Could not decrypt introduction points. Please "
  5394. "check your authorization for this service!");
  5395. return -1;
  5396. } else if (ipos_encrypted[0] == (int)REND_STEALTH_AUTH) {
  5397. char *dec;
  5398. int declen;
  5399. if (ipos_encrypted_size < CIPHER_IV_LEN + 2) {
  5400. log_warn(LD_REND, "Size of encrypted introduction points is too "
  5401. "small.");
  5402. return -1;
  5403. }
  5404. dec = tor_malloc_zero(ipos_encrypted_size - CIPHER_IV_LEN - 1);
  5405. declen = crypto_cipher_decrypt_with_iv(descriptor_cookie, dec,
  5406. ipos_encrypted_size -
  5407. CIPHER_IV_LEN - 1,
  5408. ipos_encrypted + 1,
  5409. ipos_encrypted_size - 1);
  5410. if (declen < 0) {
  5411. log_warn(LD_REND, "Decrypting introduction points failed!");
  5412. tor_free(dec);
  5413. return -1;
  5414. }
  5415. *ipos_decrypted = dec;
  5416. *ipos_decrypted_size = declen;
  5417. return 0;
  5418. } else {
  5419. log_warn(LD_REND, "Unknown authorization type number: %d",
  5420. ipos_encrypted[0]);
  5421. return -1;
  5422. }
  5423. }
  5424. /** Parse the encoded introduction points in <b>intro_points_encoded</b> of
  5425. * length <b>intro_points_encoded_size</b> and write the result to the
  5426. * descriptor in <b>parsed</b>; return the number of successfully parsed
  5427. * introduction points or -1 in case of a failure. */
  5428. int
  5429. rend_parse_introduction_points(rend_service_descriptor_t *parsed,
  5430. const char *intro_points_encoded,
  5431. size_t intro_points_encoded_size)
  5432. {
  5433. const char *current_ipo, *end_of_intro_points;
  5434. smartlist_t *tokens = NULL;
  5435. directory_token_t *tok;
  5436. rend_intro_point_t *intro;
  5437. extend_info_t *info;
  5438. int result, num_ok=1;
  5439. memarea_t *area = NULL;
  5440. tor_assert(parsed);
  5441. /** Function may only be invoked once. */
  5442. tor_assert(!parsed->intro_nodes);
  5443. if (!intro_points_encoded || intro_points_encoded_size == 0) {
  5444. log_warn(LD_REND, "Empty or zero size introduction point list");
  5445. goto err;
  5446. }
  5447. /* Consider one intro point after the other. */
  5448. current_ipo = intro_points_encoded;
  5449. end_of_intro_points = intro_points_encoded + intro_points_encoded_size;
  5450. tokens = smartlist_new();
  5451. parsed->intro_nodes = smartlist_new();
  5452. area = memarea_new();
  5453. while (!fast_memcmpstart(current_ipo, end_of_intro_points-current_ipo,
  5454. "introduction-point ")) {
  5455. /* Determine end of string. */
  5456. const char *eos = tor_memstr(current_ipo, end_of_intro_points-current_ipo,
  5457. "\nintroduction-point ");
  5458. if (!eos)
  5459. eos = end_of_intro_points;
  5460. else
  5461. eos = eos+1;
  5462. tor_assert(eos <= intro_points_encoded+intro_points_encoded_size);
  5463. /* Free tokens and clear token list. */
  5464. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  5465. smartlist_clear(tokens);
  5466. memarea_clear(area);
  5467. /* Tokenize string. */
  5468. if (tokenize_string(area, current_ipo, eos, tokens, ipo_token_table, 0)) {
  5469. log_warn(LD_REND, "Error tokenizing introduction point");
  5470. goto err;
  5471. }
  5472. /* Advance to next introduction point, if available. */
  5473. current_ipo = eos;
  5474. /* Check minimum allowed length of introduction point. */
  5475. if (smartlist_len(tokens) < 5) {
  5476. log_warn(LD_REND, "Impossibly short introduction point.");
  5477. goto err;
  5478. }
  5479. /* Allocate new intro point and extend info. */
  5480. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  5481. info = intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  5482. /* Parse identifier. */
  5483. tok = find_by_keyword(tokens, R_IPO_IDENTIFIER);
  5484. if (base32_decode(info->identity_digest, DIGEST_LEN,
  5485. tok->args[0], REND_INTRO_POINT_ID_LEN_BASE32) < 0) {
  5486. log_warn(LD_REND, "Identity digest contains illegal characters: %s",
  5487. tok->args[0]);
  5488. rend_intro_point_free(intro);
  5489. goto err;
  5490. }
  5491. /* Write identifier to nickname. */
  5492. info->nickname[0] = '$';
  5493. base16_encode(info->nickname + 1, sizeof(info->nickname) - 1,
  5494. info->identity_digest, DIGEST_LEN);
  5495. /* Parse IP address. */
  5496. tok = find_by_keyword(tokens, R_IPO_IP_ADDRESS);
  5497. if (tor_addr_parse(&info->addr, tok->args[0])<0) {
  5498. log_warn(LD_REND, "Could not parse introduction point address.");
  5499. rend_intro_point_free(intro);
  5500. goto err;
  5501. }
  5502. if (tor_addr_family(&info->addr) != AF_INET) {
  5503. log_warn(LD_REND, "Introduction point address was not ipv4.");
  5504. rend_intro_point_free(intro);
  5505. goto err;
  5506. }
  5507. /* Parse onion port. */
  5508. tok = find_by_keyword(tokens, R_IPO_ONION_PORT);
  5509. info->port = (uint16_t) tor_parse_long(tok->args[0],10,1,65535,
  5510. &num_ok,NULL);
  5511. if (!info->port || !num_ok) {
  5512. log_warn(LD_REND, "Introduction point onion port %s is invalid",
  5513. escaped(tok->args[0]));
  5514. rend_intro_point_free(intro);
  5515. goto err;
  5516. }
  5517. /* Parse onion key. */
  5518. tok = find_by_keyword(tokens, R_IPO_ONION_KEY);
  5519. if (!crypto_pk_public_exponent_ok(tok->key)) {
  5520. log_warn(LD_REND,
  5521. "Introduction point's onion key had invalid exponent.");
  5522. rend_intro_point_free(intro);
  5523. goto err;
  5524. }
  5525. info->onion_key = tok->key;
  5526. tok->key = NULL; /* Prevent free */
  5527. /* Parse service key. */
  5528. tok = find_by_keyword(tokens, R_IPO_SERVICE_KEY);
  5529. if (!crypto_pk_public_exponent_ok(tok->key)) {
  5530. log_warn(LD_REND,
  5531. "Introduction point key had invalid exponent.");
  5532. rend_intro_point_free(intro);
  5533. goto err;
  5534. }
  5535. intro->intro_key = tok->key;
  5536. tok->key = NULL; /* Prevent free */
  5537. /* Add extend info to list of introduction points. */
  5538. smartlist_add(parsed->intro_nodes, intro);
  5539. }
  5540. result = smartlist_len(parsed->intro_nodes);
  5541. goto done;
  5542. err:
  5543. result = -1;
  5544. done:
  5545. /* Free tokens and clear token list. */
  5546. if (tokens) {
  5547. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  5548. smartlist_free(tokens);
  5549. }
  5550. if (area)
  5551. memarea_drop_all(area);
  5552. return result;
  5553. }
  5554. /** Parse the content of a client_key file in <b>ckstr</b> and add
  5555. * rend_authorized_client_t's for each parsed client to
  5556. * <b>parsed_clients</b>. Return the number of parsed clients as result
  5557. * or -1 for failure. */
  5558. int
  5559. rend_parse_client_keys(strmap_t *parsed_clients, const char *ckstr)
  5560. {
  5561. int result = -1;
  5562. smartlist_t *tokens;
  5563. directory_token_t *tok;
  5564. const char *current_entry = NULL;
  5565. memarea_t *area = NULL;
  5566. char *err_msg = NULL;
  5567. if (!ckstr || strlen(ckstr) == 0)
  5568. return -1;
  5569. tokens = smartlist_new();
  5570. /* Begin parsing with first entry, skipping comments or whitespace at the
  5571. * beginning. */
  5572. area = memarea_new();
  5573. current_entry = eat_whitespace(ckstr);
  5574. while (!strcmpstart(current_entry, "client-name ")) {
  5575. rend_authorized_client_t *parsed_entry;
  5576. /* Determine end of string. */
  5577. const char *eos = strstr(current_entry, "\nclient-name ");
  5578. if (!eos)
  5579. eos = current_entry + strlen(current_entry);
  5580. else
  5581. eos = eos + 1;
  5582. /* Free tokens and clear token list. */
  5583. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  5584. smartlist_clear(tokens);
  5585. memarea_clear(area);
  5586. /* Tokenize string. */
  5587. if (tokenize_string(area, current_entry, eos, tokens,
  5588. client_keys_token_table, 0)) {
  5589. log_warn(LD_REND, "Error tokenizing client keys file.");
  5590. goto err;
  5591. }
  5592. /* Advance to next entry, if available. */
  5593. current_entry = eos;
  5594. /* Check minimum allowed length of token list. */
  5595. if (smartlist_len(tokens) < 2) {
  5596. log_warn(LD_REND, "Impossibly short client key entry.");
  5597. goto err;
  5598. }
  5599. /* Parse client name. */
  5600. tok = find_by_keyword(tokens, C_CLIENT_NAME);
  5601. tor_assert(tok == smartlist_get(tokens, 0));
  5602. tor_assert(tok->n_args == 1);
  5603. if (!rend_valid_client_name(tok->args[0])) {
  5604. log_warn(LD_CONFIG, "Illegal client name: %s. (Length must be "
  5605. "between 1 and %d, and valid characters are "
  5606. "[A-Za-z0-9+-_].)", tok->args[0], REND_CLIENTNAME_MAX_LEN);
  5607. goto err;
  5608. }
  5609. /* Check if client name is duplicate. */
  5610. if (strmap_get(parsed_clients, tok->args[0])) {
  5611. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains a "
  5612. "duplicate client name: '%s'. Ignoring.", tok->args[0]);
  5613. goto err;
  5614. }
  5615. parsed_entry = tor_malloc_zero(sizeof(rend_authorized_client_t));
  5616. parsed_entry->client_name = tor_strdup(tok->args[0]);
  5617. strmap_set(parsed_clients, parsed_entry->client_name, parsed_entry);
  5618. /* Parse client key. */
  5619. tok = find_opt_by_keyword(tokens, C_CLIENT_KEY);
  5620. if (tok) {
  5621. parsed_entry->client_key = tok->key;
  5622. tok->key = NULL; /* Prevent free */
  5623. }
  5624. /* Parse descriptor cookie. */
  5625. tok = find_by_keyword(tokens, C_DESCRIPTOR_COOKIE);
  5626. tor_assert(tok->n_args == 1);
  5627. if (rend_auth_decode_cookie(tok->args[0], parsed_entry->descriptor_cookie,
  5628. NULL, &err_msg) < 0) {
  5629. tor_assert(err_msg);
  5630. log_warn(LD_REND, "%s", err_msg);
  5631. tor_free(err_msg);
  5632. goto err;
  5633. }
  5634. }
  5635. result = strmap_size(parsed_clients);
  5636. goto done;
  5637. err:
  5638. result = -1;
  5639. done:
  5640. /* Free tokens and clear token list. */
  5641. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  5642. smartlist_free(tokens);
  5643. if (area)
  5644. memarea_drop_all(area);
  5645. return result;
  5646. }
  5647. /** Called on startup; right now we just handle scanning the unparseable
  5648. * descriptor dumps, but hang anything else we might need to do in the
  5649. * future here as well.
  5650. */
  5651. void
  5652. routerparse_init(void)
  5653. {
  5654. /*
  5655. * Check both if the sandbox is active and whether it's configured; no
  5656. * point in loading all that if we won't be able to use it after the
  5657. * sandbox becomes active.
  5658. */
  5659. if (!(sandbox_is_active() || get_options()->Sandbox)) {
  5660. dump_desc_init();
  5661. }
  5662. }
  5663. /** Clean up all data structures used by routerparse.c at exit */
  5664. void
  5665. routerparse_free_all(void)
  5666. {
  5667. dump_desc_fifo_cleanup();
  5668. }