routerparse.c 196 KB

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