routerparse.c 175 KB

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