routerparse.c 193 KB

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