routerparse.c 204 KB

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