routerparse.c 198 KB

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