routerparse.c 171 KB

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