routerparse.c 171 KB

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