routerparse.c 196 KB

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