routerparse.c 197 KB

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