routerparse.c 198 KB

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