routerparse.c 184 KB

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