routerparse.c 187 KB

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