routerparse.c 217 KB

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