routerparse.c 177 KB

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