routerparse.c 172 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2012, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file routerparse.c
  8. * \brief Code to parse and validate router descriptors and directories.
  9. **/
  10. #include "or.h"
  11. #include "config.h"
  12. #include "circuitstats.h"
  13. #include "dirserv.h"
  14. #include "dirvote.h"
  15. #include "policies.h"
  16. #include "rendcommon.h"
  17. #include "router.h"
  18. #include "routerlist.h"
  19. #include "memarea.h"
  20. #include "microdesc.h"
  21. #include "networkstatus.h"
  22. #include "rephist.h"
  23. #include "routerparse.h"
  24. #undef log
  25. #include <math.h>
  26. /****************************************************************************/
  27. /** Enumeration of possible token types. The ones starting with K_ correspond
  28. * to directory 'keywords'. ERR_ is an error in the tokenizing process, EOF_
  29. * is an end-of-file marker, and NIL_ is used to encode not-a-token.
  30. */
  31. typedef enum {
  32. K_ACCEPT = 0,
  33. K_ACCEPT6,
  34. K_DIRECTORY_SIGNATURE,
  35. K_RECOMMENDED_SOFTWARE,
  36. K_REJECT,
  37. K_REJECT6,
  38. K_ROUTER,
  39. K_SIGNED_DIRECTORY,
  40. K_SIGNING_KEY,
  41. K_ONION_KEY,
  42. K_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. 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. uint8_t k[CURVE25519_PUBKEY_LEN+32];
  1159. int r;
  1160. tor_assert(tok->n_args >= 1);
  1161. r = base64_decode((char*)k, sizeof(k), tok->args[0], strlen(tok->args[0]));
  1162. if (r != CURVE25519_PUBKEY_LEN) {
  1163. log_warn(LD_DIR, "Bogus onion-key-ntor in routerinfo");
  1164. goto err;
  1165. }
  1166. router->onion_curve25519_pkey =
  1167. tor_malloc(sizeof(curve25519_public_key_t));
  1168. memcpy(router->onion_curve25519_pkey->public_key,
  1169. k, CURVE25519_PUBKEY_LEN);
  1170. }
  1171. tok = find_by_keyword(tokens, K_SIGNING_KEY);
  1172. router->identity_pkey = tok->key;
  1173. tok->key = NULL; /* Prevent free */
  1174. if (crypto_pk_get_digest(router->identity_pkey,
  1175. router->cache_info.identity_digest)) {
  1176. log_warn(LD_DIR, "Couldn't calculate key digest"); goto err;
  1177. }
  1178. if ((tok = find_opt_by_keyword(tokens, K_FINGERPRINT))) {
  1179. /* If there's a fingerprint line, it must match the identity digest. */
  1180. char d[DIGEST_LEN];
  1181. tor_assert(tok->n_args == 1);
  1182. tor_strstrip(tok->args[0], " ");
  1183. if (base16_decode(d, DIGEST_LEN, tok->args[0], strlen(tok->args[0]))) {
  1184. log_warn(LD_DIR, "Couldn't decode router fingerprint %s",
  1185. escaped(tok->args[0]));
  1186. goto err;
  1187. }
  1188. if (tor_memneq(d,router->cache_info.identity_digest, DIGEST_LEN)) {
  1189. log_warn(LD_DIR, "Fingerprint '%s' does not match identity digest.",
  1190. tok->args[0]);
  1191. goto err;
  1192. }
  1193. }
  1194. if ((tok = find_opt_by_keyword(tokens, K_PLATFORM))) {
  1195. router->platform = tor_strdup(tok->args[0]);
  1196. }
  1197. if ((tok = find_opt_by_keyword(tokens, K_CONTACT))) {
  1198. router->contact_info = tor_strdup(tok->args[0]);
  1199. }
  1200. if (find_opt_by_keyword(tokens, K_REJECT6) ||
  1201. find_opt_by_keyword(tokens, K_ACCEPT6)) {
  1202. log_warn(LD_DIR, "Rejecting router with reject6/accept6 line: they crash "
  1203. "older Tors.");
  1204. goto err;
  1205. }
  1206. {
  1207. smartlist_t *or_addresses = find_all_by_keyword(tokens, K_OR_ADDRESS);
  1208. if (or_addresses) {
  1209. find_single_ipv6_orport(or_addresses, &router->ipv6_addr,
  1210. &router->ipv6_orport);
  1211. smartlist_free(or_addresses);
  1212. }
  1213. }
  1214. exit_policy_tokens = find_all_exitpolicy(tokens);
  1215. if (!smartlist_len(exit_policy_tokens)) {
  1216. log_warn(LD_DIR, "No exit policy tokens in descriptor.");
  1217. goto err;
  1218. }
  1219. SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
  1220. if (router_add_exit_policy(router,t)<0) {
  1221. log_warn(LD_DIR,"Error in exit policy");
  1222. goto err;
  1223. });
  1224. policy_expand_private(&router->exit_policy);
  1225. if ((tok = find_opt_by_keyword(tokens, K_IPV6_POLICY)) && tok->n_args) {
  1226. router->ipv6_exit_policy = parse_short_policy(tok->args[0]);
  1227. if (! router->ipv6_exit_policy) {
  1228. log_warn(LD_DIR , "Error in ipv6-policy %s", escaped(tok->args[0]));
  1229. goto err;
  1230. }
  1231. }
  1232. if (policy_is_reject_star(router->exit_policy, AF_INET) &&
  1233. (!router->ipv6_exit_policy ||
  1234. short_policy_is_reject_star(router->ipv6_exit_policy)))
  1235. router->policy_is_reject_star = 1;
  1236. if ((tok = find_opt_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
  1237. int i;
  1238. router->declared_family = smartlist_new();
  1239. for (i=0;i<tok->n_args;++i) {
  1240. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  1241. log_warn(LD_DIR, "Illegal nickname %s in family line",
  1242. escaped(tok->args[i]));
  1243. goto err;
  1244. }
  1245. smartlist_add(router->declared_family, tor_strdup(tok->args[i]));
  1246. }
  1247. }
  1248. if (find_opt_by_keyword(tokens, K_CACHES_EXTRA_INFO))
  1249. router->caches_extra_info = 1;
  1250. if (find_opt_by_keyword(tokens, K_ALLOW_SINGLE_HOP_EXITS))
  1251. router->allow_single_hop_exits = 1;
  1252. if ((tok = find_opt_by_keyword(tokens, K_EXTRA_INFO_DIGEST))) {
  1253. tor_assert(tok->n_args >= 1);
  1254. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  1255. base16_decode(router->cache_info.extra_info_digest,
  1256. DIGEST_LEN, tok->args[0], HEX_DIGEST_LEN);
  1257. } else {
  1258. log_warn(LD_DIR, "Invalid extra info digest %s", escaped(tok->args[0]));
  1259. }
  1260. }
  1261. if (find_opt_by_keyword(tokens, K_HIDDEN_SERVICE_DIR)) {
  1262. router->wants_to_be_hs_dir = 1;
  1263. }
  1264. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1265. note_crypto_pk_op(VERIFY_RTR);
  1266. #ifdef COUNT_DISTINCT_DIGESTS
  1267. if (!verified_digests)
  1268. verified_digests = digestmap_new();
  1269. digestmap_set(verified_digests, signed_digest, (void*)(uintptr_t)1);
  1270. #endif
  1271. if (check_signature_token(digest, DIGEST_LEN, tok, router->identity_pkey, 0,
  1272. "router descriptor") < 0)
  1273. goto err;
  1274. if (!router->or_port) {
  1275. log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
  1276. goto err;
  1277. }
  1278. if (!router->platform) {
  1279. router->platform = tor_strdup("<unknown>");
  1280. }
  1281. goto done;
  1282. err:
  1283. dump_desc(s_dup, "router descriptor");
  1284. routerinfo_free(router);
  1285. router = NULL;
  1286. done:
  1287. if (tokens) {
  1288. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1289. smartlist_free(tokens);
  1290. }
  1291. smartlist_free(exit_policy_tokens);
  1292. if (area) {
  1293. DUMP_AREA(area, "routerinfo");
  1294. memarea_drop_all(area);
  1295. }
  1296. return router;
  1297. }
  1298. /** Parse a single extrainfo entry from the string <b>s</b>, ending at
  1299. * <b>end</b>. (If <b>end</b> is NULL, parse up to the end of <b>s</b>.) If
  1300. * <b>cache_copy</b> is true, make a copy of the extra-info document in the
  1301. * cache_info fields of the result. If <b>routermap</b> is provided, use it
  1302. * as a map from router identity to routerinfo_t when looking up signing keys.
  1303. */
  1304. extrainfo_t *
  1305. extrainfo_parse_entry_from_string(const char *s, const char *end,
  1306. int cache_copy, struct digest_ri_map_t *routermap)
  1307. {
  1308. extrainfo_t *extrainfo = NULL;
  1309. char digest[128];
  1310. smartlist_t *tokens = NULL;
  1311. directory_token_t *tok;
  1312. crypto_pk_t *key = NULL;
  1313. routerinfo_t *router = NULL;
  1314. memarea_t *area = NULL;
  1315. const char *s_dup = s;
  1316. if (!end) {
  1317. end = s + strlen(s);
  1318. }
  1319. /* point 'end' to a point immediately after the final newline. */
  1320. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  1321. --end;
  1322. if (router_get_extrainfo_hash(s, end-s, digest) < 0) {
  1323. log_warn(LD_DIR, "Couldn't compute router hash.");
  1324. goto err;
  1325. }
  1326. tokens = smartlist_new();
  1327. area = memarea_new();
  1328. if (tokenize_string(area,s,end,tokens,extrainfo_token_table,0)) {
  1329. log_warn(LD_DIR, "Error tokenizing extra-info document.");
  1330. goto err;
  1331. }
  1332. if (smartlist_len(tokens) < 2) {
  1333. log_warn(LD_DIR, "Impossibly short extra-info document.");
  1334. goto err;
  1335. }
  1336. tok = smartlist_get(tokens,0);
  1337. if (tok->tp != K_EXTRA_INFO) {
  1338. log_warn(LD_DIR,"Entry does not start with \"extra-info\"");
  1339. goto err;
  1340. }
  1341. extrainfo = tor_malloc_zero(sizeof(extrainfo_t));
  1342. extrainfo->cache_info.is_extrainfo = 1;
  1343. if (cache_copy)
  1344. extrainfo->cache_info.signed_descriptor_body = tor_strndup(s, end-s);
  1345. extrainfo->cache_info.signed_descriptor_len = end-s;
  1346. memcpy(extrainfo->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1347. tor_assert(tok->n_args >= 2);
  1348. if (!is_legal_nickname(tok->args[0])) {
  1349. log_warn(LD_DIR,"Bad nickname %s on \"extra-info\"",escaped(tok->args[0]));
  1350. goto err;
  1351. }
  1352. strlcpy(extrainfo->nickname, tok->args[0], sizeof(extrainfo->nickname));
  1353. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  1354. base16_decode(extrainfo->cache_info.identity_digest, DIGEST_LEN,
  1355. tok->args[1], HEX_DIGEST_LEN)) {
  1356. log_warn(LD_DIR,"Invalid fingerprint %s on \"extra-info\"",
  1357. escaped(tok->args[1]));
  1358. goto err;
  1359. }
  1360. tok = find_by_keyword(tokens, K_PUBLISHED);
  1361. if (parse_iso_time(tok->args[0], &extrainfo->cache_info.published_on)) {
  1362. log_warn(LD_DIR,"Invalid published time %s on \"extra-info\"",
  1363. escaped(tok->args[0]));
  1364. goto err;
  1365. }
  1366. if (routermap &&
  1367. (router = digestmap_get((digestmap_t*)routermap,
  1368. extrainfo->cache_info.identity_digest))) {
  1369. key = router->identity_pkey;
  1370. }
  1371. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1372. if (strcmp(tok->object_type, "SIGNATURE") ||
  1373. tok->object_size < 128 || tok->object_size > 512) {
  1374. log_warn(LD_DIR, "Bad object type or length on extra-info signature");
  1375. goto err;
  1376. }
  1377. if (key) {
  1378. note_crypto_pk_op(VERIFY_RTR);
  1379. if (check_signature_token(digest, DIGEST_LEN, tok, key, 0,
  1380. "extra-info") < 0)
  1381. goto err;
  1382. if (router)
  1383. extrainfo->cache_info.send_unencrypted =
  1384. router->cache_info.send_unencrypted;
  1385. } else {
  1386. extrainfo->pending_sig = tor_memdup(tok->object_body,
  1387. tok->object_size);
  1388. extrainfo->pending_sig_len = tok->object_size;
  1389. }
  1390. goto done;
  1391. err:
  1392. dump_desc(s_dup, "extra-info descriptor");
  1393. extrainfo_free(extrainfo);
  1394. extrainfo = NULL;
  1395. done:
  1396. if (tokens) {
  1397. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1398. smartlist_free(tokens);
  1399. }
  1400. if (area) {
  1401. DUMP_AREA(area, "extrainfo");
  1402. memarea_drop_all(area);
  1403. }
  1404. return extrainfo;
  1405. }
  1406. /** Parse a key certificate from <b>s</b>; point <b>end-of-string</b> to
  1407. * the first character after the certificate. */
  1408. authority_cert_t *
  1409. authority_cert_parse_from_string(const char *s, const char **end_of_string)
  1410. {
  1411. /** Reject any certificate at least this big; it is probably an overflow, an
  1412. * attack, a bug, or some other nonsense. */
  1413. #define MAX_CERT_SIZE (128*1024)
  1414. authority_cert_t *cert = NULL, *old_cert;
  1415. smartlist_t *tokens = NULL;
  1416. char digest[DIGEST_LEN];
  1417. directory_token_t *tok;
  1418. char fp_declared[DIGEST_LEN];
  1419. char *eos;
  1420. size_t len;
  1421. int found;
  1422. memarea_t *area = NULL;
  1423. const char *s_dup = s;
  1424. s = eat_whitespace(s);
  1425. eos = strstr(s, "\ndir-key-certification");
  1426. if (! eos) {
  1427. log_warn(LD_DIR, "No signature found on key certificate");
  1428. return NULL;
  1429. }
  1430. eos = strstr(eos, "\n-----END SIGNATURE-----\n");
  1431. if (! eos) {
  1432. log_warn(LD_DIR, "No end-of-signature found on key certificate");
  1433. return NULL;
  1434. }
  1435. eos = strchr(eos+2, '\n');
  1436. tor_assert(eos);
  1437. ++eos;
  1438. len = eos - s;
  1439. if (len > MAX_CERT_SIZE) {
  1440. log_warn(LD_DIR, "Certificate is far too big (at %lu bytes long); "
  1441. "rejecting", (unsigned long)len);
  1442. return NULL;
  1443. }
  1444. tokens = smartlist_new();
  1445. area = memarea_new();
  1446. if (tokenize_string(area,s, eos, tokens, dir_key_certificate_table, 0) < 0) {
  1447. log_warn(LD_DIR, "Error tokenizing key certificate");
  1448. goto err;
  1449. }
  1450. if (router_get_hash_impl(s, strlen(s), digest, "dir-key-certificate-version",
  1451. "\ndir-key-certification", '\n', DIGEST_SHA1) < 0)
  1452. goto err;
  1453. tok = smartlist_get(tokens, 0);
  1454. if (tok->tp != K_DIR_KEY_CERTIFICATE_VERSION || strcmp(tok->args[0], "3")) {
  1455. log_warn(LD_DIR,
  1456. "Key certificate does not begin with a recognized version (3).");
  1457. goto err;
  1458. }
  1459. cert = tor_malloc_zero(sizeof(authority_cert_t));
  1460. memcpy(cert->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1461. tok = find_by_keyword(tokens, K_DIR_SIGNING_KEY);
  1462. tor_assert(tok->key);
  1463. cert->signing_key = tok->key;
  1464. tok->key = NULL;
  1465. if (crypto_pk_get_digest(cert->signing_key, cert->signing_key_digest))
  1466. goto err;
  1467. tok = find_by_keyword(tokens, K_DIR_IDENTITY_KEY);
  1468. tor_assert(tok->key);
  1469. cert->identity_key = tok->key;
  1470. tok->key = NULL;
  1471. tok = find_by_keyword(tokens, K_FINGERPRINT);
  1472. tor_assert(tok->n_args);
  1473. if (base16_decode(fp_declared, DIGEST_LEN, tok->args[0],
  1474. strlen(tok->args[0]))) {
  1475. log_warn(LD_DIR, "Couldn't decode key certificate fingerprint %s",
  1476. escaped(tok->args[0]));
  1477. goto err;
  1478. }
  1479. if (crypto_pk_get_digest(cert->identity_key,
  1480. cert->cache_info.identity_digest))
  1481. goto err;
  1482. if (tor_memneq(cert->cache_info.identity_digest, fp_declared, DIGEST_LEN)) {
  1483. log_warn(LD_DIR, "Digest of certificate key didn't match declared "
  1484. "fingerprint");
  1485. goto err;
  1486. }
  1487. tok = find_opt_by_keyword(tokens, K_DIR_ADDRESS);
  1488. if (tok) {
  1489. struct in_addr in;
  1490. char *address = NULL;
  1491. tor_assert(tok->n_args);
  1492. /* XXX024 use some tor_addr parse function below instead. -RD */
  1493. if (tor_addr_port_split(LOG_WARN, tok->args[0], &address,
  1494. &cert->dir_port) < 0 ||
  1495. tor_inet_aton(address, &in) == 0) {
  1496. log_warn(LD_DIR, "Couldn't parse dir-address in certificate");
  1497. tor_free(address);
  1498. goto err;
  1499. }
  1500. cert->addr = ntohl(in.s_addr);
  1501. tor_free(address);
  1502. }
  1503. tok = find_by_keyword(tokens, K_DIR_KEY_PUBLISHED);
  1504. if (parse_iso_time(tok->args[0], &cert->cache_info.published_on) < 0) {
  1505. goto err;
  1506. }
  1507. tok = find_by_keyword(tokens, K_DIR_KEY_EXPIRES);
  1508. if (parse_iso_time(tok->args[0], &cert->expires) < 0) {
  1509. goto err;
  1510. }
  1511. tok = smartlist_get(tokens, smartlist_len(tokens)-1);
  1512. if (tok->tp != K_DIR_KEY_CERTIFICATION) {
  1513. log_warn(LD_DIR, "Certificate didn't end with dir-key-certification.");
  1514. goto err;
  1515. }
  1516. /* If we already have this cert, don't bother checking the signature. */
  1517. old_cert = authority_cert_get_by_digests(
  1518. cert->cache_info.identity_digest,
  1519. cert->signing_key_digest);
  1520. found = 0;
  1521. if (old_cert) {
  1522. /* XXXX We could just compare signed_descriptor_digest, but that wouldn't
  1523. * buy us much. */
  1524. if (old_cert->cache_info.signed_descriptor_len == len &&
  1525. old_cert->cache_info.signed_descriptor_body &&
  1526. tor_memeq(s, old_cert->cache_info.signed_descriptor_body, len)) {
  1527. log_debug(LD_DIR, "We already checked the signature on this "
  1528. "certificate; no need to do so again.");
  1529. found = 1;
  1530. cert->is_cross_certified = old_cert->is_cross_certified;
  1531. }
  1532. }
  1533. if (!found) {
  1534. if (check_signature_token(digest, DIGEST_LEN, tok, cert->identity_key, 0,
  1535. "key certificate")) {
  1536. goto err;
  1537. }
  1538. if ((tok = find_opt_by_keyword(tokens, K_DIR_KEY_CROSSCERT))) {
  1539. /* XXXX Once all authorities generate cross-certified certificates,
  1540. * make this field mandatory. */
  1541. if (check_signature_token(cert->cache_info.identity_digest,
  1542. DIGEST_LEN,
  1543. tok,
  1544. cert->signing_key,
  1545. CST_NO_CHECK_OBJTYPE,
  1546. "key cross-certification")) {
  1547. goto err;
  1548. }
  1549. cert->is_cross_certified = 1;
  1550. }
  1551. }
  1552. cert->cache_info.signed_descriptor_len = len;
  1553. cert->cache_info.signed_descriptor_body = tor_malloc(len+1);
  1554. memcpy(cert->cache_info.signed_descriptor_body, s, len);
  1555. cert->cache_info.signed_descriptor_body[len] = 0;
  1556. cert->cache_info.saved_location = SAVED_NOWHERE;
  1557. if (end_of_string) {
  1558. *end_of_string = eat_whitespace(eos);
  1559. }
  1560. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1561. smartlist_free(tokens);
  1562. if (area) {
  1563. DUMP_AREA(area, "authority cert");
  1564. memarea_drop_all(area);
  1565. }
  1566. return cert;
  1567. err:
  1568. dump_desc(s_dup, "authority cert");
  1569. authority_cert_free(cert);
  1570. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1571. smartlist_free(tokens);
  1572. if (area) {
  1573. DUMP_AREA(area, "authority cert");
  1574. memarea_drop_all(area);
  1575. }
  1576. return NULL;
  1577. }
  1578. /** Helper: given a string <b>s</b>, return the start of the next router-status
  1579. * object (starting with "r " at the start of a line). If none is found,
  1580. * return the start of the directory footer, or the next directory signature.
  1581. * If none is found, return the end of the string. */
  1582. static INLINE const char *
  1583. find_start_of_next_routerstatus(const char *s)
  1584. {
  1585. const char *eos, *footer, *sig;
  1586. if ((eos = strstr(s, "\nr ")))
  1587. ++eos;
  1588. else
  1589. eos = s + strlen(s);
  1590. footer = tor_memstr(s, eos-s, "\ndirectory-footer");
  1591. sig = tor_memstr(s, eos-s, "\ndirectory-signature");
  1592. if (footer && sig)
  1593. return MIN(footer, sig) + 1;
  1594. else if (footer)
  1595. return footer+1;
  1596. else if (sig)
  1597. return sig+1;
  1598. else
  1599. return eos;
  1600. }
  1601. /** Given a string at *<b>s</b>, containing a routerstatus object, and an
  1602. * empty smartlist at <b>tokens</b>, parse and return the first router status
  1603. * object in the string, and advance *<b>s</b> to just after the end of the
  1604. * router status. Return NULL and advance *<b>s</b> on error.
  1605. *
  1606. * If <b>vote</b> and <b>vote_rs</b> are provided, don't allocate a fresh
  1607. * routerstatus but use <b>vote_rs</b> instead.
  1608. *
  1609. * If <b>consensus_method</b> is nonzero, this routerstatus is part of a
  1610. * consensus, and we should parse it according to the method used to
  1611. * make that consensus.
  1612. *
  1613. * Parse according to the syntax used by the consensus flavor <b>flav</b>.
  1614. **/
  1615. static routerstatus_t *
  1616. routerstatus_parse_entry_from_string(memarea_t *area,
  1617. const char **s, smartlist_t *tokens,
  1618. networkstatus_t *vote,
  1619. vote_routerstatus_t *vote_rs,
  1620. int consensus_method,
  1621. consensus_flavor_t flav)
  1622. {
  1623. const char *eos, *s_dup = *s;
  1624. routerstatus_t *rs = NULL;
  1625. directory_token_t *tok;
  1626. char timebuf[ISO_TIME_LEN+1];
  1627. struct in_addr in;
  1628. int offset = 0;
  1629. tor_assert(tokens);
  1630. tor_assert(bool_eq(vote, vote_rs));
  1631. if (!consensus_method)
  1632. flav = FLAV_NS;
  1633. tor_assert(flav == FLAV_NS || flav == FLAV_MICRODESC);
  1634. eos = find_start_of_next_routerstatus(*s);
  1635. if (tokenize_string(area,*s, eos, tokens, rtrstatus_token_table,0)) {
  1636. log_warn(LD_DIR, "Error tokenizing router status");
  1637. goto err;
  1638. }
  1639. if (smartlist_len(tokens) < 1) {
  1640. log_warn(LD_DIR, "Impossibly short router status");
  1641. goto err;
  1642. }
  1643. tok = find_by_keyword(tokens, K_R);
  1644. tor_assert(tok->n_args >= 7); /* guaranteed by GE(7) in K_R setup */
  1645. if (flav == FLAV_NS) {
  1646. if (tok->n_args < 8) {
  1647. log_warn(LD_DIR, "Too few arguments to r");
  1648. goto err;
  1649. }
  1650. } else if (flav == FLAV_MICRODESC) {
  1651. offset = -1; /* There is no identity digest */
  1652. }
  1653. if (vote_rs) {
  1654. rs = &vote_rs->status;
  1655. } else {
  1656. rs = tor_malloc_zero(sizeof(routerstatus_t));
  1657. }
  1658. if (!is_legal_nickname(tok->args[0])) {
  1659. log_warn(LD_DIR,
  1660. "Invalid nickname %s in router status; skipping.",
  1661. escaped(tok->args[0]));
  1662. goto err;
  1663. }
  1664. strlcpy(rs->nickname, tok->args[0], sizeof(rs->nickname));
  1665. if (digest_from_base64(rs->identity_digest, tok->args[1])) {
  1666. log_warn(LD_DIR, "Error decoding identity digest %s",
  1667. escaped(tok->args[1]));
  1668. goto err;
  1669. }
  1670. if (flav == FLAV_NS) {
  1671. if (digest_from_base64(rs->descriptor_digest, tok->args[2])) {
  1672. log_warn(LD_DIR, "Error decoding descriptor digest %s",
  1673. escaped(tok->args[2]));
  1674. goto err;
  1675. }
  1676. }
  1677. if (tor_snprintf(timebuf, sizeof(timebuf), "%s %s",
  1678. tok->args[3+offset], tok->args[4+offset]) < 0 ||
  1679. parse_iso_time(timebuf, &rs->published_on)<0) {
  1680. log_warn(LD_DIR, "Error parsing time '%s %s' [%d %d]",
  1681. tok->args[3+offset], tok->args[4+offset],
  1682. offset, (int)flav);
  1683. goto err;
  1684. }
  1685. if (tor_inet_aton(tok->args[5+offset], &in) == 0) {
  1686. log_warn(LD_DIR, "Error parsing router address in network-status %s",
  1687. escaped(tok->args[5+offset]));
  1688. goto err;
  1689. }
  1690. rs->addr = ntohl(in.s_addr);
  1691. rs->or_port = (uint16_t) tor_parse_long(tok->args[6+offset],
  1692. 10,0,65535,NULL,NULL);
  1693. rs->dir_port = (uint16_t) tor_parse_long(tok->args[7+offset],
  1694. 10,0,65535,NULL,NULL);
  1695. {
  1696. smartlist_t *a_lines = find_all_by_keyword(tokens, K_A);
  1697. if (a_lines) {
  1698. find_single_ipv6_orport(a_lines, &rs->ipv6_addr, &rs->ipv6_orport);
  1699. smartlist_free(a_lines);
  1700. }
  1701. }
  1702. tok = find_opt_by_keyword(tokens, K_S);
  1703. if (tok && vote) {
  1704. int i;
  1705. vote_rs->flags = 0;
  1706. for (i=0; i < tok->n_args; ++i) {
  1707. int p = smartlist_string_pos(vote->known_flags, tok->args[i]);
  1708. if (p >= 0) {
  1709. vote_rs->flags |= (U64_LITERAL(1)<<p);
  1710. } else {
  1711. log_warn(LD_DIR, "Flags line had a flag %s not listed in known_flags.",
  1712. escaped(tok->args[i]));
  1713. goto err;
  1714. }
  1715. }
  1716. } else if (tok) {
  1717. int i;
  1718. for (i=0; i < tok->n_args; ++i) {
  1719. if (!strcmp(tok->args[i], "Exit"))
  1720. rs->is_exit = 1;
  1721. else if (!strcmp(tok->args[i], "Stable"))
  1722. rs->is_stable = 1;
  1723. else if (!strcmp(tok->args[i], "Fast"))
  1724. rs->is_fast = 1;
  1725. else if (!strcmp(tok->args[i], "Running"))
  1726. rs->is_flagged_running = 1;
  1727. else if (!strcmp(tok->args[i], "Named"))
  1728. rs->is_named = 1;
  1729. else if (!strcmp(tok->args[i], "Valid"))
  1730. rs->is_valid = 1;
  1731. else if (!strcmp(tok->args[i], "V2Dir"))
  1732. rs->is_v2_dir = 1;
  1733. else if (!strcmp(tok->args[i], "Guard"))
  1734. rs->is_possible_guard = 1;
  1735. else if (!strcmp(tok->args[i], "BadExit"))
  1736. rs->is_bad_exit = 1;
  1737. else if (!strcmp(tok->args[i], "BadDirectory"))
  1738. rs->is_bad_directory = 1;
  1739. else if (!strcmp(tok->args[i], "Authority"))
  1740. rs->is_authority = 1;
  1741. else if (!strcmp(tok->args[i], "Unnamed") &&
  1742. consensus_method >= 2) {
  1743. /* Unnamed is computed right by consensus method 2 and later. */
  1744. rs->is_unnamed = 1;
  1745. } else if (!strcmp(tok->args[i], "HSDir")) {
  1746. rs->is_hs_dir = 1;
  1747. }
  1748. }
  1749. }
  1750. if ((tok = find_opt_by_keyword(tokens, K_V))) {
  1751. tor_assert(tok->n_args == 1);
  1752. rs->version_known = 1;
  1753. if (strcmpstart(tok->args[0], "Tor ")) {
  1754. rs->version_supports_microdesc_cache = 1;
  1755. rs->version_supports_optimistic_data = 1;
  1756. } else {
  1757. rs->version_supports_microdesc_cache =
  1758. tor_version_supports_microdescriptors(tok->args[0]);
  1759. rs->version_supports_optimistic_data =
  1760. tor_version_as_new_as(tok->args[0], "0.2.3.1-alpha");
  1761. rs->version_supports_extend2_cells =
  1762. tor_version_as_new_as(tok->args[0], "0.2.4.7-alpha");
  1763. }
  1764. if (vote_rs) {
  1765. vote_rs->version = tor_strdup(tok->args[0]);
  1766. }
  1767. }
  1768. /* handle weighting/bandwidth info */
  1769. if ((tok = find_opt_by_keyword(tokens, K_W))) {
  1770. int i;
  1771. for (i=0; i < tok->n_args; ++i) {
  1772. if (!strcmpstart(tok->args[i], "Bandwidth=")) {
  1773. int ok;
  1774. rs->bandwidth = (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
  1775. 10, 0, UINT32_MAX,
  1776. &ok, NULL);
  1777. if (!ok) {
  1778. log_warn(LD_DIR, "Invalid Bandwidth %s", escaped(tok->args[i]));
  1779. goto err;
  1780. }
  1781. rs->has_bandwidth = 1;
  1782. } else if (!strcmpstart(tok->args[i], "Measured=")) {
  1783. int ok;
  1784. rs->measured_bw =
  1785. (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
  1786. 10, 0, UINT32_MAX, &ok, NULL);
  1787. if (!ok) {
  1788. log_warn(LD_DIR, "Invalid Measured Bandwidth %s",
  1789. escaped(tok->args[i]));
  1790. goto err;
  1791. }
  1792. rs->has_measured_bw = 1;
  1793. }
  1794. }
  1795. }
  1796. /* parse exit policy summaries */
  1797. if ((tok = find_opt_by_keyword(tokens, K_P))) {
  1798. tor_assert(tok->n_args == 1);
  1799. if (strcmpstart(tok->args[0], "accept ") &&
  1800. strcmpstart(tok->args[0], "reject ")) {
  1801. log_warn(LD_DIR, "Unknown exit policy summary type %s.",
  1802. escaped(tok->args[0]));
  1803. goto err;
  1804. }
  1805. /* XXX weasel: parse this into ports and represent them somehow smart,
  1806. * maybe not here but somewhere on if we need it for the client.
  1807. * we should still parse it here to check it's valid tho.
  1808. */
  1809. rs->exitsummary = tor_strdup(tok->args[0]);
  1810. rs->has_exitsummary = 1;
  1811. }
  1812. if (vote_rs) {
  1813. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, t) {
  1814. if (t->tp == K_M && t->n_args) {
  1815. vote_microdesc_hash_t *line =
  1816. tor_malloc(sizeof(vote_microdesc_hash_t));
  1817. line->next = vote_rs->microdesc;
  1818. line->microdesc_hash_line = tor_strdup(t->args[0]);
  1819. vote_rs->microdesc = line;
  1820. }
  1821. } SMARTLIST_FOREACH_END(t);
  1822. } else if (flav == FLAV_MICRODESC) {
  1823. tok = find_opt_by_keyword(tokens, K_M);
  1824. if (tok) {
  1825. tor_assert(tok->n_args);
  1826. if (digest256_from_base64(rs->descriptor_digest, tok->args[0])) {
  1827. log_warn(LD_DIR, "Error decoding microdescriptor digest %s",
  1828. escaped(tok->args[0]));
  1829. goto err;
  1830. }
  1831. } else {
  1832. log_info(LD_BUG, "Found an entry in networkstatus with no "
  1833. "microdescriptor digest. (Router %s=%s at %s:%d.)",
  1834. rs->nickname, hex_str(rs->identity_digest, DIGEST_LEN),
  1835. fmt_addr32(rs->addr), rs->or_port);
  1836. }
  1837. }
  1838. if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME))
  1839. rs->is_named = 0;
  1840. goto done;
  1841. err:
  1842. dump_desc(s_dup, "routerstatus entry");
  1843. if (rs && !vote_rs)
  1844. routerstatus_free(rs);
  1845. rs = NULL;
  1846. done:
  1847. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1848. smartlist_clear(tokens);
  1849. if (area) {
  1850. DUMP_AREA(area, "routerstatus entry");
  1851. memarea_clear(area);
  1852. }
  1853. *s = eos;
  1854. return rs;
  1855. }
  1856. /** Helper to sort a smartlist of pointers to routerstatus_t */
  1857. int
  1858. compare_routerstatus_entries(const void **_a, const void **_b)
  1859. {
  1860. const routerstatus_t *a = *_a, *b = *_b;
  1861. return fast_memcmp(a->identity_digest, b->identity_digest, DIGEST_LEN);
  1862. }
  1863. /** Helper: used in call to _smartlist_uniq to clear out duplicate entries. */
  1864. static void
  1865. free_duplicate_routerstatus_entry_(void *e)
  1866. {
  1867. log_warn(LD_DIR,
  1868. "Network-status has two entries for the same router. "
  1869. "Dropping one.");
  1870. routerstatus_free(e);
  1871. }
  1872. /** Given a v2 network-status object in <b>s</b>, try to
  1873. * parse it and return the result. Return NULL on failure. Check the
  1874. * signature of the network status, but do not (yet) check the signing key for
  1875. * authority.
  1876. */
  1877. networkstatus_v2_t *
  1878. networkstatus_v2_parse_from_string(const char *s)
  1879. {
  1880. const char *eos, *s_dup = s;
  1881. smartlist_t *tokens = smartlist_new();
  1882. smartlist_t *footer_tokens = smartlist_new();
  1883. networkstatus_v2_t *ns = NULL;
  1884. char ns_digest[DIGEST_LEN];
  1885. char tmp_digest[DIGEST_LEN];
  1886. struct in_addr in;
  1887. directory_token_t *tok;
  1888. int i;
  1889. memarea_t *area = NULL;
  1890. if (router_get_networkstatus_v2_hash(s, ns_digest)) {
  1891. log_warn(LD_DIR, "Unable to compute digest of network-status");
  1892. goto err;
  1893. }
  1894. area = memarea_new();
  1895. eos = find_start_of_next_routerstatus(s);
  1896. if (tokenize_string(area, s, eos, tokens, netstatus_token_table,0)) {
  1897. log_warn(LD_DIR, "Error tokenizing network-status header.");
  1898. goto err;
  1899. }
  1900. ns = tor_malloc_zero(sizeof(networkstatus_v2_t));
  1901. memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN);
  1902. tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
  1903. tor_assert(tok->n_args >= 1);
  1904. if (strcmp(tok->args[0], "2")) {
  1905. log_warn(LD_BUG, "Got a non-v2 networkstatus. Version was "
  1906. "%s", escaped(tok->args[0]));
  1907. goto err;
  1908. }
  1909. tok = find_by_keyword(tokens, K_DIR_SOURCE);
  1910. tor_assert(tok->n_args >= 3);
  1911. ns->source_address = tor_strdup(tok->args[0]);
  1912. if (tor_inet_aton(tok->args[1], &in) == 0) {
  1913. log_warn(LD_DIR, "Error parsing network-status source address %s",
  1914. escaped(tok->args[1]));
  1915. goto err;
  1916. }
  1917. ns->source_addr = ntohl(in.s_addr);
  1918. ns->source_dirport =
  1919. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
  1920. if (ns->source_dirport == 0) {
  1921. log_warn(LD_DIR, "Directory source without dirport; skipping.");
  1922. goto err;
  1923. }
  1924. tok = find_by_keyword(tokens, K_FINGERPRINT);
  1925. tor_assert(tok->n_args);
  1926. if (base16_decode(ns->identity_digest, DIGEST_LEN, tok->args[0],
  1927. strlen(tok->args[0]))) {
  1928. log_warn(LD_DIR, "Couldn't decode networkstatus fingerprint %s",
  1929. escaped(tok->args[0]));
  1930. goto err;
  1931. }
  1932. if ((tok = find_opt_by_keyword(tokens, K_CONTACT))) {
  1933. tor_assert(tok->n_args);
  1934. ns->contact = tor_strdup(tok->args[0]);
  1935. }
  1936. tok = find_by_keyword(tokens, K_DIR_SIGNING_KEY);
  1937. tor_assert(tok->key);
  1938. ns->signing_key = tok->key;
  1939. tok->key = NULL;
  1940. if (crypto_pk_get_digest(ns->signing_key, tmp_digest)<0) {
  1941. log_warn(LD_DIR, "Couldn't compute signing key digest");
  1942. goto err;
  1943. }
  1944. if (tor_memneq(tmp_digest, ns->identity_digest, DIGEST_LEN)) {
  1945. log_warn(LD_DIR,
  1946. "network-status fingerprint did not match dir-signing-key");
  1947. goto err;
  1948. }
  1949. if ((tok = find_opt_by_keyword(tokens, K_DIR_OPTIONS))) {
  1950. for (i=0; i < tok->n_args; ++i) {
  1951. if (!strcmp(tok->args[i], "Names"))
  1952. ns->binds_names = 1;
  1953. if (!strcmp(tok->args[i], "Versions"))
  1954. ns->recommends_versions = 1;
  1955. if (!strcmp(tok->args[i], "BadExits"))
  1956. ns->lists_bad_exits = 1;
  1957. if (!strcmp(tok->args[i], "BadDirectories"))
  1958. ns->lists_bad_directories = 1;
  1959. }
  1960. }
  1961. if (ns->recommends_versions) {
  1962. if (!(tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  1963. log_warn(LD_DIR, "Missing client-versions on versioning directory");
  1964. goto err;
  1965. }
  1966. ns->client_versions = tor_strdup(tok->args[0]);
  1967. if (!(tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS)) ||
  1968. tok->n_args<1) {
  1969. log_warn(LD_DIR, "Missing server-versions on versioning directory");
  1970. goto err;
  1971. }
  1972. ns->server_versions = tor_strdup(tok->args[0]);
  1973. }
  1974. tok = find_by_keyword(tokens, K_PUBLISHED);
  1975. tor_assert(tok->n_args == 1);
  1976. if (parse_iso_time(tok->args[0], &ns->published_on) < 0) {
  1977. goto err;
  1978. }
  1979. ns->entries = smartlist_new();
  1980. s = eos;
  1981. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1982. smartlist_clear(tokens);
  1983. memarea_clear(area);
  1984. while (!strcmpstart(s, "r ")) {
  1985. routerstatus_t *rs;
  1986. if ((rs = routerstatus_parse_entry_from_string(area, &s, tokens,
  1987. NULL, NULL, 0, 0)))
  1988. smartlist_add(ns->entries, rs);
  1989. }
  1990. smartlist_sort(ns->entries, compare_routerstatus_entries);
  1991. smartlist_uniq(ns->entries, compare_routerstatus_entries,
  1992. free_duplicate_routerstatus_entry_);
  1993. if (tokenize_string(area,s, NULL, footer_tokens, dir_footer_token_table,0)) {
  1994. log_warn(LD_DIR, "Error tokenizing network-status footer.");
  1995. goto err;
  1996. }
  1997. if (smartlist_len(footer_tokens) < 1) {
  1998. log_warn(LD_DIR, "Too few items in network-status footer.");
  1999. goto err;
  2000. }
  2001. tok = smartlist_get(footer_tokens, smartlist_len(footer_tokens)-1);
  2002. if (tok->tp != K_DIRECTORY_SIGNATURE) {
  2003. log_warn(LD_DIR,
  2004. "Expected network-status footer to end with a signature.");
  2005. goto err;
  2006. }
  2007. note_crypto_pk_op(VERIFY_DIR);
  2008. if (check_signature_token(ns_digest, DIGEST_LEN, tok, ns->signing_key, 0,
  2009. "network-status") < 0)
  2010. goto err;
  2011. goto done;
  2012. err:
  2013. dump_desc(s_dup, "v2 networkstatus");
  2014. networkstatus_v2_free(ns);
  2015. ns = NULL;
  2016. done:
  2017. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2018. smartlist_free(tokens);
  2019. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_clear(t));
  2020. smartlist_free(footer_tokens);
  2021. if (area) {
  2022. DUMP_AREA(area, "v2 networkstatus");
  2023. memarea_drop_all(area);
  2024. }
  2025. return ns;
  2026. }
  2027. /** Verify the bandwidth weights of a network status document */
  2028. int
  2029. networkstatus_verify_bw_weights(networkstatus_t *ns)
  2030. {
  2031. int64_t weight_scale;
  2032. int64_t G=0, M=0, E=0, D=0, T=0;
  2033. double Wgg, Wgm, Wgd, Wmg, Wmm, Wme, Wmd, Weg, Wem, Wee, Wed;
  2034. double Gtotal=0, Mtotal=0, Etotal=0;
  2035. const char *casename = NULL;
  2036. int valid = 1;
  2037. weight_scale = circuit_build_times_get_bw_scale(ns);
  2038. Wgg = networkstatus_get_bw_weight(ns, "Wgg", -1);
  2039. Wgm = networkstatus_get_bw_weight(ns, "Wgm", -1);
  2040. Wgd = networkstatus_get_bw_weight(ns, "Wgd", -1);
  2041. Wmg = networkstatus_get_bw_weight(ns, "Wmg", -1);
  2042. Wmm = networkstatus_get_bw_weight(ns, "Wmm", -1);
  2043. Wme = networkstatus_get_bw_weight(ns, "Wme", -1);
  2044. Wmd = networkstatus_get_bw_weight(ns, "Wmd", -1);
  2045. Weg = networkstatus_get_bw_weight(ns, "Weg", -1);
  2046. Wem = networkstatus_get_bw_weight(ns, "Wem", -1);
  2047. Wee = networkstatus_get_bw_weight(ns, "Wee", -1);
  2048. Wed = networkstatus_get_bw_weight(ns, "Wed", -1);
  2049. if (Wgg<0 || Wgm<0 || Wgd<0 || Wmg<0 || Wmm<0 || Wme<0 || Wmd<0 || Weg<0
  2050. || Wem<0 || Wee<0 || Wed<0) {
  2051. log_warn(LD_BUG, "No bandwidth weights produced in consensus!");
  2052. return 0;
  2053. }
  2054. // First, sanity check basic summing properties that hold for all cases
  2055. // We use > 1 as the check for these because they are computed as integers.
  2056. // Sometimes there are rounding errors.
  2057. if (fabs(Wmm - weight_scale) > 1) {
  2058. log_warn(LD_BUG, "Wmm=%f != "I64_FORMAT,
  2059. Wmm, I64_PRINTF_ARG(weight_scale));
  2060. valid = 0;
  2061. }
  2062. if (fabs(Wem - Wee) > 1) {
  2063. log_warn(LD_BUG, "Wem=%f != Wee=%f", Wem, Wee);
  2064. valid = 0;
  2065. }
  2066. if (fabs(Wgm - Wgg) > 1) {
  2067. log_warn(LD_BUG, "Wgm=%f != Wgg=%f", Wgm, Wgg);
  2068. valid = 0;
  2069. }
  2070. if (fabs(Weg - Wed) > 1) {
  2071. log_warn(LD_BUG, "Wed=%f != Weg=%f", Wed, Weg);
  2072. valid = 0;
  2073. }
  2074. if (fabs(Wgg + Wmg - weight_scale) > 0.001*weight_scale) {
  2075. log_warn(LD_BUG, "Wgg=%f != "I64_FORMAT" - Wmg=%f", Wgg,
  2076. I64_PRINTF_ARG(weight_scale), Wmg);
  2077. valid = 0;
  2078. }
  2079. if (fabs(Wee + Wme - weight_scale) > 0.001*weight_scale) {
  2080. log_warn(LD_BUG, "Wee=%f != "I64_FORMAT" - Wme=%f", Wee,
  2081. I64_PRINTF_ARG(weight_scale), Wme);
  2082. valid = 0;
  2083. }
  2084. if (fabs(Wgd + Wmd + Wed - weight_scale) > 0.001*weight_scale) {
  2085. log_warn(LD_BUG, "Wgd=%f + Wmd=%f + Wed=%f != "I64_FORMAT,
  2086. Wgd, Wmd, Wed, I64_PRINTF_ARG(weight_scale));
  2087. valid = 0;
  2088. }
  2089. Wgg /= weight_scale;
  2090. Wgm /= weight_scale;
  2091. Wgd /= weight_scale;
  2092. Wmg /= weight_scale;
  2093. Wmm /= weight_scale;
  2094. Wme /= weight_scale;
  2095. Wmd /= weight_scale;
  2096. Weg /= weight_scale;
  2097. Wem /= weight_scale;
  2098. Wee /= weight_scale;
  2099. Wed /= weight_scale;
  2100. // Then, gather G, M, E, D, T to determine case
  2101. SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) {
  2102. if (rs->has_bandwidth) {
  2103. T += rs->bandwidth;
  2104. if (rs->is_exit && rs->is_possible_guard) {
  2105. D += rs->bandwidth;
  2106. Gtotal += Wgd*rs->bandwidth;
  2107. Mtotal += Wmd*rs->bandwidth;
  2108. Etotal += Wed*rs->bandwidth;
  2109. } else if (rs->is_exit) {
  2110. E += rs->bandwidth;
  2111. Mtotal += Wme*rs->bandwidth;
  2112. Etotal += Wee*rs->bandwidth;
  2113. } else if (rs->is_possible_guard) {
  2114. G += rs->bandwidth;
  2115. Gtotal += Wgg*rs->bandwidth;
  2116. Mtotal += Wmg*rs->bandwidth;
  2117. } else {
  2118. M += rs->bandwidth;
  2119. Mtotal += Wmm*rs->bandwidth;
  2120. }
  2121. } else {
  2122. log_warn(LD_BUG, "Missing consensus bandwidth for router %s",
  2123. routerstatus_describe(rs));
  2124. }
  2125. } SMARTLIST_FOREACH_END(rs);
  2126. // Finally, check equality conditions depending upon case 1, 2 or 3
  2127. // Full equality cases: 1, 3b
  2128. // Partial equality cases: 2b (E=G), 3a (M=E)
  2129. // Fully unknown: 2a
  2130. if (3*E >= T && 3*G >= T) {
  2131. // Case 1: Neither are scarce
  2132. casename = "Case 1";
  2133. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  2134. log_warn(LD_DIR,
  2135. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  2136. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2137. " T="I64_FORMAT". "
  2138. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2139. casename, Etotal, Mtotal,
  2140. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2141. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2142. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2143. valid = 0;
  2144. }
  2145. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2146. log_warn(LD_DIR,
  2147. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2148. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2149. " T="I64_FORMAT". "
  2150. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2151. casename, Etotal, Gtotal,
  2152. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2153. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2154. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2155. valid = 0;
  2156. }
  2157. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  2158. log_warn(LD_DIR,
  2159. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  2160. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2161. " T="I64_FORMAT". "
  2162. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2163. casename, Mtotal, Gtotal,
  2164. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2165. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2166. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2167. valid = 0;
  2168. }
  2169. } else if (3*E < T && 3*G < T) {
  2170. int64_t R = MIN(E, G);
  2171. int64_t S = MAX(E, G);
  2172. /*
  2173. * Case 2: Both Guards and Exits are scarce
  2174. * Balance D between E and G, depending upon
  2175. * D capacity and scarcity. Devote no extra
  2176. * bandwidth to middle nodes.
  2177. */
  2178. if (R+D < S) { // Subcase a
  2179. double Rtotal, Stotal;
  2180. if (E < G) {
  2181. Rtotal = Etotal;
  2182. Stotal = Gtotal;
  2183. } else {
  2184. Rtotal = Gtotal;
  2185. Stotal = Etotal;
  2186. }
  2187. casename = "Case 2a";
  2188. // Rtotal < Stotal
  2189. if (Rtotal > Stotal) {
  2190. log_warn(LD_DIR,
  2191. "Bw Weight Failure for %s: Rtotal %f > Stotal %f. "
  2192. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2193. " T="I64_FORMAT". "
  2194. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2195. casename, Rtotal, Stotal,
  2196. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2197. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2198. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2199. valid = 0;
  2200. }
  2201. // Rtotal < T/3
  2202. if (3*Rtotal > T) {
  2203. log_warn(LD_DIR,
  2204. "Bw Weight Failure for %s: 3*Rtotal %f > T "
  2205. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
  2206. " D="I64_FORMAT" T="I64_FORMAT". "
  2207. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2208. casename, Rtotal*3, I64_PRINTF_ARG(T),
  2209. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2210. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2211. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2212. valid = 0;
  2213. }
  2214. // Stotal < T/3
  2215. if (3*Stotal > T) {
  2216. log_warn(LD_DIR,
  2217. "Bw Weight Failure for %s: 3*Stotal %f > T "
  2218. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
  2219. " D="I64_FORMAT" T="I64_FORMAT". "
  2220. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2221. casename, Stotal*3, I64_PRINTF_ARG(T),
  2222. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2223. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2224. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2225. valid = 0;
  2226. }
  2227. // Mtotal > T/3
  2228. if (3*Mtotal < T) {
  2229. log_warn(LD_DIR,
  2230. "Bw Weight Failure for %s: 3*Mtotal %f < T "
  2231. I64_FORMAT". "
  2232. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2233. " T="I64_FORMAT". "
  2234. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2235. casename, Mtotal*3, I64_PRINTF_ARG(T),
  2236. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2237. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2238. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2239. valid = 0;
  2240. }
  2241. } else { // Subcase b: R+D > S
  2242. casename = "Case 2b";
  2243. /* Check the rare-M redirect case. */
  2244. if (D != 0 && 3*M < T) {
  2245. casename = "Case 2b (balanced)";
  2246. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  2247. log_warn(LD_DIR,
  2248. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  2249. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2250. " T="I64_FORMAT". "
  2251. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2252. casename, Etotal, Mtotal,
  2253. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2254. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2255. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2256. valid = 0;
  2257. }
  2258. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2259. log_warn(LD_DIR,
  2260. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2261. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2262. " T="I64_FORMAT". "
  2263. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2264. casename, Etotal, Gtotal,
  2265. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2266. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2267. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2268. valid = 0;
  2269. }
  2270. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  2271. log_warn(LD_DIR,
  2272. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  2273. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2274. " T="I64_FORMAT". "
  2275. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2276. casename, Mtotal, Gtotal,
  2277. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2278. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2279. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2280. valid = 0;
  2281. }
  2282. } else {
  2283. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2284. log_warn(LD_DIR,
  2285. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2286. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2287. " T="I64_FORMAT". "
  2288. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2289. casename, Etotal, Gtotal,
  2290. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2291. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2292. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2293. valid = 0;
  2294. }
  2295. }
  2296. }
  2297. } else { // if (E < T/3 || G < T/3) {
  2298. int64_t S = MIN(E, G);
  2299. int64_t NS = MAX(E, G);
  2300. if (3*(S+D) < T) { // Subcase a:
  2301. double Stotal;
  2302. double NStotal;
  2303. if (G < E) {
  2304. casename = "Case 3a (G scarce)";
  2305. Stotal = Gtotal;
  2306. NStotal = Etotal;
  2307. } else { // if (G >= E) {
  2308. casename = "Case 3a (E scarce)";
  2309. NStotal = Gtotal;
  2310. Stotal = Etotal;
  2311. }
  2312. // Stotal < T/3
  2313. if (3*Stotal > T) {
  2314. log_warn(LD_DIR,
  2315. "Bw Weight Failure for %s: 3*Stotal %f > T "
  2316. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
  2317. " D="I64_FORMAT" T="I64_FORMAT". "
  2318. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2319. casename, Stotal*3, I64_PRINTF_ARG(T),
  2320. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2321. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2322. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2323. valid = 0;
  2324. }
  2325. if (NS >= M) {
  2326. if (fabs(NStotal-Mtotal) > 0.01*MAX(NStotal,Mtotal)) {
  2327. log_warn(LD_DIR,
  2328. "Bw Weight Failure for %s: NStotal %f != Mtotal %f. "
  2329. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2330. " T="I64_FORMAT". "
  2331. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2332. casename, NStotal, Mtotal,
  2333. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2334. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2335. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2336. valid = 0;
  2337. }
  2338. } else {
  2339. // if NS < M, NStotal > T/3 because only one of G or E is scarce
  2340. if (3*NStotal < T) {
  2341. log_warn(LD_DIR,
  2342. "Bw Weight Failure for %s: 3*NStotal %f < T "
  2343. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT
  2344. " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT". "
  2345. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2346. casename, NStotal*3, I64_PRINTF_ARG(T),
  2347. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2348. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2349. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2350. valid = 0;
  2351. }
  2352. }
  2353. } else { // Subcase b: S+D >= T/3
  2354. casename = "Case 3b";
  2355. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  2356. log_warn(LD_DIR,
  2357. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  2358. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2359. " T="I64_FORMAT". "
  2360. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2361. casename, Etotal, Mtotal,
  2362. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2363. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2364. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2365. valid = 0;
  2366. }
  2367. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2368. log_warn(LD_DIR,
  2369. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2370. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2371. " T="I64_FORMAT". "
  2372. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2373. casename, Etotal, Gtotal,
  2374. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2375. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2376. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2377. valid = 0;
  2378. }
  2379. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  2380. log_warn(LD_DIR,
  2381. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  2382. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2383. " T="I64_FORMAT". "
  2384. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2385. casename, Mtotal, Gtotal,
  2386. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2387. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2388. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2389. valid = 0;
  2390. }
  2391. }
  2392. }
  2393. if (valid)
  2394. log_notice(LD_DIR, "Bandwidth-weight %s is verified and valid.",
  2395. casename);
  2396. return valid;
  2397. }
  2398. /** Parse a v3 networkstatus vote, opinion, or consensus (depending on
  2399. * ns_type), from <b>s</b>, and return the result. Return NULL on failure. */
  2400. networkstatus_t *
  2401. networkstatus_parse_vote_from_string(const char *s, const char **eos_out,
  2402. networkstatus_type_t ns_type)
  2403. {
  2404. smartlist_t *tokens = smartlist_new();
  2405. smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;
  2406. networkstatus_voter_info_t *voter = NULL;
  2407. networkstatus_t *ns = NULL;
  2408. digests_t ns_digests;
  2409. const char *cert, *end_of_header, *end_of_footer, *s_dup = s;
  2410. directory_token_t *tok;
  2411. int ok;
  2412. struct in_addr in;
  2413. int i, inorder, n_signatures = 0;
  2414. memarea_t *area = NULL, *rs_area = NULL;
  2415. consensus_flavor_t flav = FLAV_NS;
  2416. char *last_kwd=NULL;
  2417. tor_assert(s);
  2418. if (eos_out)
  2419. *eos_out = NULL;
  2420. if (router_get_networkstatus_v3_hashes(s, &ns_digests)) {
  2421. log_warn(LD_DIR, "Unable to compute digest of network-status");
  2422. goto err;
  2423. }
  2424. area = memarea_new();
  2425. end_of_header = find_start_of_next_routerstatus(s);
  2426. if (tokenize_string(area, s, end_of_header, tokens,
  2427. (ns_type == NS_TYPE_CONSENSUS) ?
  2428. networkstatus_consensus_token_table :
  2429. networkstatus_token_table, 0)) {
  2430. log_warn(LD_DIR, "Error tokenizing network-status vote header");
  2431. goto err;
  2432. }
  2433. ns = tor_malloc_zero(sizeof(networkstatus_t));
  2434. memcpy(&ns->digests, &ns_digests, sizeof(ns_digests));
  2435. tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
  2436. tor_assert(tok);
  2437. if (tok->n_args > 1) {
  2438. int flavor = networkstatus_parse_flavor_name(tok->args[1]);
  2439. if (flavor < 0) {
  2440. log_warn(LD_DIR, "Can't parse document with unknown flavor %s",
  2441. escaped(tok->args[1]));
  2442. goto err;
  2443. }
  2444. ns->flavor = flav = flavor;
  2445. }
  2446. if (flav != FLAV_NS && ns_type != NS_TYPE_CONSENSUS) {
  2447. log_warn(LD_DIR, "Flavor found on non-consensus networkstatus.");
  2448. goto err;
  2449. }
  2450. if (ns_type != NS_TYPE_CONSENSUS) {
  2451. const char *end_of_cert = NULL;
  2452. if (!(cert = strstr(s, "\ndir-key-certificate-version")))
  2453. goto err;
  2454. ++cert;
  2455. ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);
  2456. if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)
  2457. goto err;
  2458. }
  2459. tok = find_by_keyword(tokens, K_VOTE_STATUS);
  2460. tor_assert(tok->n_args);
  2461. if (!strcmp(tok->args[0], "vote")) {
  2462. ns->type = NS_TYPE_VOTE;
  2463. } else if (!strcmp(tok->args[0], "consensus")) {
  2464. ns->type = NS_TYPE_CONSENSUS;
  2465. } else if (!strcmp(tok->args[0], "opinion")) {
  2466. ns->type = NS_TYPE_OPINION;
  2467. } else {
  2468. log_warn(LD_DIR, "Unrecognized vote status %s in network-status",
  2469. escaped(tok->args[0]));
  2470. goto err;
  2471. }
  2472. if (ns_type != ns->type) {
  2473. log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus.");
  2474. goto err;
  2475. }
  2476. if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
  2477. tok = find_by_keyword(tokens, K_PUBLISHED);
  2478. if (parse_iso_time(tok->args[0], &ns->published))
  2479. goto err;
  2480. ns->supported_methods = smartlist_new();
  2481. tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHODS);
  2482. if (tok) {
  2483. for (i=0; i < tok->n_args; ++i)
  2484. smartlist_add(ns->supported_methods, tor_strdup(tok->args[i]));
  2485. } else {
  2486. smartlist_add(ns->supported_methods, tor_strdup("1"));
  2487. }
  2488. } else {
  2489. tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHOD);
  2490. if (tok) {
  2491. ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX,
  2492. &ok, NULL);
  2493. if (!ok)
  2494. goto err;
  2495. } else {
  2496. ns->consensus_method = 1;
  2497. }
  2498. }
  2499. tok = find_by_keyword(tokens, K_VALID_AFTER);
  2500. if (parse_iso_time(tok->args[0], &ns->valid_after))
  2501. goto err;
  2502. tok = find_by_keyword(tokens, K_FRESH_UNTIL);
  2503. if (parse_iso_time(tok->args[0], &ns->fresh_until))
  2504. goto err;
  2505. tok = find_by_keyword(tokens, K_VALID_UNTIL);
  2506. if (parse_iso_time(tok->args[0], &ns->valid_until))
  2507. goto err;
  2508. tok = find_by_keyword(tokens, K_VOTING_DELAY);
  2509. tor_assert(tok->n_args >= 2);
  2510. ns->vote_seconds =
  2511. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);
  2512. if (!ok)
  2513. goto err;
  2514. ns->dist_seconds =
  2515. (int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL);
  2516. if (!ok)
  2517. goto err;
  2518. if (ns->valid_after + MIN_VOTE_INTERVAL > ns->fresh_until) {
  2519. log_warn(LD_DIR, "Vote/consensus freshness interval is too short");
  2520. goto err;
  2521. }
  2522. if (ns->valid_after + MIN_VOTE_INTERVAL*2 > ns->valid_until) {
  2523. log_warn(LD_DIR, "Vote/consensus liveness interval is too short");
  2524. goto err;
  2525. }
  2526. if (ns->vote_seconds < MIN_VOTE_SECONDS) {
  2527. log_warn(LD_DIR, "Vote seconds is too short");
  2528. goto err;
  2529. }
  2530. if (ns->dist_seconds < MIN_DIST_SECONDS) {
  2531. log_warn(LD_DIR, "Dist seconds is too short");
  2532. goto err;
  2533. }
  2534. if ((tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  2535. ns->client_versions = tor_strdup(tok->args[0]);
  2536. }
  2537. if ((tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS))) {
  2538. ns->server_versions = tor_strdup(tok->args[0]);
  2539. }
  2540. tok = find_by_keyword(tokens, K_KNOWN_FLAGS);
  2541. ns->known_flags = smartlist_new();
  2542. inorder = 1;
  2543. for (i = 0; i < tok->n_args; ++i) {
  2544. smartlist_add(ns->known_flags, tor_strdup(tok->args[i]));
  2545. if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) {
  2546. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  2547. inorder = 0;
  2548. }
  2549. }
  2550. if (!inorder) {
  2551. log_warn(LD_DIR, "known-flags not in order");
  2552. goto err;
  2553. }
  2554. if (ns->type != NS_TYPE_CONSENSUS &&
  2555. smartlist_len(ns->known_flags) > MAX_KNOWN_FLAGS_IN_VOTE) {
  2556. /* If we allowed more than 64 flags in votes, then parsing them would make
  2557. * us invoke undefined behavior whenever we used 1<<flagnum to do a
  2558. * bit-shift. This is only for votes and opinions: consensus users don't
  2559. * care about flags they don't recognize, and so don't build a bitfield
  2560. * for them. */
  2561. log_warn(LD_DIR, "Too many known-flags in consensus vote or opinion");
  2562. goto err;
  2563. }
  2564. tok = find_opt_by_keyword(tokens, K_PARAMS);
  2565. if (tok) {
  2566. int any_dups = 0;
  2567. inorder = 1;
  2568. ns->net_params = smartlist_new();
  2569. for (i = 0; i < tok->n_args; ++i) {
  2570. int ok=0;
  2571. char *eq = strchr(tok->args[i], '=');
  2572. size_t eq_pos;
  2573. if (!eq) {
  2574. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  2575. goto err;
  2576. }
  2577. eq_pos = eq-tok->args[i];
  2578. tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
  2579. if (!ok) {
  2580. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  2581. goto err;
  2582. }
  2583. if (i > 0 && strcmp(tok->args[i-1], tok->args[i]) >= 0) {
  2584. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  2585. inorder = 0;
  2586. }
  2587. if (last_kwd && eq_pos == strlen(last_kwd) &&
  2588. fast_memeq(last_kwd, tok->args[i], eq_pos)) {
  2589. log_warn(LD_DIR, "Duplicate value for %s parameter",
  2590. escaped(tok->args[i]));
  2591. any_dups = 1;
  2592. }
  2593. tor_free(last_kwd);
  2594. last_kwd = tor_strndup(tok->args[i], eq_pos);
  2595. smartlist_add(ns->net_params, tor_strdup(tok->args[i]));
  2596. }
  2597. if (!inorder) {
  2598. log_warn(LD_DIR, "params not in order");
  2599. goto err;
  2600. }
  2601. if (any_dups) {
  2602. log_warn(LD_DIR, "Duplicate in parameters");
  2603. goto err;
  2604. }
  2605. }
  2606. ns->voters = smartlist_new();
  2607. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  2608. tok = _tok;
  2609. if (tok->tp == K_DIR_SOURCE) {
  2610. tor_assert(tok->n_args >= 6);
  2611. if (voter)
  2612. smartlist_add(ns->voters, voter);
  2613. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  2614. voter->sigs = smartlist_new();
  2615. if (ns->type != NS_TYPE_CONSENSUS)
  2616. memcpy(voter->vote_digest, ns_digests.d[DIGEST_SHA1], DIGEST_LEN);
  2617. voter->nickname = tor_strdup(tok->args[0]);
  2618. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  2619. base16_decode(voter->identity_digest, sizeof(voter->identity_digest),
  2620. tok->args[1], HEX_DIGEST_LEN) < 0) {
  2621. log_warn(LD_DIR, "Error decoding identity digest %s in "
  2622. "network-status vote.", escaped(tok->args[1]));
  2623. goto err;
  2624. }
  2625. if (ns->type != NS_TYPE_CONSENSUS &&
  2626. tor_memneq(ns->cert->cache_info.identity_digest,
  2627. voter->identity_digest, DIGEST_LEN)) {
  2628. log_warn(LD_DIR,"Mismatch between identities in certificate and vote");
  2629. goto err;
  2630. }
  2631. voter->address = tor_strdup(tok->args[2]);
  2632. if (!tor_inet_aton(tok->args[3], &in)) {
  2633. log_warn(LD_DIR, "Error decoding IP address %s in network-status.",
  2634. escaped(tok->args[3]));
  2635. goto err;
  2636. }
  2637. voter->addr = ntohl(in.s_addr);
  2638. voter->dir_port = (uint16_t)
  2639. tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);
  2640. if (!ok)
  2641. goto err;
  2642. voter->or_port = (uint16_t)
  2643. tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);
  2644. if (!ok)
  2645. goto err;
  2646. } else if (tok->tp == K_CONTACT) {
  2647. if (!voter || voter->contact) {
  2648. log_warn(LD_DIR, "contact element is out of place.");
  2649. goto err;
  2650. }
  2651. voter->contact = tor_strdup(tok->args[0]);
  2652. } else if (tok->tp == K_VOTE_DIGEST) {
  2653. tor_assert(ns->type == NS_TYPE_CONSENSUS);
  2654. tor_assert(tok->n_args >= 1);
  2655. if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {
  2656. log_warn(LD_DIR, "vote-digest element is out of place.");
  2657. goto err;
  2658. }
  2659. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  2660. base16_decode(voter->vote_digest, sizeof(voter->vote_digest),
  2661. tok->args[0], HEX_DIGEST_LEN) < 0) {
  2662. log_warn(LD_DIR, "Error decoding vote digest %s in "
  2663. "network-status consensus.", escaped(tok->args[0]));
  2664. goto err;
  2665. }
  2666. }
  2667. } SMARTLIST_FOREACH_END(_tok);
  2668. if (voter) {
  2669. smartlist_add(ns->voters, voter);
  2670. voter = NULL;
  2671. }
  2672. if (smartlist_len(ns->voters) == 0) {
  2673. log_warn(LD_DIR, "Missing dir-source elements in a vote networkstatus.");
  2674. goto err;
  2675. } else if (ns->type != NS_TYPE_CONSENSUS && smartlist_len(ns->voters) != 1) {
  2676. log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus.");
  2677. goto err;
  2678. }
  2679. if (ns->type != NS_TYPE_CONSENSUS &&
  2680. (tok = find_opt_by_keyword(tokens, K_LEGACY_DIR_KEY))) {
  2681. int bad = 1;
  2682. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  2683. networkstatus_voter_info_t *voter = smartlist_get(ns->voters, 0);
  2684. if (base16_decode(voter->legacy_id_digest, DIGEST_LEN,
  2685. tok->args[0], HEX_DIGEST_LEN)<0)
  2686. bad = 1;
  2687. else
  2688. bad = 0;
  2689. }
  2690. if (bad) {
  2691. log_warn(LD_DIR, "Invalid legacy key digest %s on vote.",
  2692. escaped(tok->args[0]));
  2693. }
  2694. }
  2695. /* Parse routerstatus lines. */
  2696. rs_tokens = smartlist_new();
  2697. rs_area = memarea_new();
  2698. s = end_of_header;
  2699. ns->routerstatus_list = smartlist_new();
  2700. while (!strcmpstart(s, "r ")) {
  2701. if (ns->type != NS_TYPE_CONSENSUS) {
  2702. vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  2703. if (routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, ns,
  2704. rs, 0, 0))
  2705. smartlist_add(ns->routerstatus_list, rs);
  2706. else {
  2707. tor_free(rs->version);
  2708. tor_free(rs);
  2709. }
  2710. } else {
  2711. routerstatus_t *rs;
  2712. if ((rs = routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens,
  2713. NULL, NULL,
  2714. ns->consensus_method,
  2715. flav)))
  2716. smartlist_add(ns->routerstatus_list, rs);
  2717. }
  2718. }
  2719. for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {
  2720. routerstatus_t *rs1, *rs2;
  2721. if (ns->type != NS_TYPE_CONSENSUS) {
  2722. vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);
  2723. vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);
  2724. rs1 = &a->status; rs2 = &b->status;
  2725. } else {
  2726. rs1 = smartlist_get(ns->routerstatus_list, i-1);
  2727. rs2 = smartlist_get(ns->routerstatus_list, i);
  2728. }
  2729. if (fast_memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN)
  2730. >= 0) {
  2731. log_warn(LD_DIR, "Vote networkstatus entries not sorted by identity "
  2732. "digest");
  2733. goto err;
  2734. }
  2735. }
  2736. /* Parse footer; check signature. */
  2737. footer_tokens = smartlist_new();
  2738. if ((end_of_footer = strstr(s, "\nnetwork-status-version ")))
  2739. ++end_of_footer;
  2740. else
  2741. end_of_footer = s + strlen(s);
  2742. if (tokenize_string(area,s, end_of_footer, footer_tokens,
  2743. networkstatus_vote_footer_token_table, 0)) {
  2744. log_warn(LD_DIR, "Error tokenizing network-status vote footer.");
  2745. goto err;
  2746. }
  2747. {
  2748. int found_sig = 0;
  2749. SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
  2750. tok = _tok;
  2751. if (tok->tp == K_DIRECTORY_SIGNATURE)
  2752. found_sig = 1;
  2753. else if (found_sig) {
  2754. log_warn(LD_DIR, "Extraneous token after first directory-signature");
  2755. goto err;
  2756. }
  2757. } SMARTLIST_FOREACH_END(_tok);
  2758. }
  2759. if ((tok = find_opt_by_keyword(footer_tokens, K_DIRECTORY_FOOTER))) {
  2760. if (tok != smartlist_get(footer_tokens, 0)) {
  2761. log_warn(LD_DIR, "Misplaced directory-footer token");
  2762. goto err;
  2763. }
  2764. }
  2765. tok = find_opt_by_keyword(footer_tokens, K_BW_WEIGHTS);
  2766. if (tok) {
  2767. ns->weight_params = smartlist_new();
  2768. for (i = 0; i < tok->n_args; ++i) {
  2769. int ok=0;
  2770. char *eq = strchr(tok->args[i], '=');
  2771. if (!eq) {
  2772. log_warn(LD_DIR, "Bad element '%s' in weight params",
  2773. escaped(tok->args[i]));
  2774. goto err;
  2775. }
  2776. tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
  2777. if (!ok) {
  2778. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  2779. goto err;
  2780. }
  2781. smartlist_add(ns->weight_params, tor_strdup(tok->args[i]));
  2782. }
  2783. }
  2784. SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
  2785. char declared_identity[DIGEST_LEN];
  2786. networkstatus_voter_info_t *v;
  2787. document_signature_t *sig;
  2788. const char *id_hexdigest = NULL;
  2789. const char *sk_hexdigest = NULL;
  2790. digest_algorithm_t alg = DIGEST_SHA1;
  2791. tok = _tok;
  2792. if (tok->tp != K_DIRECTORY_SIGNATURE)
  2793. continue;
  2794. tor_assert(tok->n_args >= 2);
  2795. if (tok->n_args == 2) {
  2796. id_hexdigest = tok->args[0];
  2797. sk_hexdigest = tok->args[1];
  2798. } else {
  2799. const char *algname = tok->args[0];
  2800. int a;
  2801. id_hexdigest = tok->args[1];
  2802. sk_hexdigest = tok->args[2];
  2803. a = crypto_digest_algorithm_parse_name(algname);
  2804. if (a<0) {
  2805. log_warn(LD_DIR, "Unknown digest algorithm %s; skipping",
  2806. escaped(algname));
  2807. continue;
  2808. }
  2809. alg = a;
  2810. }
  2811. if (!tok->object_type ||
  2812. strcmp(tok->object_type, "SIGNATURE") ||
  2813. tok->object_size < 128 || tok->object_size > 512) {
  2814. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  2815. goto err;
  2816. }
  2817. if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
  2818. base16_decode(declared_identity, sizeof(declared_identity),
  2819. id_hexdigest, HEX_DIGEST_LEN) < 0) {
  2820. log_warn(LD_DIR, "Error decoding declared identity %s in "
  2821. "network-status vote.", escaped(id_hexdigest));
  2822. goto err;
  2823. }
  2824. if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {
  2825. log_warn(LD_DIR, "ID on signature on network-status vote does not match "
  2826. "any declared directory source.");
  2827. goto err;
  2828. }
  2829. sig = tor_malloc_zero(sizeof(document_signature_t));
  2830. memcpy(sig->identity_digest, v->identity_digest, DIGEST_LEN);
  2831. sig->alg = alg;
  2832. if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
  2833. base16_decode(sig->signing_key_digest, sizeof(sig->signing_key_digest),
  2834. sk_hexdigest, HEX_DIGEST_LEN) < 0) {
  2835. log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
  2836. "network-status vote.", escaped(sk_hexdigest));
  2837. tor_free(sig);
  2838. goto err;
  2839. }
  2840. if (ns->type != NS_TYPE_CONSENSUS) {
  2841. if (tor_memneq(declared_identity, ns->cert->cache_info.identity_digest,
  2842. DIGEST_LEN)) {
  2843. log_warn(LD_DIR, "Digest mismatch between declared and actual on "
  2844. "network-status vote.");
  2845. tor_free(sig);
  2846. goto err;
  2847. }
  2848. }
  2849. if (voter_get_sig_by_algorithm(v, sig->alg)) {
  2850. /* We already parsed a vote with this algorithm from this voter. Use the
  2851. first one. */
  2852. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "We received a networkstatus "
  2853. "that contains two votes from the same voter with the same "
  2854. "algorithm. Ignoring the second vote.");
  2855. tor_free(sig);
  2856. continue;
  2857. }
  2858. if (ns->type != NS_TYPE_CONSENSUS) {
  2859. if (check_signature_token(ns_digests.d[DIGEST_SHA1], DIGEST_LEN,
  2860. tok, ns->cert->signing_key, 0,
  2861. "network-status vote")) {
  2862. tor_free(sig);
  2863. goto err;
  2864. }
  2865. sig->good_signature = 1;
  2866. } else {
  2867. if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
  2868. tor_free(sig);
  2869. goto err;
  2870. }
  2871. sig->signature = tor_memdup(tok->object_body, tok->object_size);
  2872. sig->signature_len = (int) tok->object_size;
  2873. }
  2874. smartlist_add(v->sigs, sig);
  2875. ++n_signatures;
  2876. } SMARTLIST_FOREACH_END(_tok);
  2877. if (! n_signatures) {
  2878. log_warn(LD_DIR, "No signatures on networkstatus vote.");
  2879. goto err;
  2880. } else if (ns->type == NS_TYPE_VOTE && n_signatures != 1) {
  2881. log_warn(LD_DIR, "Received more than one signature on a "
  2882. "network-status vote.");
  2883. goto err;
  2884. }
  2885. if (eos_out)
  2886. *eos_out = end_of_footer;
  2887. goto done;
  2888. err:
  2889. dump_desc(s_dup, "v3 networkstatus");
  2890. networkstatus_vote_free(ns);
  2891. ns = NULL;
  2892. done:
  2893. if (tokens) {
  2894. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2895. smartlist_free(tokens);
  2896. }
  2897. if (voter) {
  2898. if (voter->sigs) {
  2899. SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
  2900. document_signature_free(sig));
  2901. smartlist_free(voter->sigs);
  2902. }
  2903. tor_free(voter->nickname);
  2904. tor_free(voter->address);
  2905. tor_free(voter->contact);
  2906. tor_free(voter);
  2907. }
  2908. if (rs_tokens) {
  2909. SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_clear(t));
  2910. smartlist_free(rs_tokens);
  2911. }
  2912. if (footer_tokens) {
  2913. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_clear(t));
  2914. smartlist_free(footer_tokens);
  2915. }
  2916. if (area) {
  2917. DUMP_AREA(area, "v3 networkstatus");
  2918. memarea_drop_all(area);
  2919. }
  2920. if (rs_area)
  2921. memarea_drop_all(rs_area);
  2922. tor_free(last_kwd);
  2923. return ns;
  2924. }
  2925. /** Return the digests_t that holds the digests of the
  2926. * <b>flavor_name</b>-flavored networkstatus according to the detached
  2927. * signatures document <b>sigs</b>, allocating a new digests_t as neeeded. */
  2928. static digests_t *
  2929. detached_get_digests(ns_detached_signatures_t *sigs, const char *flavor_name)
  2930. {
  2931. digests_t *d = strmap_get(sigs->digests, flavor_name);
  2932. if (!d) {
  2933. d = tor_malloc_zero(sizeof(digests_t));
  2934. strmap_set(sigs->digests, flavor_name, d);
  2935. }
  2936. return d;
  2937. }
  2938. /** Return the list of signatures of the <b>flavor_name</b>-flavored
  2939. * networkstatus according to the detached signatures document <b>sigs</b>,
  2940. * allocating a new digests_t as neeeded. */
  2941. static smartlist_t *
  2942. detached_get_signatures(ns_detached_signatures_t *sigs,
  2943. const char *flavor_name)
  2944. {
  2945. smartlist_t *sl = strmap_get(sigs->signatures, flavor_name);
  2946. if (!sl) {
  2947. sl = smartlist_new();
  2948. strmap_set(sigs->signatures, flavor_name, sl);
  2949. }
  2950. return sl;
  2951. }
  2952. /** Parse a detached v3 networkstatus signature document between <b>s</b> and
  2953. * <b>eos</b> and return the result. Return -1 on failure. */
  2954. ns_detached_signatures_t *
  2955. networkstatus_parse_detached_signatures(const char *s, const char *eos)
  2956. {
  2957. /* XXXX there is too much duplicate shared between this function and
  2958. * networkstatus_parse_vote_from_string(). */
  2959. directory_token_t *tok;
  2960. memarea_t *area = NULL;
  2961. digests_t *digests;
  2962. smartlist_t *tokens = smartlist_new();
  2963. ns_detached_signatures_t *sigs =
  2964. tor_malloc_zero(sizeof(ns_detached_signatures_t));
  2965. sigs->digests = strmap_new();
  2966. sigs->signatures = strmap_new();
  2967. if (!eos)
  2968. eos = s + strlen(s);
  2969. area = memarea_new();
  2970. if (tokenize_string(area,s, eos, tokens,
  2971. networkstatus_detached_signature_token_table, 0)) {
  2972. log_warn(LD_DIR, "Error tokenizing detached networkstatus signatures");
  2973. goto err;
  2974. }
  2975. /* Grab all the digest-like tokens. */
  2976. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  2977. const char *algname;
  2978. digest_algorithm_t alg;
  2979. const char *flavor;
  2980. const char *hexdigest;
  2981. size_t expected_length;
  2982. tok = _tok;
  2983. if (tok->tp == K_CONSENSUS_DIGEST) {
  2984. algname = "sha1";
  2985. alg = DIGEST_SHA1;
  2986. flavor = "ns";
  2987. hexdigest = tok->args[0];
  2988. } else if (tok->tp == K_ADDITIONAL_DIGEST) {
  2989. int a = crypto_digest_algorithm_parse_name(tok->args[1]);
  2990. if (a<0) {
  2991. log_warn(LD_DIR, "Unrecognized algorithm name %s", tok->args[0]);
  2992. continue;
  2993. }
  2994. alg = (digest_algorithm_t) a;
  2995. flavor = tok->args[0];
  2996. algname = tok->args[1];
  2997. hexdigest = tok->args[2];
  2998. } else {
  2999. continue;
  3000. }
  3001. expected_length =
  3002. (alg == DIGEST_SHA1) ? HEX_DIGEST_LEN : HEX_DIGEST256_LEN;
  3003. if (strlen(hexdigest) != expected_length) {
  3004. log_warn(LD_DIR, "Wrong length on consensus-digest in detached "
  3005. "networkstatus signatures");
  3006. goto err;
  3007. }
  3008. digests = detached_get_digests(sigs, flavor);
  3009. tor_assert(digests);
  3010. if (!tor_mem_is_zero(digests->d[alg], DIGEST256_LEN)) {
  3011. log_warn(LD_DIR, "Multiple digests for %s with %s on detached "
  3012. "signatures document", flavor, algname);
  3013. continue;
  3014. }
  3015. if (base16_decode(digests->d[alg], DIGEST256_LEN,
  3016. hexdigest, strlen(hexdigest)) < 0) {
  3017. log_warn(LD_DIR, "Bad encoding on consensus-digest in detached "
  3018. "networkstatus signatures");
  3019. goto err;
  3020. }
  3021. } SMARTLIST_FOREACH_END(_tok);
  3022. tok = find_by_keyword(tokens, K_VALID_AFTER);
  3023. if (parse_iso_time(tok->args[0], &sigs->valid_after)) {
  3024. log_warn(LD_DIR, "Bad valid-after in detached networkstatus signatures");
  3025. goto err;
  3026. }
  3027. tok = find_by_keyword(tokens, K_FRESH_UNTIL);
  3028. if (parse_iso_time(tok->args[0], &sigs->fresh_until)) {
  3029. log_warn(LD_DIR, "Bad fresh-until in detached networkstatus signatures");
  3030. goto err;
  3031. }
  3032. tok = find_by_keyword(tokens, K_VALID_UNTIL);
  3033. if (parse_iso_time(tok->args[0], &sigs->valid_until)) {
  3034. log_warn(LD_DIR, "Bad valid-until in detached networkstatus signatures");
  3035. goto err;
  3036. }
  3037. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  3038. const char *id_hexdigest;
  3039. const char *sk_hexdigest;
  3040. const char *algname;
  3041. const char *flavor;
  3042. digest_algorithm_t alg;
  3043. char id_digest[DIGEST_LEN];
  3044. char sk_digest[DIGEST_LEN];
  3045. smartlist_t *siglist;
  3046. document_signature_t *sig;
  3047. int is_duplicate;
  3048. tok = _tok;
  3049. if (tok->tp == K_DIRECTORY_SIGNATURE) {
  3050. tor_assert(tok->n_args >= 2);
  3051. flavor = "ns";
  3052. algname = "sha1";
  3053. id_hexdigest = tok->args[0];
  3054. sk_hexdigest = tok->args[1];
  3055. } else if (tok->tp == K_ADDITIONAL_SIGNATURE) {
  3056. tor_assert(tok->n_args >= 4);
  3057. flavor = tok->args[0];
  3058. algname = tok->args[1];
  3059. id_hexdigest = tok->args[2];
  3060. sk_hexdigest = tok->args[3];
  3061. } else {
  3062. continue;
  3063. }
  3064. {
  3065. int a = crypto_digest_algorithm_parse_name(algname);
  3066. if (a<0) {
  3067. log_warn(LD_DIR, "Unrecognized algorithm name %s", algname);
  3068. continue;
  3069. }
  3070. alg = (digest_algorithm_t) a;
  3071. }
  3072. if (!tok->object_type ||
  3073. strcmp(tok->object_type, "SIGNATURE") ||
  3074. tok->object_size < 128 || tok->object_size > 512) {
  3075. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  3076. goto err;
  3077. }
  3078. if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
  3079. base16_decode(id_digest, sizeof(id_digest),
  3080. id_hexdigest, HEX_DIGEST_LEN) < 0) {
  3081. log_warn(LD_DIR, "Error decoding declared identity %s in "
  3082. "network-status vote.", escaped(id_hexdigest));
  3083. goto err;
  3084. }
  3085. if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
  3086. base16_decode(sk_digest, sizeof(sk_digest),
  3087. sk_hexdigest, HEX_DIGEST_LEN) < 0) {
  3088. log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
  3089. "network-status vote.", escaped(sk_hexdigest));
  3090. goto err;
  3091. }
  3092. siglist = detached_get_signatures(sigs, flavor);
  3093. is_duplicate = 0;
  3094. SMARTLIST_FOREACH(siglist, document_signature_t *, dsig, {
  3095. if (dsig->alg == alg &&
  3096. tor_memeq(id_digest, dsig->identity_digest, DIGEST_LEN) &&
  3097. tor_memeq(sk_digest, dsig->signing_key_digest, DIGEST_LEN)) {
  3098. is_duplicate = 1;
  3099. }
  3100. });
  3101. if (is_duplicate) {
  3102. log_warn(LD_DIR, "Two signatures with identical keys and algorithm "
  3103. "found.");
  3104. continue;
  3105. }
  3106. sig = tor_malloc_zero(sizeof(document_signature_t));
  3107. sig->alg = alg;
  3108. memcpy(sig->identity_digest, id_digest, DIGEST_LEN);
  3109. memcpy(sig->signing_key_digest, sk_digest, DIGEST_LEN);
  3110. if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
  3111. tor_free(sig);
  3112. goto err;
  3113. }
  3114. sig->signature = tor_memdup(tok->object_body, tok->object_size);
  3115. sig->signature_len = (int) tok->object_size;
  3116. smartlist_add(siglist, sig);
  3117. } SMARTLIST_FOREACH_END(_tok);
  3118. goto done;
  3119. err:
  3120. ns_detached_signatures_free(sigs);
  3121. sigs = NULL;
  3122. done:
  3123. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  3124. smartlist_free(tokens);
  3125. if (area) {
  3126. DUMP_AREA(area, "detached signatures");
  3127. memarea_drop_all(area);
  3128. }
  3129. return sigs;
  3130. }
  3131. /** Parse the addr policy in the string <b>s</b> and return it. If
  3132. * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
  3133. * ADDR_POLICY_REJECT) for items that specify no action.
  3134. *
  3135. * The addr_policy_t returned by this function can have its address set to
  3136. * AF_UNSPEC for '*'. Use policy_expand_unspec() to turn this into a pair
  3137. * of AF_INET and AF_INET6 items.
  3138. */
  3139. addr_policy_t *
  3140. router_parse_addr_policy_item_from_string(const char *s, int assume_action)
  3141. {
  3142. directory_token_t *tok = NULL;
  3143. const char *cp, *eos;
  3144. /* Longest possible policy is "accept ffff:ffff:..255/ffff:...255:0-65535".
  3145. * But note that there can be an arbitrary amount of space between the
  3146. * accept and the address:mask/port element. */
  3147. char line[TOR_ADDR_BUF_LEN*2 + 32];
  3148. addr_policy_t *r;
  3149. memarea_t *area = NULL;
  3150. s = eat_whitespace(s);
  3151. if ((*s == '*' || TOR_ISDIGIT(*s)) && assume_action >= 0) {
  3152. if (tor_snprintf(line, sizeof(line), "%s %s",
  3153. assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", s)<0) {
  3154. log_warn(LD_DIR, "Policy %s is too long.", escaped(s));
  3155. return NULL;
  3156. }
  3157. cp = line;
  3158. tor_strlower(line);
  3159. } else { /* assume an already well-formed address policy line */
  3160. cp = s;
  3161. }
  3162. eos = cp + strlen(cp);
  3163. area = memarea_new();
  3164. tok = get_next_token(area, &cp, eos, routerdesc_token_table);
  3165. if (tok->tp == ERR_) {
  3166. log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
  3167. goto err;
  3168. }
  3169. if (tok->tp != K_ACCEPT && tok->tp != K_ACCEPT6 &&
  3170. tok->tp != K_REJECT && tok->tp != K_REJECT6) {
  3171. log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
  3172. goto err;
  3173. }
  3174. r = router_parse_addr_policy(tok, TAPMP_EXTENDED_STAR);
  3175. goto done;
  3176. err:
  3177. r = NULL;
  3178. done:
  3179. token_clear(tok);
  3180. if (area) {
  3181. DUMP_AREA(area, "policy item");
  3182. memarea_drop_all(area);
  3183. }
  3184. return r;
  3185. }
  3186. /** Add an exit policy stored in the token <b>tok</b> to the router info in
  3187. * <b>router</b>. Return 0 on success, -1 on failure. */
  3188. static int
  3189. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
  3190. {
  3191. addr_policy_t *newe;
  3192. newe = router_parse_addr_policy(tok, 0);
  3193. if (!newe)
  3194. return -1;
  3195. if (! router->exit_policy)
  3196. router->exit_policy = smartlist_new();
  3197. if (((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  3198. tor_addr_family(&newe->addr) == AF_INET)
  3199. ||
  3200. ((tok->tp == K_ACCEPT || tok->tp == K_REJECT) &&
  3201. tor_addr_family(&newe->addr) == AF_INET6)) {
  3202. log_warn(LD_DIR, "Mismatch between field type and address type in exit "
  3203. "policy");
  3204. addr_policy_free(newe);
  3205. return -1;
  3206. }
  3207. smartlist_add(router->exit_policy, newe);
  3208. return 0;
  3209. }
  3210. /** Given a K_ACCEPT or K_REJECT token and a router, create and return
  3211. * a new exit_policy_t corresponding to the token. */
  3212. static addr_policy_t *
  3213. router_parse_addr_policy(directory_token_t *tok, unsigned fmt_flags)
  3214. {
  3215. addr_policy_t newe;
  3216. char *arg;
  3217. tor_assert(tok->tp == K_REJECT || tok->tp == K_REJECT6 ||
  3218. tok->tp == K_ACCEPT || tok->tp == K_ACCEPT6);
  3219. if (tok->n_args != 1)
  3220. return NULL;
  3221. arg = tok->args[0];
  3222. if (!strcmpstart(arg,"private"))
  3223. return router_parse_addr_policy_private(tok);
  3224. memset(&newe, 0, sizeof(newe));
  3225. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  3226. newe.policy_type = ADDR_POLICY_REJECT;
  3227. else
  3228. newe.policy_type = ADDR_POLICY_ACCEPT;
  3229. if (tor_addr_parse_mask_ports(arg, fmt_flags, &newe.addr, &newe.maskbits,
  3230. &newe.prt_min, &newe.prt_max) < 0) {
  3231. log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
  3232. return NULL;
  3233. }
  3234. return addr_policy_get_canonical_entry(&newe);
  3235. }
  3236. /** Parse an exit policy line of the format "accept/reject private:...".
  3237. * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
  3238. * router descriptors until earlier versions are obsolete.
  3239. */
  3240. static addr_policy_t *
  3241. router_parse_addr_policy_private(directory_token_t *tok)
  3242. {
  3243. const char *arg;
  3244. uint16_t port_min, port_max;
  3245. addr_policy_t result;
  3246. arg = tok->args[0];
  3247. if (strcmpstart(arg, "private"))
  3248. return NULL;
  3249. arg += strlen("private");
  3250. arg = (char*) eat_whitespace(arg);
  3251. if (!arg || *arg != ':')
  3252. return NULL;
  3253. if (parse_port_range(arg+1, &port_min, &port_max)<0)
  3254. return NULL;
  3255. memset(&result, 0, sizeof(result));
  3256. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  3257. result.policy_type = ADDR_POLICY_REJECT;
  3258. else
  3259. result.policy_type = ADDR_POLICY_ACCEPT;
  3260. result.is_private = 1;
  3261. result.prt_min = port_min;
  3262. result.prt_max = port_max;
  3263. return addr_policy_get_canonical_entry(&result);
  3264. }
  3265. /** Log and exit if <b>t</b> is malformed */
  3266. void
  3267. assert_addr_policy_ok(smartlist_t *lst)
  3268. {
  3269. if (!lst) return;
  3270. SMARTLIST_FOREACH(lst, addr_policy_t *, t, {
  3271. tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
  3272. t->policy_type == ADDR_POLICY_ACCEPT);
  3273. tor_assert(t->prt_min <= t->prt_max);
  3274. });
  3275. }
  3276. /*
  3277. * Low-level tokenizer for router descriptors and directories.
  3278. */
  3279. /** Free all resources allocated for <b>tok</b> */
  3280. static void
  3281. token_clear(directory_token_t *tok)
  3282. {
  3283. if (tok->key)
  3284. crypto_pk_free(tok->key);
  3285. }
  3286. #define ALLOC_ZERO(sz) memarea_alloc_zero(area,sz)
  3287. #define ALLOC(sz) memarea_alloc(area,sz)
  3288. #define STRDUP(str) memarea_strdup(area,str)
  3289. #define STRNDUP(str,n) memarea_strndup(area,(str),(n))
  3290. #define RET_ERR(msg) \
  3291. STMT_BEGIN \
  3292. if (tok) token_clear(tok); \
  3293. tok = ALLOC_ZERO(sizeof(directory_token_t)); \
  3294. tok->tp = ERR_; \
  3295. tok->error = STRDUP(msg); \
  3296. goto done_tokenizing; \
  3297. STMT_END
  3298. /** Helper: make sure that the token <b>tok</b> with keyword <b>kwd</b> obeys
  3299. * the object syntax of <b>o_syn</b>. Allocate all storage in <b>area</b>.
  3300. * Return <b>tok</b> on success, or a new ERR_ token if the token didn't
  3301. * conform to the syntax we wanted.
  3302. **/
  3303. static INLINE directory_token_t *
  3304. token_check_object(memarea_t *area, const char *kwd,
  3305. directory_token_t *tok, obj_syntax o_syn)
  3306. {
  3307. char ebuf[128];
  3308. switch (o_syn) {
  3309. case NO_OBJ:
  3310. /* No object is allowed for this token. */
  3311. if (tok->object_body) {
  3312. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected object for %s", kwd);
  3313. RET_ERR(ebuf);
  3314. }
  3315. if (tok->key) {
  3316. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected public key for %s", kwd);
  3317. RET_ERR(ebuf);
  3318. }
  3319. break;
  3320. case NEED_OBJ:
  3321. /* There must be a (non-key) object. */
  3322. if (!tok->object_body) {
  3323. tor_snprintf(ebuf, sizeof(ebuf), "Missing object for %s", kwd);
  3324. RET_ERR(ebuf);
  3325. }
  3326. break;
  3327. case NEED_KEY_1024: /* There must be a 1024-bit public key. */
  3328. case NEED_SKEY_1024: /* There must be a 1024-bit private key. */
  3329. if (tok->key && crypto_pk_num_bits(tok->key) != PK_BYTES*8) {
  3330. tor_snprintf(ebuf, sizeof(ebuf), "Wrong size on key for %s: %d bits",
  3331. kwd, crypto_pk_num_bits(tok->key));
  3332. RET_ERR(ebuf);
  3333. }
  3334. /* fall through */
  3335. case NEED_KEY: /* There must be some kind of key. */
  3336. if (!tok->key) {
  3337. tor_snprintf(ebuf, sizeof(ebuf), "Missing public key for %s", kwd);
  3338. RET_ERR(ebuf);
  3339. }
  3340. if (o_syn != NEED_SKEY_1024) {
  3341. if (crypto_pk_key_is_private(tok->key)) {
  3342. tor_snprintf(ebuf, sizeof(ebuf),
  3343. "Private key given for %s, which wants a public key", kwd);
  3344. RET_ERR(ebuf);
  3345. }
  3346. } else { /* o_syn == NEED_SKEY_1024 */
  3347. if (!crypto_pk_key_is_private(tok->key)) {
  3348. tor_snprintf(ebuf, sizeof(ebuf),
  3349. "Public key given for %s, which wants a private key", kwd);
  3350. RET_ERR(ebuf);
  3351. }
  3352. }
  3353. break;
  3354. case OBJ_OK:
  3355. /* Anything goes with this token. */
  3356. break;
  3357. }
  3358. done_tokenizing:
  3359. return tok;
  3360. }
  3361. /** Helper: parse space-separated arguments from the string <b>s</b> ending at
  3362. * <b>eol</b>, and store them in the args field of <b>tok</b>. Store the
  3363. * number of parsed elements into the n_args field of <b>tok</b>. Allocate
  3364. * all storage in <b>area</b>. Return the number of arguments parsed, or
  3365. * return -1 if there was an insanely high number of arguments. */
  3366. static INLINE int
  3367. get_token_arguments(memarea_t *area, directory_token_t *tok,
  3368. const char *s, const char *eol)
  3369. {
  3370. /** Largest number of arguments we'll accept to any token, ever. */
  3371. #define MAX_ARGS 512
  3372. char *mem = memarea_strndup(area, s, eol-s);
  3373. char *cp = mem;
  3374. int j = 0;
  3375. char *args[MAX_ARGS];
  3376. while (*cp) {
  3377. if (j == MAX_ARGS)
  3378. return -1;
  3379. args[j++] = cp;
  3380. cp = (char*)find_whitespace(cp);
  3381. if (!cp || !*cp)
  3382. break; /* End of the line. */
  3383. *cp++ = '\0';
  3384. cp = (char*)eat_whitespace(cp);
  3385. }
  3386. tok->n_args = j;
  3387. tok->args = memarea_memdup(area, args, j*sizeof(char*));
  3388. return j;
  3389. #undef MAX_ARGS
  3390. }
  3391. /** Helper function: read the next token from *s, advance *s to the end of the
  3392. * token, and return the parsed token. Parse *<b>s</b> according to the list
  3393. * of tokens in <b>table</b>.
  3394. */
  3395. static directory_token_t *
  3396. get_next_token(memarea_t *area,
  3397. const char **s, const char *eos, token_rule_t *table)
  3398. {
  3399. /** Reject any object at least this big; it is probably an overflow, an
  3400. * attack, a bug, or some other nonsense. */
  3401. #define MAX_UNPARSED_OBJECT_SIZE (128*1024)
  3402. /** Reject any line at least this big; it is probably an overflow, an
  3403. * attack, a bug, or some other nonsense. */
  3404. #define MAX_LINE_LENGTH (128*1024)
  3405. const char *next, *eol, *obstart;
  3406. size_t obname_len;
  3407. int i;
  3408. directory_token_t *tok;
  3409. obj_syntax o_syn = NO_OBJ;
  3410. char ebuf[128];
  3411. const char *kwd = "";
  3412. tor_assert(area);
  3413. tok = ALLOC_ZERO(sizeof(directory_token_t));
  3414. tok->tp = ERR_;
  3415. /* Set *s to first token, eol to end-of-line, next to after first token */
  3416. *s = eat_whitespace_eos(*s, eos); /* eat multi-line whitespace */
  3417. tor_assert(eos >= *s);
  3418. eol = memchr(*s, '\n', eos-*s);
  3419. if (!eol)
  3420. eol = eos;
  3421. if (eol - *s > MAX_LINE_LENGTH) {
  3422. RET_ERR("Line far too long");
  3423. }
  3424. next = find_whitespace_eos(*s, eol);
  3425. if (!strcmp_len(*s, "opt", next-*s)) {
  3426. /* Skip past an "opt" at the start of the line. */
  3427. *s = eat_whitespace_eos_no_nl(next, eol);
  3428. next = find_whitespace_eos(*s, eol);
  3429. } else if (*s == eos) { /* If no "opt", and end-of-line, line is invalid */
  3430. RET_ERR("Unexpected EOF");
  3431. }
  3432. /* Search the table for the appropriate entry. (I tried a binary search
  3433. * instead, but it wasn't any faster.) */
  3434. for (i = 0; table[i].t ; ++i) {
  3435. if (!strcmp_len(*s, table[i].t, next-*s)) {
  3436. /* We've found the keyword. */
  3437. kwd = table[i].t;
  3438. tok->tp = table[i].v;
  3439. o_syn = table[i].os;
  3440. *s = eat_whitespace_eos_no_nl(next, eol);
  3441. /* We go ahead whether there are arguments or not, so that tok->args is
  3442. * always set if we want arguments. */
  3443. if (table[i].concat_args) {
  3444. /* The keyword takes the line as a single argument */
  3445. tok->args = ALLOC(sizeof(char*));
  3446. tok->args[0] = STRNDUP(*s,eol-*s); /* Grab everything on line */
  3447. tok->n_args = 1;
  3448. } else {
  3449. /* This keyword takes multiple arguments. */
  3450. if (get_token_arguments(area, tok, *s, eol)<0) {
  3451. tor_snprintf(ebuf, sizeof(ebuf),"Far too many arguments to %s", kwd);
  3452. RET_ERR(ebuf);
  3453. }
  3454. *s = eol;
  3455. }
  3456. if (tok->n_args < table[i].min_args) {
  3457. tor_snprintf(ebuf, sizeof(ebuf), "Too few arguments to %s", kwd);
  3458. RET_ERR(ebuf);
  3459. } else if (tok->n_args > table[i].max_args) {
  3460. tor_snprintf(ebuf, sizeof(ebuf), "Too many arguments to %s", kwd);
  3461. RET_ERR(ebuf);
  3462. }
  3463. break;
  3464. }
  3465. }
  3466. if (tok->tp == ERR_) {
  3467. /* No keyword matched; call it an "K_opt" or "A_unrecognized" */
  3468. if (**s == '@')
  3469. tok->tp = A_UNKNOWN_;
  3470. else
  3471. tok->tp = K_OPT;
  3472. tok->args = ALLOC(sizeof(char*));
  3473. tok->args[0] = STRNDUP(*s, eol-*s);
  3474. tok->n_args = 1;
  3475. o_syn = OBJ_OK;
  3476. }
  3477. /* Check whether there's an object present */
  3478. *s = eat_whitespace_eos(eol, eos); /* Scan from end of first line */
  3479. tor_assert(eos >= *s);
  3480. eol = memchr(*s, '\n', eos-*s);
  3481. if (!eol || eol-*s<11 || strcmpstart(*s, "-----BEGIN ")) /* No object. */
  3482. goto check_object;
  3483. obstart = *s; /* Set obstart to start of object spec */
  3484. if (*s+16 >= eol || memchr(*s+11,'\0',eol-*s-16) || /* no short lines, */
  3485. strcmp_len(eol-5, "-----", 5) || /* nuls or invalid endings */
  3486. (eol-*s) > MAX_UNPARSED_OBJECT_SIZE) { /* name too long */
  3487. RET_ERR("Malformed object: bad begin line");
  3488. }
  3489. tok->object_type = STRNDUP(*s+11, eol-*s-16);
  3490. obname_len = eol-*s-16; /* store objname length here to avoid a strlen() */
  3491. *s = eol+1; /* Set *s to possible start of object data (could be eos) */
  3492. /* Go to the end of the object */
  3493. next = tor_memstr(*s, eos-*s, "-----END ");
  3494. if (!next) {
  3495. RET_ERR("Malformed object: missing object end line");
  3496. }
  3497. tor_assert(eos >= next);
  3498. eol = memchr(next, '\n', eos-next);
  3499. if (!eol) /* end-of-line marker, or eos if there's no '\n' */
  3500. eol = eos;
  3501. /* Validate the ending tag, which should be 9 + NAME + 5 + eol */
  3502. if ((size_t)(eol-next) != 9+obname_len+5 ||
  3503. strcmp_len(next+9, tok->object_type, obname_len) ||
  3504. strcmp_len(eol-5, "-----", 5)) {
  3505. snprintf(ebuf, sizeof(ebuf), "Malformed object: mismatched end tag %s",
  3506. tok->object_type);
  3507. ebuf[sizeof(ebuf)-1] = '\0';
  3508. RET_ERR(ebuf);
  3509. }
  3510. if (next - *s > MAX_UNPARSED_OBJECT_SIZE)
  3511. RET_ERR("Couldn't parse object: missing footer or object much too big.");
  3512. if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) { /* If it's a public key */
  3513. tok->key = crypto_pk_new();
  3514. if (crypto_pk_read_public_key_from_string(tok->key, obstart, eol-obstart))
  3515. RET_ERR("Couldn't parse public key.");
  3516. } else if (!strcmp(tok->object_type, "RSA PRIVATE KEY")) { /* private key */
  3517. tok->key = crypto_pk_new();
  3518. if (crypto_pk_read_private_key_from_string(tok->key, obstart, eol-obstart))
  3519. RET_ERR("Couldn't parse private key.");
  3520. } else { /* If it's something else, try to base64-decode it */
  3521. int r;
  3522. tok->object_body = ALLOC(next-*s); /* really, this is too much RAM. */
  3523. r = base64_decode(tok->object_body, next-*s, *s, next-*s);
  3524. if (r<0)
  3525. RET_ERR("Malformed object: bad base64-encoded data");
  3526. tok->object_size = r;
  3527. }
  3528. *s = eol;
  3529. check_object:
  3530. tok = token_check_object(area, kwd, tok, o_syn);
  3531. done_tokenizing:
  3532. return tok;
  3533. #undef RET_ERR
  3534. #undef ALLOC
  3535. #undef ALLOC_ZERO
  3536. #undef STRDUP
  3537. #undef STRNDUP
  3538. }
  3539. /** Read all tokens from a string between <b>start</b> and <b>end</b>, and add
  3540. * them to <b>out</b>. Parse according to the token rules in <b>table</b>.
  3541. * Caller must free tokens in <b>out</b>. If <b>end</b> is NULL, use the
  3542. * entire string.
  3543. */
  3544. static int
  3545. tokenize_string(memarea_t *area,
  3546. const char *start, const char *end, smartlist_t *out,
  3547. token_rule_t *table, int flags)
  3548. {
  3549. const char **s;
  3550. directory_token_t *tok = NULL;
  3551. int counts[NIL_];
  3552. int i;
  3553. int first_nonannotation;
  3554. int prev_len = smartlist_len(out);
  3555. tor_assert(area);
  3556. s = &start;
  3557. if (!end)
  3558. end = start+strlen(start);
  3559. for (i = 0; i < NIL_; ++i)
  3560. counts[i] = 0;
  3561. SMARTLIST_FOREACH(out, const directory_token_t *, t, ++counts[t->tp]);
  3562. while (*s < end && (!tok || tok->tp != EOF_)) {
  3563. tok = get_next_token(area, s, end, table);
  3564. if (tok->tp == ERR_) {
  3565. log_warn(LD_DIR, "parse error: %s", tok->error);
  3566. token_clear(tok);
  3567. return -1;
  3568. }
  3569. ++counts[tok->tp];
  3570. smartlist_add(out, tok);
  3571. *s = eat_whitespace_eos(*s, end);
  3572. }
  3573. if (flags & TS_NOCHECK)
  3574. return 0;
  3575. if ((flags & TS_ANNOTATIONS_OK)) {
  3576. first_nonannotation = -1;
  3577. for (i = 0; i < smartlist_len(out); ++i) {
  3578. tok = smartlist_get(out, i);
  3579. if (tok->tp < MIN_ANNOTATION || tok->tp > MAX_ANNOTATION) {
  3580. first_nonannotation = i;
  3581. break;
  3582. }
  3583. }
  3584. if (first_nonannotation < 0) {
  3585. log_warn(LD_DIR, "parse error: item contains only annotations");
  3586. return -1;
  3587. }
  3588. for (i=first_nonannotation; i < smartlist_len(out); ++i) {
  3589. tok = smartlist_get(out, i);
  3590. if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
  3591. log_warn(LD_DIR, "parse error: Annotations mixed with keywords");
  3592. return -1;
  3593. }
  3594. }
  3595. if ((flags & TS_NO_NEW_ANNOTATIONS)) {
  3596. if (first_nonannotation != prev_len) {
  3597. log_warn(LD_DIR, "parse error: Unexpected annotations.");
  3598. return -1;
  3599. }
  3600. }
  3601. } else {
  3602. for (i=0; i < smartlist_len(out); ++i) {
  3603. tok = smartlist_get(out, i);
  3604. if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
  3605. log_warn(LD_DIR, "parse error: no annotations allowed.");
  3606. return -1;
  3607. }
  3608. }
  3609. first_nonannotation = 0;
  3610. }
  3611. for (i = 0; table[i].t; ++i) {
  3612. if (counts[table[i].v] < table[i].min_cnt) {
  3613. log_warn(LD_DIR, "Parse error: missing %s element.", table[i].t);
  3614. return -1;
  3615. }
  3616. if (counts[table[i].v] > table[i].max_cnt) {
  3617. log_warn(LD_DIR, "Parse error: too many %s elements.", table[i].t);
  3618. return -1;
  3619. }
  3620. if (table[i].pos & AT_START) {
  3621. if (smartlist_len(out) < 1 ||
  3622. (tok = smartlist_get(out, first_nonannotation))->tp != table[i].v) {
  3623. log_warn(LD_DIR, "Parse error: first item is not %s.", table[i].t);
  3624. return -1;
  3625. }
  3626. }
  3627. if (table[i].pos & AT_END) {
  3628. if (smartlist_len(out) < 1 ||
  3629. (tok = smartlist_get(out, smartlist_len(out)-1))->tp != table[i].v) {
  3630. log_warn(LD_DIR, "Parse error: last item is not %s.", table[i].t);
  3631. return -1;
  3632. }
  3633. }
  3634. }
  3635. return 0;
  3636. }
  3637. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
  3638. * NULL if no such keyword is found.
  3639. */
  3640. static directory_token_t *
  3641. find_opt_by_keyword(smartlist_t *s, directory_keyword keyword)
  3642. {
  3643. SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
  3644. return NULL;
  3645. }
  3646. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; fail
  3647. * with an assert if no such keyword is found.
  3648. */
  3649. static directory_token_t *
  3650. find_by_keyword_(smartlist_t *s, directory_keyword keyword,
  3651. const char *keyword_as_string)
  3652. {
  3653. directory_token_t *tok = find_opt_by_keyword(s, keyword);
  3654. if (PREDICT_UNLIKELY(!tok)) {
  3655. log_err(LD_BUG, "Missing %s [%d] in directory object that should have "
  3656. "been validated. Internal error.", keyword_as_string, (int)keyword);
  3657. tor_assert(tok);
  3658. }
  3659. return tok;
  3660. }
  3661. /** If there are any directory_token_t entries in <b>s</b> whose keyword is
  3662. * <b>k</b>, return a newly allocated smartlist_t containing all such entries,
  3663. * in the same order in which they occur in <b>s</b>. Otherwise return
  3664. * NULL. */
  3665. static smartlist_t *
  3666. find_all_by_keyword(smartlist_t *s, directory_keyword k)
  3667. {
  3668. smartlist_t *out = NULL;
  3669. SMARTLIST_FOREACH(s, directory_token_t *, t,
  3670. if (t->tp == k) {
  3671. if (!out)
  3672. out = smartlist_new();
  3673. smartlist_add(out, t);
  3674. });
  3675. return out;
  3676. }
  3677. /** Return a newly allocated smartlist of all accept or reject tokens in
  3678. * <b>s</b>.
  3679. */
  3680. static smartlist_t *
  3681. find_all_exitpolicy(smartlist_t *s)
  3682. {
  3683. smartlist_t *out = smartlist_new();
  3684. SMARTLIST_FOREACH(s, directory_token_t *, t,
  3685. if (t->tp == K_ACCEPT || t->tp == K_ACCEPT6 ||
  3686. t->tp == K_REJECT || t->tp == K_REJECT6)
  3687. smartlist_add(out,t));
  3688. return out;
  3689. }
  3690. /** Helper function for <b>router_get_hash_impl</b>: given <b>s</b>,
  3691. * <b>s_len</b>, <b>start_str</b>, <b>end_str</b>, and <b>end_c</b> with the
  3692. * same semantics as in that function, set *<b>start_out</b> (inclusive) and
  3693. * *<b>end_out</b> (exclusive) to the boundaries of the string to be hashed.
  3694. *
  3695. * Return 0 on success and -1 on failure.
  3696. */
  3697. static int
  3698. router_get_hash_impl_helper(const char *s, size_t s_len,
  3699. const char *start_str,
  3700. const char *end_str, char end_c,
  3701. const char **start_out, const char **end_out)
  3702. {
  3703. const char *start, *end;
  3704. start = tor_memstr(s, s_len, start_str);
  3705. if (!start) {
  3706. log_warn(LD_DIR,"couldn't find start of hashed material \"%s\"",start_str);
  3707. return -1;
  3708. }
  3709. if (start != s && *(start-1) != '\n') {
  3710. log_warn(LD_DIR,
  3711. "first occurrence of \"%s\" is not at the start of a line",
  3712. start_str);
  3713. return -1;
  3714. }
  3715. end = tor_memstr(start+strlen(start_str),
  3716. s_len - (start-s) - strlen(start_str), end_str);
  3717. if (!end) {
  3718. log_warn(LD_DIR,"couldn't find end of hashed material \"%s\"",end_str);
  3719. return -1;
  3720. }
  3721. end = memchr(end+strlen(end_str), end_c, s_len - (end-s) - strlen(end_str));
  3722. if (!end) {
  3723. log_warn(LD_DIR,"couldn't find EOL");
  3724. return -1;
  3725. }
  3726. ++end;
  3727. *start_out = start;
  3728. *end_out = end;
  3729. return 0;
  3730. }
  3731. /** Compute the digest of the substring of <b>s</b> taken from the first
  3732. * occurrence of <b>start_str</b> through the first instance of c after the
  3733. * first subsequent occurrence of <b>end_str</b>; store the 20-byte or 32-byte
  3734. * result in <b>digest</b>; return 0 on success.
  3735. *
  3736. * If no such substring exists, return -1.
  3737. */
  3738. static int
  3739. router_get_hash_impl(const char *s, size_t s_len, char *digest,
  3740. const char *start_str,
  3741. const char *end_str, char end_c,
  3742. digest_algorithm_t alg)
  3743. {
  3744. const char *start=NULL, *end=NULL;
  3745. if (router_get_hash_impl_helper(s,s_len,start_str,end_str,end_c,
  3746. &start,&end)<0)
  3747. return -1;
  3748. if (alg == DIGEST_SHA1) {
  3749. if (crypto_digest(digest, start, end-start)) {
  3750. log_warn(LD_BUG,"couldn't compute digest");
  3751. return -1;
  3752. }
  3753. } else {
  3754. if (crypto_digest256(digest, start, end-start, alg)) {
  3755. log_warn(LD_BUG,"couldn't compute digest");
  3756. return -1;
  3757. }
  3758. }
  3759. return 0;
  3760. }
  3761. /** As router_get_hash_impl, but compute all hashes. */
  3762. static int
  3763. router_get_hashes_impl(const char *s, size_t s_len, digests_t *digests,
  3764. const char *start_str,
  3765. const char *end_str, char end_c)
  3766. {
  3767. const char *start=NULL, *end=NULL;
  3768. if (router_get_hash_impl_helper(s,s_len,start_str,end_str,end_c,
  3769. &start,&end)<0)
  3770. return -1;
  3771. if (crypto_digest_all(digests, start, end-start)) {
  3772. log_warn(LD_BUG,"couldn't compute digests");
  3773. return -1;
  3774. }
  3775. return 0;
  3776. }
  3777. /** Assuming that s starts with a microdesc, return the start of the
  3778. * *NEXT* one. Return NULL on "not found." */
  3779. static const char *
  3780. find_start_of_next_microdesc(const char *s, const char *eos)
  3781. {
  3782. int started_with_annotations;
  3783. s = eat_whitespace_eos(s, eos);
  3784. if (!s)
  3785. return NULL;
  3786. #define CHECK_LENGTH() STMT_BEGIN \
  3787. if (s+32 > eos) \
  3788. return NULL; \
  3789. STMT_END
  3790. #define NEXT_LINE() STMT_BEGIN \
  3791. s = memchr(s, '\n', eos-s); \
  3792. if (!s || s+1 >= eos) \
  3793. return NULL; \
  3794. s++; \
  3795. STMT_END
  3796. CHECK_LENGTH();
  3797. started_with_annotations = (*s == '@');
  3798. if (started_with_annotations) {
  3799. /* Start by advancing to the first non-annotation line. */
  3800. while (*s == '@')
  3801. NEXT_LINE();
  3802. }
  3803. CHECK_LENGTH();
  3804. /* Now we should be pointed at an onion-key line. If we are, then skip
  3805. * it. */
  3806. if (!strcmpstart(s, "onion-key"))
  3807. NEXT_LINE();
  3808. /* Okay, now we're pointed at the first line of the microdescriptor which is
  3809. not an annotation or onion-key. The next line that _is_ an annotation or
  3810. onion-key is the start of the next microdescriptor. */
  3811. while (s+32 < eos) {
  3812. if (*s == '@' || !strcmpstart(s, "onion-key"))
  3813. return s;
  3814. NEXT_LINE();
  3815. }
  3816. return NULL;
  3817. #undef CHECK_LENGTH
  3818. #undef NEXT_LINE
  3819. }
  3820. /** Parse as many microdescriptors as are found from the string starting at
  3821. * <b>s</b> and ending at <b>eos</b>. If allow_annotations is set, read any
  3822. * annotations we recognize and ignore ones we don't. If <b>copy_body</b> is
  3823. * true, then strdup the bodies of the microdescriptors. Return all newly
  3824. * parsed microdescriptors in a newly allocated smartlist_t. */
  3825. smartlist_t *
  3826. microdescs_parse_from_string(const char *s, const char *eos,
  3827. int allow_annotations, int copy_body)
  3828. {
  3829. smartlist_t *tokens;
  3830. smartlist_t *result;
  3831. microdesc_t *md = NULL;
  3832. memarea_t *area;
  3833. const char *start = s;
  3834. const char *start_of_next_microdesc;
  3835. int flags = allow_annotations ? TS_ANNOTATIONS_OK : 0;
  3836. directory_token_t *tok;
  3837. if (!eos)
  3838. eos = s + strlen(s);
  3839. s = eat_whitespace_eos(s, eos);
  3840. area = memarea_new();
  3841. result = smartlist_new();
  3842. tokens = smartlist_new();
  3843. while (s < eos) {
  3844. start_of_next_microdesc = find_start_of_next_microdesc(s, eos);
  3845. if (!start_of_next_microdesc)
  3846. start_of_next_microdesc = eos;
  3847. if (tokenize_string(area, s, start_of_next_microdesc, tokens,
  3848. microdesc_token_table, flags)) {
  3849. log_warn(LD_DIR, "Unparseable microdescriptor");
  3850. goto next;
  3851. }
  3852. md = tor_malloc_zero(sizeof(microdesc_t));
  3853. {
  3854. const char *cp = tor_memstr(s, start_of_next_microdesc-s,
  3855. "onion-key");
  3856. tor_assert(cp);
  3857. md->bodylen = start_of_next_microdesc - cp;
  3858. if (copy_body)
  3859. md->body = tor_strndup(cp, md->bodylen);
  3860. else
  3861. md->body = (char*)cp;
  3862. md->off = cp - start;
  3863. }
  3864. if ((tok = find_opt_by_keyword(tokens, A_LAST_LISTED))) {
  3865. if (parse_iso_time(tok->args[0], &md->last_listed)) {
  3866. log_warn(LD_DIR, "Bad last-listed time in microdescriptor");
  3867. goto next;
  3868. }
  3869. }
  3870. tok = find_by_keyword(tokens, K_ONION_KEY);
  3871. if (!crypto_pk_public_exponent_ok(tok->key)) {
  3872. log_warn(LD_DIR,
  3873. "Relay's onion key had invalid exponent.");
  3874. goto next;
  3875. }
  3876. md->onion_pkey = tok->key;
  3877. tok->key = NULL;
  3878. if ((tok = find_opt_by_keyword(tokens, K_ONION_KEY_NTOR))) {
  3879. uint8_t k[CURVE25519_PUBKEY_LEN+32];
  3880. int r;
  3881. tor_assert(tok->n_args >= 1);
  3882. r = base64_decode((char*)k, sizeof(k),
  3883. tok->args[0], strlen(tok->args[0]));
  3884. if (r != CURVE25519_PUBKEY_LEN) {
  3885. log_warn(LD_DIR, "Bogus onion-key-ntor in microdesc");
  3886. goto next;
  3887. }
  3888. md->onion_curve25519_pkey =
  3889. tor_malloc(sizeof(curve25519_public_key_t));
  3890. memcpy(md->onion_curve25519_pkey->public_key,
  3891. k, CURVE25519_PUBKEY_LEN);
  3892. }
  3893. {
  3894. smartlist_t *a_lines = find_all_by_keyword(tokens, K_A);
  3895. if (a_lines) {
  3896. find_single_ipv6_orport(a_lines, &md->ipv6_addr, &md->ipv6_orport);
  3897. smartlist_free(a_lines);
  3898. }
  3899. }
  3900. if ((tok = find_opt_by_keyword(tokens, K_FAMILY))) {
  3901. int i;
  3902. md->family = smartlist_new();
  3903. for (i=0;i<tok->n_args;++i) {
  3904. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  3905. log_warn(LD_DIR, "Illegal nickname %s in family line",
  3906. escaped(tok->args[i]));
  3907. goto next;
  3908. }
  3909. smartlist_add(md->family, tor_strdup(tok->args[i]));
  3910. }
  3911. }
  3912. if ((tok = find_opt_by_keyword(tokens, K_P))) {
  3913. md->exit_policy = parse_short_policy(tok->args[0]);
  3914. }
  3915. if ((tok = find_opt_by_keyword(tokens, K_P6))) {
  3916. md->ipv6_exit_policy = parse_short_policy(tok->args[0]);
  3917. }
  3918. crypto_digest256(md->digest, md->body, md->bodylen, DIGEST_SHA256);
  3919. smartlist_add(result, md);
  3920. md = NULL;
  3921. next:
  3922. microdesc_free(md);
  3923. md = NULL;
  3924. memarea_clear(area);
  3925. smartlist_clear(tokens);
  3926. s = start_of_next_microdesc;
  3927. }
  3928. memarea_drop_all(area);
  3929. smartlist_free(tokens);
  3930. return result;
  3931. }
  3932. /** Return true iff this Tor version can answer directory questions
  3933. * about microdescriptors. */
  3934. int
  3935. tor_version_supports_microdescriptors(const char *platform)
  3936. {
  3937. return tor_version_as_new_as(platform, "0.2.3.1-alpha");
  3938. }
  3939. /** Parse the Tor version of the platform string <b>platform</b>,
  3940. * and compare it to the version in <b>cutoff</b>. Return 1 if
  3941. * the router is at least as new as the cutoff, else return 0.
  3942. */
  3943. int
  3944. tor_version_as_new_as(const char *platform, const char *cutoff)
  3945. {
  3946. tor_version_t cutoff_version, router_version;
  3947. char *s, *s2, *start;
  3948. char tmp[128];
  3949. tor_assert(platform);
  3950. if (tor_version_parse(cutoff, &cutoff_version)<0) {
  3951. log_warn(LD_BUG,"cutoff version '%s' unparseable.",cutoff);
  3952. return 0;
  3953. }
  3954. if (strcmpstart(platform,"Tor ")) /* nonstandard Tor; be safe and say yes */
  3955. return 1;
  3956. start = (char *)eat_whitespace(platform+3);
  3957. if (!*start) return 0;
  3958. s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
  3959. s2 = (char*)eat_whitespace(s);
  3960. if (!strcmpstart(s2, "(r") || !strcmpstart(s2, "(git-"))
  3961. s = (char*)find_whitespace(s2);
  3962. if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
  3963. return 0;
  3964. strlcpy(tmp, start, s-start+1);
  3965. if (tor_version_parse(tmp, &router_version)<0) {
  3966. log_info(LD_DIR,"Router version '%s' unparseable.",tmp);
  3967. return 1; /* be safe and say yes */
  3968. }
  3969. /* Here's why we don't need to do any special handling for svn revisions:
  3970. * - If neither has an svn revision, we're fine.
  3971. * - If the router doesn't have an svn revision, we can't assume that it
  3972. * is "at least" any svn revision, so we need to return 0.
  3973. * - If the target version doesn't have an svn revision, any svn revision
  3974. * (or none at all) is good enough, so return 1.
  3975. * - If both target and router have an svn revision, we compare them.
  3976. */
  3977. return tor_version_compare(&router_version, &cutoff_version) >= 0;
  3978. }
  3979. /** Parse a tor version from <b>s</b>, and store the result in <b>out</b>.
  3980. * Return 0 on success, -1 on failure. */
  3981. int
  3982. tor_version_parse(const char *s, tor_version_t *out)
  3983. {
  3984. char *eos=NULL;
  3985. const char *cp=NULL;
  3986. /* Format is:
  3987. * "Tor " ? NUM dot NUM dot NUM [ ( pre | rc | dot ) NUM [ - tag ] ]
  3988. */
  3989. tor_assert(s);
  3990. tor_assert(out);
  3991. memset(out, 0, sizeof(tor_version_t));
  3992. if (!strcasecmpstart(s, "Tor "))
  3993. s += 4;
  3994. /* Get major. */
  3995. out->major = (int)strtol(s,&eos,10);
  3996. if (!eos || eos==s || *eos != '.') return -1;
  3997. cp = eos+1;
  3998. /* Get minor */
  3999. out->minor = (int) strtol(cp,&eos,10);
  4000. if (!eos || eos==cp || *eos != '.') return -1;
  4001. cp = eos+1;
  4002. /* Get micro */
  4003. out->micro = (int) strtol(cp,&eos,10);
  4004. if (!eos || eos==cp) return -1;
  4005. if (!*eos) {
  4006. out->status = VER_RELEASE;
  4007. out->patchlevel = 0;
  4008. return 0;
  4009. }
  4010. cp = eos;
  4011. /* Get status */
  4012. if (*cp == '.') {
  4013. out->status = VER_RELEASE;
  4014. ++cp;
  4015. } else if (0==strncmp(cp, "pre", 3)) {
  4016. out->status = VER_PRE;
  4017. cp += 3;
  4018. } else if (0==strncmp(cp, "rc", 2)) {
  4019. out->status = VER_RC;
  4020. cp += 2;
  4021. } else {
  4022. return -1;
  4023. }
  4024. /* Get patchlevel */
  4025. out->patchlevel = (int) strtol(cp,&eos,10);
  4026. if (!eos || eos==cp) return -1;
  4027. cp = eos;
  4028. /* Get status tag. */
  4029. if (*cp == '-' || *cp == '.')
  4030. ++cp;
  4031. eos = (char*) find_whitespace(cp);
  4032. if (eos-cp >= (int)sizeof(out->status_tag))
  4033. strlcpy(out->status_tag, cp, sizeof(out->status_tag));
  4034. else {
  4035. memcpy(out->status_tag, cp, eos-cp);
  4036. out->status_tag[eos-cp] = 0;
  4037. }
  4038. cp = eat_whitespace(eos);
  4039. if (!strcmpstart(cp, "(r")) {
  4040. cp += 2;
  4041. out->svn_revision = (int) strtol(cp,&eos,10);
  4042. } else if (!strcmpstart(cp, "(git-")) {
  4043. char *close_paren = strchr(cp, ')');
  4044. int hexlen;
  4045. char digest[DIGEST_LEN];
  4046. if (! close_paren)
  4047. return -1;
  4048. cp += 5;
  4049. if (close_paren-cp > HEX_DIGEST_LEN)
  4050. return -1;
  4051. hexlen = (int)(close_paren-cp);
  4052. memwipe(digest, 0, sizeof(digest));
  4053. if ( hexlen == 0 || (hexlen % 2) == 1)
  4054. return -1;
  4055. if (base16_decode(digest, hexlen/2, cp, hexlen))
  4056. return -1;
  4057. memcpy(out->git_tag, digest, hexlen/2);
  4058. out->git_tag_len = hexlen/2;
  4059. }
  4060. return 0;
  4061. }
  4062. /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
  4063. * b. */
  4064. int
  4065. tor_version_compare(tor_version_t *a, tor_version_t *b)
  4066. {
  4067. int i;
  4068. tor_assert(a);
  4069. tor_assert(b);
  4070. if ((i = a->major - b->major))
  4071. return i;
  4072. else if ((i = a->minor - b->minor))
  4073. return i;
  4074. else if ((i = a->micro - b->micro))
  4075. return i;
  4076. else if ((i = a->status - b->status))
  4077. return i;
  4078. else if ((i = a->patchlevel - b->patchlevel))
  4079. return i;
  4080. else if ((i = strcmp(a->status_tag, b->status_tag)))
  4081. return i;
  4082. else if ((i = a->svn_revision - b->svn_revision))
  4083. return i;
  4084. else if ((i = a->git_tag_len - b->git_tag_len))
  4085. return i;
  4086. else if (a->git_tag_len)
  4087. return fast_memcmp(a->git_tag, b->git_tag, a->git_tag_len);
  4088. else
  4089. return 0;
  4090. }
  4091. /** Return true iff versions <b>a</b> and <b>b</b> belong to the same series.
  4092. */
  4093. int
  4094. tor_version_same_series(tor_version_t *a, tor_version_t *b)
  4095. {
  4096. tor_assert(a);
  4097. tor_assert(b);
  4098. return ((a->major == b->major) &&
  4099. (a->minor == b->minor) &&
  4100. (a->micro == b->micro));
  4101. }
  4102. /** Helper: Given pointers to two strings describing tor versions, return -1
  4103. * if _a precedes _b, 1 if _b precedes _a, and 0 if they are equivalent.
  4104. * Used to sort a list of versions. */
  4105. static int
  4106. compare_tor_version_str_ptr_(const void **_a, const void **_b)
  4107. {
  4108. const char *a = *_a, *b = *_b;
  4109. int ca, cb;
  4110. tor_version_t va, vb;
  4111. ca = tor_version_parse(a, &va);
  4112. cb = tor_version_parse(b, &vb);
  4113. /* If they both parse, compare them. */
  4114. if (!ca && !cb)
  4115. return tor_version_compare(&va,&vb);
  4116. /* If one parses, it comes first. */
  4117. if (!ca && cb)
  4118. return -1;
  4119. if (ca && !cb)
  4120. return 1;
  4121. /* If neither parses, compare strings. Also, the directory server admin
  4122. ** needs to be smacked upside the head. But Tor is tolerant and gentle. */
  4123. return strcmp(a,b);
  4124. }
  4125. /** Sort a list of string-representations of versions in ascending order. */
  4126. void
  4127. sort_version_list(smartlist_t *versions, int remove_duplicates)
  4128. {
  4129. smartlist_sort(versions, compare_tor_version_str_ptr_);
  4130. if (remove_duplicates)
  4131. smartlist_uniq(versions, compare_tor_version_str_ptr_, tor_free_);
  4132. }
  4133. /** Parse and validate the ASCII-encoded v2 descriptor in <b>desc</b>,
  4134. * write the parsed descriptor to the newly allocated *<b>parsed_out</b>, the
  4135. * binary descriptor ID of length DIGEST_LEN to <b>desc_id_out</b>, the
  4136. * encrypted introduction points to the newly allocated
  4137. * *<b>intro_points_encrypted_out</b>, their encrypted size to
  4138. * *<b>intro_points_encrypted_size_out</b>, the size of the encoded descriptor
  4139. * to *<b>encoded_size_out</b>, and a pointer to the possibly next
  4140. * descriptor to *<b>next_out</b>; return 0 for success (including validation)
  4141. * and -1 for failure.
  4142. */
  4143. int
  4144. rend_parse_v2_service_descriptor(rend_service_descriptor_t **parsed_out,
  4145. char *desc_id_out,
  4146. char **intro_points_encrypted_out,
  4147. size_t *intro_points_encrypted_size_out,
  4148. size_t *encoded_size_out,
  4149. const char **next_out, const char *desc)
  4150. {
  4151. rend_service_descriptor_t *result =
  4152. tor_malloc_zero(sizeof(rend_service_descriptor_t));
  4153. char desc_hash[DIGEST_LEN];
  4154. const char *eos;
  4155. smartlist_t *tokens = smartlist_new();
  4156. directory_token_t *tok;
  4157. char secret_id_part[DIGEST_LEN];
  4158. int i, version, num_ok=1;
  4159. smartlist_t *versions;
  4160. char public_key_hash[DIGEST_LEN];
  4161. char test_desc_id[DIGEST_LEN];
  4162. memarea_t *area = NULL;
  4163. tor_assert(desc);
  4164. /* Check if desc starts correctly. */
  4165. if (strncmp(desc, "rendezvous-service-descriptor ",
  4166. strlen("rendezvous-service-descriptor "))) {
  4167. log_info(LD_REND, "Descriptor does not start correctly.");
  4168. goto err;
  4169. }
  4170. /* Compute descriptor hash for later validation. */
  4171. if (router_get_hash_impl(desc, strlen(desc), desc_hash,
  4172. "rendezvous-service-descriptor ",
  4173. "\nsignature", '\n', DIGEST_SHA1) < 0) {
  4174. log_warn(LD_REND, "Couldn't compute descriptor hash.");
  4175. goto err;
  4176. }
  4177. /* Determine end of string. */
  4178. eos = strstr(desc, "\nrendezvous-service-descriptor ");
  4179. if (!eos)
  4180. eos = desc + strlen(desc);
  4181. else
  4182. eos = eos + 1;
  4183. /* Check length. */
  4184. if (eos-desc > REND_DESC_MAX_SIZE) {
  4185. /* XXX023 If we are parsing this descriptor as a server, this
  4186. * should be a protocol warning. */
  4187. log_warn(LD_REND, "Descriptor length is %d which exceeds "
  4188. "maximum rendezvous descriptor size of %d bytes.",
  4189. (int)(eos-desc), REND_DESC_MAX_SIZE);
  4190. goto err;
  4191. }
  4192. /* Tokenize descriptor. */
  4193. area = memarea_new();
  4194. if (tokenize_string(area, desc, eos, tokens, desc_token_table, 0)) {
  4195. log_warn(LD_REND, "Error tokenizing descriptor.");
  4196. goto err;
  4197. }
  4198. /* Set next to next descriptor, if available. */
  4199. *next_out = eos;
  4200. /* Set length of encoded descriptor. */
  4201. *encoded_size_out = eos - desc;
  4202. /* Check min allowed length of token list. */
  4203. if (smartlist_len(tokens) < 7) {
  4204. log_warn(LD_REND, "Impossibly short descriptor.");
  4205. goto err;
  4206. }
  4207. /* Parse base32-encoded descriptor ID. */
  4208. tok = find_by_keyword(tokens, R_RENDEZVOUS_SERVICE_DESCRIPTOR);
  4209. tor_assert(tok == smartlist_get(tokens, 0));
  4210. tor_assert(tok->n_args == 1);
  4211. if (strlen(tok->args[0]) != REND_DESC_ID_V2_LEN_BASE32 ||
  4212. strspn(tok->args[0], BASE32_CHARS) != REND_DESC_ID_V2_LEN_BASE32) {
  4213. log_warn(LD_REND, "Invalid descriptor ID: '%s'", tok->args[0]);
  4214. goto err;
  4215. }
  4216. if (base32_decode(desc_id_out, DIGEST_LEN,
  4217. tok->args[0], REND_DESC_ID_V2_LEN_BASE32) < 0) {
  4218. log_warn(LD_REND, "Descriptor ID contains illegal characters: %s",
  4219. tok->args[0]);
  4220. goto err;
  4221. }
  4222. /* Parse descriptor version. */
  4223. tok = find_by_keyword(tokens, R_VERSION);
  4224. tor_assert(tok->n_args == 1);
  4225. result->version =
  4226. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &num_ok, NULL);
  4227. if (result->version != 2 || !num_ok) {
  4228. /* If it's <2, it shouldn't be under this format. If the number
  4229. * is greater than 2, we bumped it because we broke backward
  4230. * compatibility. See how version numbers in our other formats
  4231. * work. */
  4232. log_warn(LD_REND, "Unrecognized descriptor version: %s",
  4233. escaped(tok->args[0]));
  4234. goto err;
  4235. }
  4236. /* Parse public key. */
  4237. tok = find_by_keyword(tokens, R_PERMANENT_KEY);
  4238. result->pk = tok->key;
  4239. tok->key = NULL; /* Prevent free */
  4240. /* Parse secret ID part. */
  4241. tok = find_by_keyword(tokens, R_SECRET_ID_PART);
  4242. tor_assert(tok->n_args == 1);
  4243. if (strlen(tok->args[0]) != REND_SECRET_ID_PART_LEN_BASE32 ||
  4244. strspn(tok->args[0], BASE32_CHARS) != REND_SECRET_ID_PART_LEN_BASE32) {
  4245. log_warn(LD_REND, "Invalid secret ID part: '%s'", tok->args[0]);
  4246. goto err;
  4247. }
  4248. if (base32_decode(secret_id_part, DIGEST_LEN, tok->args[0], 32) < 0) {
  4249. log_warn(LD_REND, "Secret ID part contains illegal characters: %s",
  4250. tok->args[0]);
  4251. goto err;
  4252. }
  4253. /* Parse publication time -- up-to-date check is done when storing the
  4254. * descriptor. */
  4255. tok = find_by_keyword(tokens, R_PUBLICATION_TIME);
  4256. tor_assert(tok->n_args == 1);
  4257. if (parse_iso_time(tok->args[0], &result->timestamp) < 0) {
  4258. log_warn(LD_REND, "Invalid publication time: '%s'", tok->args[0]);
  4259. goto err;
  4260. }
  4261. /* Parse protocol versions. */
  4262. tok = find_by_keyword(tokens, R_PROTOCOL_VERSIONS);
  4263. tor_assert(tok->n_args == 1);
  4264. versions = smartlist_new();
  4265. smartlist_split_string(versions, tok->args[0], ",",
  4266. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  4267. for (i = 0; i < smartlist_len(versions); i++) {
  4268. version = (int) tor_parse_long(smartlist_get(versions, i),
  4269. 10, 0, INT_MAX, &num_ok, NULL);
  4270. if (!num_ok) /* It's a string; let's ignore it. */
  4271. continue;
  4272. if (version >= REND_PROTOCOL_VERSION_BITMASK_WIDTH)
  4273. /* Avoid undefined left-shift behaviour. */
  4274. continue;
  4275. result->protocols |= 1 << version;
  4276. }
  4277. SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
  4278. smartlist_free(versions);
  4279. /* Parse encrypted introduction points. Don't verify. */
  4280. tok = find_opt_by_keyword(tokens, R_INTRODUCTION_POINTS);
  4281. if (tok) {
  4282. if (strcmp(tok->object_type, "MESSAGE")) {
  4283. log_warn(LD_DIR, "Bad object type: introduction points should be of "
  4284. "type MESSAGE");
  4285. goto err;
  4286. }
  4287. *intro_points_encrypted_out = tor_memdup(tok->object_body,
  4288. tok->object_size);
  4289. *intro_points_encrypted_size_out = tok->object_size;
  4290. } else {
  4291. *intro_points_encrypted_out = NULL;
  4292. *intro_points_encrypted_size_out = 0;
  4293. }
  4294. /* Parse and verify signature. */
  4295. tok = find_by_keyword(tokens, R_SIGNATURE);
  4296. note_crypto_pk_op(VERIFY_RTR);
  4297. if (check_signature_token(desc_hash, DIGEST_LEN, tok, result->pk, 0,
  4298. "v2 rendezvous service descriptor") < 0)
  4299. goto err;
  4300. /* Verify that descriptor ID belongs to public key and secret ID part. */
  4301. crypto_pk_get_digest(result->pk, public_key_hash);
  4302. rend_get_descriptor_id_bytes(test_desc_id, public_key_hash,
  4303. secret_id_part);
  4304. if (tor_memneq(desc_id_out, test_desc_id, DIGEST_LEN)) {
  4305. log_warn(LD_REND, "Parsed descriptor ID does not match "
  4306. "computed descriptor ID.");
  4307. goto err;
  4308. }
  4309. goto done;
  4310. err:
  4311. rend_service_descriptor_free(result);
  4312. result = NULL;
  4313. done:
  4314. if (tokens) {
  4315. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4316. smartlist_free(tokens);
  4317. }
  4318. if (area)
  4319. memarea_drop_all(area);
  4320. *parsed_out = result;
  4321. if (result)
  4322. return 0;
  4323. return -1;
  4324. }
  4325. /** Decrypt the encrypted introduction points in <b>ipos_encrypted</b> of
  4326. * length <b>ipos_encrypted_size</b> using <b>descriptor_cookie</b> and
  4327. * write the result to a newly allocated string that is pointed to by
  4328. * <b>ipos_decrypted</b> and its length to <b>ipos_decrypted_size</b>.
  4329. * Return 0 if decryption was successful and -1 otherwise. */
  4330. int
  4331. rend_decrypt_introduction_points(char **ipos_decrypted,
  4332. size_t *ipos_decrypted_size,
  4333. const char *descriptor_cookie,
  4334. const char *ipos_encrypted,
  4335. size_t ipos_encrypted_size)
  4336. {
  4337. tor_assert(ipos_encrypted);
  4338. tor_assert(descriptor_cookie);
  4339. if (ipos_encrypted_size < 2) {
  4340. log_warn(LD_REND, "Size of encrypted introduction points is too "
  4341. "small.");
  4342. return -1;
  4343. }
  4344. if (ipos_encrypted[0] == (int)REND_BASIC_AUTH) {
  4345. char iv[CIPHER_IV_LEN], client_id[REND_BASIC_AUTH_CLIENT_ID_LEN],
  4346. session_key[CIPHER_KEY_LEN], *dec;
  4347. int declen, client_blocks;
  4348. size_t pos = 0, len, client_entries_len;
  4349. crypto_digest_t *digest;
  4350. crypto_cipher_t *cipher;
  4351. client_blocks = (int) ipos_encrypted[1];
  4352. client_entries_len = client_blocks * REND_BASIC_AUTH_CLIENT_MULTIPLE *
  4353. REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
  4354. if (ipos_encrypted_size < 2 + client_entries_len + CIPHER_IV_LEN + 1) {
  4355. log_warn(LD_REND, "Size of encrypted introduction points is too "
  4356. "small.");
  4357. return -1;
  4358. }
  4359. memcpy(iv, ipos_encrypted + 2 + client_entries_len, CIPHER_IV_LEN);
  4360. digest = crypto_digest_new();
  4361. crypto_digest_add_bytes(digest, descriptor_cookie, REND_DESC_COOKIE_LEN);
  4362. crypto_digest_add_bytes(digest, iv, CIPHER_IV_LEN);
  4363. crypto_digest_get_digest(digest, client_id,
  4364. REND_BASIC_AUTH_CLIENT_ID_LEN);
  4365. crypto_digest_free(digest);
  4366. for (pos = 2; pos < 2 + client_entries_len;
  4367. pos += REND_BASIC_AUTH_CLIENT_ENTRY_LEN) {
  4368. if (tor_memeq(ipos_encrypted + pos, client_id,
  4369. REND_BASIC_AUTH_CLIENT_ID_LEN)) {
  4370. /* Attempt to decrypt introduction points. */
  4371. cipher = crypto_cipher_new(descriptor_cookie);
  4372. if (crypto_cipher_decrypt(cipher, session_key, ipos_encrypted
  4373. + pos + REND_BASIC_AUTH_CLIENT_ID_LEN,
  4374. CIPHER_KEY_LEN) < 0) {
  4375. log_warn(LD_REND, "Could not decrypt session key for client.");
  4376. crypto_cipher_free(cipher);
  4377. return -1;
  4378. }
  4379. crypto_cipher_free(cipher);
  4380. len = ipos_encrypted_size - 2 - client_entries_len - CIPHER_IV_LEN;
  4381. dec = tor_malloc(len);
  4382. declen = crypto_cipher_decrypt_with_iv(session_key, dec, len,
  4383. ipos_encrypted + 2 + client_entries_len,
  4384. ipos_encrypted_size - 2 - client_entries_len);
  4385. if (declen < 0) {
  4386. log_warn(LD_REND, "Could not decrypt introduction point string.");
  4387. tor_free(dec);
  4388. return -1;
  4389. }
  4390. if (fast_memcmpstart(dec, declen, "introduction-point ")) {
  4391. log_warn(LD_REND, "Decrypted introduction points don't "
  4392. "look like we could parse them.");
  4393. tor_free(dec);
  4394. continue;
  4395. }
  4396. *ipos_decrypted = dec;
  4397. *ipos_decrypted_size = declen;
  4398. return 0;
  4399. }
  4400. }
  4401. log_warn(LD_REND, "Could not decrypt introduction points. Please "
  4402. "check your authorization for this service!");
  4403. return -1;
  4404. } else if (ipos_encrypted[0] == (int)REND_STEALTH_AUTH) {
  4405. char *dec;
  4406. int declen;
  4407. if (ipos_encrypted_size < CIPHER_IV_LEN + 2) {
  4408. log_warn(LD_REND, "Size of encrypted introduction points is too "
  4409. "small.");
  4410. return -1;
  4411. }
  4412. dec = tor_malloc_zero(ipos_encrypted_size - CIPHER_IV_LEN - 1);
  4413. declen = crypto_cipher_decrypt_with_iv(descriptor_cookie, dec,
  4414. ipos_encrypted_size -
  4415. CIPHER_IV_LEN - 1,
  4416. ipos_encrypted + 1,
  4417. ipos_encrypted_size - 1);
  4418. if (declen < 0) {
  4419. log_warn(LD_REND, "Decrypting introduction points failed!");
  4420. tor_free(dec);
  4421. return -1;
  4422. }
  4423. *ipos_decrypted = dec;
  4424. *ipos_decrypted_size = declen;
  4425. return 0;
  4426. } else {
  4427. log_warn(LD_REND, "Unknown authorization type number: %d",
  4428. ipos_encrypted[0]);
  4429. return -1;
  4430. }
  4431. }
  4432. /** Parse the encoded introduction points in <b>intro_points_encoded</b> of
  4433. * length <b>intro_points_encoded_size</b> and write the result to the
  4434. * descriptor in <b>parsed</b>; return the number of successfully parsed
  4435. * introduction points or -1 in case of a failure. */
  4436. int
  4437. rend_parse_introduction_points(rend_service_descriptor_t *parsed,
  4438. const char *intro_points_encoded,
  4439. size_t intro_points_encoded_size)
  4440. {
  4441. const char *current_ipo, *end_of_intro_points;
  4442. smartlist_t *tokens;
  4443. directory_token_t *tok;
  4444. rend_intro_point_t *intro;
  4445. extend_info_t *info;
  4446. int result, num_ok=1;
  4447. memarea_t *area = NULL;
  4448. tor_assert(parsed);
  4449. /** Function may only be invoked once. */
  4450. tor_assert(!parsed->intro_nodes);
  4451. tor_assert(intro_points_encoded);
  4452. tor_assert(intro_points_encoded_size > 0);
  4453. /* Consider one intro point after the other. */
  4454. current_ipo = intro_points_encoded;
  4455. end_of_intro_points = intro_points_encoded + intro_points_encoded_size;
  4456. tokens = smartlist_new();
  4457. parsed->intro_nodes = smartlist_new();
  4458. area = memarea_new();
  4459. while (!fast_memcmpstart(current_ipo, end_of_intro_points-current_ipo,
  4460. "introduction-point ")) {
  4461. /* Determine end of string. */
  4462. const char *eos = tor_memstr(current_ipo, end_of_intro_points-current_ipo,
  4463. "\nintroduction-point ");
  4464. if (!eos)
  4465. eos = end_of_intro_points;
  4466. else
  4467. eos = eos+1;
  4468. tor_assert(eos <= intro_points_encoded+intro_points_encoded_size);
  4469. /* Free tokens and clear token list. */
  4470. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4471. smartlist_clear(tokens);
  4472. memarea_clear(area);
  4473. /* Tokenize string. */
  4474. if (tokenize_string(area, current_ipo, eos, tokens, ipo_token_table, 0)) {
  4475. log_warn(LD_REND, "Error tokenizing introduction point");
  4476. goto err;
  4477. }
  4478. /* Advance to next introduction point, if available. */
  4479. current_ipo = eos;
  4480. /* Check minimum allowed length of introduction point. */
  4481. if (smartlist_len(tokens) < 5) {
  4482. log_warn(LD_REND, "Impossibly short introduction point.");
  4483. goto err;
  4484. }
  4485. /* Allocate new intro point and extend info. */
  4486. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  4487. info = intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  4488. /* Parse identifier. */
  4489. tok = find_by_keyword(tokens, R_IPO_IDENTIFIER);
  4490. if (base32_decode(info->identity_digest, DIGEST_LEN,
  4491. tok->args[0], REND_INTRO_POINT_ID_LEN_BASE32) < 0) {
  4492. log_warn(LD_REND, "Identity digest contains illegal characters: %s",
  4493. tok->args[0]);
  4494. rend_intro_point_free(intro);
  4495. goto err;
  4496. }
  4497. /* Write identifier to nickname. */
  4498. info->nickname[0] = '$';
  4499. base16_encode(info->nickname + 1, sizeof(info->nickname) - 1,
  4500. info->identity_digest, DIGEST_LEN);
  4501. /* Parse IP address. */
  4502. tok = find_by_keyword(tokens, R_IPO_IP_ADDRESS);
  4503. if (tor_addr_parse(&info->addr, tok->args[0])<0) {
  4504. log_warn(LD_REND, "Could not parse introduction point address.");
  4505. rend_intro_point_free(intro);
  4506. goto err;
  4507. }
  4508. if (tor_addr_family(&info->addr) != AF_INET) {
  4509. log_warn(LD_REND, "Introduction point address was not ipv4.");
  4510. rend_intro_point_free(intro);
  4511. goto err;
  4512. }
  4513. /* Parse onion port. */
  4514. tok = find_by_keyword(tokens, R_IPO_ONION_PORT);
  4515. info->port = (uint16_t) tor_parse_long(tok->args[0],10,1,65535,
  4516. &num_ok,NULL);
  4517. if (!info->port || !num_ok) {
  4518. log_warn(LD_REND, "Introduction point onion port %s is invalid",
  4519. escaped(tok->args[0]));
  4520. rend_intro_point_free(intro);
  4521. goto err;
  4522. }
  4523. /* Parse onion key. */
  4524. tok = find_by_keyword(tokens, R_IPO_ONION_KEY);
  4525. if (!crypto_pk_public_exponent_ok(tok->key)) {
  4526. log_warn(LD_REND,
  4527. "Introduction point's onion key had invalid exponent.");
  4528. rend_intro_point_free(intro);
  4529. goto err;
  4530. }
  4531. info->onion_key = tok->key;
  4532. tok->key = NULL; /* Prevent free */
  4533. /* Parse service key. */
  4534. tok = find_by_keyword(tokens, R_IPO_SERVICE_KEY);
  4535. if (!crypto_pk_public_exponent_ok(tok->key)) {
  4536. log_warn(LD_REND,
  4537. "Introduction point key had invalid exponent.");
  4538. rend_intro_point_free(intro);
  4539. goto err;
  4540. }
  4541. intro->intro_key = tok->key;
  4542. tok->key = NULL; /* Prevent free */
  4543. /* Add extend info to list of introduction points. */
  4544. smartlist_add(parsed->intro_nodes, intro);
  4545. }
  4546. result = smartlist_len(parsed->intro_nodes);
  4547. goto done;
  4548. err:
  4549. result = -1;
  4550. done:
  4551. /* Free tokens and clear token list. */
  4552. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4553. smartlist_free(tokens);
  4554. if (area)
  4555. memarea_drop_all(area);
  4556. return result;
  4557. }
  4558. /** Parse the content of a client_key file in <b>ckstr</b> and add
  4559. * rend_authorized_client_t's for each parsed client to
  4560. * <b>parsed_clients</b>. Return the number of parsed clients as result
  4561. * or -1 for failure. */
  4562. int
  4563. rend_parse_client_keys(strmap_t *parsed_clients, const char *ckstr)
  4564. {
  4565. int result = -1;
  4566. smartlist_t *tokens;
  4567. directory_token_t *tok;
  4568. const char *current_entry = NULL;
  4569. memarea_t *area = NULL;
  4570. if (!ckstr || strlen(ckstr) == 0)
  4571. return -1;
  4572. tokens = smartlist_new();
  4573. /* Begin parsing with first entry, skipping comments or whitespace at the
  4574. * beginning. */
  4575. area = memarea_new();
  4576. current_entry = eat_whitespace(ckstr);
  4577. while (!strcmpstart(current_entry, "client-name ")) {
  4578. rend_authorized_client_t *parsed_entry;
  4579. size_t len;
  4580. char descriptor_cookie_tmp[REND_DESC_COOKIE_LEN+2];
  4581. /* Determine end of string. */
  4582. const char *eos = strstr(current_entry, "\nclient-name ");
  4583. if (!eos)
  4584. eos = current_entry + strlen(current_entry);
  4585. else
  4586. eos = eos + 1;
  4587. /* Free tokens and clear token list. */
  4588. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4589. smartlist_clear(tokens);
  4590. memarea_clear(area);
  4591. /* Tokenize string. */
  4592. if (tokenize_string(area, current_entry, eos, tokens,
  4593. client_keys_token_table, 0)) {
  4594. log_warn(LD_REND, "Error tokenizing client keys file.");
  4595. goto err;
  4596. }
  4597. /* Advance to next entry, if available. */
  4598. current_entry = eos;
  4599. /* Check minimum allowed length of token list. */
  4600. if (smartlist_len(tokens) < 2) {
  4601. log_warn(LD_REND, "Impossibly short client key entry.");
  4602. goto err;
  4603. }
  4604. /* Parse client name. */
  4605. tok = find_by_keyword(tokens, C_CLIENT_NAME);
  4606. tor_assert(tok == smartlist_get(tokens, 0));
  4607. tor_assert(tok->n_args == 1);
  4608. len = strlen(tok->args[0]);
  4609. if (len < 1 || len > 19 ||
  4610. strspn(tok->args[0], REND_LEGAL_CLIENTNAME_CHARACTERS) != len) {
  4611. log_warn(LD_CONFIG, "Illegal client name: %s. (Length must be "
  4612. "between 1 and 19, and valid characters are "
  4613. "[A-Za-z0-9+-_].)", tok->args[0]);
  4614. goto err;
  4615. }
  4616. /* Check if client name is duplicate. */
  4617. if (strmap_get(parsed_clients, tok->args[0])) {
  4618. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains a "
  4619. "duplicate client name: '%s'. Ignoring.", tok->args[0]);
  4620. goto err;
  4621. }
  4622. parsed_entry = tor_malloc_zero(sizeof(rend_authorized_client_t));
  4623. parsed_entry->client_name = tor_strdup(tok->args[0]);
  4624. strmap_set(parsed_clients, parsed_entry->client_name, parsed_entry);
  4625. /* Parse client key. */
  4626. tok = find_opt_by_keyword(tokens, C_CLIENT_KEY);
  4627. if (tok) {
  4628. parsed_entry->client_key = tok->key;
  4629. tok->key = NULL; /* Prevent free */
  4630. }
  4631. /* Parse descriptor cookie. */
  4632. tok = find_by_keyword(tokens, C_DESCRIPTOR_COOKIE);
  4633. tor_assert(tok->n_args == 1);
  4634. if (strlen(tok->args[0]) != REND_DESC_COOKIE_LEN_BASE64 + 2) {
  4635. log_warn(LD_REND, "Descriptor cookie has illegal length: %s",
  4636. escaped(tok->args[0]));
  4637. goto err;
  4638. }
  4639. /* The size of descriptor_cookie_tmp needs to be REND_DESC_COOKIE_LEN+2,
  4640. * because a base64 encoding of length 24 does not fit into 16 bytes in all
  4641. * cases. */
  4642. if (base64_decode(descriptor_cookie_tmp, sizeof(descriptor_cookie_tmp),
  4643. tok->args[0], strlen(tok->args[0]))
  4644. != REND_DESC_COOKIE_LEN) {
  4645. log_warn(LD_REND, "Descriptor cookie contains illegal characters: "
  4646. "%s", escaped(tok->args[0]));
  4647. goto err;
  4648. }
  4649. memcpy(parsed_entry->descriptor_cookie, descriptor_cookie_tmp,
  4650. REND_DESC_COOKIE_LEN);
  4651. }
  4652. result = strmap_size(parsed_clients);
  4653. goto done;
  4654. err:
  4655. result = -1;
  4656. done:
  4657. /* Free tokens and clear token list. */
  4658. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4659. smartlist_free(tokens);
  4660. if (area)
  4661. memarea_drop_all(area);
  4662. return result;
  4663. }