routerparse.c 170 KB

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