routerparse.c 192 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563
  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. 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. /** Check whether the object body of the token in <b>tok</b> has a good
  1052. * signature for <b>digest</b> using key <b>pkey</b>.
  1053. * If <b>CST_NO_CHECK_OBJTYPE</b> is set, do not check
  1054. * the object type of the signature object. Use <b>doctype</b> as the type of
  1055. * the document when generating log messages. Return 0 on success, negative
  1056. * on failure.
  1057. */
  1058. static int
  1059. check_signature_token(const char *digest,
  1060. ssize_t digest_len,
  1061. directory_token_t *tok,
  1062. crypto_pk_t *pkey,
  1063. int flags,
  1064. const char *doctype)
  1065. {
  1066. char *signed_digest;
  1067. size_t keysize;
  1068. const int check_objtype = ! (flags & CST_NO_CHECK_OBJTYPE);
  1069. tor_assert(pkey);
  1070. tor_assert(tok);
  1071. tor_assert(digest);
  1072. tor_assert(doctype);
  1073. if (check_objtype) {
  1074. if (strcmp(tok->object_type, "SIGNATURE")) {
  1075. log_warn(LD_DIR, "Bad object type on %s signature", doctype);
  1076. return -1;
  1077. }
  1078. }
  1079. keysize = crypto_pk_keysize(pkey);
  1080. signed_digest = tor_malloc(keysize);
  1081. if (crypto_pk_public_checksig(pkey, signed_digest, keysize,
  1082. tok->object_body, tok->object_size)
  1083. < digest_len) {
  1084. log_warn(LD_DIR, "Error reading %s: invalid signature.", doctype);
  1085. tor_free(signed_digest);
  1086. return -1;
  1087. }
  1088. // log_debug(LD_DIR,"Signed %s hash starts %s", doctype,
  1089. // hex_str(signed_digest,4));
  1090. if (tor_memneq(digest, signed_digest, digest_len)) {
  1091. log_warn(LD_DIR, "Error reading %s: signature does not match.", doctype);
  1092. tor_free(signed_digest);
  1093. return -1;
  1094. }
  1095. tor_free(signed_digest);
  1096. return 0;
  1097. }
  1098. /** Helper: move *<b>s_ptr</b> ahead to the next router, the next extra-info,
  1099. * or to the first of the annotations proceeding the next router or
  1100. * extra-info---whichever comes first. Set <b>is_extrainfo_out</b> to true if
  1101. * we found an extrainfo, or false if found a router. Do not scan beyond
  1102. * <b>eos</b>. Return -1 if we found nothing; 0 if we found something. */
  1103. static int
  1104. find_start_of_next_router_or_extrainfo(const char **s_ptr,
  1105. const char *eos,
  1106. int *is_extrainfo_out)
  1107. {
  1108. const char *annotations = NULL;
  1109. const char *s = *s_ptr;
  1110. s = eat_whitespace_eos(s, eos);
  1111. while (s < eos-32) { /* 32 gives enough room for a the first keyword. */
  1112. /* We're at the start of a line. */
  1113. tor_assert(*s != '\n');
  1114. if (*s == '@' && !annotations) {
  1115. annotations = s;
  1116. } else if (*s == 'r' && !strcmpstart(s, "router ")) {
  1117. *s_ptr = annotations ? annotations : s;
  1118. *is_extrainfo_out = 0;
  1119. return 0;
  1120. } else if (*s == 'e' && !strcmpstart(s, "extra-info ")) {
  1121. *s_ptr = annotations ? annotations : s;
  1122. *is_extrainfo_out = 1;
  1123. return 0;
  1124. }
  1125. if (!(s = memchr(s+1, '\n', eos-(s+1))))
  1126. break;
  1127. s = eat_whitespace_eos(s, eos);
  1128. }
  1129. return -1;
  1130. }
  1131. /** Given a string *<b>s</b> containing a concatenated sequence of router
  1132. * descriptors (or extra-info documents if <b>is_extrainfo</b> is set), parses
  1133. * them and stores the result in <b>dest</b>. All routers are marked running
  1134. * and valid. Advances *s to a point immediately following the last router
  1135. * entry. Ignore any trailing router entries that are not complete.
  1136. *
  1137. * If <b>saved_location</b> isn't SAVED_IN_CACHE, make a local copy of each
  1138. * descriptor in the signed_descriptor_body field of each routerinfo_t. If it
  1139. * isn't SAVED_NOWHERE, remember the offset of each descriptor.
  1140. *
  1141. * Returns 0 on success and -1 on failure. Adds a digest to
  1142. * <b>invalid_digests_out</b> for every entry that was unparseable or
  1143. * invalid. (This may cause duplicate entries.)
  1144. */
  1145. int
  1146. router_parse_list_from_string(const char **s, const char *eos,
  1147. smartlist_t *dest,
  1148. saved_location_t saved_location,
  1149. int want_extrainfo,
  1150. int allow_annotations,
  1151. const char *prepend_annotations,
  1152. smartlist_t *invalid_digests_out)
  1153. {
  1154. routerinfo_t *router;
  1155. extrainfo_t *extrainfo;
  1156. signed_descriptor_t *signed_desc = NULL;
  1157. void *elt;
  1158. const char *end, *start;
  1159. int have_extrainfo;
  1160. tor_assert(s);
  1161. tor_assert(*s);
  1162. tor_assert(dest);
  1163. start = *s;
  1164. if (!eos)
  1165. eos = *s + strlen(*s);
  1166. tor_assert(eos >= *s);
  1167. while (1) {
  1168. char raw_digest[DIGEST_LEN];
  1169. int have_raw_digest = 0;
  1170. int dl_again = 0;
  1171. if (find_start_of_next_router_or_extrainfo(s, eos, &have_extrainfo) < 0)
  1172. break;
  1173. end = tor_memstr(*s, eos-*s, "\nrouter-signature");
  1174. if (end)
  1175. end = tor_memstr(end, eos-end, "\n-----END SIGNATURE-----\n");
  1176. if (end)
  1177. end += strlen("\n-----END SIGNATURE-----\n");
  1178. if (!end)
  1179. break;
  1180. elt = NULL;
  1181. if (have_extrainfo && want_extrainfo) {
  1182. routerlist_t *rl = router_get_routerlist();
  1183. have_raw_digest = router_get_extrainfo_hash(*s, end-*s, raw_digest) == 0;
  1184. extrainfo = extrainfo_parse_entry_from_string(*s, end,
  1185. saved_location != SAVED_IN_CACHE,
  1186. rl->identity_map, &dl_again);
  1187. if (extrainfo) {
  1188. signed_desc = &extrainfo->cache_info;
  1189. elt = extrainfo;
  1190. }
  1191. } else if (!have_extrainfo && !want_extrainfo) {
  1192. have_raw_digest = router_get_router_hash(*s, end-*s, raw_digest) == 0;
  1193. router = router_parse_entry_from_string(*s, end,
  1194. saved_location != SAVED_IN_CACHE,
  1195. allow_annotations,
  1196. prepend_annotations, &dl_again);
  1197. if (router) {
  1198. log_debug(LD_DIR, "Read router '%s', purpose '%s'",
  1199. router_describe(router),
  1200. router_purpose_to_string(router->purpose));
  1201. signed_desc = &router->cache_info;
  1202. elt = router;
  1203. }
  1204. }
  1205. if (! elt && ! dl_again && have_raw_digest && invalid_digests_out) {
  1206. smartlist_add(invalid_digests_out, tor_memdup(raw_digest, DIGEST_LEN));
  1207. }
  1208. if (!elt) {
  1209. *s = end;
  1210. continue;
  1211. }
  1212. if (saved_location != SAVED_NOWHERE) {
  1213. tor_assert(signed_desc);
  1214. signed_desc->saved_location = saved_location;
  1215. signed_desc->saved_offset = *s - start;
  1216. }
  1217. *s = end;
  1218. smartlist_add(dest, elt);
  1219. }
  1220. return 0;
  1221. }
  1222. /* For debugging: define to count every descriptor digest we've seen so we
  1223. * know if we need to try harder to avoid duplicate verifies. */
  1224. #undef COUNT_DISTINCT_DIGESTS
  1225. #ifdef COUNT_DISTINCT_DIGESTS
  1226. static digestmap_t *verified_digests = NULL;
  1227. #endif
  1228. /** Log the total count of the number of distinct router digests we've ever
  1229. * verified. When compared to the number of times we've verified routerdesc
  1230. * signatures <i>in toto</i>, this will tell us if we're doing too much
  1231. * multiple-verification. */
  1232. void
  1233. dump_distinct_digest_count(int severity)
  1234. {
  1235. #ifdef COUNT_DISTINCT_DIGESTS
  1236. if (!verified_digests)
  1237. verified_digests = digestmap_new();
  1238. tor_log(severity, LD_GENERAL, "%d *distinct* router digests verified",
  1239. digestmap_size(verified_digests));
  1240. #else
  1241. (void)severity; /* suppress "unused parameter" warning */
  1242. #endif
  1243. }
  1244. /** Try to find an IPv6 OR port in <b>list</b> of directory_token_t's
  1245. * with at least one argument (use GE(1) in setup). If found, store
  1246. * address and port number to <b>addr_out</b> and
  1247. * <b>port_out</b>. Return number of OR ports found. */
  1248. static int
  1249. find_single_ipv6_orport(const smartlist_t *list,
  1250. tor_addr_t *addr_out,
  1251. uint16_t *port_out)
  1252. {
  1253. int ret = 0;
  1254. tor_assert(list != NULL);
  1255. tor_assert(addr_out != NULL);
  1256. tor_assert(port_out != NULL);
  1257. SMARTLIST_FOREACH_BEGIN(list, directory_token_t *, t) {
  1258. tor_addr_t a;
  1259. maskbits_t bits;
  1260. uint16_t port_min, port_max;
  1261. tor_assert(t->n_args >= 1);
  1262. /* XXXX Prop186 the full spec allows much more than this. */
  1263. if (tor_addr_parse_mask_ports(t->args[0], 0,
  1264. &a, &bits, &port_min,
  1265. &port_max) == AF_INET6 &&
  1266. bits == 128 &&
  1267. port_min == port_max) {
  1268. /* Okay, this is one we can understand. Use it and ignore
  1269. any potential more addresses in list. */
  1270. tor_addr_copy(addr_out, &a);
  1271. *port_out = port_min;
  1272. ret = 1;
  1273. break;
  1274. }
  1275. } SMARTLIST_FOREACH_END(t);
  1276. return ret;
  1277. }
  1278. /** Helper function: reads a single router entry from *<b>s</b> ...
  1279. * *<b>end</b>. Mallocs a new router and returns it if all goes well, else
  1280. * returns NULL. If <b>cache_copy</b> is true, duplicate the contents of
  1281. * s through end into the signed_descriptor_body of the resulting
  1282. * routerinfo_t.
  1283. *
  1284. * If <b>end</b> is NULL, <b>s</b> must be properly NUL-terminated.
  1285. *
  1286. * If <b>allow_annotations</b>, it's okay to encounter annotations in <b>s</b>
  1287. * before the router; if it's false, reject the router if it's annotated. If
  1288. * <b>prepend_annotations</b> is set, it should contain some annotations:
  1289. * append them to the front of the router before parsing it, and keep them
  1290. * around when caching the router.
  1291. *
  1292. * Only one of allow_annotations and prepend_annotations may be set.
  1293. *
  1294. * If <b>can_dl_again_out</b> is provided, set *<b>can_dl_again_out</b> to 1
  1295. * if it's okay to try to download a descriptor with this same digest again,
  1296. * and 0 if it isn't. (It might not be okay to download it again if part of
  1297. * the part covered by the digest is invalid.)
  1298. */
  1299. routerinfo_t *
  1300. router_parse_entry_from_string(const char *s, const char *end,
  1301. int cache_copy, int allow_annotations,
  1302. const char *prepend_annotations,
  1303. int *can_dl_again_out)
  1304. {
  1305. routerinfo_t *router = NULL;
  1306. char digest[128];
  1307. smartlist_t *tokens = NULL, *exit_policy_tokens = NULL;
  1308. directory_token_t *tok;
  1309. struct in_addr in;
  1310. const char *start_of_annotations, *cp, *s_dup = s;
  1311. size_t prepend_len = prepend_annotations ? strlen(prepend_annotations) : 0;
  1312. int ok = 1;
  1313. memarea_t *area = NULL;
  1314. tor_cert_t *ntor_cc_cert = NULL;
  1315. /* Do not set this to '1' until we have parsed everything that we intend to
  1316. * parse that's covered by the hash. */
  1317. int can_dl_again = 0;
  1318. tor_assert(!allow_annotations || !prepend_annotations);
  1319. if (!end) {
  1320. end = s + strlen(s);
  1321. }
  1322. /* point 'end' to a point immediately after the final newline. */
  1323. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  1324. --end;
  1325. area = memarea_new();
  1326. tokens = smartlist_new();
  1327. if (prepend_annotations) {
  1328. if (tokenize_string(area,prepend_annotations,NULL,tokens,
  1329. routerdesc_token_table,TS_NOCHECK)) {
  1330. log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
  1331. goto err;
  1332. }
  1333. }
  1334. start_of_annotations = s;
  1335. cp = tor_memstr(s, end-s, "\nrouter ");
  1336. if (!cp) {
  1337. if (end-s < 7 || strcmpstart(s, "router ")) {
  1338. log_warn(LD_DIR, "No router keyword found.");
  1339. goto err;
  1340. }
  1341. } else {
  1342. s = cp+1;
  1343. }
  1344. if (start_of_annotations != s) { /* We have annotations */
  1345. if (allow_annotations) {
  1346. if (tokenize_string(area,start_of_annotations,s,tokens,
  1347. routerdesc_token_table,TS_NOCHECK)) {
  1348. log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
  1349. goto err;
  1350. }
  1351. } else {
  1352. log_warn(LD_DIR, "Found unexpected annotations on router descriptor not "
  1353. "loaded from disk. Dropping it.");
  1354. goto err;
  1355. }
  1356. }
  1357. if (router_get_router_hash(s, end - s, digest) < 0) {
  1358. log_warn(LD_DIR, "Couldn't compute router hash.");
  1359. goto err;
  1360. }
  1361. {
  1362. int flags = 0;
  1363. if (allow_annotations)
  1364. flags |= TS_ANNOTATIONS_OK;
  1365. if (prepend_annotations)
  1366. flags |= TS_ANNOTATIONS_OK|TS_NO_NEW_ANNOTATIONS;
  1367. if (tokenize_string(area,s,end,tokens,routerdesc_token_table, flags)) {
  1368. log_warn(LD_DIR, "Error tokenizing router descriptor.");
  1369. goto err;
  1370. }
  1371. }
  1372. if (smartlist_len(tokens) < 2) {
  1373. log_warn(LD_DIR, "Impossibly short router descriptor.");
  1374. goto err;
  1375. }
  1376. tok = find_by_keyword(tokens, K_ROUTER);
  1377. const int router_token_pos = smartlist_pos(tokens, tok);
  1378. tor_assert(tok->n_args >= 5);
  1379. router = tor_malloc_zero(sizeof(routerinfo_t));
  1380. router->cert_expiration_time = TIME_MAX;
  1381. router->cache_info.routerlist_index = -1;
  1382. router->cache_info.annotations_len = s-start_of_annotations + prepend_len;
  1383. router->cache_info.signed_descriptor_len = end-s;
  1384. if (cache_copy) {
  1385. size_t len = router->cache_info.signed_descriptor_len +
  1386. router->cache_info.annotations_len;
  1387. char *signed_body =
  1388. router->cache_info.signed_descriptor_body = tor_malloc(len+1);
  1389. if (prepend_annotations) {
  1390. memcpy(signed_body, prepend_annotations, prepend_len);
  1391. signed_body += prepend_len;
  1392. }
  1393. /* This assertion will always succeed.
  1394. * len == signed_desc_len + annotations_len
  1395. * == end-s + s-start_of_annotations + prepend_len
  1396. * == end-start_of_annotations + prepend_len
  1397. * We already wrote prepend_len bytes into the buffer; now we're
  1398. * writing end-start_of_annotations -NM. */
  1399. tor_assert(signed_body+(end-start_of_annotations) ==
  1400. router->cache_info.signed_descriptor_body+len);
  1401. memcpy(signed_body, start_of_annotations, end-start_of_annotations);
  1402. router->cache_info.signed_descriptor_body[len] = '\0';
  1403. tor_assert(strlen(router->cache_info.signed_descriptor_body) == len);
  1404. }
  1405. memcpy(router->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1406. router->nickname = tor_strdup(tok->args[0]);
  1407. if (!is_legal_nickname(router->nickname)) {
  1408. log_warn(LD_DIR,"Router nickname is invalid");
  1409. goto err;
  1410. }
  1411. if (!tor_inet_aton(tok->args[1], &in)) {
  1412. log_warn(LD_DIR,"Router address is not an IP address.");
  1413. goto err;
  1414. }
  1415. router->addr = ntohl(in.s_addr);
  1416. router->or_port =
  1417. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,&ok,NULL);
  1418. if (!ok) {
  1419. log_warn(LD_DIR,"Invalid OR port %s", escaped(tok->args[2]));
  1420. goto err;
  1421. }
  1422. router->dir_port =
  1423. (uint16_t) tor_parse_long(tok->args[4],10,0,65535,&ok,NULL);
  1424. if (!ok) {
  1425. log_warn(LD_DIR,"Invalid dir port %s", escaped(tok->args[4]));
  1426. goto err;
  1427. }
  1428. tok = find_by_keyword(tokens, K_BANDWIDTH);
  1429. tor_assert(tok->n_args >= 3);
  1430. router->bandwidthrate = (int)
  1431. tor_parse_long(tok->args[0],10,1,INT_MAX,&ok,NULL);
  1432. if (!ok) {
  1433. log_warn(LD_DIR, "bandwidthrate %s unreadable or 0. Failing.",
  1434. escaped(tok->args[0]));
  1435. goto err;
  1436. }
  1437. router->bandwidthburst =
  1438. (int) tor_parse_long(tok->args[1],10,0,INT_MAX,&ok,NULL);
  1439. if (!ok) {
  1440. log_warn(LD_DIR, "Invalid bandwidthburst %s", escaped(tok->args[1]));
  1441. goto err;
  1442. }
  1443. router->bandwidthcapacity = (int)
  1444. tor_parse_long(tok->args[2],10,0,INT_MAX,&ok,NULL);
  1445. if (!ok) {
  1446. log_warn(LD_DIR, "Invalid bandwidthcapacity %s", escaped(tok->args[1]));
  1447. goto err;
  1448. }
  1449. if ((tok = find_opt_by_keyword(tokens, A_PURPOSE))) {
  1450. tor_assert(tok->n_args);
  1451. router->purpose = router_purpose_from_string(tok->args[0]);
  1452. } else {
  1453. router->purpose = ROUTER_PURPOSE_GENERAL;
  1454. }
  1455. router->cache_info.send_unencrypted =
  1456. (router->purpose == ROUTER_PURPOSE_GENERAL) ? 1 : 0;
  1457. if ((tok = find_opt_by_keyword(tokens, K_UPTIME))) {
  1458. tor_assert(tok->n_args >= 1);
  1459. router->uptime = tor_parse_long(tok->args[0],10,0,LONG_MAX,&ok,NULL);
  1460. if (!ok) {
  1461. log_warn(LD_DIR, "Invalid uptime %s", escaped(tok->args[0]));
  1462. goto err;
  1463. }
  1464. }
  1465. if ((tok = find_opt_by_keyword(tokens, K_HIBERNATING))) {
  1466. tor_assert(tok->n_args >= 1);
  1467. router->is_hibernating
  1468. = (tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL) != 0);
  1469. }
  1470. tok = find_by_keyword(tokens, K_PUBLISHED);
  1471. tor_assert(tok->n_args == 1);
  1472. if (parse_iso_time(tok->args[0], &router->cache_info.published_on) < 0)
  1473. goto err;
  1474. tok = find_by_keyword(tokens, K_ONION_KEY);
  1475. if (!crypto_pk_public_exponent_ok(tok->key)) {
  1476. log_warn(LD_DIR,
  1477. "Relay's onion key had invalid exponent.");
  1478. goto err;
  1479. }
  1480. router->onion_pkey = tok->key;
  1481. tok->key = NULL; /* Prevent free */
  1482. if ((tok = find_opt_by_keyword(tokens, K_ONION_KEY_NTOR))) {
  1483. curve25519_public_key_t k;
  1484. tor_assert(tok->n_args >= 1);
  1485. if (curve25519_public_from_base64(&k, tok->args[0]) < 0) {
  1486. log_warn(LD_DIR, "Bogus ntor-onion-key in routerinfo");
  1487. goto err;
  1488. }
  1489. router->onion_curve25519_pkey =
  1490. tor_memdup(&k, sizeof(curve25519_public_key_t));
  1491. }
  1492. tok = find_by_keyword(tokens, K_SIGNING_KEY);
  1493. router->identity_pkey = tok->key;
  1494. tok->key = NULL; /* Prevent free */
  1495. if (crypto_pk_get_digest(router->identity_pkey,
  1496. router->cache_info.identity_digest)) {
  1497. log_warn(LD_DIR, "Couldn't calculate key digest"); goto err;
  1498. }
  1499. {
  1500. directory_token_t *ed_sig_tok, *ed_cert_tok, *cc_tap_tok, *cc_ntor_tok,
  1501. *master_key_tok;
  1502. ed_sig_tok = find_opt_by_keyword(tokens, K_ROUTER_SIG_ED25519);
  1503. ed_cert_tok = find_opt_by_keyword(tokens, K_IDENTITY_ED25519);
  1504. master_key_tok = find_opt_by_keyword(tokens, K_MASTER_KEY_ED25519);
  1505. cc_tap_tok = find_opt_by_keyword(tokens, K_ONION_KEY_CROSSCERT);
  1506. cc_ntor_tok = find_opt_by_keyword(tokens, K_NTOR_ONION_KEY_CROSSCERT);
  1507. int n_ed_toks = !!ed_sig_tok + !!ed_cert_tok +
  1508. !!cc_tap_tok + !!cc_ntor_tok;
  1509. if ((n_ed_toks != 0 && n_ed_toks != 4) ||
  1510. (n_ed_toks == 4 && !router->onion_curve25519_pkey)) {
  1511. log_warn(LD_DIR, "Router descriptor with only partial ed25519/"
  1512. "cross-certification support");
  1513. goto err;
  1514. }
  1515. if (master_key_tok && !ed_sig_tok) {
  1516. log_warn(LD_DIR, "Router descriptor has ed25519 master key but no "
  1517. "certificate");
  1518. goto err;
  1519. }
  1520. if (ed_sig_tok) {
  1521. tor_assert(ed_cert_tok && cc_tap_tok && cc_ntor_tok);
  1522. const int ed_cert_token_pos = smartlist_pos(tokens, ed_cert_tok);
  1523. if (ed_cert_token_pos == -1 || router_token_pos == -1 ||
  1524. (ed_cert_token_pos != router_token_pos + 1 &&
  1525. ed_cert_token_pos != router_token_pos - 1)) {
  1526. log_warn(LD_DIR, "Ed25519 certificate in wrong position");
  1527. goto err;
  1528. }
  1529. if (ed_sig_tok != smartlist_get(tokens, smartlist_len(tokens)-2)) {
  1530. log_warn(LD_DIR, "Ed25519 signature in wrong position");
  1531. goto err;
  1532. }
  1533. if (strcmp(ed_cert_tok->object_type, "ED25519 CERT")) {
  1534. log_warn(LD_DIR, "Wrong object type on identity-ed25519 in decriptor");
  1535. goto err;
  1536. }
  1537. if (strcmp(cc_ntor_tok->object_type, "ED25519 CERT")) {
  1538. log_warn(LD_DIR, "Wrong object type on ntor-onion-key-crosscert "
  1539. "in decriptor");
  1540. goto err;
  1541. }
  1542. if (strcmp(cc_tap_tok->object_type, "CROSSCERT")) {
  1543. log_warn(LD_DIR, "Wrong object type on onion-key-crosscert "
  1544. "in decriptor");
  1545. goto err;
  1546. }
  1547. if (strcmp(cc_ntor_tok->args[0], "0") &&
  1548. strcmp(cc_ntor_tok->args[0], "1")) {
  1549. log_warn(LD_DIR, "Bad sign bit on ntor-onion-key-crosscert");
  1550. goto err;
  1551. }
  1552. int ntor_cc_sign_bit = !strcmp(cc_ntor_tok->args[0], "1");
  1553. uint8_t d256[DIGEST256_LEN];
  1554. const char *signed_start, *signed_end;
  1555. tor_cert_t *cert = tor_cert_parse(
  1556. (const uint8_t*)ed_cert_tok->object_body,
  1557. ed_cert_tok->object_size);
  1558. if (! cert) {
  1559. log_warn(LD_DIR, "Couldn't parse ed25519 cert");
  1560. goto err;
  1561. }
  1562. /* makes sure it gets freed. */
  1563. router->cache_info.signing_key_cert = cert;
  1564. if (cert->cert_type != CERT_TYPE_ID_SIGNING ||
  1565. ! cert->signing_key_included) {
  1566. log_warn(LD_DIR, "Invalid form for ed25519 cert");
  1567. goto err;
  1568. }
  1569. if (master_key_tok) {
  1570. /* This token is optional, but if it's present, it must match
  1571. * the signature in the signing cert, or supplant it. */
  1572. tor_assert(master_key_tok->n_args >= 1);
  1573. ed25519_public_key_t pkey;
  1574. if (ed25519_public_from_base64(&pkey, master_key_tok->args[0])<0) {
  1575. log_warn(LD_DIR, "Can't parse ed25519 master key");
  1576. goto err;
  1577. }
  1578. if (fast_memneq(&cert->signing_key.pubkey,
  1579. pkey.pubkey, ED25519_PUBKEY_LEN)) {
  1580. log_warn(LD_DIR, "Ed25519 master key does not match "
  1581. "key in certificate");
  1582. goto err;
  1583. }
  1584. }
  1585. ntor_cc_cert = tor_cert_parse((const uint8_t*)cc_ntor_tok->object_body,
  1586. cc_ntor_tok->object_size);
  1587. if (!ntor_cc_cert) {
  1588. log_warn(LD_DIR, "Couldn't parse ntor-onion-key-crosscert cert");
  1589. goto err;
  1590. }
  1591. if (ntor_cc_cert->cert_type != CERT_TYPE_ONION_ID ||
  1592. ! ed25519_pubkey_eq(&ntor_cc_cert->signed_key, &cert->signing_key)) {
  1593. log_warn(LD_DIR, "Invalid contents for ntor-onion-key-crosscert cert");
  1594. goto err;
  1595. }
  1596. ed25519_public_key_t ntor_cc_pk;
  1597. if (ed25519_public_key_from_curve25519_public_key(&ntor_cc_pk,
  1598. router->onion_curve25519_pkey,
  1599. ntor_cc_sign_bit)<0) {
  1600. log_warn(LD_DIR, "Error converting onion key to ed25519");
  1601. goto err;
  1602. }
  1603. if (router_get_hash_impl_helper(s, end-s, "router ",
  1604. "\nrouter-sig-ed25519",
  1605. ' ', &signed_start, &signed_end) < 0) {
  1606. log_warn(LD_DIR, "Can't find ed25519-signed portion of descriptor");
  1607. goto err;
  1608. }
  1609. crypto_digest_t *d = crypto_digest256_new(DIGEST_SHA256);
  1610. crypto_digest_add_bytes(d, ED_DESC_SIGNATURE_PREFIX,
  1611. strlen(ED_DESC_SIGNATURE_PREFIX));
  1612. crypto_digest_add_bytes(d, signed_start, signed_end-signed_start);
  1613. crypto_digest_get_digest(d, (char*)d256, sizeof(d256));
  1614. crypto_digest_free(d);
  1615. ed25519_checkable_t check[3];
  1616. int check_ok[3];
  1617. time_t expires = TIME_MAX;
  1618. if (tor_cert_get_checkable_sig(&check[0], cert, NULL, &expires) < 0) {
  1619. log_err(LD_BUG, "Couldn't create 'checkable' for cert.");
  1620. goto err;
  1621. }
  1622. if (tor_cert_get_checkable_sig(&check[1],
  1623. ntor_cc_cert, &ntor_cc_pk, &expires) < 0) {
  1624. log_err(LD_BUG, "Couldn't create 'checkable' for ntor_cc_cert.");
  1625. goto err;
  1626. }
  1627. if (ed25519_signature_from_base64(&check[2].signature,
  1628. ed_sig_tok->args[0])<0) {
  1629. log_warn(LD_DIR, "Couldn't decode ed25519 signature");
  1630. goto err;
  1631. }
  1632. check[2].pubkey = &cert->signed_key;
  1633. check[2].msg = d256;
  1634. check[2].len = DIGEST256_LEN;
  1635. if (ed25519_checksig_batch(check_ok, check, 3) < 0) {
  1636. log_warn(LD_DIR, "Incorrect ed25519 signature(s)");
  1637. goto err;
  1638. }
  1639. if (check_tap_onion_key_crosscert(
  1640. (const uint8_t*)cc_tap_tok->object_body,
  1641. (int)cc_tap_tok->object_size,
  1642. router->onion_pkey,
  1643. &cert->signing_key,
  1644. (const uint8_t*)router->cache_info.identity_digest)<0) {
  1645. log_warn(LD_DIR, "Incorrect TAP cross-verification");
  1646. goto err;
  1647. }
  1648. /* We check this before adding it to the routerlist. */
  1649. router->cert_expiration_time = expires;
  1650. }
  1651. }
  1652. if ((tok = find_opt_by_keyword(tokens, K_FINGERPRINT))) {
  1653. /* If there's a fingerprint line, it must match the identity digest. */
  1654. char d[DIGEST_LEN];
  1655. tor_assert(tok->n_args == 1);
  1656. tor_strstrip(tok->args[0], " ");
  1657. if (base16_decode(d, DIGEST_LEN,
  1658. tok->args[0], strlen(tok->args[0])) != DIGEST_LEN) {
  1659. log_warn(LD_DIR, "Couldn't decode router fingerprint %s",
  1660. escaped(tok->args[0]));
  1661. goto err;
  1662. }
  1663. if (tor_memneq(d,router->cache_info.identity_digest, DIGEST_LEN)) {
  1664. log_warn(LD_DIR, "Fingerprint '%s' does not match identity digest.",
  1665. tok->args[0]);
  1666. goto err;
  1667. }
  1668. }
  1669. if ((tok = find_opt_by_keyword(tokens, K_PLATFORM))) {
  1670. router->platform = tor_strdup(tok->args[0]);
  1671. }
  1672. if ((tok = find_opt_by_keyword(tokens, K_PROTO))) {
  1673. router->protocol_list = tor_strdup(tok->args[0]);
  1674. }
  1675. if ((tok = find_opt_by_keyword(tokens, K_CONTACT))) {
  1676. router->contact_info = tor_strdup(tok->args[0]);
  1677. }
  1678. if (find_opt_by_keyword(tokens, K_REJECT6) ||
  1679. find_opt_by_keyword(tokens, K_ACCEPT6)) {
  1680. log_warn(LD_DIR, "Rejecting router with reject6/accept6 line: they crash "
  1681. "older Tors.");
  1682. goto err;
  1683. }
  1684. {
  1685. smartlist_t *or_addresses = find_all_by_keyword(tokens, K_OR_ADDRESS);
  1686. if (or_addresses) {
  1687. find_single_ipv6_orport(or_addresses, &router->ipv6_addr,
  1688. &router->ipv6_orport);
  1689. smartlist_free(or_addresses);
  1690. }
  1691. }
  1692. exit_policy_tokens = find_all_exitpolicy(tokens);
  1693. if (!smartlist_len(exit_policy_tokens)) {
  1694. log_warn(LD_DIR, "No exit policy tokens in descriptor.");
  1695. goto err;
  1696. }
  1697. SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
  1698. if (router_add_exit_policy(router,t)<0) {
  1699. log_warn(LD_DIR,"Error in exit policy");
  1700. goto err;
  1701. });
  1702. policy_expand_private(&router->exit_policy);
  1703. if ((tok = find_opt_by_keyword(tokens, K_IPV6_POLICY)) && tok->n_args) {
  1704. router->ipv6_exit_policy = parse_short_policy(tok->args[0]);
  1705. if (! router->ipv6_exit_policy) {
  1706. log_warn(LD_DIR , "Error in ipv6-policy %s", escaped(tok->args[0]));
  1707. goto err;
  1708. }
  1709. }
  1710. if (policy_is_reject_star(router->exit_policy, AF_INET, 1) &&
  1711. (!router->ipv6_exit_policy ||
  1712. short_policy_is_reject_star(router->ipv6_exit_policy)))
  1713. router->policy_is_reject_star = 1;
  1714. if ((tok = find_opt_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
  1715. int i;
  1716. router->declared_family = smartlist_new();
  1717. for (i=0;i<tok->n_args;++i) {
  1718. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  1719. log_warn(LD_DIR, "Illegal nickname %s in family line",
  1720. escaped(tok->args[i]));
  1721. goto err;
  1722. }
  1723. smartlist_add_strdup(router->declared_family, tok->args[i]);
  1724. }
  1725. }
  1726. if (find_opt_by_keyword(tokens, K_CACHES_EXTRA_INFO))
  1727. router->caches_extra_info = 1;
  1728. if (find_opt_by_keyword(tokens, K_ALLOW_SINGLE_HOP_EXITS))
  1729. router->allow_single_hop_exits = 1;
  1730. if ((tok = find_opt_by_keyword(tokens, K_EXTRA_INFO_DIGEST))) {
  1731. tor_assert(tok->n_args >= 1);
  1732. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  1733. if (base16_decode(router->cache_info.extra_info_digest, DIGEST_LEN,
  1734. tok->args[0], HEX_DIGEST_LEN) != DIGEST_LEN) {
  1735. log_warn(LD_DIR,"Invalid extra info digest");
  1736. }
  1737. } else {
  1738. log_warn(LD_DIR, "Invalid extra info digest %s", escaped(tok->args[0]));
  1739. }
  1740. if (tok->n_args >= 2) {
  1741. if (digest256_from_base64(router->cache_info.extra_info_digest256,
  1742. tok->args[1]) < 0) {
  1743. log_warn(LD_DIR, "Invalid extra info digest256 %s",
  1744. escaped(tok->args[1]));
  1745. }
  1746. }
  1747. }
  1748. if (find_opt_by_keyword(tokens, K_HIDDEN_SERVICE_DIR)) {
  1749. router->wants_to_be_hs_dir = 1;
  1750. }
  1751. /* This router accepts tunnelled directory requests via begindir if it has
  1752. * an open dirport or it included "tunnelled-dir-server". */
  1753. if (find_opt_by_keyword(tokens, K_DIR_TUNNELLED) || router->dir_port > 0) {
  1754. router->supports_tunnelled_dir_requests = 1;
  1755. }
  1756. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1757. note_crypto_pk_op(VERIFY_RTR);
  1758. #ifdef COUNT_DISTINCT_DIGESTS
  1759. if (!verified_digests)
  1760. verified_digests = digestmap_new();
  1761. digestmap_set(verified_digests, signed_digest, (void*)(uintptr_t)1);
  1762. #endif
  1763. if (!router->or_port) {
  1764. log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
  1765. goto err;
  1766. }
  1767. /* We've checked everything that's covered by the hash. */
  1768. can_dl_again = 1;
  1769. if (check_signature_token(digest, DIGEST_LEN, tok, router->identity_pkey, 0,
  1770. "router descriptor") < 0)
  1771. goto err;
  1772. if (!router->platform) {
  1773. router->platform = tor_strdup("<unknown>");
  1774. }
  1775. goto done;
  1776. err:
  1777. dump_desc(s_dup, "router descriptor");
  1778. routerinfo_free(router);
  1779. router = NULL;
  1780. done:
  1781. tor_cert_free(ntor_cc_cert);
  1782. if (tokens) {
  1783. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1784. smartlist_free(tokens);
  1785. }
  1786. smartlist_free(exit_policy_tokens);
  1787. if (area) {
  1788. DUMP_AREA(area, "routerinfo");
  1789. memarea_drop_all(area);
  1790. }
  1791. if (can_dl_again_out)
  1792. *can_dl_again_out = can_dl_again;
  1793. return router;
  1794. }
  1795. /** Parse a single extrainfo entry from the string <b>s</b>, ending at
  1796. * <b>end</b>. (If <b>end</b> is NULL, parse up to the end of <b>s</b>.) If
  1797. * <b>cache_copy</b> is true, make a copy of the extra-info document in the
  1798. * cache_info fields of the result. If <b>routermap</b> is provided, use it
  1799. * as a map from router identity to routerinfo_t when looking up signing keys.
  1800. *
  1801. * If <b>can_dl_again_out</b> is provided, set *<b>can_dl_again_out</b> to 1
  1802. * if it's okay to try to download an extrainfo with this same digest again,
  1803. * and 0 if it isn't. (It might not be okay to download it again if part of
  1804. * the part covered by the digest is invalid.)
  1805. */
  1806. extrainfo_t *
  1807. extrainfo_parse_entry_from_string(const char *s, const char *end,
  1808. int cache_copy, struct digest_ri_map_t *routermap,
  1809. int *can_dl_again_out)
  1810. {
  1811. extrainfo_t *extrainfo = NULL;
  1812. char digest[128];
  1813. smartlist_t *tokens = NULL;
  1814. directory_token_t *tok;
  1815. crypto_pk_t *key = NULL;
  1816. routerinfo_t *router = NULL;
  1817. memarea_t *area = NULL;
  1818. const char *s_dup = s;
  1819. /* Do not set this to '1' until we have parsed everything that we intend to
  1820. * parse that's covered by the hash. */
  1821. int can_dl_again = 0;
  1822. if (!end) {
  1823. end = s + strlen(s);
  1824. }
  1825. /* point 'end' to a point immediately after the final newline. */
  1826. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  1827. --end;
  1828. if (router_get_extrainfo_hash(s, end-s, digest) < 0) {
  1829. log_warn(LD_DIR, "Couldn't compute router hash.");
  1830. goto err;
  1831. }
  1832. tokens = smartlist_new();
  1833. area = memarea_new();
  1834. if (tokenize_string(area,s,end,tokens,extrainfo_token_table,0)) {
  1835. log_warn(LD_DIR, "Error tokenizing extra-info document.");
  1836. goto err;
  1837. }
  1838. if (smartlist_len(tokens) < 2) {
  1839. log_warn(LD_DIR, "Impossibly short extra-info document.");
  1840. goto err;
  1841. }
  1842. /* XXXX Accept this in position 1 too, and ed identity in position 0. */
  1843. tok = smartlist_get(tokens,0);
  1844. if (tok->tp != K_EXTRA_INFO) {
  1845. log_warn(LD_DIR,"Entry does not start with \"extra-info\"");
  1846. goto err;
  1847. }
  1848. extrainfo = tor_malloc_zero(sizeof(extrainfo_t));
  1849. extrainfo->cache_info.is_extrainfo = 1;
  1850. if (cache_copy)
  1851. extrainfo->cache_info.signed_descriptor_body = tor_memdup_nulterm(s,end-s);
  1852. extrainfo->cache_info.signed_descriptor_len = end-s;
  1853. memcpy(extrainfo->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1854. crypto_digest256((char*)extrainfo->digest256, s, end-s, DIGEST_SHA256);
  1855. tor_assert(tok->n_args >= 2);
  1856. if (!is_legal_nickname(tok->args[0])) {
  1857. log_warn(LD_DIR,"Bad nickname %s on \"extra-info\"",escaped(tok->args[0]));
  1858. goto err;
  1859. }
  1860. strlcpy(extrainfo->nickname, tok->args[0], sizeof(extrainfo->nickname));
  1861. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  1862. base16_decode(extrainfo->cache_info.identity_digest, DIGEST_LEN,
  1863. tok->args[1], HEX_DIGEST_LEN) != DIGEST_LEN) {
  1864. log_warn(LD_DIR,"Invalid fingerprint %s on \"extra-info\"",
  1865. escaped(tok->args[1]));
  1866. goto err;
  1867. }
  1868. tok = find_by_keyword(tokens, K_PUBLISHED);
  1869. if (parse_iso_time(tok->args[0], &extrainfo->cache_info.published_on)) {
  1870. log_warn(LD_DIR,"Invalid published time %s on \"extra-info\"",
  1871. escaped(tok->args[0]));
  1872. goto err;
  1873. }
  1874. {
  1875. directory_token_t *ed_sig_tok, *ed_cert_tok;
  1876. ed_sig_tok = find_opt_by_keyword(tokens, K_ROUTER_SIG_ED25519);
  1877. ed_cert_tok = find_opt_by_keyword(tokens, K_IDENTITY_ED25519);
  1878. int n_ed_toks = !!ed_sig_tok + !!ed_cert_tok;
  1879. if (n_ed_toks != 0 && n_ed_toks != 2) {
  1880. log_warn(LD_DIR, "Router descriptor with only partial ed25519/"
  1881. "cross-certification support");
  1882. goto err;
  1883. }
  1884. if (ed_sig_tok) {
  1885. tor_assert(ed_cert_tok);
  1886. const int ed_cert_token_pos = smartlist_pos(tokens, ed_cert_tok);
  1887. if (ed_cert_token_pos != 1) {
  1888. /* Accept this in position 0 XXXX */
  1889. log_warn(LD_DIR, "Ed25519 certificate in wrong position");
  1890. goto err;
  1891. }
  1892. if (ed_sig_tok != smartlist_get(tokens, smartlist_len(tokens)-2)) {
  1893. log_warn(LD_DIR, "Ed25519 signature in wrong position");
  1894. goto err;
  1895. }
  1896. if (strcmp(ed_cert_tok->object_type, "ED25519 CERT")) {
  1897. log_warn(LD_DIR, "Wrong object type on identity-ed25519 in decriptor");
  1898. goto err;
  1899. }
  1900. uint8_t d256[DIGEST256_LEN];
  1901. const char *signed_start, *signed_end;
  1902. tor_cert_t *cert = tor_cert_parse(
  1903. (const uint8_t*)ed_cert_tok->object_body,
  1904. ed_cert_tok->object_size);
  1905. if (! cert) {
  1906. log_warn(LD_DIR, "Couldn't parse ed25519 cert");
  1907. goto err;
  1908. }
  1909. /* makes sure it gets freed. */
  1910. extrainfo->cache_info.signing_key_cert = cert;
  1911. if (cert->cert_type != CERT_TYPE_ID_SIGNING ||
  1912. ! cert->signing_key_included) {
  1913. log_warn(LD_DIR, "Invalid form for ed25519 cert");
  1914. goto err;
  1915. }
  1916. if (router_get_hash_impl_helper(s, end-s, "extra-info ",
  1917. "\nrouter-sig-ed25519",
  1918. ' ', &signed_start, &signed_end) < 0) {
  1919. log_warn(LD_DIR, "Can't find ed25519-signed portion of extrainfo");
  1920. goto err;
  1921. }
  1922. crypto_digest_t *d = crypto_digest256_new(DIGEST_SHA256);
  1923. crypto_digest_add_bytes(d, ED_DESC_SIGNATURE_PREFIX,
  1924. strlen(ED_DESC_SIGNATURE_PREFIX));
  1925. crypto_digest_add_bytes(d, signed_start, signed_end-signed_start);
  1926. crypto_digest_get_digest(d, (char*)d256, sizeof(d256));
  1927. crypto_digest_free(d);
  1928. ed25519_checkable_t check[2];
  1929. int check_ok[2];
  1930. if (tor_cert_get_checkable_sig(&check[0], cert, NULL, NULL) < 0) {
  1931. log_err(LD_BUG, "Couldn't create 'checkable' for cert.");
  1932. goto err;
  1933. }
  1934. if (ed25519_signature_from_base64(&check[1].signature,
  1935. ed_sig_tok->args[0])<0) {
  1936. log_warn(LD_DIR, "Couldn't decode ed25519 signature");
  1937. goto err;
  1938. }
  1939. check[1].pubkey = &cert->signed_key;
  1940. check[1].msg = d256;
  1941. check[1].len = DIGEST256_LEN;
  1942. if (ed25519_checksig_batch(check_ok, check, 2) < 0) {
  1943. log_warn(LD_DIR, "Incorrect ed25519 signature(s)");
  1944. goto err;
  1945. }
  1946. /* We don't check the certificate expiration time: checking that it
  1947. * matches the cert in the router descriptor is adequate. */
  1948. }
  1949. }
  1950. /* We've checked everything that's covered by the hash. */
  1951. can_dl_again = 1;
  1952. if (routermap &&
  1953. (router = digestmap_get((digestmap_t*)routermap,
  1954. extrainfo->cache_info.identity_digest))) {
  1955. key = router->identity_pkey;
  1956. }
  1957. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1958. if (strcmp(tok->object_type, "SIGNATURE") ||
  1959. tok->object_size < 128 || tok->object_size > 512) {
  1960. log_warn(LD_DIR, "Bad object type or length on extra-info signature");
  1961. goto err;
  1962. }
  1963. if (key) {
  1964. note_crypto_pk_op(VERIFY_RTR);
  1965. if (check_signature_token(digest, DIGEST_LEN, tok, key, 0,
  1966. "extra-info") < 0)
  1967. goto err;
  1968. if (router)
  1969. extrainfo->cache_info.send_unencrypted =
  1970. router->cache_info.send_unencrypted;
  1971. } else {
  1972. extrainfo->pending_sig = tor_memdup(tok->object_body,
  1973. tok->object_size);
  1974. extrainfo->pending_sig_len = tok->object_size;
  1975. }
  1976. goto done;
  1977. err:
  1978. dump_desc(s_dup, "extra-info descriptor");
  1979. extrainfo_free(extrainfo);
  1980. extrainfo = NULL;
  1981. done:
  1982. if (tokens) {
  1983. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1984. smartlist_free(tokens);
  1985. }
  1986. if (area) {
  1987. DUMP_AREA(area, "extrainfo");
  1988. memarea_drop_all(area);
  1989. }
  1990. if (can_dl_again_out)
  1991. *can_dl_again_out = can_dl_again;
  1992. return extrainfo;
  1993. }
  1994. /** Parse a key certificate from <b>s</b>; point <b>end-of-string</b> to
  1995. * the first character after the certificate. */
  1996. authority_cert_t *
  1997. authority_cert_parse_from_string(const char *s, const char **end_of_string)
  1998. {
  1999. /** Reject any certificate at least this big; it is probably an overflow, an
  2000. * attack, a bug, or some other nonsense. */
  2001. #define MAX_CERT_SIZE (128*1024)
  2002. authority_cert_t *cert = NULL, *old_cert;
  2003. smartlist_t *tokens = NULL;
  2004. char digest[DIGEST_LEN];
  2005. directory_token_t *tok;
  2006. char fp_declared[DIGEST_LEN];
  2007. char *eos;
  2008. size_t len;
  2009. int found;
  2010. memarea_t *area = NULL;
  2011. const char *s_dup = s;
  2012. s = eat_whitespace(s);
  2013. eos = strstr(s, "\ndir-key-certification");
  2014. if (! eos) {
  2015. log_warn(LD_DIR, "No signature found on key certificate");
  2016. return NULL;
  2017. }
  2018. eos = strstr(eos, "\n-----END SIGNATURE-----\n");
  2019. if (! eos) {
  2020. log_warn(LD_DIR, "No end-of-signature found on key certificate");
  2021. return NULL;
  2022. }
  2023. eos = strchr(eos+2, '\n');
  2024. tor_assert(eos);
  2025. ++eos;
  2026. len = eos - s;
  2027. if (len > MAX_CERT_SIZE) {
  2028. log_warn(LD_DIR, "Certificate is far too big (at %lu bytes long); "
  2029. "rejecting", (unsigned long)len);
  2030. return NULL;
  2031. }
  2032. tokens = smartlist_new();
  2033. area = memarea_new();
  2034. if (tokenize_string(area,s, eos, tokens, dir_key_certificate_table, 0) < 0) {
  2035. log_warn(LD_DIR, "Error tokenizing key certificate");
  2036. goto err;
  2037. }
  2038. if (router_get_hash_impl(s, strlen(s), digest, "dir-key-certificate-version",
  2039. "\ndir-key-certification", '\n', DIGEST_SHA1) < 0)
  2040. goto err;
  2041. tok = smartlist_get(tokens, 0);
  2042. if (tok->tp != K_DIR_KEY_CERTIFICATE_VERSION || strcmp(tok->args[0], "3")) {
  2043. log_warn(LD_DIR,
  2044. "Key certificate does not begin with a recognized version (3).");
  2045. goto err;
  2046. }
  2047. cert = tor_malloc_zero(sizeof(authority_cert_t));
  2048. memcpy(cert->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  2049. tok = find_by_keyword(tokens, K_DIR_SIGNING_KEY);
  2050. tor_assert(tok->key);
  2051. cert->signing_key = tok->key;
  2052. tok->key = NULL;
  2053. if (crypto_pk_get_digest(cert->signing_key, cert->signing_key_digest))
  2054. goto err;
  2055. tok = find_by_keyword(tokens, K_DIR_IDENTITY_KEY);
  2056. tor_assert(tok->key);
  2057. cert->identity_key = tok->key;
  2058. tok->key = NULL;
  2059. tok = find_by_keyword(tokens, K_FINGERPRINT);
  2060. tor_assert(tok->n_args);
  2061. if (base16_decode(fp_declared, DIGEST_LEN, tok->args[0],
  2062. strlen(tok->args[0])) != DIGEST_LEN) {
  2063. log_warn(LD_DIR, "Couldn't decode key certificate fingerprint %s",
  2064. escaped(tok->args[0]));
  2065. goto err;
  2066. }
  2067. if (crypto_pk_get_digest(cert->identity_key,
  2068. cert->cache_info.identity_digest))
  2069. goto err;
  2070. if (tor_memneq(cert->cache_info.identity_digest, fp_declared, DIGEST_LEN)) {
  2071. log_warn(LD_DIR, "Digest of certificate key didn't match declared "
  2072. "fingerprint");
  2073. goto err;
  2074. }
  2075. tok = find_opt_by_keyword(tokens, K_DIR_ADDRESS);
  2076. if (tok) {
  2077. struct in_addr in;
  2078. char *address = NULL;
  2079. tor_assert(tok->n_args);
  2080. /* XXX++ use some tor_addr parse function below instead. -RD */
  2081. if (tor_addr_port_split(LOG_WARN, tok->args[0], &address,
  2082. &cert->dir_port) < 0 ||
  2083. tor_inet_aton(address, &in) == 0) {
  2084. log_warn(LD_DIR, "Couldn't parse dir-address in certificate");
  2085. tor_free(address);
  2086. goto err;
  2087. }
  2088. cert->addr = ntohl(in.s_addr);
  2089. tor_free(address);
  2090. }
  2091. tok = find_by_keyword(tokens, K_DIR_KEY_PUBLISHED);
  2092. if (parse_iso_time(tok->args[0], &cert->cache_info.published_on) < 0) {
  2093. goto err;
  2094. }
  2095. tok = find_by_keyword(tokens, K_DIR_KEY_EXPIRES);
  2096. if (parse_iso_time(tok->args[0], &cert->expires) < 0) {
  2097. goto err;
  2098. }
  2099. tok = smartlist_get(tokens, smartlist_len(tokens)-1);
  2100. if (tok->tp != K_DIR_KEY_CERTIFICATION) {
  2101. log_warn(LD_DIR, "Certificate didn't end with dir-key-certification.");
  2102. goto err;
  2103. }
  2104. /* If we already have this cert, don't bother checking the signature. */
  2105. old_cert = authority_cert_get_by_digests(
  2106. cert->cache_info.identity_digest,
  2107. cert->signing_key_digest);
  2108. found = 0;
  2109. if (old_cert) {
  2110. /* XXXX We could just compare signed_descriptor_digest, but that wouldn't
  2111. * buy us much. */
  2112. if (old_cert->cache_info.signed_descriptor_len == len &&
  2113. old_cert->cache_info.signed_descriptor_body &&
  2114. tor_memeq(s, old_cert->cache_info.signed_descriptor_body, len)) {
  2115. log_debug(LD_DIR, "We already checked the signature on this "
  2116. "certificate; no need to do so again.");
  2117. found = 1;
  2118. }
  2119. }
  2120. if (!found) {
  2121. if (check_signature_token(digest, DIGEST_LEN, tok, cert->identity_key, 0,
  2122. "key certificate")) {
  2123. goto err;
  2124. }
  2125. tok = find_by_keyword(tokens, K_DIR_KEY_CROSSCERT);
  2126. if (check_signature_token(cert->cache_info.identity_digest,
  2127. DIGEST_LEN,
  2128. tok,
  2129. cert->signing_key,
  2130. CST_NO_CHECK_OBJTYPE,
  2131. "key cross-certification")) {
  2132. goto err;
  2133. }
  2134. }
  2135. cert->cache_info.signed_descriptor_len = len;
  2136. cert->cache_info.signed_descriptor_body = tor_malloc(len+1);
  2137. memcpy(cert->cache_info.signed_descriptor_body, s, len);
  2138. cert->cache_info.signed_descriptor_body[len] = 0;
  2139. cert->cache_info.saved_location = SAVED_NOWHERE;
  2140. if (end_of_string) {
  2141. *end_of_string = eat_whitespace(eos);
  2142. }
  2143. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2144. smartlist_free(tokens);
  2145. if (area) {
  2146. DUMP_AREA(area, "authority cert");
  2147. memarea_drop_all(area);
  2148. }
  2149. return cert;
  2150. err:
  2151. dump_desc(s_dup, "authority cert");
  2152. authority_cert_free(cert);
  2153. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2154. smartlist_free(tokens);
  2155. if (area) {
  2156. DUMP_AREA(area, "authority cert");
  2157. memarea_drop_all(area);
  2158. }
  2159. return NULL;
  2160. }
  2161. /** Helper: given a string <b>s</b>, return the start of the next router-status
  2162. * object (starting with "r " at the start of a line). If none is found,
  2163. * return the start of the directory footer, or the next directory signature.
  2164. * If none is found, return the end of the string. */
  2165. static inline const char *
  2166. find_start_of_next_routerstatus(const char *s)
  2167. {
  2168. const char *eos, *footer, *sig;
  2169. if ((eos = strstr(s, "\nr ")))
  2170. ++eos;
  2171. else
  2172. eos = s + strlen(s);
  2173. footer = tor_memstr(s, eos-s, "\ndirectory-footer");
  2174. sig = tor_memstr(s, eos-s, "\ndirectory-signature");
  2175. if (footer && sig)
  2176. return MIN(footer, sig) + 1;
  2177. else if (footer)
  2178. return footer+1;
  2179. else if (sig)
  2180. return sig+1;
  2181. else
  2182. return eos;
  2183. }
  2184. /** Parse the GuardFraction string from a consensus or vote.
  2185. *
  2186. * If <b>vote</b> or <b>vote_rs</b> are set the document getting
  2187. * parsed is a vote routerstatus. Otherwise it's a consensus. This is
  2188. * the same semantic as in routerstatus_parse_entry_from_string(). */
  2189. STATIC int
  2190. routerstatus_parse_guardfraction(const char *guardfraction_str,
  2191. networkstatus_t *vote,
  2192. vote_routerstatus_t *vote_rs,
  2193. routerstatus_t *rs)
  2194. {
  2195. int ok;
  2196. const char *end_of_header = NULL;
  2197. int is_consensus = !vote_rs;
  2198. uint32_t guardfraction;
  2199. tor_assert(bool_eq(vote, vote_rs));
  2200. /* If this info comes from a consensus, but we should't apply
  2201. guardfraction, just exit. */
  2202. if (is_consensus && !should_apply_guardfraction(NULL)) {
  2203. return 0;
  2204. }
  2205. end_of_header = strchr(guardfraction_str, '=');
  2206. if (!end_of_header) {
  2207. return -1;
  2208. }
  2209. guardfraction = (uint32_t)tor_parse_ulong(end_of_header+1,
  2210. 10, 0, 100, &ok, NULL);
  2211. if (!ok) {
  2212. log_warn(LD_DIR, "Invalid GuardFraction %s", escaped(guardfraction_str));
  2213. return -1;
  2214. }
  2215. log_debug(LD_GENERAL, "[*] Parsed %s guardfraction '%s' for '%s'.",
  2216. is_consensus ? "consensus" : "vote",
  2217. guardfraction_str, rs->nickname);
  2218. if (!is_consensus) { /* We are parsing a vote */
  2219. vote_rs->status.guardfraction_percentage = guardfraction;
  2220. vote_rs->status.has_guardfraction = 1;
  2221. } else {
  2222. /* We are parsing a consensus. Only apply guardfraction to guards. */
  2223. if (rs->is_possible_guard) {
  2224. rs->guardfraction_percentage = guardfraction;
  2225. rs->has_guardfraction = 1;
  2226. } else {
  2227. log_warn(LD_BUG, "Got GuardFraction for non-guard %s. "
  2228. "This is not supposed to happen. Not applying. ", rs->nickname);
  2229. }
  2230. }
  2231. return 0;
  2232. }
  2233. /** Given a string at *<b>s</b>, containing a routerstatus object, and an
  2234. * empty smartlist at <b>tokens</b>, parse and return the first router status
  2235. * object in the string, and advance *<b>s</b> to just after the end of the
  2236. * router status. Return NULL and advance *<b>s</b> on error.
  2237. *
  2238. * If <b>vote</b> and <b>vote_rs</b> are provided, don't allocate a fresh
  2239. * routerstatus but use <b>vote_rs</b> instead.
  2240. *
  2241. * If <b>consensus_method</b> is nonzero, this routerstatus is part of a
  2242. * consensus, and we should parse it according to the method used to
  2243. * make that consensus.
  2244. *
  2245. * Parse according to the syntax used by the consensus flavor <b>flav</b>.
  2246. **/
  2247. STATIC routerstatus_t *
  2248. routerstatus_parse_entry_from_string(memarea_t *area,
  2249. const char **s, smartlist_t *tokens,
  2250. networkstatus_t *vote,
  2251. vote_routerstatus_t *vote_rs,
  2252. int consensus_method,
  2253. consensus_flavor_t flav)
  2254. {
  2255. const char *eos, *s_dup = *s;
  2256. routerstatus_t *rs = NULL;
  2257. directory_token_t *tok;
  2258. char timebuf[ISO_TIME_LEN+1];
  2259. struct in_addr in;
  2260. int offset = 0;
  2261. tor_assert(tokens);
  2262. tor_assert(bool_eq(vote, vote_rs));
  2263. if (!consensus_method)
  2264. flav = FLAV_NS;
  2265. tor_assert(flav == FLAV_NS || flav == FLAV_MICRODESC);
  2266. eos = find_start_of_next_routerstatus(*s);
  2267. if (tokenize_string(area,*s, eos, tokens, rtrstatus_token_table,0)) {
  2268. log_warn(LD_DIR, "Error tokenizing router status");
  2269. goto err;
  2270. }
  2271. if (smartlist_len(tokens) < 1) {
  2272. log_warn(LD_DIR, "Impossibly short router status");
  2273. goto err;
  2274. }
  2275. tok = find_by_keyword(tokens, K_R);
  2276. tor_assert(tok->n_args >= 7); /* guaranteed by GE(7) in K_R setup */
  2277. if (flav == FLAV_NS) {
  2278. if (tok->n_args < 8) {
  2279. log_warn(LD_DIR, "Too few arguments to r");
  2280. goto err;
  2281. }
  2282. } else if (flav == FLAV_MICRODESC) {
  2283. offset = -1; /* There is no identity digest */
  2284. }
  2285. if (vote_rs) {
  2286. rs = &vote_rs->status;
  2287. } else {
  2288. rs = tor_malloc_zero(sizeof(routerstatus_t));
  2289. }
  2290. if (!is_legal_nickname(tok->args[0])) {
  2291. log_warn(LD_DIR,
  2292. "Invalid nickname %s in router status; skipping.",
  2293. escaped(tok->args[0]));
  2294. goto err;
  2295. }
  2296. strlcpy(rs->nickname, tok->args[0], sizeof(rs->nickname));
  2297. if (digest_from_base64(rs->identity_digest, tok->args[1])) {
  2298. log_warn(LD_DIR, "Error decoding identity digest %s",
  2299. escaped(tok->args[1]));
  2300. goto err;
  2301. }
  2302. if (flav == FLAV_NS) {
  2303. if (digest_from_base64(rs->descriptor_digest, tok->args[2])) {
  2304. log_warn(LD_DIR, "Error decoding descriptor digest %s",
  2305. escaped(tok->args[2]));
  2306. goto err;
  2307. }
  2308. }
  2309. if (tor_snprintf(timebuf, sizeof(timebuf), "%s %s",
  2310. tok->args[3+offset], tok->args[4+offset]) < 0 ||
  2311. parse_iso_time(timebuf, &rs->published_on)<0) {
  2312. log_warn(LD_DIR, "Error parsing time '%s %s' [%d %d]",
  2313. tok->args[3+offset], tok->args[4+offset],
  2314. offset, (int)flav);
  2315. goto err;
  2316. }
  2317. if (tor_inet_aton(tok->args[5+offset], &in) == 0) {
  2318. log_warn(LD_DIR, "Error parsing router address in network-status %s",
  2319. escaped(tok->args[5+offset]));
  2320. goto err;
  2321. }
  2322. rs->addr = ntohl(in.s_addr);
  2323. rs->or_port = (uint16_t) tor_parse_long(tok->args[6+offset],
  2324. 10,0,65535,NULL,NULL);
  2325. rs->dir_port = (uint16_t) tor_parse_long(tok->args[7+offset],
  2326. 10,0,65535,NULL,NULL);
  2327. {
  2328. smartlist_t *a_lines = find_all_by_keyword(tokens, K_A);
  2329. if (a_lines) {
  2330. find_single_ipv6_orport(a_lines, &rs->ipv6_addr, &rs->ipv6_orport);
  2331. smartlist_free(a_lines);
  2332. }
  2333. }
  2334. tok = find_opt_by_keyword(tokens, K_S);
  2335. if (tok && vote) {
  2336. int i;
  2337. vote_rs->flags = 0;
  2338. for (i=0; i < tok->n_args; ++i) {
  2339. int p = smartlist_string_pos(vote->known_flags, tok->args[i]);
  2340. if (p >= 0) {
  2341. vote_rs->flags |= (U64_LITERAL(1)<<p);
  2342. } else {
  2343. log_warn(LD_DIR, "Flags line had a flag %s not listed in known_flags.",
  2344. escaped(tok->args[i]));
  2345. goto err;
  2346. }
  2347. }
  2348. } else if (tok) {
  2349. /* This is a consensus, not a vote. */
  2350. int i;
  2351. for (i=0; i < tok->n_args; ++i) {
  2352. if (!strcmp(tok->args[i], "Exit"))
  2353. rs->is_exit = 1;
  2354. else if (!strcmp(tok->args[i], "Stable"))
  2355. rs->is_stable = 1;
  2356. else if (!strcmp(tok->args[i], "Fast"))
  2357. rs->is_fast = 1;
  2358. else if (!strcmp(tok->args[i], "Running"))
  2359. rs->is_flagged_running = 1;
  2360. else if (!strcmp(tok->args[i], "Named"))
  2361. rs->is_named = 1;
  2362. else if (!strcmp(tok->args[i], "Valid"))
  2363. rs->is_valid = 1;
  2364. else if (!strcmp(tok->args[i], "Guard"))
  2365. rs->is_possible_guard = 1;
  2366. else if (!strcmp(tok->args[i], "BadExit"))
  2367. rs->is_bad_exit = 1;
  2368. else if (!strcmp(tok->args[i], "Authority"))
  2369. rs->is_authority = 1;
  2370. else if (!strcmp(tok->args[i], "Unnamed") &&
  2371. consensus_method >= 2) {
  2372. /* Unnamed is computed right by consensus method 2 and later. */
  2373. rs->is_unnamed = 1;
  2374. } else if (!strcmp(tok->args[i], "HSDir")) {
  2375. rs->is_hs_dir = 1;
  2376. } else if (!strcmp(tok->args[i], "V2Dir")) {
  2377. rs->is_v2_dir = 1;
  2378. }
  2379. }
  2380. /* These are implied true by having been included in a consensus made
  2381. * with a given method */
  2382. rs->is_flagged_running = 1; /* Starting with consensus method 4. */
  2383. if (consensus_method >= MIN_METHOD_FOR_EXCLUDING_INVALID_NODES)
  2384. rs->is_valid = 1;
  2385. }
  2386. int found_protocol_list = 0;
  2387. if ((tok = find_opt_by_keyword(tokens, K_PROTO))) {
  2388. found_protocol_list = 1;
  2389. rs->protocols_known = 1;
  2390. rs->supports_extend2_cells =
  2391. protocol_list_supports_protocol(tok->args[0], PRT_RELAY, 2);
  2392. rs->supports_ed25519_link_handshake =
  2393. protocol_list_supports_protocol(tok->args[0], PRT_LINKAUTH, 3);
  2394. }
  2395. if ((tok = find_opt_by_keyword(tokens, K_V))) {
  2396. tor_assert(tok->n_args == 1);
  2397. if (!strcmpstart(tok->args[0], "Tor ") && !found_protocol_list) {
  2398. /* We only do version checks like this in the case where
  2399. * the version is a "Tor" version, and where there is no
  2400. * list of protocol versions that we should be looking at instead. */
  2401. rs->supports_extend2_cells =
  2402. tor_version_as_new_as(tok->args[0], "0.2.4.8-alpha");
  2403. rs->protocols_known = 1;
  2404. }
  2405. if (vote_rs) {
  2406. vote_rs->version = tor_strdup(tok->args[0]);
  2407. }
  2408. }
  2409. /* handle weighting/bandwidth info */
  2410. if ((tok = find_opt_by_keyword(tokens, K_W))) {
  2411. int i;
  2412. for (i=0; i < tok->n_args; ++i) {
  2413. if (!strcmpstart(tok->args[i], "Bandwidth=")) {
  2414. int ok;
  2415. rs->bandwidth_kb =
  2416. (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
  2417. 10, 0, UINT32_MAX,
  2418. &ok, NULL);
  2419. if (!ok) {
  2420. log_warn(LD_DIR, "Invalid Bandwidth %s", escaped(tok->args[i]));
  2421. goto err;
  2422. }
  2423. rs->has_bandwidth = 1;
  2424. } else if (!strcmpstart(tok->args[i], "Measured=") && vote_rs) {
  2425. int ok;
  2426. vote_rs->measured_bw_kb =
  2427. (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
  2428. 10, 0, UINT32_MAX, &ok, NULL);
  2429. if (!ok) {
  2430. log_warn(LD_DIR, "Invalid Measured Bandwidth %s",
  2431. escaped(tok->args[i]));
  2432. goto err;
  2433. }
  2434. vote_rs->has_measured_bw = 1;
  2435. vote->has_measured_bws = 1;
  2436. } else if (!strcmpstart(tok->args[i], "Unmeasured=1")) {
  2437. rs->bw_is_unmeasured = 1;
  2438. } else if (!strcmpstart(tok->args[i], "GuardFraction=")) {
  2439. if (routerstatus_parse_guardfraction(tok->args[i],
  2440. vote, vote_rs, rs) < 0) {
  2441. goto err;
  2442. }
  2443. }
  2444. }
  2445. }
  2446. /* parse exit policy summaries */
  2447. if ((tok = find_opt_by_keyword(tokens, K_P))) {
  2448. tor_assert(tok->n_args == 1);
  2449. if (strcmpstart(tok->args[0], "accept ") &&
  2450. strcmpstart(tok->args[0], "reject ")) {
  2451. log_warn(LD_DIR, "Unknown exit policy summary type %s.",
  2452. escaped(tok->args[0]));
  2453. goto err;
  2454. }
  2455. /* XXX weasel: parse this into ports and represent them somehow smart,
  2456. * maybe not here but somewhere on if we need it for the client.
  2457. * we should still parse it here to check it's valid tho.
  2458. */
  2459. rs->exitsummary = tor_strdup(tok->args[0]);
  2460. rs->has_exitsummary = 1;
  2461. }
  2462. if (vote_rs) {
  2463. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, t) {
  2464. if (t->tp == K_M && t->n_args) {
  2465. vote_microdesc_hash_t *line =
  2466. tor_malloc(sizeof(vote_microdesc_hash_t));
  2467. line->next = vote_rs->microdesc;
  2468. line->microdesc_hash_line = tor_strdup(t->args[0]);
  2469. vote_rs->microdesc = line;
  2470. }
  2471. if (t->tp == K_ID) {
  2472. tor_assert(t->n_args >= 2);
  2473. if (!strcmp(t->args[0], "ed25519")) {
  2474. vote_rs->has_ed25519_listing = 1;
  2475. if (strcmp(t->args[1], "none") &&
  2476. digest256_from_base64((char*)vote_rs->ed25519_id,
  2477. t->args[1])<0) {
  2478. log_warn(LD_DIR, "Bogus ed25519 key in networkstatus vote");
  2479. goto err;
  2480. }
  2481. }
  2482. }
  2483. if (t->tp == K_PROTO) {
  2484. tor_assert(t->n_args == 1);
  2485. vote_rs->protocols = tor_strdup(t->args[0]);
  2486. }
  2487. } SMARTLIST_FOREACH_END(t);
  2488. } else if (flav == FLAV_MICRODESC) {
  2489. tok = find_opt_by_keyword(tokens, K_M);
  2490. if (tok) {
  2491. tor_assert(tok->n_args);
  2492. if (digest256_from_base64(rs->descriptor_digest, tok->args[0])) {
  2493. log_warn(LD_DIR, "Error decoding microdescriptor digest %s",
  2494. escaped(tok->args[0]));
  2495. goto err;
  2496. }
  2497. } else {
  2498. log_info(LD_BUG, "Found an entry in networkstatus with no "
  2499. "microdescriptor digest. (Router %s ($%s) at %s:%d.)",
  2500. rs->nickname, hex_str(rs->identity_digest, DIGEST_LEN),
  2501. fmt_addr32(rs->addr), rs->or_port);
  2502. }
  2503. }
  2504. if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME))
  2505. rs->is_named = 0;
  2506. goto done;
  2507. err:
  2508. dump_desc(s_dup, "routerstatus entry");
  2509. if (rs && !vote_rs)
  2510. routerstatus_free(rs);
  2511. rs = NULL;
  2512. done:
  2513. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2514. smartlist_clear(tokens);
  2515. if (area) {
  2516. DUMP_AREA(area, "routerstatus entry");
  2517. memarea_clear(area);
  2518. }
  2519. *s = eos;
  2520. return rs;
  2521. }
  2522. int
  2523. compare_vote_routerstatus_entries(const void **_a, const void **_b)
  2524. {
  2525. const vote_routerstatus_t *a = *_a, *b = *_b;
  2526. return fast_memcmp(a->status.identity_digest, b->status.identity_digest,
  2527. DIGEST_LEN);
  2528. }
  2529. /** Verify the bandwidth weights of a network status document */
  2530. int
  2531. networkstatus_verify_bw_weights(networkstatus_t *ns, int consensus_method)
  2532. {
  2533. int64_t weight_scale;
  2534. int64_t G=0, M=0, E=0, D=0, T=0;
  2535. double Wgg, Wgm, Wgd, Wmg, Wmm, Wme, Wmd, Weg, Wem, Wee, Wed;
  2536. double Gtotal=0, Mtotal=0, Etotal=0;
  2537. const char *casename = NULL;
  2538. int valid = 1;
  2539. (void) consensus_method;
  2540. weight_scale = networkstatus_get_weight_scale_param(ns);
  2541. Wgg = networkstatus_get_bw_weight(ns, "Wgg", -1);
  2542. Wgm = networkstatus_get_bw_weight(ns, "Wgm", -1);
  2543. Wgd = networkstatus_get_bw_weight(ns, "Wgd", -1);
  2544. Wmg = networkstatus_get_bw_weight(ns, "Wmg", -1);
  2545. Wmm = networkstatus_get_bw_weight(ns, "Wmm", -1);
  2546. Wme = networkstatus_get_bw_weight(ns, "Wme", -1);
  2547. Wmd = networkstatus_get_bw_weight(ns, "Wmd", -1);
  2548. Weg = networkstatus_get_bw_weight(ns, "Weg", -1);
  2549. Wem = networkstatus_get_bw_weight(ns, "Wem", -1);
  2550. Wee = networkstatus_get_bw_weight(ns, "Wee", -1);
  2551. Wed = networkstatus_get_bw_weight(ns, "Wed", -1);
  2552. if (Wgg<0 || Wgm<0 || Wgd<0 || Wmg<0 || Wmm<0 || Wme<0 || Wmd<0 || Weg<0
  2553. || Wem<0 || Wee<0 || Wed<0) {
  2554. log_warn(LD_BUG, "No bandwidth weights produced in consensus!");
  2555. return 0;
  2556. }
  2557. // First, sanity check basic summing properties that hold for all cases
  2558. // We use > 1 as the check for these because they are computed as integers.
  2559. // Sometimes there are rounding errors.
  2560. if (fabs(Wmm - weight_scale) > 1) {
  2561. log_warn(LD_BUG, "Wmm=%f != "I64_FORMAT,
  2562. Wmm, I64_PRINTF_ARG(weight_scale));
  2563. valid = 0;
  2564. }
  2565. if (fabs(Wem - Wee) > 1) {
  2566. log_warn(LD_BUG, "Wem=%f != Wee=%f", Wem, Wee);
  2567. valid = 0;
  2568. }
  2569. if (fabs(Wgm - Wgg) > 1) {
  2570. log_warn(LD_BUG, "Wgm=%f != Wgg=%f", Wgm, Wgg);
  2571. valid = 0;
  2572. }
  2573. if (fabs(Weg - Wed) > 1) {
  2574. log_warn(LD_BUG, "Wed=%f != Weg=%f", Wed, Weg);
  2575. valid = 0;
  2576. }
  2577. if (fabs(Wgg + Wmg - weight_scale) > 0.001*weight_scale) {
  2578. log_warn(LD_BUG, "Wgg=%f != "I64_FORMAT" - Wmg=%f", Wgg,
  2579. I64_PRINTF_ARG(weight_scale), Wmg);
  2580. valid = 0;
  2581. }
  2582. if (fabs(Wee + Wme - weight_scale) > 0.001*weight_scale) {
  2583. log_warn(LD_BUG, "Wee=%f != "I64_FORMAT" - Wme=%f", Wee,
  2584. I64_PRINTF_ARG(weight_scale), Wme);
  2585. valid = 0;
  2586. }
  2587. if (fabs(Wgd + Wmd + Wed - weight_scale) > 0.001*weight_scale) {
  2588. log_warn(LD_BUG, "Wgd=%f + Wmd=%f + Wed=%f != "I64_FORMAT,
  2589. Wgd, Wmd, Wed, I64_PRINTF_ARG(weight_scale));
  2590. valid = 0;
  2591. }
  2592. Wgg /= weight_scale;
  2593. Wgm /= weight_scale;
  2594. Wgd /= weight_scale;
  2595. Wmg /= weight_scale;
  2596. Wmm /= weight_scale;
  2597. Wme /= weight_scale;
  2598. Wmd /= weight_scale;
  2599. Weg /= weight_scale;
  2600. Wem /= weight_scale;
  2601. Wee /= weight_scale;
  2602. Wed /= weight_scale;
  2603. // Then, gather G, M, E, D, T to determine case
  2604. SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) {
  2605. int is_exit = 0;
  2606. /* Bug #2203: Don't count bad exits as exits for balancing */
  2607. is_exit = rs->is_exit && !rs->is_bad_exit;
  2608. if (rs->has_bandwidth) {
  2609. T += rs->bandwidth_kb;
  2610. if (is_exit && rs->is_possible_guard) {
  2611. D += rs->bandwidth_kb;
  2612. Gtotal += Wgd*rs->bandwidth_kb;
  2613. Mtotal += Wmd*rs->bandwidth_kb;
  2614. Etotal += Wed*rs->bandwidth_kb;
  2615. } else if (is_exit) {
  2616. E += rs->bandwidth_kb;
  2617. Mtotal += Wme*rs->bandwidth_kb;
  2618. Etotal += Wee*rs->bandwidth_kb;
  2619. } else if (rs->is_possible_guard) {
  2620. G += rs->bandwidth_kb;
  2621. Gtotal += Wgg*rs->bandwidth_kb;
  2622. Mtotal += Wmg*rs->bandwidth_kb;
  2623. } else {
  2624. M += rs->bandwidth_kb;
  2625. Mtotal += Wmm*rs->bandwidth_kb;
  2626. }
  2627. } else {
  2628. log_warn(LD_BUG, "Missing consensus bandwidth for router %s",
  2629. routerstatus_describe(rs));
  2630. }
  2631. } SMARTLIST_FOREACH_END(rs);
  2632. // Finally, check equality conditions depending upon case 1, 2 or 3
  2633. // Full equality cases: 1, 3b
  2634. // Partial equality cases: 2b (E=G), 3a (M=E)
  2635. // Fully unknown: 2a
  2636. if (3*E >= T && 3*G >= T) {
  2637. // Case 1: Neither are scarce
  2638. casename = "Case 1";
  2639. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  2640. log_warn(LD_DIR,
  2641. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  2642. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2643. " T="I64_FORMAT". "
  2644. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2645. casename, Etotal, Mtotal,
  2646. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2647. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2648. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2649. valid = 0;
  2650. }
  2651. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2652. log_warn(LD_DIR,
  2653. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2654. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2655. " T="I64_FORMAT". "
  2656. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2657. casename, Etotal, Gtotal,
  2658. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2659. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2660. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2661. valid = 0;
  2662. }
  2663. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  2664. log_warn(LD_DIR,
  2665. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  2666. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2667. " T="I64_FORMAT". "
  2668. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2669. casename, Mtotal, Gtotal,
  2670. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2671. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2672. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2673. valid = 0;
  2674. }
  2675. } else if (3*E < T && 3*G < T) {
  2676. int64_t R = MIN(E, G);
  2677. int64_t S = MAX(E, G);
  2678. /*
  2679. * Case 2: Both Guards and Exits are scarce
  2680. * Balance D between E and G, depending upon
  2681. * D capacity and scarcity. Devote no extra
  2682. * bandwidth to middle nodes.
  2683. */
  2684. if (R+D < S) { // Subcase a
  2685. double Rtotal, Stotal;
  2686. if (E < G) {
  2687. Rtotal = Etotal;
  2688. Stotal = Gtotal;
  2689. } else {
  2690. Rtotal = Gtotal;
  2691. Stotal = Etotal;
  2692. }
  2693. casename = "Case 2a";
  2694. // Rtotal < Stotal
  2695. if (Rtotal > Stotal) {
  2696. log_warn(LD_DIR,
  2697. "Bw Weight Failure for %s: Rtotal %f > Stotal %f. "
  2698. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2699. " T="I64_FORMAT". "
  2700. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2701. casename, Rtotal, Stotal,
  2702. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2703. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2704. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2705. valid = 0;
  2706. }
  2707. // Rtotal < T/3
  2708. if (3*Rtotal > T) {
  2709. log_warn(LD_DIR,
  2710. "Bw Weight Failure for %s: 3*Rtotal %f > T "
  2711. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
  2712. " D="I64_FORMAT" T="I64_FORMAT". "
  2713. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2714. casename, Rtotal*3, I64_PRINTF_ARG(T),
  2715. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2716. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2717. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2718. valid = 0;
  2719. }
  2720. // Stotal < T/3
  2721. if (3*Stotal > T) {
  2722. log_warn(LD_DIR,
  2723. "Bw Weight Failure for %s: 3*Stotal %f > T "
  2724. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
  2725. " D="I64_FORMAT" T="I64_FORMAT". "
  2726. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2727. casename, Stotal*3, I64_PRINTF_ARG(T),
  2728. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2729. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2730. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2731. valid = 0;
  2732. }
  2733. // Mtotal > T/3
  2734. if (3*Mtotal < T) {
  2735. log_warn(LD_DIR,
  2736. "Bw Weight Failure for %s: 3*Mtotal %f < T "
  2737. I64_FORMAT". "
  2738. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2739. " T="I64_FORMAT". "
  2740. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2741. casename, Mtotal*3, I64_PRINTF_ARG(T),
  2742. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2743. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2744. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2745. valid = 0;
  2746. }
  2747. } else { // Subcase b: R+D > S
  2748. casename = "Case 2b";
  2749. /* Check the rare-M redirect case. */
  2750. if (D != 0 && 3*M < T) {
  2751. casename = "Case 2b (balanced)";
  2752. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  2753. log_warn(LD_DIR,
  2754. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  2755. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2756. " T="I64_FORMAT". "
  2757. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2758. casename, Etotal, Mtotal,
  2759. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2760. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2761. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2762. valid = 0;
  2763. }
  2764. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2765. log_warn(LD_DIR,
  2766. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2767. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2768. " T="I64_FORMAT". "
  2769. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2770. casename, Etotal, Gtotal,
  2771. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2772. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2773. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2774. valid = 0;
  2775. }
  2776. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  2777. log_warn(LD_DIR,
  2778. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  2779. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2780. " T="I64_FORMAT". "
  2781. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2782. casename, Mtotal, Gtotal,
  2783. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2784. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2785. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2786. valid = 0;
  2787. }
  2788. } else {
  2789. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2790. log_warn(LD_DIR,
  2791. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2792. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2793. " T="I64_FORMAT". "
  2794. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2795. casename, Etotal, Gtotal,
  2796. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2797. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2798. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2799. valid = 0;
  2800. }
  2801. }
  2802. }
  2803. } else { // if (E < T/3 || G < T/3) {
  2804. int64_t S = MIN(E, G);
  2805. int64_t NS = MAX(E, G);
  2806. if (3*(S+D) < T) { // Subcase a:
  2807. double Stotal;
  2808. double NStotal;
  2809. if (G < E) {
  2810. casename = "Case 3a (G scarce)";
  2811. Stotal = Gtotal;
  2812. NStotal = Etotal;
  2813. } else { // if (G >= E) {
  2814. casename = "Case 3a (E scarce)";
  2815. NStotal = Gtotal;
  2816. Stotal = Etotal;
  2817. }
  2818. // Stotal < T/3
  2819. if (3*Stotal > T) {
  2820. log_warn(LD_DIR,
  2821. "Bw Weight Failure for %s: 3*Stotal %f > T "
  2822. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
  2823. " D="I64_FORMAT" T="I64_FORMAT". "
  2824. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2825. casename, Stotal*3, I64_PRINTF_ARG(T),
  2826. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2827. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2828. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2829. valid = 0;
  2830. }
  2831. if (NS >= M) {
  2832. if (fabs(NStotal-Mtotal) > 0.01*MAX(NStotal,Mtotal)) {
  2833. log_warn(LD_DIR,
  2834. "Bw Weight Failure for %s: NStotal %f != Mtotal %f. "
  2835. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2836. " T="I64_FORMAT". "
  2837. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2838. casename, NStotal, Mtotal,
  2839. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2840. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2841. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2842. valid = 0;
  2843. }
  2844. } else {
  2845. // if NS < M, NStotal > T/3 because only one of G or E is scarce
  2846. if (3*NStotal < T) {
  2847. log_warn(LD_DIR,
  2848. "Bw Weight Failure for %s: 3*NStotal %f < T "
  2849. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT
  2850. " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT". "
  2851. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2852. casename, NStotal*3, I64_PRINTF_ARG(T),
  2853. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2854. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2855. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2856. valid = 0;
  2857. }
  2858. }
  2859. } else { // Subcase b: S+D >= T/3
  2860. casename = "Case 3b";
  2861. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  2862. log_warn(LD_DIR,
  2863. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  2864. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2865. " T="I64_FORMAT". "
  2866. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2867. casename, Etotal, Mtotal,
  2868. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2869. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2870. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2871. valid = 0;
  2872. }
  2873. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2874. log_warn(LD_DIR,
  2875. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2876. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2877. " T="I64_FORMAT". "
  2878. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2879. casename, Etotal, Gtotal,
  2880. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2881. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2882. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2883. valid = 0;
  2884. }
  2885. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  2886. log_warn(LD_DIR,
  2887. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  2888. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2889. " T="I64_FORMAT". "
  2890. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2891. casename, Mtotal, Gtotal,
  2892. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2893. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2894. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2895. valid = 0;
  2896. }
  2897. }
  2898. }
  2899. if (valid)
  2900. log_notice(LD_DIR, "Bandwidth-weight %s is verified and valid.",
  2901. casename);
  2902. return valid;
  2903. }
  2904. /** Parse and extract all SR commits from <b>tokens</b> and place them in
  2905. * <b>ns</b>. */
  2906. static void
  2907. extract_shared_random_commits(networkstatus_t *ns, smartlist_t *tokens)
  2908. {
  2909. smartlist_t *chunks = NULL;
  2910. tor_assert(ns);
  2911. tor_assert(tokens);
  2912. /* Commits are only present in a vote. */
  2913. tor_assert(ns->type == NS_TYPE_VOTE);
  2914. ns->sr_info.commits = smartlist_new();
  2915. smartlist_t *commits = find_all_by_keyword(tokens, K_COMMIT);
  2916. /* It's normal that a vote might contain no commits even if it participates
  2917. * in the SR protocol. Don't treat it as an error. */
  2918. if (commits == NULL) {
  2919. goto end;
  2920. }
  2921. /* Parse the commit. We do NO validation of number of arguments or ordering
  2922. * for forward compatibility, it's the parse commit job to inform us if it's
  2923. * supported or not. */
  2924. chunks = smartlist_new();
  2925. SMARTLIST_FOREACH_BEGIN(commits, directory_token_t *, tok) {
  2926. /* Extract all arguments and put them in the chunks list. */
  2927. for (int i = 0; i < tok->n_args; i++) {
  2928. smartlist_add(chunks, tok->args[i]);
  2929. }
  2930. sr_commit_t *commit = sr_parse_commit(chunks);
  2931. smartlist_clear(chunks);
  2932. if (commit == NULL) {
  2933. /* Get voter identity so we can warn that this dirauth vote contains
  2934. * commit we can't parse. */
  2935. networkstatus_voter_info_t *voter = smartlist_get(ns->voters, 0);
  2936. tor_assert(voter);
  2937. log_warn(LD_DIR, "SR: Unable to parse commit %s from vote of voter %s.",
  2938. escaped(tok->object_body),
  2939. hex_str(voter->identity_digest,
  2940. sizeof(voter->identity_digest)));
  2941. /* Commitment couldn't be parsed. Continue onto the next commit because
  2942. * this one could be unsupported for instance. */
  2943. continue;
  2944. }
  2945. /* Add newly created commit object to the vote. */
  2946. smartlist_add(ns->sr_info.commits, commit);
  2947. } SMARTLIST_FOREACH_END(tok);
  2948. end:
  2949. smartlist_free(chunks);
  2950. smartlist_free(commits);
  2951. }
  2952. /** Check if a shared random value of type <b>srv_type</b> is in
  2953. * <b>tokens</b>. If there is, parse it and set it to <b>srv_out</b>. Return
  2954. * -1 on failure, 0 on success. The resulting srv is allocated on the heap and
  2955. * it's the responsibility of the caller to free it. */
  2956. static int
  2957. extract_one_srv(smartlist_t *tokens, directory_keyword srv_type,
  2958. sr_srv_t **srv_out)
  2959. {
  2960. int ret = -1;
  2961. directory_token_t *tok;
  2962. sr_srv_t *srv = NULL;
  2963. smartlist_t *chunks;
  2964. tor_assert(tokens);
  2965. chunks = smartlist_new();
  2966. tok = find_opt_by_keyword(tokens, srv_type);
  2967. if (!tok) {
  2968. /* That's fine, no SRV is allowed. */
  2969. ret = 0;
  2970. goto end;
  2971. }
  2972. for (int i = 0; i < tok->n_args; i++) {
  2973. smartlist_add(chunks, tok->args[i]);
  2974. }
  2975. srv = sr_parse_srv(chunks);
  2976. if (srv == NULL) {
  2977. log_warn(LD_DIR, "SR: Unparseable SRV %s", escaped(tok->object_body));
  2978. goto end;
  2979. }
  2980. /* All is good. */
  2981. *srv_out = srv;
  2982. ret = 0;
  2983. end:
  2984. smartlist_free(chunks);
  2985. return ret;
  2986. }
  2987. /** Extract any shared random values found in <b>tokens</b> and place them in
  2988. * the networkstatus <b>ns</b>. */
  2989. static void
  2990. extract_shared_random_srvs(networkstatus_t *ns, smartlist_t *tokens)
  2991. {
  2992. const char *voter_identity;
  2993. networkstatus_voter_info_t *voter;
  2994. tor_assert(ns);
  2995. tor_assert(tokens);
  2996. /* Can be only one of them else code flow. */
  2997. tor_assert(ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_CONSENSUS);
  2998. if (ns->type == NS_TYPE_VOTE) {
  2999. voter = smartlist_get(ns->voters, 0);
  3000. tor_assert(voter);
  3001. voter_identity = hex_str(voter->identity_digest,
  3002. sizeof(voter->identity_digest));
  3003. } else {
  3004. /* Consensus has multiple voters so no specific voter. */
  3005. voter_identity = "consensus";
  3006. }
  3007. /* We extract both and on error, everything is stopped because it means
  3008. * the votes is malformed for the shared random value(s). */
  3009. if (extract_one_srv(tokens, K_PREVIOUS_SRV, &ns->sr_info.previous_srv) < 0) {
  3010. log_warn(LD_DIR, "SR: Unable to parse previous SRV from %s",
  3011. voter_identity);
  3012. /* Maybe we have a chance with the current SRV so let's try it anyway. */
  3013. }
  3014. if (extract_one_srv(tokens, K_CURRENT_SRV, &ns->sr_info.current_srv) < 0) {
  3015. log_warn(LD_DIR, "SR: Unable to parse current SRV from %s",
  3016. voter_identity);
  3017. }
  3018. }
  3019. /** Parse a v3 networkstatus vote, opinion, or consensus (depending on
  3020. * ns_type), from <b>s</b>, and return the result. Return NULL on failure. */
  3021. networkstatus_t *
  3022. networkstatus_parse_vote_from_string(const char *s, const char **eos_out,
  3023. networkstatus_type_t ns_type)
  3024. {
  3025. smartlist_t *tokens = smartlist_new();
  3026. smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;
  3027. networkstatus_voter_info_t *voter = NULL;
  3028. networkstatus_t *ns = NULL;
  3029. common_digests_t ns_digests;
  3030. const char *cert, *end_of_header, *end_of_footer, *s_dup = s;
  3031. directory_token_t *tok;
  3032. struct in_addr in;
  3033. int i, inorder, n_signatures = 0;
  3034. memarea_t *area = NULL, *rs_area = NULL;
  3035. consensus_flavor_t flav = FLAV_NS;
  3036. char *last_kwd=NULL;
  3037. tor_assert(s);
  3038. if (eos_out)
  3039. *eos_out = NULL;
  3040. if (router_get_networkstatus_v3_hashes(s, &ns_digests)) {
  3041. log_warn(LD_DIR, "Unable to compute digest of network-status");
  3042. goto err;
  3043. }
  3044. area = memarea_new();
  3045. end_of_header = find_start_of_next_routerstatus(s);
  3046. if (tokenize_string(area, s, end_of_header, tokens,
  3047. (ns_type == NS_TYPE_CONSENSUS) ?
  3048. networkstatus_consensus_token_table :
  3049. networkstatus_token_table, 0)) {
  3050. log_warn(LD_DIR, "Error tokenizing network-status header");
  3051. goto err;
  3052. }
  3053. ns = tor_malloc_zero(sizeof(networkstatus_t));
  3054. memcpy(&ns->digests, &ns_digests, sizeof(ns_digests));
  3055. tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
  3056. tor_assert(tok);
  3057. if (tok->n_args > 1) {
  3058. int flavor = networkstatus_parse_flavor_name(tok->args[1]);
  3059. if (flavor < 0) {
  3060. log_warn(LD_DIR, "Can't parse document with unknown flavor %s",
  3061. escaped(tok->args[1]));
  3062. goto err;
  3063. }
  3064. ns->flavor = flav = flavor;
  3065. }
  3066. if (flav != FLAV_NS && ns_type != NS_TYPE_CONSENSUS) {
  3067. log_warn(LD_DIR, "Flavor found on non-consensus networkstatus.");
  3068. goto err;
  3069. }
  3070. if (ns_type != NS_TYPE_CONSENSUS) {
  3071. const char *end_of_cert = NULL;
  3072. if (!(cert = strstr(s, "\ndir-key-certificate-version")))
  3073. goto err;
  3074. ++cert;
  3075. ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);
  3076. if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)
  3077. goto err;
  3078. }
  3079. tok = find_by_keyword(tokens, K_VOTE_STATUS);
  3080. tor_assert(tok->n_args);
  3081. if (!strcmp(tok->args[0], "vote")) {
  3082. ns->type = NS_TYPE_VOTE;
  3083. } else if (!strcmp(tok->args[0], "consensus")) {
  3084. ns->type = NS_TYPE_CONSENSUS;
  3085. } else if (!strcmp(tok->args[0], "opinion")) {
  3086. ns->type = NS_TYPE_OPINION;
  3087. } else {
  3088. log_warn(LD_DIR, "Unrecognized vote status %s in network-status",
  3089. escaped(tok->args[0]));
  3090. goto err;
  3091. }
  3092. if (ns_type != ns->type) {
  3093. log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus.");
  3094. goto err;
  3095. }
  3096. if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
  3097. tok = find_by_keyword(tokens, K_PUBLISHED);
  3098. if (parse_iso_time(tok->args[0], &ns->published))
  3099. goto err;
  3100. ns->supported_methods = smartlist_new();
  3101. tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHODS);
  3102. if (tok) {
  3103. for (i=0; i < tok->n_args; ++i)
  3104. smartlist_add_strdup(ns->supported_methods, tok->args[i]);
  3105. } else {
  3106. smartlist_add_strdup(ns->supported_methods, "1");
  3107. }
  3108. } else {
  3109. tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHOD);
  3110. if (tok) {
  3111. int num_ok;
  3112. ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX,
  3113. &num_ok, NULL);
  3114. if (!num_ok)
  3115. goto err;
  3116. } else {
  3117. ns->consensus_method = 1;
  3118. }
  3119. }
  3120. if ((tok = find_opt_by_keyword(tokens, K_RECOMMENDED_CLIENT_PROTOCOLS)))
  3121. ns->recommended_client_protocols = tor_strdup(tok->args[0]);
  3122. if ((tok = find_opt_by_keyword(tokens, K_RECOMMENDED_RELAY_PROTOCOLS)))
  3123. ns->recommended_relay_protocols = tor_strdup(tok->args[0]);
  3124. if ((tok = find_opt_by_keyword(tokens, K_REQUIRED_CLIENT_PROTOCOLS)))
  3125. ns->required_client_protocols = tor_strdup(tok->args[0]);
  3126. if ((tok = find_opt_by_keyword(tokens, K_REQUIRED_RELAY_PROTOCOLS)))
  3127. ns->required_relay_protocols = tor_strdup(tok->args[0]);
  3128. tok = find_by_keyword(tokens, K_VALID_AFTER);
  3129. if (parse_iso_time(tok->args[0], &ns->valid_after))
  3130. goto err;
  3131. tok = find_by_keyword(tokens, K_FRESH_UNTIL);
  3132. if (parse_iso_time(tok->args[0], &ns->fresh_until))
  3133. goto err;
  3134. tok = find_by_keyword(tokens, K_VALID_UNTIL);
  3135. if (parse_iso_time(tok->args[0], &ns->valid_until))
  3136. goto err;
  3137. tok = find_by_keyword(tokens, K_VOTING_DELAY);
  3138. tor_assert(tok->n_args >= 2);
  3139. {
  3140. int ok;
  3141. ns->vote_seconds =
  3142. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);
  3143. if (!ok)
  3144. goto err;
  3145. ns->dist_seconds =
  3146. (int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL);
  3147. if (!ok)
  3148. goto err;
  3149. }
  3150. if (ns->valid_after +
  3151. (get_options()->TestingTorNetwork ?
  3152. MIN_VOTE_INTERVAL_TESTING : MIN_VOTE_INTERVAL) > ns->fresh_until) {
  3153. log_warn(LD_DIR, "Vote/consensus freshness interval is too short");
  3154. goto err;
  3155. }
  3156. if (ns->valid_after +
  3157. (get_options()->TestingTorNetwork ?
  3158. MIN_VOTE_INTERVAL_TESTING : MIN_VOTE_INTERVAL)*2 > ns->valid_until) {
  3159. log_warn(LD_DIR, "Vote/consensus liveness interval is too short");
  3160. goto err;
  3161. }
  3162. if (ns->vote_seconds < MIN_VOTE_SECONDS) {
  3163. log_warn(LD_DIR, "Vote seconds is too short");
  3164. goto err;
  3165. }
  3166. if (ns->dist_seconds < MIN_DIST_SECONDS) {
  3167. log_warn(LD_DIR, "Dist seconds is too short");
  3168. goto err;
  3169. }
  3170. if ((tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  3171. ns->client_versions = tor_strdup(tok->args[0]);
  3172. }
  3173. if ((tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS))) {
  3174. ns->server_versions = tor_strdup(tok->args[0]);
  3175. }
  3176. {
  3177. smartlist_t *package_lst = find_all_by_keyword(tokens, K_PACKAGE);
  3178. ns->package_lines = smartlist_new();
  3179. if (package_lst) {
  3180. SMARTLIST_FOREACH(package_lst, directory_token_t *, t,
  3181. smartlist_add_strdup(ns->package_lines, t->args[0]));
  3182. }
  3183. smartlist_free(package_lst);
  3184. }
  3185. tok = find_by_keyword(tokens, K_KNOWN_FLAGS);
  3186. ns->known_flags = smartlist_new();
  3187. inorder = 1;
  3188. for (i = 0; i < tok->n_args; ++i) {
  3189. smartlist_add_strdup(ns->known_flags, tok->args[i]);
  3190. if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) {
  3191. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  3192. inorder = 0;
  3193. }
  3194. }
  3195. if (!inorder) {
  3196. log_warn(LD_DIR, "known-flags not in order");
  3197. goto err;
  3198. }
  3199. if (ns->type != NS_TYPE_CONSENSUS &&
  3200. smartlist_len(ns->known_flags) > MAX_KNOWN_FLAGS_IN_VOTE) {
  3201. /* If we allowed more than 64 flags in votes, then parsing them would make
  3202. * us invoke undefined behavior whenever we used 1<<flagnum to do a
  3203. * bit-shift. This is only for votes and opinions: consensus users don't
  3204. * care about flags they don't recognize, and so don't build a bitfield
  3205. * for them. */
  3206. log_warn(LD_DIR, "Too many known-flags in consensus vote or opinion");
  3207. goto err;
  3208. }
  3209. tok = find_opt_by_keyword(tokens, K_PARAMS);
  3210. if (tok) {
  3211. int any_dups = 0;
  3212. inorder = 1;
  3213. ns->net_params = smartlist_new();
  3214. for (i = 0; i < tok->n_args; ++i) {
  3215. int ok=0;
  3216. char *eq = strchr(tok->args[i], '=');
  3217. size_t eq_pos;
  3218. if (!eq) {
  3219. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  3220. goto err;
  3221. }
  3222. eq_pos = eq-tok->args[i];
  3223. tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
  3224. if (!ok) {
  3225. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  3226. goto err;
  3227. }
  3228. if (i > 0 && strcmp(tok->args[i-1], tok->args[i]) >= 0) {
  3229. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  3230. inorder = 0;
  3231. }
  3232. if (last_kwd && eq_pos == strlen(last_kwd) &&
  3233. fast_memeq(last_kwd, tok->args[i], eq_pos)) {
  3234. log_warn(LD_DIR, "Duplicate value for %s parameter",
  3235. escaped(tok->args[i]));
  3236. any_dups = 1;
  3237. }
  3238. tor_free(last_kwd);
  3239. last_kwd = tor_strndup(tok->args[i], eq_pos);
  3240. smartlist_add_strdup(ns->net_params, tok->args[i]);
  3241. }
  3242. if (!inorder) {
  3243. log_warn(LD_DIR, "params not in order");
  3244. goto err;
  3245. }
  3246. if (any_dups) {
  3247. log_warn(LD_DIR, "Duplicate in parameters");
  3248. goto err;
  3249. }
  3250. }
  3251. ns->voters = smartlist_new();
  3252. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  3253. tok = _tok;
  3254. if (tok->tp == K_DIR_SOURCE) {
  3255. tor_assert(tok->n_args >= 6);
  3256. if (voter)
  3257. smartlist_add(ns->voters, voter);
  3258. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  3259. voter->sigs = smartlist_new();
  3260. if (ns->type != NS_TYPE_CONSENSUS)
  3261. memcpy(voter->vote_digest, ns_digests.d[DIGEST_SHA1], DIGEST_LEN);
  3262. voter->nickname = tor_strdup(tok->args[0]);
  3263. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  3264. base16_decode(voter->identity_digest, sizeof(voter->identity_digest),
  3265. tok->args[1], HEX_DIGEST_LEN)
  3266. != sizeof(voter->identity_digest)) {
  3267. log_warn(LD_DIR, "Error decoding identity digest %s in "
  3268. "network-status document.", escaped(tok->args[1]));
  3269. goto err;
  3270. }
  3271. if (ns->type != NS_TYPE_CONSENSUS &&
  3272. tor_memneq(ns->cert->cache_info.identity_digest,
  3273. voter->identity_digest, DIGEST_LEN)) {
  3274. log_warn(LD_DIR,"Mismatch between identities in certificate and vote");
  3275. goto err;
  3276. }
  3277. if (ns->type != NS_TYPE_CONSENSUS) {
  3278. if (authority_cert_is_blacklisted(ns->cert)) {
  3279. log_warn(LD_DIR, "Rejecting vote signature made with blacklisted "
  3280. "signing key %s",
  3281. hex_str(ns->cert->signing_key_digest, DIGEST_LEN));
  3282. goto err;
  3283. }
  3284. }
  3285. voter->address = tor_strdup(tok->args[2]);
  3286. if (!tor_inet_aton(tok->args[3], &in)) {
  3287. log_warn(LD_DIR, "Error decoding IP address %s in network-status.",
  3288. escaped(tok->args[3]));
  3289. goto err;
  3290. }
  3291. voter->addr = ntohl(in.s_addr);
  3292. int ok;
  3293. voter->dir_port = (uint16_t)
  3294. tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);
  3295. if (!ok)
  3296. goto err;
  3297. voter->or_port = (uint16_t)
  3298. tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);
  3299. if (!ok)
  3300. goto err;
  3301. } else if (tok->tp == K_CONTACT) {
  3302. if (!voter || voter->contact) {
  3303. log_warn(LD_DIR, "contact element is out of place.");
  3304. goto err;
  3305. }
  3306. voter->contact = tor_strdup(tok->args[0]);
  3307. } else if (tok->tp == K_VOTE_DIGEST) {
  3308. tor_assert(ns->type == NS_TYPE_CONSENSUS);
  3309. tor_assert(tok->n_args >= 1);
  3310. if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {
  3311. log_warn(LD_DIR, "vote-digest element is out of place.");
  3312. goto err;
  3313. }
  3314. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  3315. base16_decode(voter->vote_digest, sizeof(voter->vote_digest),
  3316. tok->args[0], HEX_DIGEST_LEN)
  3317. != sizeof(voter->vote_digest)) {
  3318. log_warn(LD_DIR, "Error decoding vote digest %s in "
  3319. "network-status consensus.", escaped(tok->args[0]));
  3320. goto err;
  3321. }
  3322. }
  3323. } SMARTLIST_FOREACH_END(_tok);
  3324. if (voter) {
  3325. smartlist_add(ns->voters, voter);
  3326. voter = NULL;
  3327. }
  3328. if (smartlist_len(ns->voters) == 0) {
  3329. log_warn(LD_DIR, "Missing dir-source elements in a networkstatus.");
  3330. goto err;
  3331. } else if (ns->type != NS_TYPE_CONSENSUS && smartlist_len(ns->voters) != 1) {
  3332. log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus.");
  3333. goto err;
  3334. }
  3335. if (ns->type != NS_TYPE_CONSENSUS &&
  3336. (tok = find_opt_by_keyword(tokens, K_LEGACY_DIR_KEY))) {
  3337. int bad = 1;
  3338. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  3339. networkstatus_voter_info_t *voter_0 = smartlist_get(ns->voters, 0);
  3340. if (base16_decode(voter_0->legacy_id_digest, DIGEST_LEN,
  3341. tok->args[0], HEX_DIGEST_LEN) != DIGEST_LEN)
  3342. bad = 1;
  3343. else
  3344. bad = 0;
  3345. }
  3346. if (bad) {
  3347. log_warn(LD_DIR, "Invalid legacy key digest %s on vote.",
  3348. escaped(tok->args[0]));
  3349. }
  3350. }
  3351. /* If this is a vote document, check if information about the shared
  3352. randomness protocol is included, and extract it. */
  3353. if (ns->type == NS_TYPE_VOTE) {
  3354. /* Does this authority participates in the SR protocol? */
  3355. tok = find_opt_by_keyword(tokens, K_SR_FLAG);
  3356. if (tok) {
  3357. ns->sr_info.participate = 1;
  3358. /* Get the SR commitments and reveals from the vote. */
  3359. extract_shared_random_commits(ns, tokens);
  3360. }
  3361. }
  3362. /* For both a vote and consensus, extract the shared random values. */
  3363. if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_CONSENSUS) {
  3364. extract_shared_random_srvs(ns, tokens);
  3365. }
  3366. /* Parse routerstatus lines. */
  3367. rs_tokens = smartlist_new();
  3368. rs_area = memarea_new();
  3369. s = end_of_header;
  3370. ns->routerstatus_list = smartlist_new();
  3371. while (!strcmpstart(s, "r ")) {
  3372. if (ns->type != NS_TYPE_CONSENSUS) {
  3373. vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  3374. if (routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, ns,
  3375. rs, 0, 0))
  3376. smartlist_add(ns->routerstatus_list, rs);
  3377. else {
  3378. tor_free(rs->version);
  3379. tor_free(rs);
  3380. }
  3381. } else {
  3382. routerstatus_t *rs;
  3383. if ((rs = routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens,
  3384. NULL, NULL,
  3385. ns->consensus_method,
  3386. flav))) {
  3387. /* Use exponential-backoff scheduling when downloading microdescs */
  3388. rs->dl_status.backoff = DL_SCHED_RANDOM_EXPONENTIAL;
  3389. smartlist_add(ns->routerstatus_list, rs);
  3390. }
  3391. }
  3392. }
  3393. for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {
  3394. routerstatus_t *rs1, *rs2;
  3395. if (ns->type != NS_TYPE_CONSENSUS) {
  3396. vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);
  3397. vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);
  3398. rs1 = &a->status; rs2 = &b->status;
  3399. } else {
  3400. rs1 = smartlist_get(ns->routerstatus_list, i-1);
  3401. rs2 = smartlist_get(ns->routerstatus_list, i);
  3402. }
  3403. if (fast_memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN)
  3404. >= 0) {
  3405. log_warn(LD_DIR, "Networkstatus entries not sorted by identity digest");
  3406. goto err;
  3407. }
  3408. }
  3409. if (ns_type != NS_TYPE_CONSENSUS) {
  3410. digest256map_t *ed_id_map = digest256map_new();
  3411. SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, vote_routerstatus_t *,
  3412. vrs) {
  3413. if (! vrs->has_ed25519_listing ||
  3414. tor_mem_is_zero((const char *)vrs->ed25519_id, DIGEST256_LEN))
  3415. continue;
  3416. if (digest256map_get(ed_id_map, vrs->ed25519_id) != NULL) {
  3417. log_warn(LD_DIR, "Vote networkstatus ed25519 identities were not "
  3418. "unique");
  3419. digest256map_free(ed_id_map, NULL);
  3420. goto err;
  3421. }
  3422. digest256map_set(ed_id_map, vrs->ed25519_id, (void*)1);
  3423. } SMARTLIST_FOREACH_END(vrs);
  3424. digest256map_free(ed_id_map, NULL);
  3425. }
  3426. /* Parse footer; check signature. */
  3427. footer_tokens = smartlist_new();
  3428. if ((end_of_footer = strstr(s, "\nnetwork-status-version ")))
  3429. ++end_of_footer;
  3430. else
  3431. end_of_footer = s + strlen(s);
  3432. if (tokenize_string(area,s, end_of_footer, footer_tokens,
  3433. networkstatus_vote_footer_token_table, 0)) {
  3434. log_warn(LD_DIR, "Error tokenizing network-status vote footer.");
  3435. goto err;
  3436. }
  3437. {
  3438. int found_sig = 0;
  3439. SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
  3440. tok = _tok;
  3441. if (tok->tp == K_DIRECTORY_SIGNATURE)
  3442. found_sig = 1;
  3443. else if (found_sig) {
  3444. log_warn(LD_DIR, "Extraneous token after first directory-signature");
  3445. goto err;
  3446. }
  3447. } SMARTLIST_FOREACH_END(_tok);
  3448. }
  3449. if ((tok = find_opt_by_keyword(footer_tokens, K_DIRECTORY_FOOTER))) {
  3450. if (tok != smartlist_get(footer_tokens, 0)) {
  3451. log_warn(LD_DIR, "Misplaced directory-footer token");
  3452. goto err;
  3453. }
  3454. }
  3455. tok = find_opt_by_keyword(footer_tokens, K_BW_WEIGHTS);
  3456. if (tok) {
  3457. ns->weight_params = smartlist_new();
  3458. for (i = 0; i < tok->n_args; ++i) {
  3459. int ok=0;
  3460. char *eq = strchr(tok->args[i], '=');
  3461. if (!eq) {
  3462. log_warn(LD_DIR, "Bad element '%s' in weight params",
  3463. escaped(tok->args[i]));
  3464. goto err;
  3465. }
  3466. tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
  3467. if (!ok) {
  3468. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  3469. goto err;
  3470. }
  3471. smartlist_add_strdup(ns->weight_params, tok->args[i]);
  3472. }
  3473. }
  3474. SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
  3475. char declared_identity[DIGEST_LEN];
  3476. networkstatus_voter_info_t *v;
  3477. document_signature_t *sig;
  3478. const char *id_hexdigest = NULL;
  3479. const char *sk_hexdigest = NULL;
  3480. digest_algorithm_t alg = DIGEST_SHA1;
  3481. tok = _tok;
  3482. if (tok->tp != K_DIRECTORY_SIGNATURE)
  3483. continue;
  3484. tor_assert(tok->n_args >= 2);
  3485. if (tok->n_args == 2) {
  3486. id_hexdigest = tok->args[0];
  3487. sk_hexdigest = tok->args[1];
  3488. } else {
  3489. const char *algname = tok->args[0];
  3490. int a;
  3491. id_hexdigest = tok->args[1];
  3492. sk_hexdigest = tok->args[2];
  3493. a = crypto_digest_algorithm_parse_name(algname);
  3494. if (a<0) {
  3495. log_warn(LD_DIR, "Unknown digest algorithm %s; skipping",
  3496. escaped(algname));
  3497. continue;
  3498. }
  3499. alg = a;
  3500. }
  3501. if (!tok->object_type ||
  3502. strcmp(tok->object_type, "SIGNATURE") ||
  3503. tok->object_size < 128 || tok->object_size > 512) {
  3504. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  3505. goto err;
  3506. }
  3507. if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
  3508. base16_decode(declared_identity, sizeof(declared_identity),
  3509. id_hexdigest, HEX_DIGEST_LEN)
  3510. != sizeof(declared_identity)) {
  3511. log_warn(LD_DIR, "Error decoding declared identity %s in "
  3512. "network-status document.", escaped(id_hexdigest));
  3513. goto err;
  3514. }
  3515. if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {
  3516. log_warn(LD_DIR, "ID on signature on network-status document does "
  3517. "not match any declared directory source.");
  3518. goto err;
  3519. }
  3520. sig = tor_malloc_zero(sizeof(document_signature_t));
  3521. memcpy(sig->identity_digest, v->identity_digest, DIGEST_LEN);
  3522. sig->alg = alg;
  3523. if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
  3524. base16_decode(sig->signing_key_digest, sizeof(sig->signing_key_digest),
  3525. sk_hexdigest, HEX_DIGEST_LEN)
  3526. != sizeof(sig->signing_key_digest)) {
  3527. log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
  3528. "network-status document.", escaped(sk_hexdigest));
  3529. tor_free(sig);
  3530. goto err;
  3531. }
  3532. if (ns->type != NS_TYPE_CONSENSUS) {
  3533. if (tor_memneq(declared_identity, ns->cert->cache_info.identity_digest,
  3534. DIGEST_LEN)) {
  3535. log_warn(LD_DIR, "Digest mismatch between declared and actual on "
  3536. "network-status vote.");
  3537. tor_free(sig);
  3538. goto err;
  3539. }
  3540. }
  3541. if (voter_get_sig_by_algorithm(v, sig->alg)) {
  3542. /* We already parsed a vote with this algorithm from this voter. Use the
  3543. first one. */
  3544. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "We received a networkstatus "
  3545. "that contains two signatures from the same voter with the same "
  3546. "algorithm. Ignoring the second signature.");
  3547. tor_free(sig);
  3548. continue;
  3549. }
  3550. if (ns->type != NS_TYPE_CONSENSUS) {
  3551. if (check_signature_token(ns_digests.d[DIGEST_SHA1], DIGEST_LEN,
  3552. tok, ns->cert->signing_key, 0,
  3553. "network-status document")) {
  3554. tor_free(sig);
  3555. goto err;
  3556. }
  3557. sig->good_signature = 1;
  3558. } else {
  3559. if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
  3560. tor_free(sig);
  3561. goto err;
  3562. }
  3563. sig->signature = tor_memdup(tok->object_body, tok->object_size);
  3564. sig->signature_len = (int) tok->object_size;
  3565. }
  3566. smartlist_add(v->sigs, sig);
  3567. ++n_signatures;
  3568. } SMARTLIST_FOREACH_END(_tok);
  3569. if (! n_signatures) {
  3570. log_warn(LD_DIR, "No signatures on networkstatus document.");
  3571. goto err;
  3572. } else if (ns->type == NS_TYPE_VOTE && n_signatures != 1) {
  3573. log_warn(LD_DIR, "Received more than one signature on a "
  3574. "network-status vote.");
  3575. goto err;
  3576. }
  3577. if (eos_out)
  3578. *eos_out = end_of_footer;
  3579. goto done;
  3580. err:
  3581. dump_desc(s_dup, "v3 networkstatus");
  3582. networkstatus_vote_free(ns);
  3583. ns = NULL;
  3584. done:
  3585. if (tokens) {
  3586. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  3587. smartlist_free(tokens);
  3588. }
  3589. if (voter) {
  3590. if (voter->sigs) {
  3591. SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
  3592. document_signature_free(sig));
  3593. smartlist_free(voter->sigs);
  3594. }
  3595. tor_free(voter->nickname);
  3596. tor_free(voter->address);
  3597. tor_free(voter->contact);
  3598. tor_free(voter);
  3599. }
  3600. if (rs_tokens) {
  3601. SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_clear(t));
  3602. smartlist_free(rs_tokens);
  3603. }
  3604. if (footer_tokens) {
  3605. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_clear(t));
  3606. smartlist_free(footer_tokens);
  3607. }
  3608. if (area) {
  3609. DUMP_AREA(area, "v3 networkstatus");
  3610. memarea_drop_all(area);
  3611. }
  3612. if (rs_area)
  3613. memarea_drop_all(rs_area);
  3614. tor_free(last_kwd);
  3615. return ns;
  3616. }
  3617. /** Return the common_digests_t that holds the digests of the
  3618. * <b>flavor_name</b>-flavored networkstatus according to the detached
  3619. * signatures document <b>sigs</b>, allocating a new common_digests_t as
  3620. * neeeded. */
  3621. static common_digests_t *
  3622. detached_get_digests(ns_detached_signatures_t *sigs, const char *flavor_name)
  3623. {
  3624. common_digests_t *d = strmap_get(sigs->digests, flavor_name);
  3625. if (!d) {
  3626. d = tor_malloc_zero(sizeof(common_digests_t));
  3627. strmap_set(sigs->digests, flavor_name, d);
  3628. }
  3629. return d;
  3630. }
  3631. /** Return the list of signatures of the <b>flavor_name</b>-flavored
  3632. * networkstatus according to the detached signatures document <b>sigs</b>,
  3633. * allocating a new common_digests_t as neeeded. */
  3634. static smartlist_t *
  3635. detached_get_signatures(ns_detached_signatures_t *sigs,
  3636. const char *flavor_name)
  3637. {
  3638. smartlist_t *sl = strmap_get(sigs->signatures, flavor_name);
  3639. if (!sl) {
  3640. sl = smartlist_new();
  3641. strmap_set(sigs->signatures, flavor_name, sl);
  3642. }
  3643. return sl;
  3644. }
  3645. /** Parse a detached v3 networkstatus signature document between <b>s</b> and
  3646. * <b>eos</b> and return the result. Return -1 on failure. */
  3647. ns_detached_signatures_t *
  3648. networkstatus_parse_detached_signatures(const char *s, const char *eos)
  3649. {
  3650. /* XXXX there is too much duplicate shared between this function and
  3651. * networkstatus_parse_vote_from_string(). */
  3652. directory_token_t *tok;
  3653. memarea_t *area = NULL;
  3654. common_digests_t *digests;
  3655. smartlist_t *tokens = smartlist_new();
  3656. ns_detached_signatures_t *sigs =
  3657. tor_malloc_zero(sizeof(ns_detached_signatures_t));
  3658. sigs->digests = strmap_new();
  3659. sigs->signatures = strmap_new();
  3660. if (!eos)
  3661. eos = s + strlen(s);
  3662. area = memarea_new();
  3663. if (tokenize_string(area,s, eos, tokens,
  3664. networkstatus_detached_signature_token_table, 0)) {
  3665. log_warn(LD_DIR, "Error tokenizing detached networkstatus signatures");
  3666. goto err;
  3667. }
  3668. /* Grab all the digest-like tokens. */
  3669. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  3670. const char *algname;
  3671. digest_algorithm_t alg;
  3672. const char *flavor;
  3673. const char *hexdigest;
  3674. size_t expected_length, digest_length;
  3675. tok = _tok;
  3676. if (tok->tp == K_CONSENSUS_DIGEST) {
  3677. algname = "sha1";
  3678. alg = DIGEST_SHA1;
  3679. flavor = "ns";
  3680. hexdigest = tok->args[0];
  3681. } else if (tok->tp == K_ADDITIONAL_DIGEST) {
  3682. int a = crypto_digest_algorithm_parse_name(tok->args[1]);
  3683. if (a<0) {
  3684. log_warn(LD_DIR, "Unrecognized algorithm name %s", tok->args[0]);
  3685. continue;
  3686. }
  3687. alg = (digest_algorithm_t) a;
  3688. flavor = tok->args[0];
  3689. algname = tok->args[1];
  3690. hexdigest = tok->args[2];
  3691. } else {
  3692. continue;
  3693. }
  3694. digest_length = crypto_digest_algorithm_get_length(alg);
  3695. expected_length = digest_length * 2; /* hex encoding */
  3696. if (strlen(hexdigest) != expected_length) {
  3697. log_warn(LD_DIR, "Wrong length on consensus-digest in detached "
  3698. "networkstatus signatures");
  3699. goto err;
  3700. }
  3701. digests = detached_get_digests(sigs, flavor);
  3702. tor_assert(digests);
  3703. if (!tor_mem_is_zero(digests->d[alg], digest_length)) {
  3704. log_warn(LD_DIR, "Multiple digests for %s with %s on detached "
  3705. "signatures document", flavor, algname);
  3706. continue;
  3707. }
  3708. if (base16_decode(digests->d[alg], digest_length,
  3709. hexdigest, strlen(hexdigest)) != (int) digest_length) {
  3710. log_warn(LD_DIR, "Bad encoding on consensus-digest in detached "
  3711. "networkstatus signatures");
  3712. goto err;
  3713. }
  3714. } SMARTLIST_FOREACH_END(_tok);
  3715. tok = find_by_keyword(tokens, K_VALID_AFTER);
  3716. if (parse_iso_time(tok->args[0], &sigs->valid_after)) {
  3717. log_warn(LD_DIR, "Bad valid-after in detached networkstatus signatures");
  3718. goto err;
  3719. }
  3720. tok = find_by_keyword(tokens, K_FRESH_UNTIL);
  3721. if (parse_iso_time(tok->args[0], &sigs->fresh_until)) {
  3722. log_warn(LD_DIR, "Bad fresh-until in detached networkstatus signatures");
  3723. goto err;
  3724. }
  3725. tok = find_by_keyword(tokens, K_VALID_UNTIL);
  3726. if (parse_iso_time(tok->args[0], &sigs->valid_until)) {
  3727. log_warn(LD_DIR, "Bad valid-until in detached networkstatus signatures");
  3728. goto err;
  3729. }
  3730. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  3731. const char *id_hexdigest;
  3732. const char *sk_hexdigest;
  3733. const char *algname;
  3734. const char *flavor;
  3735. digest_algorithm_t alg;
  3736. char id_digest[DIGEST_LEN];
  3737. char sk_digest[DIGEST_LEN];
  3738. smartlist_t *siglist;
  3739. document_signature_t *sig;
  3740. int is_duplicate;
  3741. tok = _tok;
  3742. if (tok->tp == K_DIRECTORY_SIGNATURE) {
  3743. tor_assert(tok->n_args >= 2);
  3744. flavor = "ns";
  3745. algname = "sha1";
  3746. id_hexdigest = tok->args[0];
  3747. sk_hexdigest = tok->args[1];
  3748. } else if (tok->tp == K_ADDITIONAL_SIGNATURE) {
  3749. tor_assert(tok->n_args >= 4);
  3750. flavor = tok->args[0];
  3751. algname = tok->args[1];
  3752. id_hexdigest = tok->args[2];
  3753. sk_hexdigest = tok->args[3];
  3754. } else {
  3755. continue;
  3756. }
  3757. {
  3758. int a = crypto_digest_algorithm_parse_name(algname);
  3759. if (a<0) {
  3760. log_warn(LD_DIR, "Unrecognized algorithm name %s", algname);
  3761. continue;
  3762. }
  3763. alg = (digest_algorithm_t) a;
  3764. }
  3765. if (!tok->object_type ||
  3766. strcmp(tok->object_type, "SIGNATURE") ||
  3767. tok->object_size < 128 || tok->object_size > 512) {
  3768. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  3769. goto err;
  3770. }
  3771. if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
  3772. base16_decode(id_digest, sizeof(id_digest),
  3773. id_hexdigest, HEX_DIGEST_LEN) != sizeof(id_digest)) {
  3774. log_warn(LD_DIR, "Error decoding declared identity %s in "
  3775. "network-status vote.", escaped(id_hexdigest));
  3776. goto err;
  3777. }
  3778. if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
  3779. base16_decode(sk_digest, sizeof(sk_digest),
  3780. sk_hexdigest, HEX_DIGEST_LEN) != sizeof(sk_digest)) {
  3781. log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
  3782. "network-status vote.", escaped(sk_hexdigest));
  3783. goto err;
  3784. }
  3785. siglist = detached_get_signatures(sigs, flavor);
  3786. is_duplicate = 0;
  3787. SMARTLIST_FOREACH(siglist, document_signature_t *, dsig, {
  3788. if (dsig->alg == alg &&
  3789. tor_memeq(id_digest, dsig->identity_digest, DIGEST_LEN) &&
  3790. tor_memeq(sk_digest, dsig->signing_key_digest, DIGEST_LEN)) {
  3791. is_duplicate = 1;
  3792. }
  3793. });
  3794. if (is_duplicate) {
  3795. log_warn(LD_DIR, "Two signatures with identical keys and algorithm "
  3796. "found.");
  3797. continue;
  3798. }
  3799. sig = tor_malloc_zero(sizeof(document_signature_t));
  3800. sig->alg = alg;
  3801. memcpy(sig->identity_digest, id_digest, DIGEST_LEN);
  3802. memcpy(sig->signing_key_digest, sk_digest, DIGEST_LEN);
  3803. if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
  3804. tor_free(sig);
  3805. goto err;
  3806. }
  3807. sig->signature = tor_memdup(tok->object_body, tok->object_size);
  3808. sig->signature_len = (int) tok->object_size;
  3809. smartlist_add(siglist, sig);
  3810. } SMARTLIST_FOREACH_END(_tok);
  3811. goto done;
  3812. err:
  3813. ns_detached_signatures_free(sigs);
  3814. sigs = NULL;
  3815. done:
  3816. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  3817. smartlist_free(tokens);
  3818. if (area) {
  3819. DUMP_AREA(area, "detached signatures");
  3820. memarea_drop_all(area);
  3821. }
  3822. return sigs;
  3823. }
  3824. /** Parse the addr policy in the string <b>s</b> and return it. If
  3825. * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
  3826. * ADDR_POLICY_REJECT) for items that specify no action.
  3827. *
  3828. * Returns NULL on policy errors.
  3829. *
  3830. * Set *<b>malformed_list</b> to true if the entire policy list should be
  3831. * discarded. Otherwise, set it to false, and only this item should be ignored
  3832. * on error - the rest of the policy list can continue to be processed and
  3833. * used.
  3834. *
  3835. * The addr_policy_t returned by this function can have its address set to
  3836. * AF_UNSPEC for '*'. Use policy_expand_unspec() to turn this into a pair
  3837. * of AF_INET and AF_INET6 items.
  3838. */
  3839. MOCK_IMPL(addr_policy_t *,
  3840. router_parse_addr_policy_item_from_string,(const char *s, int assume_action,
  3841. int *malformed_list))
  3842. {
  3843. directory_token_t *tok = NULL;
  3844. const char *cp, *eos;
  3845. /* Longest possible policy is
  3846. * "accept6 [ffff:ffff:..255]/128:10000-65535",
  3847. * which contains a max-length IPv6 address, plus 26 characters.
  3848. * But note that there can be an arbitrary amount of space between the
  3849. * accept and the address:mask/port element.
  3850. * We don't need to multiply TOR_ADDR_BUF_LEN by 2, as there is only one
  3851. * IPv6 address. But making the buffer shorter might cause valid long lines,
  3852. * which parsed in previous versions, to fail to parse in new versions.
  3853. * (These lines would have to have excessive amounts of whitespace.) */
  3854. char line[TOR_ADDR_BUF_LEN*2 + 32];
  3855. addr_policy_t *r;
  3856. memarea_t *area = NULL;
  3857. tor_assert(malformed_list);
  3858. *malformed_list = 0;
  3859. s = eat_whitespace(s);
  3860. /* We can only do assume_action on []-quoted IPv6, as "a" (accept)
  3861. * and ":" (port separator) are ambiguous */
  3862. if ((*s == '*' || *s == '[' || TOR_ISDIGIT(*s)) && assume_action >= 0) {
  3863. if (tor_snprintf(line, sizeof(line), "%s %s",
  3864. assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", s)<0) {
  3865. log_warn(LD_DIR, "Policy %s is too long.", escaped(s));
  3866. return NULL;
  3867. }
  3868. cp = line;
  3869. tor_strlower(line);
  3870. } else { /* assume an already well-formed address policy line */
  3871. cp = s;
  3872. }
  3873. eos = cp + strlen(cp);
  3874. area = memarea_new();
  3875. tok = get_next_token(area, &cp, eos, routerdesc_token_table);
  3876. if (tok->tp == ERR_) {
  3877. log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
  3878. goto err;
  3879. }
  3880. if (tok->tp != K_ACCEPT && tok->tp != K_ACCEPT6 &&
  3881. tok->tp != K_REJECT && tok->tp != K_REJECT6) {
  3882. log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
  3883. goto err;
  3884. }
  3885. /* Use the extended interpretation of accept/reject *,
  3886. * expanding it into an IPv4 wildcard and an IPv6 wildcard.
  3887. * Also permit *4 and *6 for IPv4 and IPv6 only wildcards. */
  3888. r = router_parse_addr_policy(tok, TAPMP_EXTENDED_STAR);
  3889. if (!r) {
  3890. goto err;
  3891. }
  3892. /* Ensure that accept6/reject6 fields are followed by IPv6 addresses.
  3893. * AF_UNSPEC addresses are only permitted on the accept/reject field type.
  3894. * Unlike descriptors, torrcs exit policy accept/reject can be followed by
  3895. * either an IPv4 or IPv6 address. */
  3896. if ((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  3897. tor_addr_family(&r->addr) != AF_INET6) {
  3898. /* This is a non-fatal error, just ignore this one entry. */
  3899. *malformed_list = 0;
  3900. log_warn(LD_DIR, "IPv4 address '%s' with accept6/reject6 field type in "
  3901. "exit policy. Ignoring, but continuing to parse rules. (Use "
  3902. "accept/reject with IPv4 addresses.)",
  3903. tok->n_args == 1 ? tok->args[0] : "");
  3904. addr_policy_free(r);
  3905. r = NULL;
  3906. goto done;
  3907. }
  3908. goto done;
  3909. err:
  3910. *malformed_list = 1;
  3911. r = NULL;
  3912. done:
  3913. token_clear(tok);
  3914. if (area) {
  3915. DUMP_AREA(area, "policy item");
  3916. memarea_drop_all(area);
  3917. }
  3918. return r;
  3919. }
  3920. /** Add an exit policy stored in the token <b>tok</b> to the router info in
  3921. * <b>router</b>. Return 0 on success, -1 on failure. */
  3922. static int
  3923. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
  3924. {
  3925. addr_policy_t *newe;
  3926. /* Use the standard interpretation of accept/reject *, an IPv4 wildcard. */
  3927. newe = router_parse_addr_policy(tok, 0);
  3928. if (!newe)
  3929. return -1;
  3930. if (! router->exit_policy)
  3931. router->exit_policy = smartlist_new();
  3932. /* Ensure that in descriptors, accept/reject fields are followed by
  3933. * IPv4 addresses, and accept6/reject6 fields are followed by
  3934. * IPv6 addresses. Unlike torrcs, descriptor exit policies do not permit
  3935. * accept/reject followed by IPv6. */
  3936. if (((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  3937. tor_addr_family(&newe->addr) == AF_INET)
  3938. ||
  3939. ((tok->tp == K_ACCEPT || tok->tp == K_REJECT) &&
  3940. tor_addr_family(&newe->addr) == AF_INET6)) {
  3941. /* There's nothing the user can do about other relays' descriptors,
  3942. * so we don't provide usage advice here. */
  3943. log_warn(LD_DIR, "Mismatch between field type and address type in exit "
  3944. "policy '%s'. Discarding entire router descriptor.",
  3945. tok->n_args == 1 ? tok->args[0] : "");
  3946. addr_policy_free(newe);
  3947. return -1;
  3948. }
  3949. smartlist_add(router->exit_policy, newe);
  3950. return 0;
  3951. }
  3952. /** Given a K_ACCEPT[6] or K_REJECT[6] token and a router, create and return
  3953. * a new exit_policy_t corresponding to the token. If TAPMP_EXTENDED_STAR
  3954. * is set in fmt_flags, K_ACCEPT6 and K_REJECT6 tokens followed by *
  3955. * expand to IPv6-only policies, otherwise they expand to IPv4 and IPv6
  3956. * policies */
  3957. static addr_policy_t *
  3958. router_parse_addr_policy(directory_token_t *tok, unsigned fmt_flags)
  3959. {
  3960. addr_policy_t newe;
  3961. char *arg;
  3962. tor_assert(tok->tp == K_REJECT || tok->tp == K_REJECT6 ||
  3963. tok->tp == K_ACCEPT || tok->tp == K_ACCEPT6);
  3964. if (tok->n_args != 1)
  3965. return NULL;
  3966. arg = tok->args[0];
  3967. if (!strcmpstart(arg,"private"))
  3968. return router_parse_addr_policy_private(tok);
  3969. memset(&newe, 0, sizeof(newe));
  3970. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  3971. newe.policy_type = ADDR_POLICY_REJECT;
  3972. else
  3973. newe.policy_type = ADDR_POLICY_ACCEPT;
  3974. /* accept6/reject6 * produces an IPv6 wildcard address only.
  3975. * (accept/reject * produces rules for IPv4 and IPv6 wildcard addresses.) */
  3976. if ((fmt_flags & TAPMP_EXTENDED_STAR)
  3977. && (tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6)) {
  3978. fmt_flags |= TAPMP_STAR_IPV6_ONLY;
  3979. }
  3980. if (tor_addr_parse_mask_ports(arg, fmt_flags, &newe.addr, &newe.maskbits,
  3981. &newe.prt_min, &newe.prt_max) < 0) {
  3982. log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
  3983. return NULL;
  3984. }
  3985. return addr_policy_get_canonical_entry(&newe);
  3986. }
  3987. /** Parse an exit policy line of the format "accept[6]/reject[6] private:...".
  3988. * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
  3989. * router descriptors until earlier versions are obsolete.
  3990. *
  3991. * accept/reject and accept6/reject6 private all produce rules for both
  3992. * IPv4 and IPv6 addresses.
  3993. */
  3994. static addr_policy_t *
  3995. router_parse_addr_policy_private(directory_token_t *tok)
  3996. {
  3997. const char *arg;
  3998. uint16_t port_min, port_max;
  3999. addr_policy_t result;
  4000. arg = tok->args[0];
  4001. if (strcmpstart(arg, "private"))
  4002. return NULL;
  4003. arg += strlen("private");
  4004. arg = (char*) eat_whitespace(arg);
  4005. if (!arg || *arg != ':')
  4006. return NULL;
  4007. if (parse_port_range(arg+1, &port_min, &port_max)<0)
  4008. return NULL;
  4009. memset(&result, 0, sizeof(result));
  4010. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  4011. result.policy_type = ADDR_POLICY_REJECT;
  4012. else
  4013. result.policy_type = ADDR_POLICY_ACCEPT;
  4014. result.is_private = 1;
  4015. result.prt_min = port_min;
  4016. result.prt_max = port_max;
  4017. if (tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) {
  4018. log_warn(LD_GENERAL,
  4019. "'%s' expands into rules which apply to all private IPv4 and "
  4020. "IPv6 addresses. (Use accept/reject private:* for IPv4 and "
  4021. "IPv6.)", tok->n_args == 1 ? tok->args[0] : "");
  4022. }
  4023. return addr_policy_get_canonical_entry(&result);
  4024. }
  4025. /** Log and exit if <b>t</b> is malformed */
  4026. void
  4027. assert_addr_policy_ok(smartlist_t *lst)
  4028. {
  4029. if (!lst) return;
  4030. SMARTLIST_FOREACH(lst, addr_policy_t *, t, {
  4031. tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
  4032. t->policy_type == ADDR_POLICY_ACCEPT);
  4033. tor_assert(t->prt_min <= t->prt_max);
  4034. });
  4035. }
  4036. /** Return a newly allocated smartlist of all accept or reject tokens in
  4037. * <b>s</b>.
  4038. */
  4039. static smartlist_t *
  4040. find_all_exitpolicy(smartlist_t *s)
  4041. {
  4042. smartlist_t *out = smartlist_new();
  4043. SMARTLIST_FOREACH(s, directory_token_t *, t,
  4044. if (t->tp == K_ACCEPT || t->tp == K_ACCEPT6 ||
  4045. t->tp == K_REJECT || t->tp == K_REJECT6)
  4046. smartlist_add(out,t));
  4047. return out;
  4048. }
  4049. /** Helper function for <b>router_get_hash_impl</b>: given <b>s</b>,
  4050. * <b>s_len</b>, <b>start_str</b>, <b>end_str</b>, and <b>end_c</b> with the
  4051. * same semantics as in that function, set *<b>start_out</b> (inclusive) and
  4052. * *<b>end_out</b> (exclusive) to the boundaries of the string to be hashed.
  4053. *
  4054. * Return 0 on success and -1 on failure.
  4055. */
  4056. static int
  4057. router_get_hash_impl_helper(const char *s, size_t s_len,
  4058. const char *start_str,
  4059. const char *end_str, char end_c,
  4060. const char **start_out, const char **end_out)
  4061. {
  4062. const char *start, *end;
  4063. start = tor_memstr(s, s_len, start_str);
  4064. if (!start) {
  4065. log_warn(LD_DIR,"couldn't find start of hashed material \"%s\"",start_str);
  4066. return -1;
  4067. }
  4068. if (start != s && *(start-1) != '\n') {
  4069. log_warn(LD_DIR,
  4070. "first occurrence of \"%s\" is not at the start of a line",
  4071. start_str);
  4072. return -1;
  4073. }
  4074. end = tor_memstr(start+strlen(start_str),
  4075. s_len - (start-s) - strlen(start_str), end_str);
  4076. if (!end) {
  4077. log_warn(LD_DIR,"couldn't find end of hashed material \"%s\"",end_str);
  4078. return -1;
  4079. }
  4080. end = memchr(end+strlen(end_str), end_c, s_len - (end-s) - strlen(end_str));
  4081. if (!end) {
  4082. log_warn(LD_DIR,"couldn't find EOL");
  4083. return -1;
  4084. }
  4085. ++end;
  4086. *start_out = start;
  4087. *end_out = end;
  4088. return 0;
  4089. }
  4090. /** Compute the digest of the substring of <b>s</b> taken from the first
  4091. * occurrence of <b>start_str</b> through the first instance of c after the
  4092. * first subsequent occurrence of <b>end_str</b>; store the 20-byte or 32-byte
  4093. * result in <b>digest</b>; return 0 on success.
  4094. *
  4095. * If no such substring exists, return -1.
  4096. */
  4097. static int
  4098. router_get_hash_impl(const char *s, size_t s_len, char *digest,
  4099. const char *start_str,
  4100. const char *end_str, char end_c,
  4101. digest_algorithm_t alg)
  4102. {
  4103. const char *start=NULL, *end=NULL;
  4104. if (router_get_hash_impl_helper(s,s_len,start_str,end_str,end_c,
  4105. &start,&end)<0)
  4106. return -1;
  4107. if (alg == DIGEST_SHA1) {
  4108. if (crypto_digest(digest, start, end-start) < 0) {
  4109. log_warn(LD_BUG,"couldn't compute digest");
  4110. return -1;
  4111. }
  4112. } else {
  4113. if (crypto_digest256(digest, start, end-start, alg) < 0) {
  4114. log_warn(LD_BUG,"couldn't compute digest");
  4115. return -1;
  4116. }
  4117. }
  4118. return 0;
  4119. }
  4120. /** As router_get_hash_impl, but compute all hashes. */
  4121. static int
  4122. router_get_hashes_impl(const char *s, size_t s_len, common_digests_t *digests,
  4123. const char *start_str,
  4124. const char *end_str, char end_c)
  4125. {
  4126. const char *start=NULL, *end=NULL;
  4127. if (router_get_hash_impl_helper(s,s_len,start_str,end_str,end_c,
  4128. &start,&end)<0)
  4129. return -1;
  4130. if (crypto_common_digests(digests, start, end-start)) {
  4131. log_warn(LD_BUG,"couldn't compute digests");
  4132. return -1;
  4133. }
  4134. return 0;
  4135. }
  4136. /** Assuming that s starts with a microdesc, return the start of the
  4137. * *NEXT* one. Return NULL on "not found." */
  4138. static const char *
  4139. find_start_of_next_microdesc(const char *s, const char *eos)
  4140. {
  4141. int started_with_annotations;
  4142. s = eat_whitespace_eos(s, eos);
  4143. if (!s)
  4144. return NULL;
  4145. #define CHECK_LENGTH() STMT_BEGIN \
  4146. if (s+32 > eos) \
  4147. return NULL; \
  4148. STMT_END
  4149. #define NEXT_LINE() STMT_BEGIN \
  4150. s = memchr(s, '\n', eos-s); \
  4151. if (!s || s+1 >= eos) \
  4152. return NULL; \
  4153. s++; \
  4154. STMT_END
  4155. CHECK_LENGTH();
  4156. started_with_annotations = (*s == '@');
  4157. if (started_with_annotations) {
  4158. /* Start by advancing to the first non-annotation line. */
  4159. while (*s == '@')
  4160. NEXT_LINE();
  4161. }
  4162. CHECK_LENGTH();
  4163. /* Now we should be pointed at an onion-key line. If we are, then skip
  4164. * it. */
  4165. if (!strcmpstart(s, "onion-key"))
  4166. NEXT_LINE();
  4167. /* Okay, now we're pointed at the first line of the microdescriptor which is
  4168. not an annotation or onion-key. The next line that _is_ an annotation or
  4169. onion-key is the start of the next microdescriptor. */
  4170. while (s+32 < eos) {
  4171. if (*s == '@' || !strcmpstart(s, "onion-key"))
  4172. return s;
  4173. NEXT_LINE();
  4174. }
  4175. return NULL;
  4176. #undef CHECK_LENGTH
  4177. #undef NEXT_LINE
  4178. }
  4179. /** Parse as many microdescriptors as are found from the string starting at
  4180. * <b>s</b> and ending at <b>eos</b>. If allow_annotations is set, read any
  4181. * annotations we recognize and ignore ones we don't.
  4182. *
  4183. * If <b>saved_location</b> isn't SAVED_IN_CACHE, make a local copy of each
  4184. * descriptor in the body field of each microdesc_t.
  4185. *
  4186. * Return all newly parsed microdescriptors in a newly allocated
  4187. * smartlist_t. If <b>invalid_disgests_out</b> is provided, add a SHA256
  4188. * microdesc digest to it for every microdesc that we found to be badly
  4189. * formed. (This may cause duplicates) */
  4190. smartlist_t *
  4191. microdescs_parse_from_string(const char *s, const char *eos,
  4192. int allow_annotations,
  4193. saved_location_t where,
  4194. smartlist_t *invalid_digests_out)
  4195. {
  4196. smartlist_t *tokens;
  4197. smartlist_t *result;
  4198. microdesc_t *md = NULL;
  4199. memarea_t *area;
  4200. const char *start = s;
  4201. const char *start_of_next_microdesc;
  4202. int flags = allow_annotations ? TS_ANNOTATIONS_OK : 0;
  4203. const int copy_body = (where != SAVED_IN_CACHE);
  4204. directory_token_t *tok;
  4205. if (!eos)
  4206. eos = s + strlen(s);
  4207. s = eat_whitespace_eos(s, eos);
  4208. area = memarea_new();
  4209. result = smartlist_new();
  4210. tokens = smartlist_new();
  4211. while (s < eos) {
  4212. int okay = 0;
  4213. start_of_next_microdesc = find_start_of_next_microdesc(s, eos);
  4214. if (!start_of_next_microdesc)
  4215. start_of_next_microdesc = eos;
  4216. md = tor_malloc_zero(sizeof(microdesc_t));
  4217. {
  4218. const char *cp = tor_memstr(s, start_of_next_microdesc-s,
  4219. "onion-key");
  4220. const int no_onion_key = (cp == NULL);
  4221. if (no_onion_key) {
  4222. cp = s; /* So that we have *some* junk to put in the body */
  4223. }
  4224. md->bodylen = start_of_next_microdesc - cp;
  4225. md->saved_location = where;
  4226. if (copy_body)
  4227. md->body = tor_memdup_nulterm(cp, md->bodylen);
  4228. else
  4229. md->body = (char*)cp;
  4230. md->off = cp - start;
  4231. crypto_digest256(md->digest, md->body, md->bodylen, DIGEST_SHA256);
  4232. if (no_onion_key) {
  4233. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Malformed or truncated descriptor");
  4234. goto next;
  4235. }
  4236. }
  4237. if (tokenize_string(area, s, start_of_next_microdesc, tokens,
  4238. microdesc_token_table, flags)) {
  4239. log_warn(LD_DIR, "Unparseable microdescriptor");
  4240. goto next;
  4241. }
  4242. if ((tok = find_opt_by_keyword(tokens, A_LAST_LISTED))) {
  4243. if (parse_iso_time(tok->args[0], &md->last_listed)) {
  4244. log_warn(LD_DIR, "Bad last-listed time in microdescriptor");
  4245. goto next;
  4246. }
  4247. }
  4248. tok = find_by_keyword(tokens, K_ONION_KEY);
  4249. if (!crypto_pk_public_exponent_ok(tok->key)) {
  4250. log_warn(LD_DIR,
  4251. "Relay's onion key had invalid exponent.");
  4252. goto next;
  4253. }
  4254. md->onion_pkey = tok->key;
  4255. tok->key = NULL;
  4256. if ((tok = find_opt_by_keyword(tokens, K_ONION_KEY_NTOR))) {
  4257. curve25519_public_key_t k;
  4258. tor_assert(tok->n_args >= 1);
  4259. if (curve25519_public_from_base64(&k, tok->args[0]) < 0) {
  4260. log_warn(LD_DIR, "Bogus ntor-onion-key in microdesc");
  4261. goto next;
  4262. }
  4263. md->onion_curve25519_pkey =
  4264. tor_memdup(&k, sizeof(curve25519_public_key_t));
  4265. }
  4266. smartlist_t *id_lines = find_all_by_keyword(tokens, K_ID);
  4267. if (id_lines) {
  4268. SMARTLIST_FOREACH_BEGIN(id_lines, directory_token_t *, t) {
  4269. tor_assert(t->n_args >= 2);
  4270. if (!strcmp(t->args[0], "ed25519")) {
  4271. if (md->ed25519_identity_pkey) {
  4272. log_warn(LD_DIR, "Extra ed25519 key in microdesc");
  4273. goto next;
  4274. }
  4275. ed25519_public_key_t k;
  4276. if (ed25519_public_from_base64(&k, t->args[1])<0) {
  4277. log_warn(LD_DIR, "Bogus ed25519 key in microdesc");
  4278. goto next;
  4279. }
  4280. md->ed25519_identity_pkey = tor_memdup(&k, sizeof(k));
  4281. }
  4282. } SMARTLIST_FOREACH_END(t);
  4283. smartlist_free(id_lines);
  4284. }
  4285. {
  4286. smartlist_t *a_lines = find_all_by_keyword(tokens, K_A);
  4287. if (a_lines) {
  4288. find_single_ipv6_orport(a_lines, &md->ipv6_addr, &md->ipv6_orport);
  4289. smartlist_free(a_lines);
  4290. }
  4291. }
  4292. if ((tok = find_opt_by_keyword(tokens, K_FAMILY))) {
  4293. int i;
  4294. md->family = smartlist_new();
  4295. for (i=0;i<tok->n_args;++i) {
  4296. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  4297. log_warn(LD_DIR, "Illegal nickname %s in family line",
  4298. escaped(tok->args[i]));
  4299. goto next;
  4300. }
  4301. smartlist_add_strdup(md->family, tok->args[i]);
  4302. }
  4303. }
  4304. if ((tok = find_opt_by_keyword(tokens, K_P))) {
  4305. md->exit_policy = parse_short_policy(tok->args[0]);
  4306. }
  4307. if ((tok = find_opt_by_keyword(tokens, K_P6))) {
  4308. md->ipv6_exit_policy = parse_short_policy(tok->args[0]);
  4309. }
  4310. smartlist_add(result, md);
  4311. okay = 1;
  4312. md = NULL;
  4313. next:
  4314. if (! okay && invalid_digests_out) {
  4315. smartlist_add(invalid_digests_out,
  4316. tor_memdup(md->digest, DIGEST256_LEN));
  4317. }
  4318. microdesc_free(md);
  4319. md = NULL;
  4320. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4321. memarea_clear(area);
  4322. smartlist_clear(tokens);
  4323. s = start_of_next_microdesc;
  4324. }
  4325. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4326. memarea_drop_all(area);
  4327. smartlist_free(tokens);
  4328. return result;
  4329. }
  4330. /** Parse the Tor version of the platform string <b>platform</b>,
  4331. * and compare it to the version in <b>cutoff</b>. Return 1 if
  4332. * the router is at least as new as the cutoff, else return 0.
  4333. */
  4334. int
  4335. tor_version_as_new_as(const char *platform, const char *cutoff)
  4336. {
  4337. tor_version_t cutoff_version, router_version;
  4338. char *s, *s2, *start;
  4339. char tmp[128];
  4340. tor_assert(platform);
  4341. if (tor_version_parse(cutoff, &cutoff_version)<0) {
  4342. log_warn(LD_BUG,"cutoff version '%s' unparseable.",cutoff);
  4343. return 0;
  4344. }
  4345. if (strcmpstart(platform,"Tor ")) /* nonstandard Tor; be safe and say yes */
  4346. return 1;
  4347. start = (char *)eat_whitespace(platform+3);
  4348. if (!*start) return 0;
  4349. s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
  4350. s2 = (char*)eat_whitespace(s);
  4351. if (!strcmpstart(s2, "(r") || !strcmpstart(s2, "(git-"))
  4352. s = (char*)find_whitespace(s2);
  4353. if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
  4354. return 0;
  4355. strlcpy(tmp, start, s-start+1);
  4356. if (tor_version_parse(tmp, &router_version)<0) {
  4357. log_info(LD_DIR,"Router version '%s' unparseable.",tmp);
  4358. return 1; /* be safe and say yes */
  4359. }
  4360. /* Here's why we don't need to do any special handling for svn revisions:
  4361. * - If neither has an svn revision, we're fine.
  4362. * - If the router doesn't have an svn revision, we can't assume that it
  4363. * is "at least" any svn revision, so we need to return 0.
  4364. * - If the target version doesn't have an svn revision, any svn revision
  4365. * (or none at all) is good enough, so return 1.
  4366. * - If both target and router have an svn revision, we compare them.
  4367. */
  4368. return tor_version_compare(&router_version, &cutoff_version) >= 0;
  4369. }
  4370. /** Parse a tor version from <b>s</b>, and store the result in <b>out</b>.
  4371. * Return 0 on success, -1 on failure. */
  4372. int
  4373. tor_version_parse(const char *s, tor_version_t *out)
  4374. {
  4375. char *eos=NULL;
  4376. const char *cp=NULL;
  4377. /* Format is:
  4378. * "Tor " ? NUM dot NUM [ dot NUM [ ( pre | rc | dot ) NUM ] ] [ - tag ]
  4379. */
  4380. tor_assert(s);
  4381. tor_assert(out);
  4382. memset(out, 0, sizeof(tor_version_t));
  4383. out->status = VER_RELEASE;
  4384. if (!strcasecmpstart(s, "Tor "))
  4385. s += 4;
  4386. cp = s;
  4387. #define NUMBER(m) \
  4388. do { \
  4389. out->m = (int)strtol(cp, &eos, 10); \
  4390. if (!eos || eos == cp) \
  4391. return -1; \
  4392. cp = eos; \
  4393. } while (0)
  4394. #define DOT() \
  4395. do { \
  4396. if (*cp != '.') \
  4397. return -1; \
  4398. ++cp; \
  4399. } while (0)
  4400. NUMBER(major);
  4401. DOT();
  4402. NUMBER(minor);
  4403. if (*cp == 0)
  4404. return 0;
  4405. else if (*cp == '-')
  4406. goto status_tag;
  4407. DOT();
  4408. NUMBER(micro);
  4409. /* Get status */
  4410. if (*cp == 0) {
  4411. return 0;
  4412. } else if (*cp == '.') {
  4413. ++cp;
  4414. } else if (*cp == '-') {
  4415. goto status_tag;
  4416. } else if (0==strncmp(cp, "pre", 3)) {
  4417. out->status = VER_PRE;
  4418. cp += 3;
  4419. } else if (0==strncmp(cp, "rc", 2)) {
  4420. out->status = VER_RC;
  4421. cp += 2;
  4422. } else {
  4423. return -1;
  4424. }
  4425. NUMBER(patchlevel);
  4426. status_tag:
  4427. /* Get status tag. */
  4428. if (*cp == '-' || *cp == '.')
  4429. ++cp;
  4430. eos = (char*) find_whitespace(cp);
  4431. if (eos-cp >= (int)sizeof(out->status_tag))
  4432. strlcpy(out->status_tag, cp, sizeof(out->status_tag));
  4433. else {
  4434. memcpy(out->status_tag, cp, eos-cp);
  4435. out->status_tag[eos-cp] = 0;
  4436. }
  4437. cp = eat_whitespace(eos);
  4438. if (!strcmpstart(cp, "(r")) {
  4439. cp += 2;
  4440. out->svn_revision = (int) strtol(cp,&eos,10);
  4441. } else if (!strcmpstart(cp, "(git-")) {
  4442. char *close_paren = strchr(cp, ')');
  4443. int hexlen;
  4444. char digest[DIGEST_LEN];
  4445. if (! close_paren)
  4446. return -1;
  4447. cp += 5;
  4448. if (close_paren-cp > HEX_DIGEST_LEN)
  4449. return -1;
  4450. hexlen = (int)(close_paren-cp);
  4451. memwipe(digest, 0, sizeof(digest));
  4452. if ( hexlen == 0 || (hexlen % 2) == 1)
  4453. return -1;
  4454. if (base16_decode(digest, hexlen/2, cp, hexlen) != hexlen/2)
  4455. return -1;
  4456. memcpy(out->git_tag, digest, hexlen/2);
  4457. out->git_tag_len = hexlen/2;
  4458. }
  4459. return 0;
  4460. #undef NUMBER
  4461. #undef DOT
  4462. }
  4463. /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
  4464. * b. */
  4465. int
  4466. tor_version_compare(tor_version_t *a, tor_version_t *b)
  4467. {
  4468. int i;
  4469. tor_assert(a);
  4470. tor_assert(b);
  4471. if ((i = a->major - b->major))
  4472. return i;
  4473. else if ((i = a->minor - b->minor))
  4474. return i;
  4475. else if ((i = a->micro - b->micro))
  4476. return i;
  4477. else if ((i = a->status - b->status))
  4478. return i;
  4479. else if ((i = a->patchlevel - b->patchlevel))
  4480. return i;
  4481. else if ((i = strcmp(a->status_tag, b->status_tag)))
  4482. return i;
  4483. else if ((i = a->svn_revision - b->svn_revision))
  4484. return i;
  4485. else if ((i = a->git_tag_len - b->git_tag_len))
  4486. return i;
  4487. else if (a->git_tag_len)
  4488. return fast_memcmp(a->git_tag, b->git_tag, a->git_tag_len);
  4489. else
  4490. return 0;
  4491. }
  4492. /** Return true iff versions <b>a</b> and <b>b</b> belong to the same series.
  4493. */
  4494. int
  4495. tor_version_same_series(tor_version_t *a, tor_version_t *b)
  4496. {
  4497. tor_assert(a);
  4498. tor_assert(b);
  4499. return ((a->major == b->major) &&
  4500. (a->minor == b->minor) &&
  4501. (a->micro == b->micro));
  4502. }
  4503. /** Helper: Given pointers to two strings describing tor versions, return -1
  4504. * if _a precedes _b, 1 if _b precedes _a, and 0 if they are equivalent.
  4505. * Used to sort a list of versions. */
  4506. static int
  4507. compare_tor_version_str_ptr_(const void **_a, const void **_b)
  4508. {
  4509. const char *a = *_a, *b = *_b;
  4510. int ca, cb;
  4511. tor_version_t va, vb;
  4512. ca = tor_version_parse(a, &va);
  4513. cb = tor_version_parse(b, &vb);
  4514. /* If they both parse, compare them. */
  4515. if (!ca && !cb)
  4516. return tor_version_compare(&va,&vb);
  4517. /* If one parses, it comes first. */
  4518. if (!ca && cb)
  4519. return -1;
  4520. if (ca && !cb)
  4521. return 1;
  4522. /* If neither parses, compare strings. Also, the directory server admin
  4523. ** needs to be smacked upside the head. But Tor is tolerant and gentle. */
  4524. return strcmp(a,b);
  4525. }
  4526. /** Sort a list of string-representations of versions in ascending order. */
  4527. void
  4528. sort_version_list(smartlist_t *versions, int remove_duplicates)
  4529. {
  4530. smartlist_sort(versions, compare_tor_version_str_ptr_);
  4531. if (remove_duplicates)
  4532. smartlist_uniq(versions, compare_tor_version_str_ptr_, tor_free_);
  4533. }
  4534. /** Parse and validate the ASCII-encoded v2 descriptor in <b>desc</b>,
  4535. * write the parsed descriptor to the newly allocated *<b>parsed_out</b>, the
  4536. * binary descriptor ID of length DIGEST_LEN to <b>desc_id_out</b>, the
  4537. * encrypted introduction points to the newly allocated
  4538. * *<b>intro_points_encrypted_out</b>, their encrypted size to
  4539. * *<b>intro_points_encrypted_size_out</b>, the size of the encoded descriptor
  4540. * to *<b>encoded_size_out</b>, and a pointer to the possibly next
  4541. * descriptor to *<b>next_out</b>; return 0 for success (including validation)
  4542. * and -1 for failure.
  4543. *
  4544. * If <b>as_hsdir</b> is 1, we're parsing this as an HSDir, and we should
  4545. * be strict about time formats.
  4546. */
  4547. int
  4548. rend_parse_v2_service_descriptor(rend_service_descriptor_t **parsed_out,
  4549. char *desc_id_out,
  4550. char **intro_points_encrypted_out,
  4551. size_t *intro_points_encrypted_size_out,
  4552. size_t *encoded_size_out,
  4553. const char **next_out, const char *desc,
  4554. int as_hsdir)
  4555. {
  4556. rend_service_descriptor_t *result =
  4557. tor_malloc_zero(sizeof(rend_service_descriptor_t));
  4558. char desc_hash[DIGEST_LEN];
  4559. const char *eos;
  4560. smartlist_t *tokens = smartlist_new();
  4561. directory_token_t *tok;
  4562. char secret_id_part[DIGEST_LEN];
  4563. int i, version, num_ok=1;
  4564. smartlist_t *versions;
  4565. char public_key_hash[DIGEST_LEN];
  4566. char test_desc_id[DIGEST_LEN];
  4567. memarea_t *area = NULL;
  4568. const int strict_time_fmt = as_hsdir;
  4569. tor_assert(desc);
  4570. /* Check if desc starts correctly. */
  4571. if (strncmp(desc, "rendezvous-service-descriptor ",
  4572. strlen("rendezvous-service-descriptor "))) {
  4573. log_info(LD_REND, "Descriptor does not start correctly.");
  4574. goto err;
  4575. }
  4576. /* Compute descriptor hash for later validation. */
  4577. if (router_get_hash_impl(desc, strlen(desc), desc_hash,
  4578. "rendezvous-service-descriptor ",
  4579. "\nsignature", '\n', DIGEST_SHA1) < 0) {
  4580. log_warn(LD_REND, "Couldn't compute descriptor hash.");
  4581. goto err;
  4582. }
  4583. /* Determine end of string. */
  4584. eos = strstr(desc, "\nrendezvous-service-descriptor ");
  4585. if (!eos)
  4586. eos = desc + strlen(desc);
  4587. else
  4588. eos = eos + 1;
  4589. /* Check length. */
  4590. if (eos-desc > REND_DESC_MAX_SIZE) {
  4591. /* XXXX+ If we are parsing this descriptor as a server, this
  4592. * should be a protocol warning. */
  4593. log_warn(LD_REND, "Descriptor length is %d which exceeds "
  4594. "maximum rendezvous descriptor size of %d bytes.",
  4595. (int)(eos-desc), REND_DESC_MAX_SIZE);
  4596. goto err;
  4597. }
  4598. /* Tokenize descriptor. */
  4599. area = memarea_new();
  4600. if (tokenize_string(area, desc, eos, tokens, desc_token_table, 0)) {
  4601. log_warn(LD_REND, "Error tokenizing descriptor.");
  4602. goto err;
  4603. }
  4604. /* Set next to next descriptor, if available. */
  4605. *next_out = eos;
  4606. /* Set length of encoded descriptor. */
  4607. *encoded_size_out = eos - desc;
  4608. /* Check min allowed length of token list. */
  4609. if (smartlist_len(tokens) < 7) {
  4610. log_warn(LD_REND, "Impossibly short descriptor.");
  4611. goto err;
  4612. }
  4613. /* Parse base32-encoded descriptor ID. */
  4614. tok = find_by_keyword(tokens, R_RENDEZVOUS_SERVICE_DESCRIPTOR);
  4615. tor_assert(tok == smartlist_get(tokens, 0));
  4616. tor_assert(tok->n_args == 1);
  4617. if (!rend_valid_descriptor_id(tok->args[0])) {
  4618. log_warn(LD_REND, "Invalid descriptor ID: '%s'", tok->args[0]);
  4619. goto err;
  4620. }
  4621. if (base32_decode(desc_id_out, DIGEST_LEN,
  4622. tok->args[0], REND_DESC_ID_V2_LEN_BASE32) < 0) {
  4623. log_warn(LD_REND, "Descriptor ID contains illegal characters: %s",
  4624. tok->args[0]);
  4625. goto err;
  4626. }
  4627. /* Parse descriptor version. */
  4628. tok = find_by_keyword(tokens, R_VERSION);
  4629. tor_assert(tok->n_args == 1);
  4630. result->version =
  4631. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &num_ok, NULL);
  4632. if (result->version != 2 || !num_ok) {
  4633. /* If it's <2, it shouldn't be under this format. If the number
  4634. * is greater than 2, we bumped it because we broke backward
  4635. * compatibility. See how version numbers in our other formats
  4636. * work. */
  4637. log_warn(LD_REND, "Unrecognized descriptor version: %s",
  4638. escaped(tok->args[0]));
  4639. goto err;
  4640. }
  4641. /* Parse public key. */
  4642. tok = find_by_keyword(tokens, R_PERMANENT_KEY);
  4643. result->pk = tok->key;
  4644. tok->key = NULL; /* Prevent free */
  4645. /* Parse secret ID part. */
  4646. tok = find_by_keyword(tokens, R_SECRET_ID_PART);
  4647. tor_assert(tok->n_args == 1);
  4648. if (strlen(tok->args[0]) != REND_SECRET_ID_PART_LEN_BASE32 ||
  4649. strspn(tok->args[0], BASE32_CHARS) != REND_SECRET_ID_PART_LEN_BASE32) {
  4650. log_warn(LD_REND, "Invalid secret ID part: '%s'", tok->args[0]);
  4651. goto err;
  4652. }
  4653. if (base32_decode(secret_id_part, DIGEST_LEN, tok->args[0], 32) < 0) {
  4654. log_warn(LD_REND, "Secret ID part contains illegal characters: %s",
  4655. tok->args[0]);
  4656. goto err;
  4657. }
  4658. /* Parse publication time -- up-to-date check is done when storing the
  4659. * descriptor. */
  4660. tok = find_by_keyword(tokens, R_PUBLICATION_TIME);
  4661. tor_assert(tok->n_args == 1);
  4662. if (parse_iso_time_(tok->args[0], &result->timestamp,
  4663. strict_time_fmt, 0) < 0) {
  4664. log_warn(LD_REND, "Invalid publication time: '%s'", tok->args[0]);
  4665. goto err;
  4666. }
  4667. /* Parse protocol versions. */
  4668. tok = find_by_keyword(tokens, R_PROTOCOL_VERSIONS);
  4669. tor_assert(tok->n_args == 1);
  4670. versions = smartlist_new();
  4671. smartlist_split_string(versions, tok->args[0], ",",
  4672. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  4673. for (i = 0; i < smartlist_len(versions); i++) {
  4674. version = (int) tor_parse_long(smartlist_get(versions, i),
  4675. 10, 0, INT_MAX, &num_ok, NULL);
  4676. if (!num_ok) /* It's a string; let's ignore it. */
  4677. continue;
  4678. if (version >= REND_PROTOCOL_VERSION_BITMASK_WIDTH)
  4679. /* Avoid undefined left-shift behaviour. */
  4680. continue;
  4681. result->protocols |= 1 << version;
  4682. }
  4683. SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
  4684. smartlist_free(versions);
  4685. /* Parse encrypted introduction points. Don't verify. */
  4686. tok = find_opt_by_keyword(tokens, R_INTRODUCTION_POINTS);
  4687. if (tok) {
  4688. if (strcmp(tok->object_type, "MESSAGE")) {
  4689. log_warn(LD_DIR, "Bad object type: introduction points should be of "
  4690. "type MESSAGE");
  4691. goto err;
  4692. }
  4693. *intro_points_encrypted_out = tor_memdup(tok->object_body,
  4694. tok->object_size);
  4695. *intro_points_encrypted_size_out = tok->object_size;
  4696. } else {
  4697. *intro_points_encrypted_out = NULL;
  4698. *intro_points_encrypted_size_out = 0;
  4699. }
  4700. /* Parse and verify signature. */
  4701. tok = find_by_keyword(tokens, R_SIGNATURE);
  4702. note_crypto_pk_op(VERIFY_RTR);
  4703. if (check_signature_token(desc_hash, DIGEST_LEN, tok, result->pk, 0,
  4704. "v2 rendezvous service descriptor") < 0)
  4705. goto err;
  4706. /* Verify that descriptor ID belongs to public key and secret ID part. */
  4707. crypto_pk_get_digest(result->pk, public_key_hash);
  4708. rend_get_descriptor_id_bytes(test_desc_id, public_key_hash,
  4709. secret_id_part);
  4710. if (tor_memneq(desc_id_out, test_desc_id, DIGEST_LEN)) {
  4711. log_warn(LD_REND, "Parsed descriptor ID does not match "
  4712. "computed descriptor ID.");
  4713. goto err;
  4714. }
  4715. goto done;
  4716. err:
  4717. rend_service_descriptor_free(result);
  4718. result = NULL;
  4719. done:
  4720. if (tokens) {
  4721. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4722. smartlist_free(tokens);
  4723. }
  4724. if (area)
  4725. memarea_drop_all(area);
  4726. *parsed_out = result;
  4727. if (result)
  4728. return 0;
  4729. return -1;
  4730. }
  4731. /** Decrypt the encrypted introduction points in <b>ipos_encrypted</b> of
  4732. * length <b>ipos_encrypted_size</b> using <b>descriptor_cookie</b> and
  4733. * write the result to a newly allocated string that is pointed to by
  4734. * <b>ipos_decrypted</b> and its length to <b>ipos_decrypted_size</b>.
  4735. * Return 0 if decryption was successful and -1 otherwise. */
  4736. int
  4737. rend_decrypt_introduction_points(char **ipos_decrypted,
  4738. size_t *ipos_decrypted_size,
  4739. const char *descriptor_cookie,
  4740. const char *ipos_encrypted,
  4741. size_t ipos_encrypted_size)
  4742. {
  4743. tor_assert(ipos_encrypted);
  4744. tor_assert(descriptor_cookie);
  4745. if (ipos_encrypted_size < 2) {
  4746. log_warn(LD_REND, "Size of encrypted introduction points is too "
  4747. "small.");
  4748. return -1;
  4749. }
  4750. if (ipos_encrypted[0] == (int)REND_BASIC_AUTH) {
  4751. char iv[CIPHER_IV_LEN], client_id[REND_BASIC_AUTH_CLIENT_ID_LEN],
  4752. session_key[CIPHER_KEY_LEN], *dec;
  4753. int declen, client_blocks;
  4754. size_t pos = 0, len, client_entries_len;
  4755. crypto_digest_t *digest;
  4756. crypto_cipher_t *cipher;
  4757. client_blocks = (int) ipos_encrypted[1];
  4758. client_entries_len = client_blocks * REND_BASIC_AUTH_CLIENT_MULTIPLE *
  4759. REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
  4760. if (ipos_encrypted_size < 2 + client_entries_len + CIPHER_IV_LEN + 1) {
  4761. log_warn(LD_REND, "Size of encrypted introduction points is too "
  4762. "small.");
  4763. return -1;
  4764. }
  4765. memcpy(iv, ipos_encrypted + 2 + client_entries_len, CIPHER_IV_LEN);
  4766. digest = crypto_digest_new();
  4767. crypto_digest_add_bytes(digest, descriptor_cookie, REND_DESC_COOKIE_LEN);
  4768. crypto_digest_add_bytes(digest, iv, CIPHER_IV_LEN);
  4769. crypto_digest_get_digest(digest, client_id,
  4770. REND_BASIC_AUTH_CLIENT_ID_LEN);
  4771. crypto_digest_free(digest);
  4772. for (pos = 2; pos < 2 + client_entries_len;
  4773. pos += REND_BASIC_AUTH_CLIENT_ENTRY_LEN) {
  4774. if (tor_memeq(ipos_encrypted + pos, client_id,
  4775. REND_BASIC_AUTH_CLIENT_ID_LEN)) {
  4776. /* Attempt to decrypt introduction points. */
  4777. cipher = crypto_cipher_new(descriptor_cookie);
  4778. if (crypto_cipher_decrypt(cipher, session_key, ipos_encrypted
  4779. + pos + REND_BASIC_AUTH_CLIENT_ID_LEN,
  4780. CIPHER_KEY_LEN) < 0) {
  4781. log_warn(LD_REND, "Could not decrypt session key for client.");
  4782. crypto_cipher_free(cipher);
  4783. return -1;
  4784. }
  4785. crypto_cipher_free(cipher);
  4786. len = ipos_encrypted_size - 2 - client_entries_len - CIPHER_IV_LEN;
  4787. dec = tor_malloc(len);
  4788. declen = crypto_cipher_decrypt_with_iv(session_key, dec, len,
  4789. ipos_encrypted + 2 + client_entries_len,
  4790. ipos_encrypted_size - 2 - client_entries_len);
  4791. if (declen < 0) {
  4792. log_warn(LD_REND, "Could not decrypt introduction point string.");
  4793. tor_free(dec);
  4794. return -1;
  4795. }
  4796. if (fast_memcmpstart(dec, declen, "introduction-point ")) {
  4797. log_warn(LD_REND, "Decrypted introduction points don't "
  4798. "look like we could parse them.");
  4799. tor_free(dec);
  4800. continue;
  4801. }
  4802. *ipos_decrypted = dec;
  4803. *ipos_decrypted_size = declen;
  4804. return 0;
  4805. }
  4806. }
  4807. log_warn(LD_REND, "Could not decrypt introduction points. Please "
  4808. "check your authorization for this service!");
  4809. return -1;
  4810. } else if (ipos_encrypted[0] == (int)REND_STEALTH_AUTH) {
  4811. char *dec;
  4812. int declen;
  4813. if (ipos_encrypted_size < CIPHER_IV_LEN + 2) {
  4814. log_warn(LD_REND, "Size of encrypted introduction points is too "
  4815. "small.");
  4816. return -1;
  4817. }
  4818. dec = tor_malloc_zero(ipos_encrypted_size - CIPHER_IV_LEN - 1);
  4819. declen = crypto_cipher_decrypt_with_iv(descriptor_cookie, dec,
  4820. ipos_encrypted_size -
  4821. CIPHER_IV_LEN - 1,
  4822. ipos_encrypted + 1,
  4823. ipos_encrypted_size - 1);
  4824. if (declen < 0) {
  4825. log_warn(LD_REND, "Decrypting introduction points failed!");
  4826. tor_free(dec);
  4827. return -1;
  4828. }
  4829. *ipos_decrypted = dec;
  4830. *ipos_decrypted_size = declen;
  4831. return 0;
  4832. } else {
  4833. log_warn(LD_REND, "Unknown authorization type number: %d",
  4834. ipos_encrypted[0]);
  4835. return -1;
  4836. }
  4837. }
  4838. /** Parse the encoded introduction points in <b>intro_points_encoded</b> of
  4839. * length <b>intro_points_encoded_size</b> and write the result to the
  4840. * descriptor in <b>parsed</b>; return the number of successfully parsed
  4841. * introduction points or -1 in case of a failure. */
  4842. int
  4843. rend_parse_introduction_points(rend_service_descriptor_t *parsed,
  4844. const char *intro_points_encoded,
  4845. size_t intro_points_encoded_size)
  4846. {
  4847. const char *current_ipo, *end_of_intro_points;
  4848. smartlist_t *tokens = NULL;
  4849. directory_token_t *tok;
  4850. rend_intro_point_t *intro;
  4851. extend_info_t *info;
  4852. int result, num_ok=1;
  4853. memarea_t *area = NULL;
  4854. tor_assert(parsed);
  4855. /** Function may only be invoked once. */
  4856. tor_assert(!parsed->intro_nodes);
  4857. if (!intro_points_encoded || intro_points_encoded_size == 0) {
  4858. log_warn(LD_REND, "Empty or zero size introduction point list");
  4859. goto err;
  4860. }
  4861. /* Consider one intro point after the other. */
  4862. current_ipo = intro_points_encoded;
  4863. end_of_intro_points = intro_points_encoded + intro_points_encoded_size;
  4864. tokens = smartlist_new();
  4865. parsed->intro_nodes = smartlist_new();
  4866. area = memarea_new();
  4867. while (!fast_memcmpstart(current_ipo, end_of_intro_points-current_ipo,
  4868. "introduction-point ")) {
  4869. /* Determine end of string. */
  4870. const char *eos = tor_memstr(current_ipo, end_of_intro_points-current_ipo,
  4871. "\nintroduction-point ");
  4872. if (!eos)
  4873. eos = end_of_intro_points;
  4874. else
  4875. eos = eos+1;
  4876. tor_assert(eos <= intro_points_encoded+intro_points_encoded_size);
  4877. /* Free tokens and clear token list. */
  4878. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4879. smartlist_clear(tokens);
  4880. memarea_clear(area);
  4881. /* Tokenize string. */
  4882. if (tokenize_string(area, current_ipo, eos, tokens, ipo_token_table, 0)) {
  4883. log_warn(LD_REND, "Error tokenizing introduction point");
  4884. goto err;
  4885. }
  4886. /* Advance to next introduction point, if available. */
  4887. current_ipo = eos;
  4888. /* Check minimum allowed length of introduction point. */
  4889. if (smartlist_len(tokens) < 5) {
  4890. log_warn(LD_REND, "Impossibly short introduction point.");
  4891. goto err;
  4892. }
  4893. /* Allocate new intro point and extend info. */
  4894. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  4895. info = intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  4896. /* Parse identifier. */
  4897. tok = find_by_keyword(tokens, R_IPO_IDENTIFIER);
  4898. if (base32_decode(info->identity_digest, DIGEST_LEN,
  4899. tok->args[0], REND_INTRO_POINT_ID_LEN_BASE32) < 0) {
  4900. log_warn(LD_REND, "Identity digest contains illegal characters: %s",
  4901. tok->args[0]);
  4902. rend_intro_point_free(intro);
  4903. goto err;
  4904. }
  4905. /* Write identifier to nickname. */
  4906. info->nickname[0] = '$';
  4907. base16_encode(info->nickname + 1, sizeof(info->nickname) - 1,
  4908. info->identity_digest, DIGEST_LEN);
  4909. /* Parse IP address. */
  4910. tok = find_by_keyword(tokens, R_IPO_IP_ADDRESS);
  4911. if (tor_addr_parse(&info->addr, tok->args[0])<0) {
  4912. log_warn(LD_REND, "Could not parse introduction point address.");
  4913. rend_intro_point_free(intro);
  4914. goto err;
  4915. }
  4916. if (tor_addr_family(&info->addr) != AF_INET) {
  4917. log_warn(LD_REND, "Introduction point address was not ipv4.");
  4918. rend_intro_point_free(intro);
  4919. goto err;
  4920. }
  4921. /* Parse onion port. */
  4922. tok = find_by_keyword(tokens, R_IPO_ONION_PORT);
  4923. info->port = (uint16_t) tor_parse_long(tok->args[0],10,1,65535,
  4924. &num_ok,NULL);
  4925. if (!info->port || !num_ok) {
  4926. log_warn(LD_REND, "Introduction point onion port %s is invalid",
  4927. escaped(tok->args[0]));
  4928. rend_intro_point_free(intro);
  4929. goto err;
  4930. }
  4931. /* Parse onion key. */
  4932. tok = find_by_keyword(tokens, R_IPO_ONION_KEY);
  4933. if (!crypto_pk_public_exponent_ok(tok->key)) {
  4934. log_warn(LD_REND,
  4935. "Introduction point's onion key had invalid exponent.");
  4936. rend_intro_point_free(intro);
  4937. goto err;
  4938. }
  4939. info->onion_key = tok->key;
  4940. tok->key = NULL; /* Prevent free */
  4941. /* Parse service key. */
  4942. tok = find_by_keyword(tokens, R_IPO_SERVICE_KEY);
  4943. if (!crypto_pk_public_exponent_ok(tok->key)) {
  4944. log_warn(LD_REND,
  4945. "Introduction point key had invalid exponent.");
  4946. rend_intro_point_free(intro);
  4947. goto err;
  4948. }
  4949. intro->intro_key = tok->key;
  4950. tok->key = NULL; /* Prevent free */
  4951. /* Add extend info to list of introduction points. */
  4952. smartlist_add(parsed->intro_nodes, intro);
  4953. }
  4954. result = smartlist_len(parsed->intro_nodes);
  4955. goto done;
  4956. err:
  4957. result = -1;
  4958. done:
  4959. /* Free tokens and clear token list. */
  4960. if (tokens) {
  4961. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4962. smartlist_free(tokens);
  4963. }
  4964. if (area)
  4965. memarea_drop_all(area);
  4966. return result;
  4967. }
  4968. /** Parse the content of a client_key file in <b>ckstr</b> and add
  4969. * rend_authorized_client_t's for each parsed client to
  4970. * <b>parsed_clients</b>. Return the number of parsed clients as result
  4971. * or -1 for failure. */
  4972. int
  4973. rend_parse_client_keys(strmap_t *parsed_clients, const char *ckstr)
  4974. {
  4975. int result = -1;
  4976. smartlist_t *tokens;
  4977. directory_token_t *tok;
  4978. const char *current_entry = NULL;
  4979. memarea_t *area = NULL;
  4980. char *err_msg = NULL;
  4981. if (!ckstr || strlen(ckstr) == 0)
  4982. return -1;
  4983. tokens = smartlist_new();
  4984. /* Begin parsing with first entry, skipping comments or whitespace at the
  4985. * beginning. */
  4986. area = memarea_new();
  4987. current_entry = eat_whitespace(ckstr);
  4988. while (!strcmpstart(current_entry, "client-name ")) {
  4989. rend_authorized_client_t *parsed_entry;
  4990. /* Determine end of string. */
  4991. const char *eos = strstr(current_entry, "\nclient-name ");
  4992. if (!eos)
  4993. eos = current_entry + strlen(current_entry);
  4994. else
  4995. eos = eos + 1;
  4996. /* Free tokens and clear token list. */
  4997. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4998. smartlist_clear(tokens);
  4999. memarea_clear(area);
  5000. /* Tokenize string. */
  5001. if (tokenize_string(area, current_entry, eos, tokens,
  5002. client_keys_token_table, 0)) {
  5003. log_warn(LD_REND, "Error tokenizing client keys file.");
  5004. goto err;
  5005. }
  5006. /* Advance to next entry, if available. */
  5007. current_entry = eos;
  5008. /* Check minimum allowed length of token list. */
  5009. if (smartlist_len(tokens) < 2) {
  5010. log_warn(LD_REND, "Impossibly short client key entry.");
  5011. goto err;
  5012. }
  5013. /* Parse client name. */
  5014. tok = find_by_keyword(tokens, C_CLIENT_NAME);
  5015. tor_assert(tok == smartlist_get(tokens, 0));
  5016. tor_assert(tok->n_args == 1);
  5017. if (!rend_valid_client_name(tok->args[0])) {
  5018. log_warn(LD_CONFIG, "Illegal client name: %s. (Length must be "
  5019. "between 1 and %d, and valid characters are "
  5020. "[A-Za-z0-9+-_].)", tok->args[0], REND_CLIENTNAME_MAX_LEN);
  5021. goto err;
  5022. }
  5023. /* Check if client name is duplicate. */
  5024. if (strmap_get(parsed_clients, tok->args[0])) {
  5025. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains a "
  5026. "duplicate client name: '%s'. Ignoring.", tok->args[0]);
  5027. goto err;
  5028. }
  5029. parsed_entry = tor_malloc_zero(sizeof(rend_authorized_client_t));
  5030. parsed_entry->client_name = tor_strdup(tok->args[0]);
  5031. strmap_set(parsed_clients, parsed_entry->client_name, parsed_entry);
  5032. /* Parse client key. */
  5033. tok = find_opt_by_keyword(tokens, C_CLIENT_KEY);
  5034. if (tok) {
  5035. parsed_entry->client_key = tok->key;
  5036. tok->key = NULL; /* Prevent free */
  5037. }
  5038. /* Parse descriptor cookie. */
  5039. tok = find_by_keyword(tokens, C_DESCRIPTOR_COOKIE);
  5040. tor_assert(tok->n_args == 1);
  5041. if (rend_auth_decode_cookie(tok->args[0], parsed_entry->descriptor_cookie,
  5042. NULL, &err_msg) < 0) {
  5043. tor_assert(err_msg);
  5044. log_warn(LD_REND, "%s", err_msg);
  5045. tor_free(err_msg);
  5046. goto err;
  5047. }
  5048. }
  5049. result = strmap_size(parsed_clients);
  5050. goto done;
  5051. err:
  5052. result = -1;
  5053. done:
  5054. /* Free tokens and clear token list. */
  5055. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  5056. smartlist_free(tokens);
  5057. if (area)
  5058. memarea_drop_all(area);
  5059. return result;
  5060. }
  5061. /** Called on startup; right now we just handle scanning the unparseable
  5062. * descriptor dumps, but hang anything else we might need to do in the
  5063. * future here as well.
  5064. */
  5065. void
  5066. routerparse_init(void)
  5067. {
  5068. /*
  5069. * Check both if the sandbox is active and whether it's configured; no
  5070. * point in loading all that if we won't be able to use it after the
  5071. * sandbox becomes active.
  5072. */
  5073. if (!(sandbox_is_active() || get_options()->Sandbox)) {
  5074. dump_desc_init();
  5075. }
  5076. }
  5077. /** Clean up all data structures used by routerparse.c at exit */
  5078. void
  5079. routerparse_free_all(void)
  5080. {
  5081. dump_desc_fifo_cleanup();
  5082. }