routerparse.c 136 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096
  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-2009, 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 "memarea.h"
  12. /****************************************************************************/
  13. /** Enumeration of possible token types. The ones starting with K_ correspond
  14. * to directory 'keywords'. _ERR is an error in the tokenizing process, _EOF
  15. * is an end-of-file marker, and _NIL is used to encode not-a-token.
  16. */
  17. typedef enum {
  18. K_ACCEPT = 0,
  19. K_ACCEPT6,
  20. K_DIRECTORY_SIGNATURE,
  21. K_RECOMMENDED_SOFTWARE,
  22. K_REJECT,
  23. K_REJECT6,
  24. K_ROUTER,
  25. K_SIGNED_DIRECTORY,
  26. K_SIGNING_KEY,
  27. K_ONION_KEY,
  28. K_ROUTER_SIGNATURE,
  29. K_PUBLISHED,
  30. K_RUNNING_ROUTERS,
  31. K_ROUTER_STATUS,
  32. K_PLATFORM,
  33. K_OPT,
  34. K_BANDWIDTH,
  35. K_CONTACT,
  36. K_NETWORK_STATUS,
  37. K_UPTIME,
  38. K_DIR_SIGNING_KEY,
  39. K_FAMILY,
  40. K_FINGERPRINT,
  41. K_HIBERNATING,
  42. K_READ_HISTORY,
  43. K_WRITE_HISTORY,
  44. K_NETWORK_STATUS_VERSION,
  45. K_DIR_SOURCE,
  46. K_DIR_OPTIONS,
  47. K_CLIENT_VERSIONS,
  48. K_SERVER_VERSIONS,
  49. K_P,
  50. K_R,
  51. K_S,
  52. K_V,
  53. K_W,
  54. K_EVENTDNS,
  55. K_EXTRA_INFO,
  56. K_EXTRA_INFO_DIGEST,
  57. K_CACHES_EXTRA_INFO,
  58. K_HIDDEN_SERVICE_DIR,
  59. K_ALLOW_SINGLE_HOP_EXITS,
  60. K_DIRREQ_END,
  61. K_DIRREQ_V2_IPS,
  62. K_DIRREQ_V3_IPS,
  63. K_DIRREQ_V2_REQS,
  64. K_DIRREQ_V3_REQS,
  65. K_DIRREQ_V2_SHARE,
  66. K_DIRREQ_V3_SHARE,
  67. K_DIRREQ_V2_RESP,
  68. K_DIRREQ_V3_RESP,
  69. K_DIRREQ_V2_DIR,
  70. K_DIRREQ_V3_DIR,
  71. K_DIRREQ_V2_TUN,
  72. K_DIRREQ_V3_TUN,
  73. K_ENTRY_END,
  74. K_ENTRY_IPS,
  75. K_CELL_END,
  76. K_CELL_PROCESSED,
  77. K_CELL_QUEUED,
  78. K_CELL_TIME,
  79. K_CELL_CIRCS,
  80. K_EXIT_END,
  81. K_EXIT_WRITTEN,
  82. K_EXIT_READ,
  83. K_EXIT_OPENED,
  84. K_DIR_KEY_CERTIFICATE_VERSION,
  85. K_DIR_IDENTITY_KEY,
  86. K_DIR_KEY_PUBLISHED,
  87. K_DIR_KEY_EXPIRES,
  88. K_DIR_KEY_CERTIFICATION,
  89. K_DIR_KEY_CROSSCERT,
  90. K_DIR_ADDRESS,
  91. K_VOTE_STATUS,
  92. K_VALID_AFTER,
  93. K_FRESH_UNTIL,
  94. K_VALID_UNTIL,
  95. K_VOTING_DELAY,
  96. K_KNOWN_FLAGS,
  97. K_VOTE_DIGEST,
  98. K_CONSENSUS_DIGEST,
  99. K_CONSENSUS_METHODS,
  100. K_CONSENSUS_METHOD,
  101. K_LEGACY_DIR_KEY,
  102. A_PURPOSE,
  103. _A_UNKNOWN,
  104. R_RENDEZVOUS_SERVICE_DESCRIPTOR,
  105. R_VERSION,
  106. R_PERMANENT_KEY,
  107. R_SECRET_ID_PART,
  108. R_PUBLICATION_TIME,
  109. R_PROTOCOL_VERSIONS,
  110. R_INTRODUCTION_POINTS,
  111. R_SIGNATURE,
  112. R_IPO_IDENTIFIER,
  113. R_IPO_IP_ADDRESS,
  114. R_IPO_ONION_PORT,
  115. R_IPO_ONION_KEY,
  116. R_IPO_SERVICE_KEY,
  117. C_CLIENT_NAME,
  118. C_DESCRIPTOR_COOKIE,
  119. C_CLIENT_KEY,
  120. _ERR,
  121. _EOF,
  122. _NIL
  123. } directory_keyword;
  124. #define MIN_ANNOTATION A_PURPOSE
  125. #define MAX_ANNOTATION _A_UNKNOWN
  126. /** Structure to hold a single directory token.
  127. *
  128. * We parse a directory by breaking it into "tokens", each consisting
  129. * of a keyword, a line full of arguments, and a binary object. The
  130. * arguments and object are both optional, depending on the keyword
  131. * type.
  132. *
  133. * This structure is only allocated in memareas; do not allocate it on
  134. * the heap, or token_free() won't work.
  135. */
  136. typedef struct directory_token_t {
  137. directory_keyword tp; /**< Type of the token. */
  138. int n_args:30; /**< Number of elements in args */
  139. char **args; /**< Array of arguments from keyword line. */
  140. char *object_type; /**< -----BEGIN [object_type]-----*/
  141. size_t object_size; /**< Bytes in object_body */
  142. char *object_body; /**< Contents of object, base64-decoded. */
  143. crypto_pk_env_t *key; /**< For public keys only. Heap-allocated. */
  144. char *error; /**< For _ERR tokens only. */
  145. } directory_token_t;
  146. /* ********************************************************************** */
  147. /** We use a table of rules to decide how to parse each token type. */
  148. /** Rules for whether the keyword needs an object. */
  149. typedef enum {
  150. NO_OBJ, /**< No object, ever. */
  151. NEED_OBJ, /**< Object is required. */
  152. NEED_SKEY_1024,/**< Object is required, and must be a 1024 bit private key */
  153. NEED_KEY_1024, /**< Object is required, and must be a 1024 bit public key */
  154. NEED_KEY, /**< Object is required, and must be a public key. */
  155. OBJ_OK, /**< Object is optional. */
  156. } obj_syntax;
  157. #define AT_START 1
  158. #define AT_END 2
  159. /** Determines the parsing rules for a single token type. */
  160. typedef struct token_rule_t {
  161. /** The string value of the keyword identifying the type of item. */
  162. const char *t;
  163. /** The corresponding directory_keyword enum. */
  164. directory_keyword v;
  165. /** Minimum number of arguments for this item */
  166. int min_args;
  167. /** Maximum number of arguments for this item */
  168. int max_args;
  169. /** If true, we concatenate all arguments for this item into a single
  170. * string. */
  171. int concat_args;
  172. /** Requirements on object syntax for this item. */
  173. obj_syntax os;
  174. /** Lowest number of times this item may appear in a document. */
  175. int min_cnt;
  176. /** Highest number of times this item may appear in a document. */
  177. int max_cnt;
  178. /** One or more of AT_START/AT_END to limit where the item may appear in a
  179. * document. */
  180. int pos;
  181. /** True iff this token is an annotation. */
  182. int is_annotation;
  183. } token_rule_t;
  184. /*
  185. * Helper macros to define token tables. 's' is a string, 't' is a
  186. * directory_keyword, 'a' is a trio of argument multiplicities, and 'o' is an
  187. * object syntax.
  188. *
  189. */
  190. /** Appears to indicate the end of a table. */
  191. #define END_OF_TABLE { NULL, _NIL, 0,0,0, NO_OBJ, 0, INT_MAX, 0, 0 }
  192. /** An item with no restrictions: used for obsolete document types */
  193. #define T(s,t,a,o) { s, t, a, o, 0, INT_MAX, 0, 0 }
  194. /** An item with no restrictions on multiplicity or location. */
  195. #define T0N(s,t,a,o) { s, t, a, o, 0, INT_MAX, 0, 0 }
  196. /** An item that must appear exactly once */
  197. #define T1(s,t,a,o) { s, t, a, o, 1, 1, 0, 0 }
  198. /** An item that must appear exactly once, at the start of the document */
  199. #define T1_START(s,t,a,o) { s, t, a, o, 1, 1, AT_START, 0 }
  200. /** An item that must appear exactly once, at the end of the document */
  201. #define T1_END(s,t,a,o) { s, t, a, o, 1, 1, AT_END, 0 }
  202. /** An item that must appear one or more times */
  203. #define T1N(s,t,a,o) { s, t, a, o, 1, INT_MAX, 0, 0 }
  204. /** An item that must appear no more than once */
  205. #define T01(s,t,a,o) { s, t, a, o, 0, 1, 0, 0 }
  206. /** An annotation that must appear no more than once */
  207. #define A01(s,t,a,o) { s, t, a, o, 0, 1, 0, 1 }
  208. /* Argument multiplicity: any number of arguments. */
  209. #define ARGS 0,INT_MAX,0
  210. /* Argument multiplicity: no arguments. */
  211. #define NO_ARGS 0,0,0
  212. /* Argument multiplicity: concatenate all arguments. */
  213. #define CONCAT_ARGS 1,1,1
  214. /* Argument multiplicity: at least <b>n</b> arguments. */
  215. #define GE(n) n,INT_MAX,0
  216. /* Argument multiplicity: exactly <b>n</b> arguments. */
  217. #define EQ(n) n,n,0
  218. /** List of tokens allowable in router descriptors */
  219. static token_rule_t routerdesc_token_table[] = {
  220. T0N("reject", K_REJECT, ARGS, NO_OBJ ),
  221. T0N("accept", K_ACCEPT, ARGS, NO_OBJ ),
  222. T0N("reject6", K_REJECT6, ARGS, NO_OBJ ),
  223. T0N("accept6", K_ACCEPT6, ARGS, NO_OBJ ),
  224. T1_START( "router", K_ROUTER, GE(5), NO_OBJ ),
  225. T1( "signing-key", K_SIGNING_KEY, NO_ARGS, NEED_KEY_1024 ),
  226. T1( "onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY_1024 ),
  227. T1_END( "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ ),
  228. T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  229. T01("uptime", K_UPTIME, GE(1), NO_OBJ ),
  230. T01("fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  231. T01("hibernating", K_HIBERNATING, GE(1), NO_OBJ ),
  232. T01("platform", K_PLATFORM, CONCAT_ARGS, NO_OBJ ),
  233. T01("contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  234. T01("read-history", K_READ_HISTORY, ARGS, NO_OBJ ),
  235. T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
  236. T01("extra-info-digest", K_EXTRA_INFO_DIGEST, GE(1), NO_OBJ ),
  237. T01("hidden-service-dir", K_HIDDEN_SERVICE_DIR, NO_ARGS, NO_OBJ ),
  238. T01("allow-single-hop-exits",K_ALLOW_SINGLE_HOP_EXITS, NO_ARGS, NO_OBJ ),
  239. T01("family", K_FAMILY, ARGS, NO_OBJ ),
  240. T01("caches-extra-info", K_CACHES_EXTRA_INFO, NO_ARGS, NO_OBJ ),
  241. T01("eventdns", K_EVENTDNS, ARGS, NO_OBJ ),
  242. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  243. T1( "bandwidth", K_BANDWIDTH, GE(3), NO_OBJ ),
  244. A01("@purpose", A_PURPOSE, GE(1), NO_OBJ ),
  245. END_OF_TABLE
  246. };
  247. /** List of tokens allowable in extra-info documents. */
  248. static token_rule_t extrainfo_token_table[] = {
  249. T1_END( "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ ),
  250. T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  251. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  252. T01("read-history", K_READ_HISTORY, ARGS, NO_OBJ ),
  253. T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
  254. T01("dirreq-stats-end", K_DIRREQ_END, ARGS, NO_OBJ ),
  255. T01("dirreq-v2-ips", K_DIRREQ_V2_IPS, ARGS, NO_OBJ ),
  256. T01("dirreq-v3-ips", K_DIRREQ_V3_IPS, ARGS, NO_OBJ ),
  257. T01("dirreq-v2-reqs", K_DIRREQ_V2_REQS, ARGS, NO_OBJ ),
  258. T01("dirreq-v3-reqs", K_DIRREQ_V3_REQS, ARGS, NO_OBJ ),
  259. T01("dirreq-v2-share", K_DIRREQ_V2_SHARE, ARGS, NO_OBJ ),
  260. T01("dirreq-v3-share", K_DIRREQ_V3_SHARE, ARGS, NO_OBJ ),
  261. T01("dirreq-v2-resp", K_DIRREQ_V2_RESP, ARGS, NO_OBJ ),
  262. T01("dirreq-v3-resp", K_DIRREQ_V3_RESP, ARGS, NO_OBJ ),
  263. T01("dirreq-v2-direct-dl", K_DIRREQ_V2_DIR, ARGS, NO_OBJ ),
  264. T01("dirreq-v3-direct-dl", K_DIRREQ_V3_DIR, ARGS, NO_OBJ ),
  265. T01("dirreq-v2-tunneled-dl", K_DIRREQ_V2_TUN, ARGS, NO_OBJ ),
  266. T01("dirreq-v3-tunneled-dl", K_DIRREQ_V3_TUN, ARGS, NO_OBJ ),
  267. T01("entry-stats-end", K_ENTRY_END, ARGS, NO_OBJ ),
  268. T01("entry-ips", K_ENTRY_IPS, ARGS, NO_OBJ ),
  269. T01("cell-stats-end", K_CELL_END, ARGS, NO_OBJ ),
  270. T01("cell-processed-cells", K_CELL_PROCESSED, ARGS, NO_OBJ ),
  271. T01("cell-queued-cells", K_CELL_QUEUED, ARGS, NO_OBJ ),
  272. T01("cell-time-in-queue", K_CELL_TIME, ARGS, NO_OBJ ),
  273. T01("cell-circuits-per-decile", K_CELL_CIRCS, ARGS, NO_OBJ ),
  274. T01("exit-stats-end", K_EXIT_END, ARGS, NO_OBJ ),
  275. T01("exit-kibibytes-written", K_EXIT_WRITTEN, ARGS, NO_OBJ ),
  276. T01("exit-kibibytes-read", K_EXIT_READ, ARGS, NO_OBJ ),
  277. T01("exit-streams-opened", K_EXIT_OPENED, ARGS, NO_OBJ ),
  278. T1_START( "extra-info", K_EXTRA_INFO, GE(2), NO_OBJ ),
  279. END_OF_TABLE
  280. };
  281. /** List of tokens allowable in the body part of v2 and v3 networkstatus
  282. * documents. */
  283. static token_rule_t rtrstatus_token_table[] = {
  284. T01("p", K_P, CONCAT_ARGS, NO_OBJ ),
  285. T1( "r", K_R, GE(8), NO_OBJ ),
  286. T1( "s", K_S, ARGS, NO_OBJ ),
  287. T01("v", K_V, CONCAT_ARGS, NO_OBJ ),
  288. T01("w", K_W, ARGS, NO_OBJ ),
  289. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  290. END_OF_TABLE
  291. };
  292. /** List of tokens allowable in the header part of v2 networkstatus documents.
  293. */
  294. static token_rule_t netstatus_token_table[] = {
  295. T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  296. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  297. T1( "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  298. T1( "dir-signing-key", K_DIR_SIGNING_KEY, NO_ARGS, NEED_KEY_1024 ),
  299. T1( "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  300. T1_START("network-status-version", K_NETWORK_STATUS_VERSION,
  301. GE(1), NO_OBJ ),
  302. T1( "dir-source", K_DIR_SOURCE, GE(3), NO_OBJ ),
  303. T01("dir-options", K_DIR_OPTIONS, ARGS, NO_OBJ ),
  304. T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  305. T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  306. END_OF_TABLE
  307. };
  308. /** List of tokens allowable in the footer of v1/v2 directory/networkstatus
  309. * footers. */
  310. static token_rule_t dir_footer_token_table[] = {
  311. T1("directory-signature", K_DIRECTORY_SIGNATURE, EQ(1), NEED_OBJ ),
  312. END_OF_TABLE
  313. };
  314. /** List of tokens allowable in v1 directory headers/footers. */
  315. static token_rule_t dir_token_table[] = {
  316. /* don't enforce counts; this is obsolete. */
  317. T( "network-status", K_NETWORK_STATUS, NO_ARGS, NO_OBJ ),
  318. T( "directory-signature", K_DIRECTORY_SIGNATURE, ARGS, NEED_OBJ ),
  319. T( "recommended-software",K_RECOMMENDED_SOFTWARE,CONCAT_ARGS, NO_OBJ ),
  320. T( "signed-directory", K_SIGNED_DIRECTORY, NO_ARGS, NO_OBJ ),
  321. T( "running-routers", K_RUNNING_ROUTERS, ARGS, NO_OBJ ),
  322. T( "router-status", K_ROUTER_STATUS, ARGS, NO_OBJ ),
  323. T( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  324. T( "opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  325. T( "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  326. T( "dir-signing-key", K_DIR_SIGNING_KEY, ARGS, OBJ_OK ),
  327. T( "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  328. END_OF_TABLE
  329. };
  330. /** List of tokens common to V3 authority certificates and V3 consensuses. */
  331. #define CERTIFICATE_MEMBERS \
  332. T1("dir-key-certificate-version", K_DIR_KEY_CERTIFICATE_VERSION, \
  333. GE(1), NO_OBJ ), \
  334. T1("dir-identity-key", K_DIR_IDENTITY_KEY, NO_ARGS, NEED_KEY ),\
  335. T1("dir-key-published",K_DIR_KEY_PUBLISHED, CONCAT_ARGS, NO_OBJ), \
  336. T1("dir-key-expires", K_DIR_KEY_EXPIRES, CONCAT_ARGS, NO_OBJ), \
  337. T1("dir-signing-key", K_DIR_SIGNING_KEY, NO_ARGS, NEED_KEY ),\
  338. T01("dir-key-crosscert", K_DIR_KEY_CROSSCERT, NO_ARGS, NEED_OBJ ),\
  339. T1("dir-key-certification", K_DIR_KEY_CERTIFICATION, \
  340. NO_ARGS, NEED_OBJ), \
  341. T01("dir-address", K_DIR_ADDRESS, GE(1), NO_OBJ),
  342. /** List of tokens allowable in V3 authority certificates. */
  343. static token_rule_t dir_key_certificate_table[] = {
  344. CERTIFICATE_MEMBERS
  345. T1("fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  346. END_OF_TABLE
  347. };
  348. /** List of tokens allowable in rendezvous service descriptors */
  349. static token_rule_t desc_token_table[] = {
  350. T1_START("rendezvous-service-descriptor", R_RENDEZVOUS_SERVICE_DESCRIPTOR,
  351. EQ(1), NO_OBJ),
  352. T1("version", R_VERSION, EQ(1), NO_OBJ),
  353. T1("permanent-key", R_PERMANENT_KEY, NO_ARGS, NEED_KEY_1024),
  354. T1("secret-id-part", R_SECRET_ID_PART, EQ(1), NO_OBJ),
  355. T1("publication-time", R_PUBLICATION_TIME, CONCAT_ARGS, NO_OBJ),
  356. T1("protocol-versions", R_PROTOCOL_VERSIONS, EQ(1), NO_OBJ),
  357. T01("introduction-points", R_INTRODUCTION_POINTS, NO_ARGS, NEED_OBJ),
  358. T1_END("signature", R_SIGNATURE, NO_ARGS, NEED_OBJ),
  359. END_OF_TABLE
  360. };
  361. /** List of tokens allowed in the (encrypted) list of introduction points of
  362. * rendezvous service descriptors */
  363. static token_rule_t ipo_token_table[] = {
  364. T1_START("introduction-point", R_IPO_IDENTIFIER, EQ(1), NO_OBJ),
  365. T1("ip-address", R_IPO_IP_ADDRESS, EQ(1), NO_OBJ),
  366. T1("onion-port", R_IPO_ONION_PORT, EQ(1), NO_OBJ),
  367. T1("onion-key", R_IPO_ONION_KEY, NO_ARGS, NEED_KEY_1024),
  368. T1("service-key", R_IPO_SERVICE_KEY, NO_ARGS, NEED_KEY_1024),
  369. END_OF_TABLE
  370. };
  371. /** List of tokens allowed in the (possibly encrypted) list of introduction
  372. * points of rendezvous service descriptors */
  373. static token_rule_t client_keys_token_table[] = {
  374. T1_START("client-name", C_CLIENT_NAME, CONCAT_ARGS, NO_OBJ),
  375. T1("descriptor-cookie", C_DESCRIPTOR_COOKIE, EQ(1), NO_OBJ),
  376. T01("client-key", C_CLIENT_KEY, NO_ARGS, NEED_SKEY_1024),
  377. END_OF_TABLE
  378. };
  379. /** List of tokens allowed in V3 networkstatus votes. */
  380. static token_rule_t networkstatus_token_table[] = {
  381. T1("network-status-version", K_NETWORK_STATUS_VERSION,
  382. GE(1), NO_OBJ ),
  383. T1("vote-status", K_VOTE_STATUS, GE(1), NO_OBJ ),
  384. T1("published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  385. T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
  386. T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
  387. T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
  388. T1("voting-delay", K_VOTING_DELAY, GE(2), NO_OBJ ),
  389. T1("known-flags", K_KNOWN_FLAGS, ARGS, NO_OBJ ),
  390. T( "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  391. CERTIFICATE_MEMBERS
  392. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  393. T1( "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  394. T1( "dir-source", K_DIR_SOURCE, GE(6), NO_OBJ ),
  395. T01("legacy-dir-key", K_LEGACY_DIR_KEY, GE(1), NO_OBJ ),
  396. T1( "known-flags", K_KNOWN_FLAGS, CONCAT_ARGS, NO_OBJ ),
  397. T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  398. T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  399. T1( "consensus-methods", K_CONSENSUS_METHODS, GE(1), NO_OBJ ),
  400. END_OF_TABLE
  401. };
  402. /** List of tokens allowed in V3 networkstatus consensuses. */
  403. static token_rule_t networkstatus_consensus_token_table[] = {
  404. T1("network-status-version", K_NETWORK_STATUS_VERSION,
  405. GE(1), NO_OBJ ),
  406. T1("vote-status", K_VOTE_STATUS, GE(1), 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. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  412. T1N("dir-source", K_DIR_SOURCE, GE(6), NO_OBJ ),
  413. T1N("contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  414. T1N("vote-digest", K_VOTE_DIGEST, GE(1), NO_OBJ ),
  415. T1( "known-flags", K_KNOWN_FLAGS, CONCAT_ARGS, NO_OBJ ),
  416. T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  417. T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  418. T01("consensus-method", K_CONSENSUS_METHOD, EQ(1), NO_OBJ),
  419. END_OF_TABLE
  420. };
  421. /** List of tokens allowable in the footer of v1/v2 directory/networkstatus
  422. * footers. */
  423. static token_rule_t networkstatus_vote_footer_token_table[] = {
  424. T( "directory-signature", K_DIRECTORY_SIGNATURE, GE(2), NEED_OBJ ),
  425. END_OF_TABLE
  426. };
  427. /** List of tokens allowable in detached networkstatus signature documents. */
  428. static token_rule_t networkstatus_detached_signature_token_table[] = {
  429. T1_START("consensus-digest", K_CONSENSUS_DIGEST, 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. T1N("directory-signature", K_DIRECTORY_SIGNATURE, GE(2), NEED_OBJ ),
  434. END_OF_TABLE
  435. };
  436. #undef T
  437. /* static function prototypes */
  438. static int router_add_exit_policy(routerinfo_t *router,directory_token_t *tok);
  439. static addr_policy_t *router_parse_addr_policy(directory_token_t *tok);
  440. static addr_policy_t *router_parse_addr_policy_private(directory_token_t *tok);
  441. static int router_get_hash_impl(const char *s, char *digest,
  442. const char *start_str, const char *end_str,
  443. char end_char);
  444. static void token_free(directory_token_t *tok);
  445. static smartlist_t *find_all_exitpolicy(smartlist_t *s);
  446. static directory_token_t *_find_by_keyword(smartlist_t *s,
  447. directory_keyword keyword,
  448. const char *keyword_str);
  449. #define find_by_keyword(s, keyword) _find_by_keyword((s), (keyword), #keyword)
  450. static directory_token_t *find_opt_by_keyword(smartlist_t *s,
  451. directory_keyword keyword);
  452. #define TS_ANNOTATIONS_OK 1
  453. #define TS_NOCHECK 2
  454. #define TS_NO_NEW_ANNOTATIONS 4
  455. static int tokenize_string(memarea_t *area,
  456. const char *start, const char *end,
  457. smartlist_t *out,
  458. token_rule_t *table,
  459. int flags);
  460. static directory_token_t *get_next_token(memarea_t *area,
  461. const char **s,
  462. const char *eos,
  463. token_rule_t *table);
  464. #define CST_CHECK_AUTHORITY (1<<0)
  465. #define CST_NO_CHECK_OBJTYPE (1<<1)
  466. static int check_signature_token(const char *digest,
  467. directory_token_t *tok,
  468. crypto_pk_env_t *pkey,
  469. int flags,
  470. const char *doctype);
  471. static crypto_pk_env_t *find_dir_signing_key(const char *str, const char *eos);
  472. static int tor_version_same_series(tor_version_t *a, tor_version_t *b);
  473. #undef DEBUG_AREA_ALLOC
  474. #ifdef DEBUG_AREA_ALLOC
  475. #define DUMP_AREA(a,name) STMT_BEGIN \
  476. size_t alloc=0, used=0; \
  477. memarea_get_stats((a),&alloc,&used); \
  478. log_debug(LD_MM, "Area for %s has %lu allocated; using %lu.", \
  479. name, (unsigned long)alloc, (unsigned long)used); \
  480. STMT_END
  481. #else
  482. #define DUMP_AREA(a,name) STMT_NIL
  483. #endif
  484. /** Set <b>digest</b> to the SHA-1 digest of the hash of the directory in
  485. * <b>s</b>. Return 0 on success, -1 on failure.
  486. */
  487. int
  488. router_get_dir_hash(const char *s, char *digest)
  489. {
  490. return router_get_hash_impl(s,digest,
  491. "signed-directory","\ndirectory-signature",'\n');
  492. }
  493. /** Set <b>digest</b> to the SHA-1 digest of the hash of the first router in
  494. * <b>s</b>. Return 0 on success, -1 on failure.
  495. */
  496. int
  497. router_get_router_hash(const char *s, char *digest)
  498. {
  499. return router_get_hash_impl(s,digest,
  500. "router ","\nrouter-signature", '\n');
  501. }
  502. /** Set <b>digest</b> to the SHA-1 digest of the hash of the running-routers
  503. * string in <b>s</b>. Return 0 on success, -1 on failure.
  504. */
  505. int
  506. router_get_runningrouters_hash(const char *s, char *digest)
  507. {
  508. return router_get_hash_impl(s,digest,
  509. "network-status","\ndirectory-signature", '\n');
  510. }
  511. /** Set <b>digest</b> to the SHA-1 digest of the hash of the network-status
  512. * string in <b>s</b>. Return 0 on success, -1 on failure. */
  513. int
  514. router_get_networkstatus_v2_hash(const char *s, char *digest)
  515. {
  516. return router_get_hash_impl(s,digest,
  517. "network-status-version","\ndirectory-signature",
  518. '\n');
  519. }
  520. /** Set <b>digest</b> to the SHA-1 digest of the hash of the network-status
  521. * string in <b>s</b>. Return 0 on success, -1 on failure. */
  522. int
  523. router_get_networkstatus_v3_hash(const char *s, char *digest)
  524. {
  525. return router_get_hash_impl(s,digest,
  526. "network-status-version","\ndirectory-signature",
  527. ' ');
  528. }
  529. /** Set <b>digest</b> to the SHA-1 digest of the hash of the extrainfo
  530. * string in <b>s</b>. Return 0 on success, -1 on failure. */
  531. int
  532. router_get_extrainfo_hash(const char *s, char *digest)
  533. {
  534. return router_get_hash_impl(s,digest,"extra-info","\nrouter-signature",'\n');
  535. }
  536. /** Helper: used to generate signatures for routers, directories and
  537. * network-status objects. Given a digest in <b>digest</b> and a secret
  538. * <b>private_key</b>, generate an PKCS1-padded signature, BASE64-encode it,
  539. * surround it with -----BEGIN/END----- pairs, and write it to the
  540. * <b>buf_len</b>-byte buffer at <b>buf</b>. Return 0 on success, -1 on
  541. * failure.
  542. */
  543. int
  544. router_append_dirobj_signature(char *buf, size_t buf_len, const char *digest,
  545. crypto_pk_env_t *private_key)
  546. {
  547. char *signature;
  548. size_t i;
  549. signature = tor_malloc(crypto_pk_keysize(private_key));
  550. if (crypto_pk_private_sign(private_key, signature, digest, DIGEST_LEN) < 0) {
  551. log_warn(LD_BUG,"Couldn't sign digest.");
  552. goto err;
  553. }
  554. if (strlcat(buf, "-----BEGIN SIGNATURE-----\n", buf_len) >= buf_len)
  555. goto truncated;
  556. i = strlen(buf);
  557. if (base64_encode(buf+i, buf_len-i, signature, 128) < 0) {
  558. log_warn(LD_BUG,"couldn't base64-encode signature");
  559. goto err;
  560. }
  561. if (strlcat(buf, "-----END SIGNATURE-----\n", buf_len) >= buf_len)
  562. goto truncated;
  563. tor_free(signature);
  564. return 0;
  565. truncated:
  566. log_warn(LD_BUG,"tried to exceed string length.");
  567. err:
  568. tor_free(signature);
  569. return -1;
  570. }
  571. /** Return VS_RECOMMENDED if <b>myversion</b> is contained in
  572. * <b>versionlist</b>. Else, return VS_EMPTY if versionlist has no
  573. * entries. Else, return VS_OLD if every member of
  574. * <b>versionlist</b> is newer than <b>myversion</b>. Else, return
  575. * VS_NEW_IN_SERIES if there is at least one member of <b>versionlist</b> in
  576. * the same series (major.minor.micro) as <b>myversion</b>, but no such member
  577. * is newer than <b>myversion.</b>. Else, return VS_NEW if every member of
  578. * <b>versionlist</b> is older than <b>myversion</b>. Else, return
  579. * VS_UNRECOMMENDED.
  580. *
  581. * (versionlist is a comma-separated list of version strings,
  582. * optionally prefixed with "Tor". Versions that can't be parsed are
  583. * ignored.)
  584. */
  585. version_status_t
  586. tor_version_is_obsolete(const char *myversion, const char *versionlist)
  587. {
  588. tor_version_t mine, other;
  589. int found_newer = 0, found_older = 0, found_newer_in_series = 0,
  590. found_any_in_series = 0, r, same;
  591. version_status_t ret = VS_UNRECOMMENDED;
  592. smartlist_t *version_sl;
  593. log_debug(LD_CONFIG,"Checking whether version '%s' is in '%s'",
  594. myversion, versionlist);
  595. if (tor_version_parse(myversion, &mine)) {
  596. log_err(LD_BUG,"I couldn't parse my own version (%s)", myversion);
  597. tor_assert(0);
  598. }
  599. version_sl = smartlist_create();
  600. smartlist_split_string(version_sl, versionlist, ",", SPLIT_SKIP_SPACE, 0);
  601. if (!strlen(versionlist)) { /* no authorities cared or agreed */
  602. ret = VS_EMPTY;
  603. goto done;
  604. }
  605. SMARTLIST_FOREACH(version_sl, const char *, cp, {
  606. if (!strcmpstart(cp, "Tor "))
  607. cp += 4;
  608. if (tor_version_parse(cp, &other)) {
  609. /* Couldn't parse other; it can't be a match. */
  610. } else {
  611. same = tor_version_same_series(&mine, &other);
  612. if (same)
  613. found_any_in_series = 1;
  614. r = tor_version_compare(&mine, &other);
  615. if (r==0) {
  616. ret = VS_RECOMMENDED;
  617. goto done;
  618. } else if (r<0) {
  619. found_newer = 1;
  620. if (same)
  621. found_newer_in_series = 1;
  622. } else if (r>0) {
  623. found_older = 1;
  624. }
  625. }
  626. });
  627. /* We didn't find the listed version. Is it new or old? */
  628. if (found_any_in_series && !found_newer_in_series && found_newer) {
  629. ret = VS_NEW_IN_SERIES;
  630. } else if (found_newer && !found_older) {
  631. ret = VS_OLD;
  632. } else if (found_older && !found_newer) {
  633. ret = VS_NEW;
  634. } else {
  635. ret = VS_UNRECOMMENDED;
  636. }
  637. done:
  638. SMARTLIST_FOREACH(version_sl, char *, version, tor_free(version));
  639. smartlist_free(version_sl);
  640. return ret;
  641. }
  642. /** Read a signed directory from <b>str</b>. If it's well-formed, return 0.
  643. * Otherwise, return -1. If we're a directory cache, cache it.
  644. */
  645. int
  646. router_parse_directory(const char *str)
  647. {
  648. directory_token_t *tok;
  649. char digest[DIGEST_LEN];
  650. time_t published_on;
  651. int r;
  652. const char *end, *cp;
  653. smartlist_t *tokens = NULL;
  654. crypto_pk_env_t *declared_key = NULL;
  655. memarea_t *area = memarea_new();
  656. /* XXXX This could be simplified a lot, but it will all go away
  657. * once pre-0.1.1.8 is obsolete, and for now it's better not to
  658. * touch it. */
  659. if (router_get_dir_hash(str, digest)) {
  660. log_warn(LD_DIR, "Unable to compute digest of directory");
  661. goto err;
  662. }
  663. log_debug(LD_DIR,"Received directory hashes to %s",hex_str(digest,4));
  664. /* Check signature first, before we try to tokenize. */
  665. cp = str;
  666. while (cp && (end = strstr(cp+1, "\ndirectory-signature")))
  667. cp = end;
  668. if (cp == str || !cp) {
  669. log_warn(LD_DIR, "No signature found on directory."); goto err;
  670. }
  671. ++cp;
  672. tokens = smartlist_create();
  673. if (tokenize_string(area,cp,strchr(cp,'\0'),tokens,dir_token_table,0)) {
  674. log_warn(LD_DIR, "Error tokenizing directory signature"); goto err;
  675. }
  676. if (smartlist_len(tokens) != 1) {
  677. log_warn(LD_DIR, "Unexpected number of tokens in signature"); goto err;
  678. }
  679. tok=smartlist_get(tokens,0);
  680. if (tok->tp != K_DIRECTORY_SIGNATURE) {
  681. log_warn(LD_DIR,"Expected a single directory signature"); goto err;
  682. }
  683. declared_key = find_dir_signing_key(str, str+strlen(str));
  684. note_crypto_pk_op(VERIFY_DIR);
  685. if (check_signature_token(digest, tok, declared_key,
  686. CST_CHECK_AUTHORITY, "directory")<0)
  687. goto err;
  688. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  689. smartlist_clear(tokens);
  690. memarea_clear(area);
  691. /* Now try to parse the first part of the directory. */
  692. if ((end = strstr(str,"\nrouter "))) {
  693. ++end;
  694. } else if ((end = strstr(str, "\ndirectory-signature"))) {
  695. ++end;
  696. } else {
  697. end = str + strlen(str);
  698. }
  699. if (tokenize_string(area,str,end,tokens,dir_token_table,0)) {
  700. log_warn(LD_DIR, "Error tokenizing directory"); goto err;
  701. }
  702. tok = find_by_keyword(tokens, K_PUBLISHED);
  703. tor_assert(tok->n_args == 1);
  704. if (parse_iso_time(tok->args[0], &published_on) < 0) {
  705. goto err;
  706. }
  707. /* Now that we know the signature is okay, and we have a
  708. * publication time, cache the directory. */
  709. if (directory_caches_v1_dir_info(get_options()) &&
  710. !authdir_mode_v1(get_options()))
  711. dirserv_set_cached_directory(str, published_on, 0);
  712. r = 0;
  713. goto done;
  714. err:
  715. r = -1;
  716. done:
  717. if (declared_key) crypto_free_pk_env(declared_key);
  718. if (tokens) {
  719. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  720. smartlist_free(tokens);
  721. }
  722. if (area) {
  723. DUMP_AREA(area, "v1 directory");
  724. memarea_drop_all(area);
  725. }
  726. return r;
  727. }
  728. /** Read a signed router status statement from <b>str</b>. If it's
  729. * well-formed, return 0. Otherwise, return -1. If we're a directory cache,
  730. * cache it.*/
  731. int
  732. router_parse_runningrouters(const char *str)
  733. {
  734. char digest[DIGEST_LEN];
  735. directory_token_t *tok;
  736. time_t published_on;
  737. int r = -1;
  738. crypto_pk_env_t *declared_key = NULL;
  739. smartlist_t *tokens = NULL;
  740. const char *eos = str + strlen(str);
  741. memarea_t *area = NULL;
  742. if (router_get_runningrouters_hash(str, digest)) {
  743. log_warn(LD_DIR, "Unable to compute digest of running-routers");
  744. goto err;
  745. }
  746. area = memarea_new();
  747. tokens = smartlist_create();
  748. if (tokenize_string(area,str,eos,tokens,dir_token_table,0)) {
  749. log_warn(LD_DIR, "Error tokenizing running-routers"); goto err;
  750. }
  751. tok = smartlist_get(tokens,0);
  752. if (tok->tp != K_NETWORK_STATUS) {
  753. log_warn(LD_DIR, "Network-status starts with wrong token");
  754. goto err;
  755. }
  756. tok = find_by_keyword(tokens, K_PUBLISHED);
  757. tor_assert(tok->n_args == 1);
  758. if (parse_iso_time(tok->args[0], &published_on) < 0) {
  759. goto err;
  760. }
  761. if (!(tok = find_opt_by_keyword(tokens, K_DIRECTORY_SIGNATURE))) {
  762. log_warn(LD_DIR, "Missing signature on running-routers");
  763. goto err;
  764. }
  765. declared_key = find_dir_signing_key(str, eos);
  766. note_crypto_pk_op(VERIFY_DIR);
  767. if (check_signature_token(digest, tok, declared_key,
  768. CST_CHECK_AUTHORITY, "running-routers")
  769. < 0)
  770. goto err;
  771. /* Now that we know the signature is okay, and we have a
  772. * publication time, cache the list. */
  773. if (get_options()->DirPort && !authdir_mode_v1(get_options()))
  774. dirserv_set_cached_directory(str, published_on, 1);
  775. r = 0;
  776. err:
  777. if (declared_key) crypto_free_pk_env(declared_key);
  778. if (tokens) {
  779. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  780. smartlist_free(tokens);
  781. }
  782. if (area) {
  783. DUMP_AREA(area, "v1 running-routers");
  784. memarea_drop_all(area);
  785. }
  786. return r;
  787. }
  788. /** Given a directory or running-routers string in <b>str</b>, try to
  789. * find the its dir-signing-key token (if any). If this token is
  790. * present, extract and return the key. Return NULL on failure. */
  791. static crypto_pk_env_t *
  792. find_dir_signing_key(const char *str, const char *eos)
  793. {
  794. const char *cp;
  795. directory_token_t *tok;
  796. crypto_pk_env_t *key = NULL;
  797. memarea_t *area = NULL;
  798. tor_assert(str);
  799. tor_assert(eos);
  800. /* Is there a dir-signing-key in the directory? */
  801. cp = tor_memstr(str, eos-str, "\nopt dir-signing-key");
  802. if (!cp)
  803. cp = tor_memstr(str, eos-str, "\ndir-signing-key");
  804. if (!cp)
  805. return NULL;
  806. ++cp; /* Now cp points to the start of the token. */
  807. area = memarea_new();
  808. tok = get_next_token(area, &cp, eos, dir_token_table);
  809. if (!tok) {
  810. log_warn(LD_DIR, "Unparseable dir-signing-key token");
  811. goto done;
  812. }
  813. if (tok->tp != K_DIR_SIGNING_KEY) {
  814. log_warn(LD_DIR, "Dir-signing-key token did not parse as expected");
  815. goto done;
  816. }
  817. if (tok->key) {
  818. key = tok->key;
  819. tok->key = NULL; /* steal reference. */
  820. } else {
  821. log_warn(LD_DIR, "Dir-signing-key token contained no key");
  822. }
  823. done:
  824. if (tok) token_free(tok);
  825. if (area) {
  826. DUMP_AREA(area, "dir-signing-key token");
  827. memarea_drop_all(area);
  828. }
  829. return key;
  830. }
  831. /** Return true iff <b>key</b> is allowed to sign directories.
  832. */
  833. static int
  834. dir_signing_key_is_trusted(crypto_pk_env_t *key)
  835. {
  836. char digest[DIGEST_LEN];
  837. if (!key) return 0;
  838. if (crypto_pk_get_digest(key, digest) < 0) {
  839. log_warn(LD_DIR, "Error computing dir-signing-key digest");
  840. return 0;
  841. }
  842. if (!router_digest_is_trusted_dir(digest)) {
  843. log_warn(LD_DIR, "Listed dir-signing-key is not trusted");
  844. return 0;
  845. }
  846. return 1;
  847. }
  848. /** Check whether the object body of the token in <b>tok</b> has a good
  849. * signature for <b>digest</b> using key <b>pkey</b>. If
  850. * <b>CST_CHECK_AUTHORITY</b> is set, make sure that <b>pkey</b> is the key of
  851. * a directory authority. If <b>CST_NO_CHECK_OBJTYPE</b> is set, do not check
  852. * the object type of the signature object. Use <b>doctype</b> as the type of
  853. * the document when generating log messages. Return 0 on success, negative
  854. * on failure.
  855. */
  856. static int
  857. check_signature_token(const char *digest,
  858. directory_token_t *tok,
  859. crypto_pk_env_t *pkey,
  860. int flags,
  861. const char *doctype)
  862. {
  863. char *signed_digest;
  864. const int check_authority = (flags & CST_CHECK_AUTHORITY);
  865. const int check_objtype = ! (flags & CST_NO_CHECK_OBJTYPE);
  866. tor_assert(pkey);
  867. tor_assert(tok);
  868. tor_assert(digest);
  869. tor_assert(doctype);
  870. if (check_authority && !dir_signing_key_is_trusted(pkey)) {
  871. log_warn(LD_DIR, "Key on %s did not come from an authority; rejecting",
  872. doctype);
  873. return -1;
  874. }
  875. if (check_objtype) {
  876. if (strcmp(tok->object_type, "SIGNATURE")) {
  877. log_warn(LD_DIR, "Bad object type on %s signature", doctype);
  878. return -1;
  879. }
  880. }
  881. signed_digest = tor_malloc(tok->object_size);
  882. if (crypto_pk_public_checksig(pkey, signed_digest, tok->object_body,
  883. tok->object_size)
  884. != DIGEST_LEN) {
  885. log_warn(LD_DIR, "Error reading %s: invalid signature.", doctype);
  886. tor_free(signed_digest);
  887. return -1;
  888. }
  889. // log_debug(LD_DIR,"Signed %s hash starts %s", doctype,
  890. // hex_str(signed_digest,4));
  891. if (memcmp(digest, signed_digest, DIGEST_LEN)) {
  892. log_warn(LD_DIR, "Error reading %s: signature does not match.", doctype);
  893. tor_free(signed_digest);
  894. return -1;
  895. }
  896. tor_free(signed_digest);
  897. return 0;
  898. }
  899. /** Helper: move *<b>s_ptr</b> ahead to the next router, the next extra-info,
  900. * or to the first of the annotations proceeding the next router or
  901. * extra-info---whichever comes first. Set <b>is_extrainfo_out</b> to true if
  902. * we found an extrainfo, or false if found a router. Do not scan beyond
  903. * <b>eos</b>. Return -1 if we found nothing; 0 if we found something. */
  904. static int
  905. find_start_of_next_router_or_extrainfo(const char **s_ptr,
  906. const char *eos,
  907. int *is_extrainfo_out)
  908. {
  909. const char *annotations = NULL;
  910. const char *s = *s_ptr;
  911. s = eat_whitespace_eos(s, eos);
  912. while (s < eos-32) { /* 32 gives enough room for a the first keyword. */
  913. /* We're at the start of a line. */
  914. tor_assert(*s != '\n');
  915. if (*s == '@' && !annotations) {
  916. annotations = s;
  917. } else if (*s == 'r' && !strcmpstart(s, "router ")) {
  918. *s_ptr = annotations ? annotations : s;
  919. *is_extrainfo_out = 0;
  920. return 0;
  921. } else if (*s == 'e' && !strcmpstart(s, "extra-info ")) {
  922. *s_ptr = annotations ? annotations : s;
  923. *is_extrainfo_out = 1;
  924. return 0;
  925. }
  926. if (!(s = memchr(s+1, '\n', eos-(s+1))))
  927. break;
  928. s = eat_whitespace_eos(s, eos);
  929. }
  930. return -1;
  931. }
  932. /** Given a string *<b>s</b> containing a concatenated sequence of router
  933. * descriptors (or extra-info documents if <b>is_extrainfo</b> is set), parses
  934. * them and stores the result in <b>dest</b>. All routers are marked running
  935. * and valid. Advances *s to a point immediately following the last router
  936. * entry. Ignore any trailing router entries that are not complete.
  937. *
  938. * If <b>saved_location</b> isn't SAVED_IN_CACHE, make a local copy of each
  939. * descriptor in the signed_descriptor_body field of each routerinfo_t. If it
  940. * isn't SAVED_NOWHERE, remember the offset of each descriptor.
  941. *
  942. * Returns 0 on success and -1 on failure.
  943. */
  944. int
  945. router_parse_list_from_string(const char **s, const char *eos,
  946. smartlist_t *dest,
  947. saved_location_t saved_location,
  948. int want_extrainfo,
  949. int allow_annotations,
  950. const char *prepend_annotations)
  951. {
  952. routerinfo_t *router;
  953. extrainfo_t *extrainfo;
  954. signed_descriptor_t *signed_desc;
  955. void *elt;
  956. const char *end, *start;
  957. int have_extrainfo;
  958. tor_assert(s);
  959. tor_assert(*s);
  960. tor_assert(dest);
  961. start = *s;
  962. if (!eos)
  963. eos = *s + strlen(*s);
  964. tor_assert(eos >= *s);
  965. while (1) {
  966. if (find_start_of_next_router_or_extrainfo(s, eos, &have_extrainfo) < 0)
  967. break;
  968. end = tor_memstr(*s, eos-*s, "\nrouter-signature");
  969. if (end)
  970. end = tor_memstr(end, eos-end, "\n-----END SIGNATURE-----\n");
  971. if (end)
  972. end += strlen("\n-----END SIGNATURE-----\n");
  973. if (!end)
  974. break;
  975. elt = NULL;
  976. if (have_extrainfo && want_extrainfo) {
  977. routerlist_t *rl = router_get_routerlist();
  978. extrainfo = extrainfo_parse_entry_from_string(*s, end,
  979. saved_location != SAVED_IN_CACHE,
  980. rl->identity_map);
  981. if (extrainfo) {
  982. signed_desc = &extrainfo->cache_info;
  983. elt = extrainfo;
  984. }
  985. } else if (!have_extrainfo && !want_extrainfo) {
  986. router = router_parse_entry_from_string(*s, end,
  987. saved_location != SAVED_IN_CACHE,
  988. allow_annotations,
  989. prepend_annotations);
  990. if (router) {
  991. log_debug(LD_DIR, "Read router '%s', purpose '%s'",
  992. router->nickname, router_purpose_to_string(router->purpose));
  993. signed_desc = &router->cache_info;
  994. elt = router;
  995. }
  996. }
  997. if (!elt) {
  998. *s = end;
  999. continue;
  1000. }
  1001. if (saved_location != SAVED_NOWHERE) {
  1002. signed_desc->saved_location = saved_location;
  1003. signed_desc->saved_offset = *s - start;
  1004. }
  1005. *s = end;
  1006. smartlist_add(dest, elt);
  1007. }
  1008. return 0;
  1009. }
  1010. /* For debugging: define to count every descriptor digest we've seen so we
  1011. * know if we need to try harder to avoid duplicate verifies. */
  1012. #undef COUNT_DISTINCT_DIGESTS
  1013. #ifdef COUNT_DISTINCT_DIGESTS
  1014. static digestmap_t *verified_digests = NULL;
  1015. #endif
  1016. /** Log the total count of the number of distinct router digests we've ever
  1017. * verified. When compared to the number of times we've verified routerdesc
  1018. * signatures <i>in toto</i>, this will tell us if we're doing too much
  1019. * multiple-verification. */
  1020. void
  1021. dump_distinct_digest_count(int severity)
  1022. {
  1023. #ifdef COUNT_DISTINCT_DIGESTS
  1024. if (!verified_digests)
  1025. verified_digests = digestmap_new();
  1026. log(severity, LD_GENERAL, "%d *distinct* router digests verified",
  1027. digestmap_size(verified_digests));
  1028. #else
  1029. (void)severity; /* suppress "unused parameter" warning */
  1030. #endif
  1031. }
  1032. /** Helper function: reads a single router entry from *<b>s</b> ...
  1033. * *<b>end</b>. Mallocs a new router and returns it if all goes well, else
  1034. * returns NULL. If <b>cache_copy</b> is true, duplicate the contents of
  1035. * s through end into the signed_descriptor_body of the resulting
  1036. * routerinfo_t.
  1037. *
  1038. * If <b>allow_annotations</b>, it's okay to encounter annotations in <b>s</b>
  1039. * before the router; if it's false, reject the router if it's annotated. If
  1040. * <b>prepend_annotations</b> is set, it should contain some annotations:
  1041. * append them to the front of the router before parsing it, and keep them
  1042. * around when caching the router.
  1043. *
  1044. * Only one of allow_annotations and prepend_annotations may be set.
  1045. */
  1046. routerinfo_t *
  1047. router_parse_entry_from_string(const char *s, const char *end,
  1048. int cache_copy, int allow_annotations,
  1049. const char *prepend_annotations)
  1050. {
  1051. routerinfo_t *router = NULL;
  1052. char digest[128];
  1053. smartlist_t *tokens = NULL, *exit_policy_tokens = NULL;
  1054. directory_token_t *tok;
  1055. struct in_addr in;
  1056. const char *start_of_annotations, *cp;
  1057. size_t prepend_len = prepend_annotations ? strlen(prepend_annotations) : 0;
  1058. int ok = 1;
  1059. memarea_t *area = NULL;
  1060. tor_assert(!allow_annotations || !prepend_annotations);
  1061. if (!end) {
  1062. end = s + strlen(s);
  1063. }
  1064. /* point 'end' to a point immediately after the final newline. */
  1065. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  1066. --end;
  1067. area = memarea_new();
  1068. tokens = smartlist_create();
  1069. if (prepend_annotations) {
  1070. if (tokenize_string(area,prepend_annotations,NULL,tokens,
  1071. routerdesc_token_table,TS_NOCHECK)) {
  1072. log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
  1073. goto err;
  1074. }
  1075. }
  1076. start_of_annotations = s;
  1077. cp = tor_memstr(s, end-s, "\nrouter ");
  1078. if (!cp) {
  1079. if (end-s < 7 || strcmpstart(s, "router ")) {
  1080. log_warn(LD_DIR, "No router keyword found.");
  1081. goto err;
  1082. }
  1083. } else {
  1084. s = cp+1;
  1085. }
  1086. if (allow_annotations && start_of_annotations != s) {
  1087. if (tokenize_string(area,start_of_annotations,s,tokens,
  1088. routerdesc_token_table,TS_NOCHECK)) {
  1089. log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
  1090. goto err;
  1091. }
  1092. }
  1093. if (router_get_router_hash(s, digest) < 0) {
  1094. log_warn(LD_DIR, "Couldn't compute router hash.");
  1095. goto err;
  1096. }
  1097. {
  1098. int flags = 0;
  1099. if (allow_annotations)
  1100. flags |= TS_ANNOTATIONS_OK;
  1101. if (prepend_annotations)
  1102. flags |= TS_ANNOTATIONS_OK|TS_NO_NEW_ANNOTATIONS;
  1103. if (tokenize_string(area,s,end,tokens,routerdesc_token_table, flags)) {
  1104. log_warn(LD_DIR, "Error tokenizing router descriptor.");
  1105. goto err;
  1106. }
  1107. }
  1108. if (smartlist_len(tokens) < 2) {
  1109. log_warn(LD_DIR, "Impossibly short router descriptor.");
  1110. goto err;
  1111. }
  1112. tok = find_by_keyword(tokens, K_ROUTER);
  1113. tor_assert(tok->n_args >= 5);
  1114. router = tor_malloc_zero(sizeof(routerinfo_t));
  1115. router->country = -1;
  1116. router->cache_info.routerlist_index = -1;
  1117. router->cache_info.annotations_len = s-start_of_annotations + prepend_len;
  1118. router->cache_info.signed_descriptor_len = end-s;
  1119. if (cache_copy) {
  1120. size_t len = router->cache_info.signed_descriptor_len +
  1121. router->cache_info.annotations_len;
  1122. char *cp =
  1123. router->cache_info.signed_descriptor_body = tor_malloc(len+1);
  1124. if (prepend_annotations) {
  1125. memcpy(cp, prepend_annotations, prepend_len);
  1126. cp += prepend_len;
  1127. }
  1128. /* This assertion will always succeed.
  1129. * len == signed_desc_len + annotations_len
  1130. * == end-s + s-start_of_annotations + prepend_len
  1131. * == end-start_of_annotations + prepend_len
  1132. * We already wrote prepend_len bytes into the buffer; now we're
  1133. * writing end-start_of_annotations -NM. */
  1134. tor_assert(cp+(end-start_of_annotations) ==
  1135. router->cache_info.signed_descriptor_body+len);
  1136. memcpy(cp, start_of_annotations, end-start_of_annotations);
  1137. router->cache_info.signed_descriptor_body[len] = '\0';
  1138. tor_assert(strlen(router->cache_info.signed_descriptor_body) == len);
  1139. }
  1140. memcpy(router->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1141. router->nickname = tor_strdup(tok->args[0]);
  1142. if (!is_legal_nickname(router->nickname)) {
  1143. log_warn(LD_DIR,"Router nickname is invalid");
  1144. goto err;
  1145. }
  1146. router->address = tor_strdup(tok->args[1]);
  1147. if (!tor_inet_aton(router->address, &in)) {
  1148. log_warn(LD_DIR,"Router address is not an IP address.");
  1149. goto err;
  1150. }
  1151. router->addr = ntohl(in.s_addr);
  1152. router->or_port =
  1153. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,&ok,NULL);
  1154. if (!ok) {
  1155. log_warn(LD_DIR,"Invalid OR port %s", escaped(tok->args[2]));
  1156. goto err;
  1157. }
  1158. router->dir_port =
  1159. (uint16_t) tor_parse_long(tok->args[4],10,0,65535,&ok,NULL);
  1160. if (!ok) {
  1161. log_warn(LD_DIR,"Invalid dir port %s", escaped(tok->args[4]));
  1162. goto err;
  1163. }
  1164. tok = find_by_keyword(tokens, K_BANDWIDTH);
  1165. tor_assert(tok->n_args >= 3);
  1166. router->bandwidthrate = (int)
  1167. tor_parse_long(tok->args[0],10,1,INT_MAX,&ok,NULL);
  1168. if (!ok) {
  1169. log_warn(LD_DIR, "bandwidthrate %s unreadable or 0. Failing.",
  1170. escaped(tok->args[0]));
  1171. goto err;
  1172. }
  1173. router->bandwidthburst =
  1174. (int) tor_parse_long(tok->args[1],10,0,INT_MAX,&ok,NULL);
  1175. if (!ok) {
  1176. log_warn(LD_DIR, "Invalid bandwidthburst %s", escaped(tok->args[1]));
  1177. goto err;
  1178. }
  1179. router->bandwidthcapacity = (int)
  1180. tor_parse_long(tok->args[2],10,0,INT_MAX,&ok,NULL);
  1181. if (!ok) {
  1182. log_warn(LD_DIR, "Invalid bandwidthcapacity %s", escaped(tok->args[1]));
  1183. goto err;
  1184. }
  1185. if ((tok = find_opt_by_keyword(tokens, A_PURPOSE))) {
  1186. tor_assert(tok->n_args);
  1187. router->purpose = router_purpose_from_string(tok->args[0]);
  1188. } else {
  1189. router->purpose = ROUTER_PURPOSE_GENERAL;
  1190. }
  1191. router->cache_info.send_unencrypted =
  1192. (router->purpose == ROUTER_PURPOSE_GENERAL) ? 1 : 0;
  1193. if ((tok = find_opt_by_keyword(tokens, K_UPTIME))) {
  1194. tor_assert(tok->n_args >= 1);
  1195. router->uptime = tor_parse_long(tok->args[0],10,0,LONG_MAX,&ok,NULL);
  1196. if (!ok) {
  1197. log_warn(LD_DIR, "Invalid uptime %s", escaped(tok->args[0]));
  1198. goto err;
  1199. }
  1200. }
  1201. if ((tok = find_opt_by_keyword(tokens, K_HIBERNATING))) {
  1202. tor_assert(tok->n_args >= 1);
  1203. router->is_hibernating
  1204. = (tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL) != 0);
  1205. }
  1206. tok = find_by_keyword(tokens, K_PUBLISHED);
  1207. tor_assert(tok->n_args == 1);
  1208. if (parse_iso_time(tok->args[0], &router->cache_info.published_on) < 0)
  1209. goto err;
  1210. tok = find_by_keyword(tokens, K_ONION_KEY);
  1211. router->onion_pkey = tok->key;
  1212. tok->key = NULL; /* Prevent free */
  1213. tok = find_by_keyword(tokens, K_SIGNING_KEY);
  1214. router->identity_pkey = tok->key;
  1215. tok->key = NULL; /* Prevent free */
  1216. if (crypto_pk_get_digest(router->identity_pkey,
  1217. router->cache_info.identity_digest)) {
  1218. log_warn(LD_DIR, "Couldn't calculate key digest"); goto err;
  1219. }
  1220. if ((tok = find_opt_by_keyword(tokens, K_FINGERPRINT))) {
  1221. /* If there's a fingerprint line, it must match the identity digest. */
  1222. char d[DIGEST_LEN];
  1223. tor_assert(tok->n_args == 1);
  1224. tor_strstrip(tok->args[0], " ");
  1225. if (base16_decode(d, DIGEST_LEN, tok->args[0], strlen(tok->args[0]))) {
  1226. log_warn(LD_DIR, "Couldn't decode router fingerprint %s",
  1227. escaped(tok->args[0]));
  1228. goto err;
  1229. }
  1230. if (memcmp(d,router->cache_info.identity_digest, DIGEST_LEN)!=0) {
  1231. log_warn(LD_DIR, "Fingerprint '%s' does not match identity digest.",
  1232. tok->args[0]);
  1233. goto err;
  1234. }
  1235. }
  1236. if ((tok = find_opt_by_keyword(tokens, K_PLATFORM))) {
  1237. router->platform = tor_strdup(tok->args[0]);
  1238. }
  1239. if ((tok = find_opt_by_keyword(tokens, K_CONTACT))) {
  1240. router->contact_info = tor_strdup(tok->args[0]);
  1241. }
  1242. if ((tok = find_opt_by_keyword(tokens, K_EVENTDNS))) {
  1243. router->has_old_dnsworkers = tok->n_args && !strcmp(tok->args[0], "0");
  1244. } else if (router->platform) {
  1245. if (! tor_version_as_new_as(router->platform, "0.1.2.2-alpha"))
  1246. router->has_old_dnsworkers = 1;
  1247. }
  1248. exit_policy_tokens = find_all_exitpolicy(tokens);
  1249. if (!smartlist_len(exit_policy_tokens)) {
  1250. log_warn(LD_DIR, "No exit policy tokens in descriptor.");
  1251. goto err;
  1252. }
  1253. SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
  1254. if (router_add_exit_policy(router,t)<0) {
  1255. log_warn(LD_DIR,"Error in exit policy");
  1256. goto err;
  1257. });
  1258. policy_expand_private(&router->exit_policy);
  1259. if (policy_is_reject_star(router->exit_policy))
  1260. router->policy_is_reject_star = 1;
  1261. if ((tok = find_opt_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
  1262. int i;
  1263. router->declared_family = smartlist_create();
  1264. for (i=0;i<tok->n_args;++i) {
  1265. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  1266. log_warn(LD_DIR, "Illegal nickname %s in family line",
  1267. escaped(tok->args[i]));
  1268. goto err;
  1269. }
  1270. smartlist_add(router->declared_family, tor_strdup(tok->args[i]));
  1271. }
  1272. }
  1273. if ((tok = find_opt_by_keyword(tokens, K_CACHES_EXTRA_INFO)))
  1274. router->caches_extra_info = 1;
  1275. if ((tok = find_opt_by_keyword(tokens, K_ALLOW_SINGLE_HOP_EXITS)))
  1276. router->allow_single_hop_exits = 1;
  1277. if ((tok = find_opt_by_keyword(tokens, K_EXTRA_INFO_DIGEST))) {
  1278. tor_assert(tok->n_args >= 1);
  1279. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  1280. base16_decode(router->cache_info.extra_info_digest,
  1281. DIGEST_LEN, tok->args[0], HEX_DIGEST_LEN);
  1282. } else {
  1283. log_warn(LD_DIR, "Invalid extra info digest %s", escaped(tok->args[0]));
  1284. }
  1285. }
  1286. if ((tok = find_opt_by_keyword(tokens, K_HIDDEN_SERVICE_DIR))) {
  1287. router->wants_to_be_hs_dir = 1;
  1288. }
  1289. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1290. note_crypto_pk_op(VERIFY_RTR);
  1291. #ifdef COUNT_DISTINCT_DIGESTS
  1292. if (!verified_digests)
  1293. verified_digests = digestmap_new();
  1294. digestmap_set(verified_digests, signed_digest, (void*)(uintptr_t)1);
  1295. #endif
  1296. if (check_signature_token(digest, tok, router->identity_pkey, 0,
  1297. "router descriptor") < 0)
  1298. goto err;
  1299. routerinfo_set_country(router);
  1300. if (!router->or_port) {
  1301. log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
  1302. goto err;
  1303. }
  1304. if (!router->platform) {
  1305. router->platform = tor_strdup("<unknown>");
  1306. }
  1307. goto done;
  1308. err:
  1309. routerinfo_free(router);
  1310. router = NULL;
  1311. done:
  1312. if (tokens) {
  1313. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1314. smartlist_free(tokens);
  1315. }
  1316. if (exit_policy_tokens) {
  1317. smartlist_free(exit_policy_tokens);
  1318. }
  1319. if (area) {
  1320. DUMP_AREA(area, "routerinfo");
  1321. memarea_drop_all(area);
  1322. }
  1323. return router;
  1324. }
  1325. /** Parse a single extrainfo entry from the string <b>s</b>, ending at
  1326. * <b>end</b>. (If <b>end</b> is NULL, parse up to the end of <b>s</b>.) If
  1327. * <b>cache_copy</b> is true, make a copy of the extra-info document in the
  1328. * cache_info fields of the result. If <b>routermap</b> is provided, use it
  1329. * as a map from router identity to routerinfo_t when looking up signing keys.
  1330. */
  1331. extrainfo_t *
  1332. extrainfo_parse_entry_from_string(const char *s, const char *end,
  1333. int cache_copy, struct digest_ri_map_t *routermap)
  1334. {
  1335. extrainfo_t *extrainfo = NULL;
  1336. char digest[128];
  1337. smartlist_t *tokens = NULL;
  1338. directory_token_t *tok;
  1339. crypto_pk_env_t *key = NULL;
  1340. routerinfo_t *router = NULL;
  1341. memarea_t *area = NULL;
  1342. if (!end) {
  1343. end = s + strlen(s);
  1344. }
  1345. /* point 'end' to a point immediately after the final newline. */
  1346. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  1347. --end;
  1348. if (router_get_extrainfo_hash(s, digest) < 0) {
  1349. log_warn(LD_DIR, "Couldn't compute router hash.");
  1350. goto err;
  1351. }
  1352. tokens = smartlist_create();
  1353. area = memarea_new();
  1354. if (tokenize_string(area,s,end,tokens,extrainfo_token_table,0)) {
  1355. log_warn(LD_DIR, "Error tokenizing extra-info document.");
  1356. goto err;
  1357. }
  1358. if (smartlist_len(tokens) < 2) {
  1359. log_warn(LD_DIR, "Impossibly short extra-info document.");
  1360. goto err;
  1361. }
  1362. tok = smartlist_get(tokens,0);
  1363. if (tok->tp != K_EXTRA_INFO) {
  1364. log_warn(LD_DIR,"Entry does not start with \"extra-info\"");
  1365. goto err;
  1366. }
  1367. extrainfo = tor_malloc_zero(sizeof(extrainfo_t));
  1368. extrainfo->cache_info.is_extrainfo = 1;
  1369. if (cache_copy)
  1370. extrainfo->cache_info.signed_descriptor_body = tor_strndup(s, end-s);
  1371. extrainfo->cache_info.signed_descriptor_len = end-s;
  1372. memcpy(extrainfo->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1373. tor_assert(tok->n_args >= 2);
  1374. if (!is_legal_nickname(tok->args[0])) {
  1375. log_warn(LD_DIR,"Bad nickname %s on \"extra-info\"",escaped(tok->args[0]));
  1376. goto err;
  1377. }
  1378. strlcpy(extrainfo->nickname, tok->args[0], sizeof(extrainfo->nickname));
  1379. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  1380. base16_decode(extrainfo->cache_info.identity_digest, DIGEST_LEN,
  1381. tok->args[1], HEX_DIGEST_LEN)) {
  1382. log_warn(LD_DIR,"Invalid fingerprint %s on \"extra-info\"",
  1383. escaped(tok->args[1]));
  1384. goto err;
  1385. }
  1386. tok = find_by_keyword(tokens, K_PUBLISHED);
  1387. if (parse_iso_time(tok->args[0], &extrainfo->cache_info.published_on)) {
  1388. log_warn(LD_DIR,"Invalid published time %s on \"extra-info\"",
  1389. escaped(tok->args[0]));
  1390. goto err;
  1391. }
  1392. if (routermap &&
  1393. (router = digestmap_get((digestmap_t*)routermap,
  1394. extrainfo->cache_info.identity_digest))) {
  1395. key = router->identity_pkey;
  1396. }
  1397. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1398. if (strcmp(tok->object_type, "SIGNATURE") ||
  1399. tok->object_size < 128 || tok->object_size > 512) {
  1400. log_warn(LD_DIR, "Bad object type or length on extra-info signature");
  1401. goto err;
  1402. }
  1403. if (key) {
  1404. note_crypto_pk_op(VERIFY_RTR);
  1405. if (check_signature_token(digest, tok, key, 0, "extra-info") < 0)
  1406. goto err;
  1407. if (router)
  1408. extrainfo->cache_info.send_unencrypted =
  1409. router->cache_info.send_unencrypted;
  1410. } else {
  1411. extrainfo->pending_sig = tor_memdup(tok->object_body,
  1412. tok->object_size);
  1413. extrainfo->pending_sig_len = tok->object_size;
  1414. }
  1415. goto done;
  1416. err:
  1417. if (extrainfo)
  1418. extrainfo_free(extrainfo);
  1419. extrainfo = NULL;
  1420. done:
  1421. if (tokens) {
  1422. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1423. smartlist_free(tokens);
  1424. }
  1425. if (area) {
  1426. DUMP_AREA(area, "extrainfo");
  1427. memarea_drop_all(area);
  1428. }
  1429. return extrainfo;
  1430. }
  1431. /** Parse a key certificate from <b>s</b>; point <b>end-of-string</b> to
  1432. * the first character after the certificate. */
  1433. authority_cert_t *
  1434. authority_cert_parse_from_string(const char *s, const char **end_of_string)
  1435. {
  1436. authority_cert_t *cert = NULL, *old_cert;
  1437. smartlist_t *tokens = NULL;
  1438. char digest[DIGEST_LEN];
  1439. directory_token_t *tok;
  1440. char fp_declared[DIGEST_LEN];
  1441. char *eos;
  1442. size_t len;
  1443. int found;
  1444. memarea_t *area = NULL;
  1445. s = eat_whitespace(s);
  1446. eos = strstr(s, "\ndir-key-certification");
  1447. if (! eos) {
  1448. log_warn(LD_DIR, "No signature found on key certificate");
  1449. return NULL;
  1450. }
  1451. eos = strstr(eos, "\n-----END SIGNATURE-----\n");
  1452. if (! eos) {
  1453. log_warn(LD_DIR, "No end-of-signature found on key certificate");
  1454. return NULL;
  1455. }
  1456. eos = strchr(eos+2, '\n');
  1457. tor_assert(eos);
  1458. ++eos;
  1459. len = eos - s;
  1460. tokens = smartlist_create();
  1461. area = memarea_new();
  1462. if (tokenize_string(area,s, eos, tokens, dir_key_certificate_table, 0) < 0) {
  1463. log_warn(LD_DIR, "Error tokenizing key certificate");
  1464. goto err;
  1465. }
  1466. if (router_get_hash_impl(s, digest, "dir-key-certificate-version",
  1467. "\ndir-key-certification", '\n') < 0)
  1468. goto err;
  1469. tok = smartlist_get(tokens, 0);
  1470. if (tok->tp != K_DIR_KEY_CERTIFICATE_VERSION || strcmp(tok->args[0], "3")) {
  1471. log_warn(LD_DIR,
  1472. "Key certificate does not begin with a recognized version (3).");
  1473. goto err;
  1474. }
  1475. cert = tor_malloc_zero(sizeof(authority_cert_t));
  1476. memcpy(cert->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1477. tok = find_by_keyword(tokens, K_DIR_SIGNING_KEY);
  1478. tor_assert(tok->key);
  1479. cert->signing_key = tok->key;
  1480. tok->key = NULL;
  1481. if (crypto_pk_get_digest(cert->signing_key, cert->signing_key_digest))
  1482. goto err;
  1483. tok = find_by_keyword(tokens, K_DIR_IDENTITY_KEY);
  1484. tor_assert(tok->key);
  1485. cert->identity_key = tok->key;
  1486. tok->key = NULL;
  1487. tok = find_by_keyword(tokens, K_FINGERPRINT);
  1488. tor_assert(tok->n_args);
  1489. if (base16_decode(fp_declared, DIGEST_LEN, tok->args[0],
  1490. strlen(tok->args[0]))) {
  1491. log_warn(LD_DIR, "Couldn't decode key certificate fingerprint %s",
  1492. escaped(tok->args[0]));
  1493. goto err;
  1494. }
  1495. if (crypto_pk_get_digest(cert->identity_key,
  1496. cert->cache_info.identity_digest))
  1497. goto err;
  1498. if (memcmp(cert->cache_info.identity_digest, fp_declared, DIGEST_LEN)) {
  1499. log_warn(LD_DIR, "Digest of certificate key didn't match declared "
  1500. "fingerprint");
  1501. goto err;
  1502. }
  1503. tok = find_opt_by_keyword(tokens, K_DIR_ADDRESS);
  1504. if (tok) {
  1505. struct in_addr in;
  1506. char *address = NULL;
  1507. tor_assert(tok->n_args);
  1508. /* XXX021 use tor_addr_port_parse() below instead. -RD */
  1509. if (parse_addr_port(LOG_WARN, tok->args[0], &address, NULL,
  1510. &cert->dir_port)<0 ||
  1511. tor_inet_aton(address, &in) == 0) {
  1512. log_warn(LD_DIR, "Couldn't parse dir-address in certificate");
  1513. tor_free(address);
  1514. goto err;
  1515. }
  1516. cert->addr = ntohl(in.s_addr);
  1517. tor_free(address);
  1518. }
  1519. tok = find_by_keyword(tokens, K_DIR_KEY_PUBLISHED);
  1520. if (parse_iso_time(tok->args[0], &cert->cache_info.published_on) < 0) {
  1521. goto err;
  1522. }
  1523. tok = find_by_keyword(tokens, K_DIR_KEY_EXPIRES);
  1524. if (parse_iso_time(tok->args[0], &cert->expires) < 0) {
  1525. goto err;
  1526. }
  1527. tok = smartlist_get(tokens, smartlist_len(tokens)-1);
  1528. if (tok->tp != K_DIR_KEY_CERTIFICATION) {
  1529. log_warn(LD_DIR, "Certificate didn't end with dir-key-certification.");
  1530. goto err;
  1531. }
  1532. /* If we already have this cert, don't bother checking the signature. */
  1533. old_cert = authority_cert_get_by_digests(
  1534. cert->cache_info.identity_digest,
  1535. cert->signing_key_digest);
  1536. found = 0;
  1537. if (old_cert) {
  1538. /* XXXX We could just compare signed_descriptor_digest, but that wouldn't
  1539. * buy us much. */
  1540. if (old_cert->cache_info.signed_descriptor_len == len &&
  1541. old_cert->cache_info.signed_descriptor_body &&
  1542. !memcmp(s, old_cert->cache_info.signed_descriptor_body, len)) {
  1543. log_debug(LD_DIR, "We already checked the signature on this "
  1544. "certificate; no need to do so again.");
  1545. found = 1;
  1546. cert->is_cross_certified = old_cert->is_cross_certified;
  1547. }
  1548. }
  1549. if (!found) {
  1550. if (check_signature_token(digest, tok, cert->identity_key, 0,
  1551. "key certificate")) {
  1552. goto err;
  1553. }
  1554. if ((tok = find_opt_by_keyword(tokens, K_DIR_KEY_CROSSCERT))) {
  1555. /* XXXX Once all authorities generate cross-certified certificates,
  1556. * make this field mandatory. */
  1557. if (check_signature_token(cert->cache_info.identity_digest,
  1558. tok,
  1559. cert->signing_key,
  1560. CST_NO_CHECK_OBJTYPE,
  1561. "key cross-certification")) {
  1562. goto err;
  1563. }
  1564. cert->is_cross_certified = 1;
  1565. }
  1566. }
  1567. cert->cache_info.signed_descriptor_len = len;
  1568. cert->cache_info.signed_descriptor_body = tor_malloc(len+1);
  1569. memcpy(cert->cache_info.signed_descriptor_body, s, len);
  1570. cert->cache_info.signed_descriptor_body[len] = 0;
  1571. cert->cache_info.saved_location = SAVED_NOWHERE;
  1572. if (end_of_string) {
  1573. *end_of_string = eat_whitespace(eos);
  1574. }
  1575. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1576. smartlist_free(tokens);
  1577. if (area) {
  1578. DUMP_AREA(area, "authority cert");
  1579. memarea_drop_all(area);
  1580. }
  1581. return cert;
  1582. err:
  1583. authority_cert_free(cert);
  1584. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1585. smartlist_free(tokens);
  1586. if (area) {
  1587. DUMP_AREA(area, "authority cert");
  1588. memarea_drop_all(area);
  1589. }
  1590. return NULL;
  1591. }
  1592. /** Helper: given a string <b>s</b>, return the start of the next router-status
  1593. * object (starting with "r " at the start of a line). If none is found,
  1594. * return the start of the next directory signature. If none is found, return
  1595. * the end of the string. */
  1596. static INLINE const char *
  1597. find_start_of_next_routerstatus(const char *s)
  1598. {
  1599. const char *eos = strstr(s, "\nr ");
  1600. if (eos) {
  1601. const char *eos2 = tor_memstr(s, eos-s, "\ndirectory-signature");
  1602. if (eos2 && eos2 < eos)
  1603. return eos2;
  1604. else
  1605. return eos+1;
  1606. } else {
  1607. if ((eos = strstr(s, "\ndirectory-signature")))
  1608. return eos+1;
  1609. return s + strlen(s);
  1610. }
  1611. }
  1612. /** Given a string at *<b>s</b>, containing a routerstatus object, and an
  1613. * empty smartlist at <b>tokens</b>, parse and return the first router status
  1614. * object in the string, and advance *<b>s</b> to just after the end of the
  1615. * router status. Return NULL and advance *<b>s</b> on error.
  1616. *
  1617. * If <b>vote</b> and <b>vote_rs</b> are provided, don't allocate a fresh
  1618. * routerstatus but use <b>vote_rs</b> instead.
  1619. *
  1620. * If <b>consensus_method</b> is nonzero, this routerstatus is part of a
  1621. * consensus, and we should parse it according to the method used to
  1622. * make that consensus.
  1623. **/
  1624. static routerstatus_t *
  1625. routerstatus_parse_entry_from_string(memarea_t *area,
  1626. const char **s, smartlist_t *tokens,
  1627. networkstatus_t *vote,
  1628. vote_routerstatus_t *vote_rs,
  1629. int consensus_method)
  1630. {
  1631. const char *eos;
  1632. routerstatus_t *rs = NULL;
  1633. directory_token_t *tok;
  1634. char timebuf[ISO_TIME_LEN+1];
  1635. struct in_addr in;
  1636. tor_assert(tokens);
  1637. tor_assert(bool_eq(vote, vote_rs));
  1638. eos = find_start_of_next_routerstatus(*s);
  1639. if (tokenize_string(area,*s, eos, tokens, rtrstatus_token_table,0)) {
  1640. log_warn(LD_DIR, "Error tokenizing router status");
  1641. goto err;
  1642. }
  1643. if (smartlist_len(tokens) < 1) {
  1644. log_warn(LD_DIR, "Impossibly short router status");
  1645. goto err;
  1646. }
  1647. tok = find_by_keyword(tokens, K_R);
  1648. tor_assert(tok->n_args >= 8);
  1649. if (vote_rs) {
  1650. rs = &vote_rs->status;
  1651. } else {
  1652. rs = tor_malloc_zero(sizeof(routerstatus_t));
  1653. }
  1654. if (!is_legal_nickname(tok->args[0])) {
  1655. log_warn(LD_DIR,
  1656. "Invalid nickname %s in router status; skipping.",
  1657. escaped(tok->args[0]));
  1658. goto err;
  1659. }
  1660. strlcpy(rs->nickname, tok->args[0], sizeof(rs->nickname));
  1661. if (digest_from_base64(rs->identity_digest, tok->args[1])) {
  1662. log_warn(LD_DIR, "Error decoding identity digest %s",
  1663. escaped(tok->args[1]));
  1664. goto err;
  1665. }
  1666. if (digest_from_base64(rs->descriptor_digest, tok->args[2])) {
  1667. log_warn(LD_DIR, "Error decoding descriptor digest %s",
  1668. escaped(tok->args[2]));
  1669. goto err;
  1670. }
  1671. if (tor_snprintf(timebuf, sizeof(timebuf), "%s %s",
  1672. tok->args[3], tok->args[4]) < 0 ||
  1673. parse_iso_time(timebuf, &rs->published_on)<0) {
  1674. log_warn(LD_DIR, "Error parsing time '%s %s'",
  1675. tok->args[3], tok->args[4]);
  1676. goto err;
  1677. }
  1678. if (tor_inet_aton(tok->args[5], &in) == 0) {
  1679. log_warn(LD_DIR, "Error parsing router address in network-status %s",
  1680. escaped(tok->args[5]));
  1681. goto err;
  1682. }
  1683. rs->addr = ntohl(in.s_addr);
  1684. rs->or_port =(uint16_t) tor_parse_long(tok->args[6],10,0,65535,NULL,NULL);
  1685. rs->dir_port = (uint16_t) tor_parse_long(tok->args[7],10,0,65535,NULL,NULL);
  1686. tok = find_opt_by_keyword(tokens, K_S);
  1687. if (tok && vote) {
  1688. int i;
  1689. vote_rs->flags = 0;
  1690. for (i=0; i < tok->n_args; ++i) {
  1691. int p = smartlist_string_pos(vote->known_flags, tok->args[i]);
  1692. if (p >= 0) {
  1693. vote_rs->flags |= (1<<p);
  1694. } else {
  1695. log_warn(LD_DIR, "Flags line had a flag %s not listed in known_flags.",
  1696. escaped(tok->args[i]));
  1697. goto err;
  1698. }
  1699. }
  1700. } else if (tok) {
  1701. int i;
  1702. for (i=0; i < tok->n_args; ++i) {
  1703. if (!strcmp(tok->args[i], "Exit"))
  1704. rs->is_exit = 1;
  1705. else if (!strcmp(tok->args[i], "Stable"))
  1706. rs->is_stable = 1;
  1707. else if (!strcmp(tok->args[i], "Fast"))
  1708. rs->is_fast = 1;
  1709. else if (!strcmp(tok->args[i], "Running"))
  1710. rs->is_running = 1;
  1711. else if (!strcmp(tok->args[i], "Named"))
  1712. rs->is_named = 1;
  1713. else if (!strcmp(tok->args[i], "Valid"))
  1714. rs->is_valid = 1;
  1715. else if (!strcmp(tok->args[i], "V2Dir"))
  1716. rs->is_v2_dir = 1;
  1717. else if (!strcmp(tok->args[i], "Guard"))
  1718. rs->is_possible_guard = 1;
  1719. else if (!strcmp(tok->args[i], "BadExit"))
  1720. rs->is_bad_exit = 1;
  1721. else if (!strcmp(tok->args[i], "BadDirectory"))
  1722. rs->is_bad_directory = 1;
  1723. else if (!strcmp(tok->args[i], "Authority"))
  1724. rs->is_authority = 1;
  1725. else if (!strcmp(tok->args[i], "Unnamed") &&
  1726. consensus_method >= 2) {
  1727. /* Unnamed is computed right by consensus method 2 and later. */
  1728. rs->is_unnamed = 1;
  1729. } else if (!strcmp(tok->args[i], "HSDir")) {
  1730. rs->is_hs_dir = 1;
  1731. }
  1732. }
  1733. }
  1734. if ((tok = find_opt_by_keyword(tokens, K_V))) {
  1735. tor_assert(tok->n_args == 1);
  1736. rs->version_known = 1;
  1737. if (strcmpstart(tok->args[0], "Tor ")) {
  1738. rs->version_supports_begindir = 1;
  1739. rs->version_supports_extrainfo_upload = 1;
  1740. rs->version_supports_conditional_consensus = 1;
  1741. } else {
  1742. rs->version_supports_begindir =
  1743. tor_version_as_new_as(tok->args[0], "0.2.0.1-alpha");
  1744. rs->version_supports_extrainfo_upload =
  1745. tor_version_as_new_as(tok->args[0], "0.2.0.0-alpha-dev (r10070)");
  1746. rs->version_supports_v3_dir =
  1747. tor_version_as_new_as(tok->args[0], "0.2.0.8-alpha");
  1748. rs->version_supports_conditional_consensus =
  1749. tor_version_as_new_as(tok->args[0], "0.2.1.1-alpha");
  1750. }
  1751. if (vote_rs) {
  1752. vote_rs->version = tor_strdup(tok->args[0]);
  1753. }
  1754. }
  1755. /* handle weighting/bandwidth info */
  1756. if ((tok = find_opt_by_keyword(tokens, K_W))) {
  1757. int i;
  1758. for (i=0; i < tok->n_args; ++i) {
  1759. if (!strcmpstart(tok->args[i], "Bandwidth=")) {
  1760. int ok;
  1761. rs->bandwidth = tor_parse_ulong(strchr(tok->args[i], '=')+1, 10,
  1762. 0, UINT32_MAX, &ok, NULL);
  1763. if (!ok) {
  1764. log_warn(LD_DIR, "Invalid Bandwidth %s", escaped(tok->args[i]));
  1765. goto err;
  1766. }
  1767. rs->has_bandwidth = 1;
  1768. } else if (!strcmpstart(tok->args[i], "Measured=")) {
  1769. int ok;
  1770. rs->measured_bw = tor_parse_ulong(strchr(tok->args[i], '=')+1, 10,
  1771. 0, UINT32_MAX, &ok, NULL);
  1772. if (!ok) {
  1773. log_warn(LD_DIR, "Invalid Measured Bandwidth %s",
  1774. escaped(tok->args[i]));
  1775. goto err;
  1776. }
  1777. rs->has_measured_bw = 1;
  1778. }
  1779. }
  1780. }
  1781. /* parse exit policy summaries */
  1782. if ((tok = find_opt_by_keyword(tokens, K_P))) {
  1783. tor_assert(tok->n_args == 1);
  1784. if (strcmpstart(tok->args[0], "accept ") &&
  1785. strcmpstart(tok->args[0], "reject ")) {
  1786. log_warn(LD_DIR, "Unknown exit policy summary type %s.",
  1787. escaped(tok->args[0]));
  1788. goto err;
  1789. }
  1790. /* XXX weasel: parse this into ports and represent them somehow smart,
  1791. * maybe not here but somewhere on if we need it for the client.
  1792. * we should still parse it here to check it's valid tho.
  1793. */
  1794. rs->exitsummary = tor_strdup(tok->args[0]);
  1795. rs->has_exitsummary = 1;
  1796. }
  1797. if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME))
  1798. rs->is_named = 0;
  1799. goto done;
  1800. err:
  1801. if (rs && !vote_rs)
  1802. routerstatus_free(rs);
  1803. rs = NULL;
  1804. done:
  1805. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1806. smartlist_clear(tokens);
  1807. if (area) {
  1808. DUMP_AREA(area, "routerstatus entry");
  1809. memarea_clear(area);
  1810. }
  1811. *s = eos;
  1812. return rs;
  1813. }
  1814. /** Helper to sort a smartlist of pointers to routerstatus_t */
  1815. int
  1816. compare_routerstatus_entries(const void **_a, const void **_b)
  1817. {
  1818. const routerstatus_t *a = *_a, *b = *_b;
  1819. return memcmp(a->identity_digest, b->identity_digest, DIGEST_LEN);
  1820. }
  1821. /** Helper: used in call to _smartlist_uniq to clear out duplicate entries. */
  1822. static void
  1823. _free_duplicate_routerstatus_entry(void *e)
  1824. {
  1825. log_warn(LD_DIR,
  1826. "Network-status has two entries for the same router. "
  1827. "Dropping one.");
  1828. routerstatus_free(e);
  1829. }
  1830. /** Given a v2 network-status object in <b>s</b>, try to
  1831. * parse it and return the result. Return NULL on failure. Check the
  1832. * signature of the network status, but do not (yet) check the signing key for
  1833. * authority.
  1834. */
  1835. networkstatus_v2_t *
  1836. networkstatus_v2_parse_from_string(const char *s)
  1837. {
  1838. const char *eos;
  1839. smartlist_t *tokens = smartlist_create();
  1840. smartlist_t *footer_tokens = smartlist_create();
  1841. networkstatus_v2_t *ns = NULL;
  1842. char ns_digest[DIGEST_LEN];
  1843. char tmp_digest[DIGEST_LEN];
  1844. struct in_addr in;
  1845. directory_token_t *tok;
  1846. int i;
  1847. memarea_t *area = NULL;
  1848. if (router_get_networkstatus_v2_hash(s, ns_digest)) {
  1849. log_warn(LD_DIR, "Unable to compute digest of network-status");
  1850. goto err;
  1851. }
  1852. area = memarea_new();
  1853. eos = find_start_of_next_routerstatus(s);
  1854. if (tokenize_string(area, s, eos, tokens, netstatus_token_table,0)) {
  1855. log_warn(LD_DIR, "Error tokenizing network-status header.");
  1856. goto err;
  1857. }
  1858. ns = tor_malloc_zero(sizeof(networkstatus_v2_t));
  1859. memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN);
  1860. tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
  1861. tor_assert(tok->n_args >= 1);
  1862. if (strcmp(tok->args[0], "2")) {
  1863. log_warn(LD_BUG, "Got a non-v2 networkstatus. Version was "
  1864. "%s", escaped(tok->args[0]));
  1865. goto err;
  1866. }
  1867. tok = find_by_keyword(tokens, K_DIR_SOURCE);
  1868. tor_assert(tok->n_args >= 3);
  1869. ns->source_address = tor_strdup(tok->args[0]);
  1870. if (tor_inet_aton(tok->args[1], &in) == 0) {
  1871. log_warn(LD_DIR, "Error parsing network-status source address %s",
  1872. escaped(tok->args[1]));
  1873. goto err;
  1874. }
  1875. ns->source_addr = ntohl(in.s_addr);
  1876. ns->source_dirport =
  1877. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
  1878. if (ns->source_dirport == 0) {
  1879. log_warn(LD_DIR, "Directory source without dirport; skipping.");
  1880. goto err;
  1881. }
  1882. tok = find_by_keyword(tokens, K_FINGERPRINT);
  1883. tor_assert(tok->n_args);
  1884. if (base16_decode(ns->identity_digest, DIGEST_LEN, tok->args[0],
  1885. strlen(tok->args[0]))) {
  1886. log_warn(LD_DIR, "Couldn't decode networkstatus fingerprint %s",
  1887. escaped(tok->args[0]));
  1888. goto err;
  1889. }
  1890. if ((tok = find_opt_by_keyword(tokens, K_CONTACT))) {
  1891. tor_assert(tok->n_args);
  1892. ns->contact = tor_strdup(tok->args[0]);
  1893. }
  1894. tok = find_by_keyword(tokens, K_DIR_SIGNING_KEY);
  1895. tor_assert(tok->key);
  1896. ns->signing_key = tok->key;
  1897. tok->key = NULL;
  1898. if (crypto_pk_get_digest(ns->signing_key, tmp_digest)<0) {
  1899. log_warn(LD_DIR, "Couldn't compute signing key digest");
  1900. goto err;
  1901. }
  1902. if (memcmp(tmp_digest, ns->identity_digest, DIGEST_LEN)) {
  1903. log_warn(LD_DIR,
  1904. "network-status fingerprint did not match dir-signing-key");
  1905. goto err;
  1906. }
  1907. if ((tok = find_opt_by_keyword(tokens, K_DIR_OPTIONS))) {
  1908. for (i=0; i < tok->n_args; ++i) {
  1909. if (!strcmp(tok->args[i], "Names"))
  1910. ns->binds_names = 1;
  1911. if (!strcmp(tok->args[i], "Versions"))
  1912. ns->recommends_versions = 1;
  1913. if (!strcmp(tok->args[i], "BadExits"))
  1914. ns->lists_bad_exits = 1;
  1915. if (!strcmp(tok->args[i], "BadDirectories"))
  1916. ns->lists_bad_directories = 1;
  1917. }
  1918. }
  1919. if (ns->recommends_versions) {
  1920. if (!(tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  1921. log_warn(LD_DIR, "Missing client-versions on versioning directory");
  1922. goto err;
  1923. }
  1924. ns->client_versions = tor_strdup(tok->args[0]);
  1925. if (!(tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS)) ||
  1926. tok->n_args<1) {
  1927. log_warn(LD_DIR, "Missing server-versions on versioning directory");
  1928. goto err;
  1929. }
  1930. ns->server_versions = tor_strdup(tok->args[0]);
  1931. }
  1932. tok = find_by_keyword(tokens, K_PUBLISHED);
  1933. tor_assert(tok->n_args == 1);
  1934. if (parse_iso_time(tok->args[0], &ns->published_on) < 0) {
  1935. goto err;
  1936. }
  1937. ns->entries = smartlist_create();
  1938. s = eos;
  1939. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1940. smartlist_clear(tokens);
  1941. memarea_clear(area);
  1942. while (!strcmpstart(s, "r ")) {
  1943. routerstatus_t *rs;
  1944. if ((rs = routerstatus_parse_entry_from_string(area, &s, tokens,
  1945. NULL, NULL, 0)))
  1946. smartlist_add(ns->entries, rs);
  1947. }
  1948. smartlist_sort(ns->entries, compare_routerstatus_entries);
  1949. smartlist_uniq(ns->entries, compare_routerstatus_entries,
  1950. _free_duplicate_routerstatus_entry);
  1951. if (tokenize_string(area,s, NULL, footer_tokens, dir_footer_token_table,0)) {
  1952. log_warn(LD_DIR, "Error tokenizing network-status footer.");
  1953. goto err;
  1954. }
  1955. if (smartlist_len(footer_tokens) < 1) {
  1956. log_warn(LD_DIR, "Too few items in network-status footer.");
  1957. goto err;
  1958. }
  1959. tok = smartlist_get(footer_tokens, smartlist_len(footer_tokens)-1);
  1960. if (tok->tp != K_DIRECTORY_SIGNATURE) {
  1961. log_warn(LD_DIR,
  1962. "Expected network-status footer to end with a signature.");
  1963. goto err;
  1964. }
  1965. note_crypto_pk_op(VERIFY_DIR);
  1966. if (check_signature_token(ns_digest, tok, ns->signing_key, 0,
  1967. "network-status") < 0)
  1968. goto err;
  1969. goto done;
  1970. err:
  1971. if (ns)
  1972. networkstatus_v2_free(ns);
  1973. ns = NULL;
  1974. done:
  1975. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1976. smartlist_free(tokens);
  1977. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_free(t));
  1978. smartlist_free(footer_tokens);
  1979. if (area) {
  1980. DUMP_AREA(area, "v2 networkstatus");
  1981. memarea_drop_all(area);
  1982. }
  1983. return ns;
  1984. }
  1985. /** Parse a v3 networkstatus vote, opinion, or consensus (depending on
  1986. * ns_type), from <b>s</b>, and return the result. Return NULL on failure. */
  1987. networkstatus_t *
  1988. networkstatus_parse_vote_from_string(const char *s, const char **eos_out,
  1989. networkstatus_type_t ns_type)
  1990. {
  1991. smartlist_t *tokens = smartlist_create();
  1992. smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;
  1993. networkstatus_voter_info_t *voter = NULL;
  1994. networkstatus_t *ns = NULL;
  1995. char ns_digest[DIGEST_LEN];
  1996. const char *cert, *end_of_header, *end_of_footer;
  1997. directory_token_t *tok;
  1998. int ok;
  1999. struct in_addr in;
  2000. int i, inorder, n_signatures = 0;
  2001. memarea_t *area = NULL, *rs_area = NULL;
  2002. tor_assert(s);
  2003. if (eos_out)
  2004. *eos_out = NULL;
  2005. if (router_get_networkstatus_v3_hash(s, ns_digest)) {
  2006. log_warn(LD_DIR, "Unable to compute digest of network-status");
  2007. goto err;
  2008. }
  2009. area = memarea_new();
  2010. end_of_header = find_start_of_next_routerstatus(s);
  2011. if (tokenize_string(area, s, end_of_header, tokens,
  2012. (ns_type == NS_TYPE_CONSENSUS) ?
  2013. networkstatus_consensus_token_table :
  2014. networkstatus_token_table, 0)) {
  2015. log_warn(LD_DIR, "Error tokenizing network-status vote header");
  2016. goto err;
  2017. }
  2018. ns = tor_malloc_zero(sizeof(networkstatus_t));
  2019. memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN);
  2020. if (ns_type != NS_TYPE_CONSENSUS) {
  2021. const char *end_of_cert = NULL;
  2022. if (!(cert = strstr(s, "\ndir-key-certificate-version")))
  2023. goto err;
  2024. ++cert;
  2025. ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);
  2026. if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)
  2027. goto err;
  2028. }
  2029. tok = find_by_keyword(tokens, K_VOTE_STATUS);
  2030. tor_assert(tok->n_args);
  2031. if (!strcmp(tok->args[0], "vote")) {
  2032. ns->type = NS_TYPE_VOTE;
  2033. } else if (!strcmp(tok->args[0], "consensus")) {
  2034. ns->type = NS_TYPE_CONSENSUS;
  2035. } else if (!strcmp(tok->args[0], "opinion")) {
  2036. ns->type = NS_TYPE_OPINION;
  2037. } else {
  2038. log_warn(LD_DIR, "Unrecognized vote status %s in network-status",
  2039. escaped(tok->args[0]));
  2040. goto err;
  2041. }
  2042. if (ns_type != ns->type) {
  2043. log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus.");
  2044. goto err;
  2045. }
  2046. if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
  2047. tok = find_by_keyword(tokens, K_PUBLISHED);
  2048. if (parse_iso_time(tok->args[0], &ns->published))
  2049. goto err;
  2050. ns->supported_methods = smartlist_create();
  2051. tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHODS);
  2052. if (tok) {
  2053. for (i=0; i < tok->n_args; ++i)
  2054. smartlist_add(ns->supported_methods, tor_strdup(tok->args[i]));
  2055. } else {
  2056. smartlist_add(ns->supported_methods, tor_strdup("1"));
  2057. }
  2058. } else {
  2059. tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHOD);
  2060. if (tok) {
  2061. ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX,
  2062. &ok, NULL);
  2063. if (!ok)
  2064. goto err;
  2065. } else {
  2066. ns->consensus_method = 1;
  2067. }
  2068. }
  2069. tok = find_by_keyword(tokens, K_VALID_AFTER);
  2070. if (parse_iso_time(tok->args[0], &ns->valid_after))
  2071. goto err;
  2072. tok = find_by_keyword(tokens, K_FRESH_UNTIL);
  2073. if (parse_iso_time(tok->args[0], &ns->fresh_until))
  2074. goto err;
  2075. tok = find_by_keyword(tokens, K_VALID_UNTIL);
  2076. if (parse_iso_time(tok->args[0], &ns->valid_until))
  2077. goto err;
  2078. tok = find_by_keyword(tokens, K_VOTING_DELAY);
  2079. tor_assert(tok->n_args >= 2);
  2080. ns->vote_seconds =
  2081. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);
  2082. if (!ok)
  2083. goto err;
  2084. ns->dist_seconds =
  2085. (int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL);
  2086. if (!ok)
  2087. goto err;
  2088. if (ns->valid_after + MIN_VOTE_INTERVAL > ns->fresh_until) {
  2089. log_warn(LD_DIR, "Vote/consensus freshness interval is too short");
  2090. goto err;
  2091. }
  2092. if (ns->valid_after + MIN_VOTE_INTERVAL*2 > ns->valid_until) {
  2093. log_warn(LD_DIR, "Vote/consensus liveness interval is too short");
  2094. goto err;
  2095. }
  2096. if (ns->vote_seconds < MIN_VOTE_SECONDS) {
  2097. log_warn(LD_DIR, "Vote seconds is too short");
  2098. goto err;
  2099. }
  2100. if (ns->dist_seconds < MIN_DIST_SECONDS) {
  2101. log_warn(LD_DIR, "Dist seconds is too short");
  2102. goto err;
  2103. }
  2104. if ((tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  2105. ns->client_versions = tor_strdup(tok->args[0]);
  2106. }
  2107. if ((tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS))) {
  2108. ns->server_versions = tor_strdup(tok->args[0]);
  2109. }
  2110. tok = find_by_keyword(tokens, K_KNOWN_FLAGS);
  2111. ns->known_flags = smartlist_create();
  2112. inorder = 1;
  2113. for (i = 0; i < tok->n_args; ++i) {
  2114. smartlist_add(ns->known_flags, tor_strdup(tok->args[i]));
  2115. if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) {
  2116. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  2117. inorder = 0;
  2118. }
  2119. }
  2120. if (!inorder) {
  2121. log_warn(LD_DIR, "known-flags not in order");
  2122. goto err;
  2123. }
  2124. ns->voters = smartlist_create();
  2125. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  2126. tok = _tok;
  2127. if (tok->tp == K_DIR_SOURCE) {
  2128. tor_assert(tok->n_args >= 6);
  2129. if (voter)
  2130. smartlist_add(ns->voters, voter);
  2131. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  2132. if (ns->type != NS_TYPE_CONSENSUS)
  2133. memcpy(voter->vote_digest, ns_digest, DIGEST_LEN);
  2134. voter->nickname = tor_strdup(tok->args[0]);
  2135. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  2136. base16_decode(voter->identity_digest, sizeof(voter->identity_digest),
  2137. tok->args[1], HEX_DIGEST_LEN) < 0) {
  2138. log_warn(LD_DIR, "Error decoding identity digest %s in "
  2139. "network-status vote.", escaped(tok->args[1]));
  2140. goto err;
  2141. }
  2142. if (ns->type != NS_TYPE_CONSENSUS &&
  2143. memcmp(ns->cert->cache_info.identity_digest,
  2144. voter->identity_digest, DIGEST_LEN)) {
  2145. log_warn(LD_DIR,"Mismatch between identities in certificate and vote");
  2146. goto err;
  2147. }
  2148. voter->address = tor_strdup(tok->args[2]);
  2149. if (!tor_inet_aton(tok->args[3], &in)) {
  2150. log_warn(LD_DIR, "Error decoding IP address %s in network-status.",
  2151. escaped(tok->args[3]));
  2152. goto err;
  2153. }
  2154. voter->addr = ntohl(in.s_addr);
  2155. voter->dir_port = (uint16_t)
  2156. tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);
  2157. if (!ok)
  2158. goto err;
  2159. voter->or_port = (uint16_t)
  2160. tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);
  2161. if (!ok)
  2162. goto err;
  2163. } else if (tok->tp == K_CONTACT) {
  2164. if (!voter || voter->contact) {
  2165. log_warn(LD_DIR, "contact element is out of place.");
  2166. goto err;
  2167. }
  2168. voter->contact = tor_strdup(tok->args[0]);
  2169. } else if (tok->tp == K_VOTE_DIGEST) {
  2170. tor_assert(ns->type == NS_TYPE_CONSENSUS);
  2171. tor_assert(tok->n_args >= 1);
  2172. if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {
  2173. log_warn(LD_DIR, "vote-digest element is out of place.");
  2174. goto err;
  2175. }
  2176. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  2177. base16_decode(voter->vote_digest, sizeof(voter->vote_digest),
  2178. tok->args[0], HEX_DIGEST_LEN) < 0) {
  2179. log_warn(LD_DIR, "Error decoding vote digest %s in "
  2180. "network-status consensus.", escaped(tok->args[0]));
  2181. goto err;
  2182. }
  2183. }
  2184. } SMARTLIST_FOREACH_END(_tok);
  2185. if (voter) {
  2186. smartlist_add(ns->voters, voter);
  2187. voter = NULL;
  2188. }
  2189. if (smartlist_len(ns->voters) == 0) {
  2190. log_warn(LD_DIR, "Missing dir-source elements in a vote networkstatus.");
  2191. goto err;
  2192. } else if (ns->type != NS_TYPE_CONSENSUS && smartlist_len(ns->voters) != 1) {
  2193. log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus.");
  2194. goto err;
  2195. }
  2196. if (ns->type != NS_TYPE_CONSENSUS &&
  2197. (tok = find_opt_by_keyword(tokens, K_LEGACY_DIR_KEY))) {
  2198. int bad = 1;
  2199. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  2200. networkstatus_voter_info_t *voter = smartlist_get(ns->voters, 0);
  2201. if (base16_decode(voter->legacy_id_digest, DIGEST_LEN,
  2202. tok->args[0], HEX_DIGEST_LEN)<0)
  2203. bad = 1;
  2204. else
  2205. bad = 0;
  2206. }
  2207. if (bad) {
  2208. log_warn(LD_DIR, "Invalid legacy key digest %s on vote.",
  2209. escaped(tok->args[0]));
  2210. }
  2211. }
  2212. /* Parse routerstatus lines. */
  2213. rs_tokens = smartlist_create();
  2214. rs_area = memarea_new();
  2215. s = end_of_header;
  2216. ns->routerstatus_list = smartlist_create();
  2217. while (!strcmpstart(s, "r ")) {
  2218. if (ns->type != NS_TYPE_CONSENSUS) {
  2219. vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  2220. if (routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, ns,
  2221. rs, 0))
  2222. smartlist_add(ns->routerstatus_list, rs);
  2223. else {
  2224. tor_free(rs->version);
  2225. tor_free(rs);
  2226. }
  2227. } else {
  2228. routerstatus_t *rs;
  2229. if ((rs = routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens,
  2230. NULL, NULL,
  2231. ns->consensus_method)))
  2232. smartlist_add(ns->routerstatus_list, rs);
  2233. }
  2234. }
  2235. for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {
  2236. routerstatus_t *rs1, *rs2;
  2237. if (ns->type != NS_TYPE_CONSENSUS) {
  2238. vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);
  2239. vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);
  2240. rs1 = &a->status; rs2 = &b->status;
  2241. } else {
  2242. rs1 = smartlist_get(ns->routerstatus_list, i-1);
  2243. rs2 = smartlist_get(ns->routerstatus_list, i);
  2244. }
  2245. if (memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN) >= 0) {
  2246. log_warn(LD_DIR, "Vote networkstatus entries not sorted by identity "
  2247. "digest");
  2248. goto err;
  2249. }
  2250. }
  2251. /* Parse footer; check signature. */
  2252. footer_tokens = smartlist_create();
  2253. if ((end_of_footer = strstr(s, "\nnetwork-status-version ")))
  2254. ++end_of_footer;
  2255. else
  2256. end_of_footer = s + strlen(s);
  2257. if (tokenize_string(area,s, end_of_footer, footer_tokens,
  2258. networkstatus_vote_footer_token_table, 0)) {
  2259. log_warn(LD_DIR, "Error tokenizing network-status vote footer.");
  2260. goto err;
  2261. }
  2262. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, _tok,
  2263. {
  2264. char declared_identity[DIGEST_LEN];
  2265. networkstatus_voter_info_t *v;
  2266. tok = _tok;
  2267. if (tok->tp != K_DIRECTORY_SIGNATURE)
  2268. continue;
  2269. tor_assert(tok->n_args >= 2);
  2270. if (!tok->object_type ||
  2271. strcmp(tok->object_type, "SIGNATURE") ||
  2272. tok->object_size < 128 || tok->object_size > 512) {
  2273. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  2274. goto err;
  2275. }
  2276. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  2277. base16_decode(declared_identity, sizeof(declared_identity),
  2278. tok->args[0], HEX_DIGEST_LEN) < 0) {
  2279. log_warn(LD_DIR, "Error decoding declared identity %s in "
  2280. "network-status vote.", escaped(tok->args[0]));
  2281. goto err;
  2282. }
  2283. if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {
  2284. log_warn(LD_DIR, "ID on signature on network-status vote does not match "
  2285. "any declared directory source.");
  2286. goto err;
  2287. }
  2288. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  2289. base16_decode(v->signing_key_digest, sizeof(v->signing_key_digest),
  2290. tok->args[1], HEX_DIGEST_LEN) < 0) {
  2291. log_warn(LD_DIR, "Error decoding declared digest %s in "
  2292. "network-status vote.", escaped(tok->args[1]));
  2293. goto err;
  2294. }
  2295. if (ns->type != NS_TYPE_CONSENSUS) {
  2296. if (memcmp(declared_identity, ns->cert->cache_info.identity_digest,
  2297. DIGEST_LEN)) {
  2298. log_warn(LD_DIR, "Digest mismatch between declared and actual on "
  2299. "network-status vote.");
  2300. goto err;
  2301. }
  2302. }
  2303. if (ns->type != NS_TYPE_CONSENSUS) {
  2304. if (check_signature_token(ns_digest, tok, ns->cert->signing_key, 0,
  2305. "network-status vote"))
  2306. goto err;
  2307. v->good_signature = 1;
  2308. } else {
  2309. if (tok->object_size >= INT_MAX)
  2310. goto err;
  2311. v->signature = tor_memdup(tok->object_body, tok->object_size);
  2312. v->signature_len = (int) tok->object_size;
  2313. }
  2314. ++n_signatures;
  2315. });
  2316. if (! n_signatures) {
  2317. log_warn(LD_DIR, "No signatures on networkstatus vote.");
  2318. goto err;
  2319. }
  2320. if (eos_out)
  2321. *eos_out = end_of_footer;
  2322. goto done;
  2323. err:
  2324. if (ns)
  2325. networkstatus_vote_free(ns);
  2326. ns = NULL;
  2327. done:
  2328. if (tokens) {
  2329. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  2330. smartlist_free(tokens);
  2331. }
  2332. if (voter) {
  2333. tor_free(voter->nickname);
  2334. tor_free(voter->address);
  2335. tor_free(voter->contact);
  2336. tor_free(voter->signature);
  2337. tor_free(voter);
  2338. }
  2339. if (rs_tokens) {
  2340. SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_free(t));
  2341. smartlist_free(rs_tokens);
  2342. }
  2343. if (footer_tokens) {
  2344. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_free(t));
  2345. smartlist_free(footer_tokens);
  2346. }
  2347. if (area) {
  2348. DUMP_AREA(area, "v3 networkstatus");
  2349. memarea_drop_all(area);
  2350. }
  2351. if (rs_area)
  2352. memarea_drop_all(rs_area);
  2353. return ns;
  2354. }
  2355. /** Parse a detached v3 networkstatus signature document between <b>s</b> and
  2356. * <b>eos</b> and return the result. Return -1 on failure. */
  2357. ns_detached_signatures_t *
  2358. networkstatus_parse_detached_signatures(const char *s, const char *eos)
  2359. {
  2360. /* XXXX there is too much duplicate shared between this function and
  2361. * networkstatus_parse_vote_from_string(). */
  2362. directory_token_t *tok;
  2363. memarea_t *area = NULL;
  2364. smartlist_t *tokens = smartlist_create();
  2365. ns_detached_signatures_t *sigs =
  2366. tor_malloc_zero(sizeof(ns_detached_signatures_t));
  2367. if (!eos)
  2368. eos = s + strlen(s);
  2369. area = memarea_new();
  2370. if (tokenize_string(area,s, eos, tokens,
  2371. networkstatus_detached_signature_token_table, 0)) {
  2372. log_warn(LD_DIR, "Error tokenizing detached networkstatus signatures");
  2373. goto err;
  2374. }
  2375. tok = find_by_keyword(tokens, K_CONSENSUS_DIGEST);
  2376. if (strlen(tok->args[0]) != HEX_DIGEST_LEN) {
  2377. log_warn(LD_DIR, "Wrong length on consensus-digest in detached "
  2378. "networkstatus signatures");
  2379. goto err;
  2380. }
  2381. if (base16_decode(sigs->networkstatus_digest, DIGEST_LEN,
  2382. tok->args[0], strlen(tok->args[0])) < 0) {
  2383. log_warn(LD_DIR, "Bad encoding on on consensus-digest in detached "
  2384. "networkstatus signatures");
  2385. goto err;
  2386. }
  2387. tok = find_by_keyword(tokens, K_VALID_AFTER);
  2388. if (parse_iso_time(tok->args[0], &sigs->valid_after)) {
  2389. log_warn(LD_DIR, "Bad valid-after in detached networkstatus signatures");
  2390. goto err;
  2391. }
  2392. tok = find_by_keyword(tokens, K_FRESH_UNTIL);
  2393. if (parse_iso_time(tok->args[0], &sigs->fresh_until)) {
  2394. log_warn(LD_DIR, "Bad fresh-until in detached networkstatus signatures");
  2395. goto err;
  2396. }
  2397. tok = find_by_keyword(tokens, K_VALID_UNTIL);
  2398. if (parse_iso_time(tok->args[0], &sigs->valid_until)) {
  2399. log_warn(LD_DIR, "Bad valid-until in detached networkstatus signatures");
  2400. goto err;
  2401. }
  2402. sigs->signatures = smartlist_create();
  2403. SMARTLIST_FOREACH(tokens, directory_token_t *, _tok,
  2404. {
  2405. char id_digest[DIGEST_LEN];
  2406. char sk_digest[DIGEST_LEN];
  2407. networkstatus_voter_info_t *voter;
  2408. tok = _tok;
  2409. if (tok->tp != K_DIRECTORY_SIGNATURE)
  2410. continue;
  2411. tor_assert(tok->n_args >= 2);
  2412. if (!tok->object_type ||
  2413. strcmp(tok->object_type, "SIGNATURE") ||
  2414. tok->object_size < 128 || tok->object_size > 512) {
  2415. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  2416. goto err;
  2417. }
  2418. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  2419. base16_decode(id_digest, sizeof(id_digest),
  2420. tok->args[0], HEX_DIGEST_LEN) < 0) {
  2421. log_warn(LD_DIR, "Error decoding declared identity %s in "
  2422. "network-status vote.", escaped(tok->args[0]));
  2423. goto err;
  2424. }
  2425. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  2426. base16_decode(sk_digest, sizeof(sk_digest),
  2427. tok->args[1], HEX_DIGEST_LEN) < 0) {
  2428. log_warn(LD_DIR, "Error decoding declared digest %s in "
  2429. "network-status vote.", escaped(tok->args[1]));
  2430. goto err;
  2431. }
  2432. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  2433. memcpy(voter->identity_digest, id_digest, DIGEST_LEN);
  2434. memcpy(voter->signing_key_digest, sk_digest, DIGEST_LEN);
  2435. if (tok->object_size >= INT_MAX)
  2436. goto err;
  2437. voter->signature = tor_memdup(tok->object_body, tok->object_size);
  2438. voter->signature_len = (int) tok->object_size;
  2439. smartlist_add(sigs->signatures, voter);
  2440. });
  2441. goto done;
  2442. err:
  2443. ns_detached_signatures_free(sigs);
  2444. sigs = NULL;
  2445. done:
  2446. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  2447. smartlist_free(tokens);
  2448. if (area) {
  2449. DUMP_AREA(area, "detached signatures");
  2450. memarea_drop_all(area);
  2451. }
  2452. return sigs;
  2453. }
  2454. /** Parse the addr policy in the string <b>s</b> and return it. If
  2455. * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
  2456. * ADDR_POLICY_REJECT) for items that specify no action.
  2457. */
  2458. addr_policy_t *
  2459. router_parse_addr_policy_item_from_string(const char *s, int assume_action)
  2460. {
  2461. directory_token_t *tok = NULL;
  2462. const char *cp, *eos;
  2463. /* Longest possible policy is "accept ffff:ffff:..255/ffff:...255:0-65535".
  2464. * But note that there can be an arbitrary amount of space between the
  2465. * accept and the address:mask/port element. */
  2466. char line[TOR_ADDR_BUF_LEN*2 + 32];
  2467. addr_policy_t *r;
  2468. memarea_t *area = NULL;
  2469. s = eat_whitespace(s);
  2470. if ((*s == '*' || TOR_ISDIGIT(*s)) && assume_action >= 0) {
  2471. if (tor_snprintf(line, sizeof(line), "%s %s",
  2472. assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", s)<0) {
  2473. log_warn(LD_DIR, "Policy %s is too long.", escaped(s));
  2474. return NULL;
  2475. }
  2476. cp = line;
  2477. tor_strlower(line);
  2478. } else { /* assume an already well-formed address policy line */
  2479. cp = s;
  2480. }
  2481. eos = cp + strlen(cp);
  2482. area = memarea_new();
  2483. tok = get_next_token(area, &cp, eos, routerdesc_token_table);
  2484. if (tok->tp == _ERR) {
  2485. log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
  2486. goto err;
  2487. }
  2488. if (tok->tp != K_ACCEPT && tok->tp != K_ACCEPT6 &&
  2489. tok->tp != K_REJECT && tok->tp != K_REJECT6) {
  2490. log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
  2491. goto err;
  2492. }
  2493. r = router_parse_addr_policy(tok);
  2494. goto done;
  2495. err:
  2496. r = NULL;
  2497. done:
  2498. token_free(tok);
  2499. if (area) {
  2500. DUMP_AREA(area, "policy item");
  2501. memarea_drop_all(area);
  2502. }
  2503. return r;
  2504. }
  2505. /** Add an exit policy stored in the token <b>tok</b> to the router info in
  2506. * <b>router</b>. Return 0 on success, -1 on failure. */
  2507. static int
  2508. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
  2509. {
  2510. addr_policy_t *newe;
  2511. newe = router_parse_addr_policy(tok);
  2512. if (!newe)
  2513. return -1;
  2514. if (! router->exit_policy)
  2515. router->exit_policy = smartlist_create();
  2516. if (((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  2517. tor_addr_family(&newe->addr) == AF_INET)
  2518. ||
  2519. ((tok->tp == K_ACCEPT || tok->tp == K_REJECT) &&
  2520. tor_addr_family(&newe->addr) == AF_INET6)) {
  2521. log_warn(LD_DIR, "Mismatch between field type and address type in exit "
  2522. "policy");
  2523. addr_policy_free(newe);
  2524. return -1;
  2525. }
  2526. smartlist_add(router->exit_policy, newe);
  2527. return 0;
  2528. }
  2529. /** Given a K_ACCEPT or K_REJECT token and a router, create and return
  2530. * a new exit_policy_t corresponding to the token. */
  2531. static addr_policy_t *
  2532. router_parse_addr_policy(directory_token_t *tok)
  2533. {
  2534. addr_policy_t newe;
  2535. char *arg;
  2536. tor_assert(tok->tp == K_REJECT || tok->tp == K_REJECT6 ||
  2537. tok->tp == K_ACCEPT || tok->tp == K_ACCEPT6);
  2538. if (tok->n_args != 1)
  2539. return NULL;
  2540. arg = tok->args[0];
  2541. if (!strcmpstart(arg,"private"))
  2542. return router_parse_addr_policy_private(tok);
  2543. memset(&newe, 0, sizeof(newe));
  2544. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  2545. newe.policy_type = ADDR_POLICY_REJECT;
  2546. else
  2547. newe.policy_type = ADDR_POLICY_ACCEPT;
  2548. if (tor_addr_parse_mask_ports(arg, &newe.addr, &newe.maskbits,
  2549. &newe.prt_min, &newe.prt_max) < 0) {
  2550. log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
  2551. return NULL;
  2552. }
  2553. return addr_policy_get_canonical_entry(&newe);
  2554. }
  2555. /** Parse an exit policy line of the format "accept/reject private:...".
  2556. * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
  2557. * router descriptors until earlier versions are obsolete.
  2558. */
  2559. static addr_policy_t *
  2560. router_parse_addr_policy_private(directory_token_t *tok)
  2561. {
  2562. const char *arg;
  2563. uint16_t port_min, port_max;
  2564. addr_policy_t result;
  2565. arg = tok->args[0];
  2566. if (strcmpstart(arg, "private"))
  2567. return NULL;
  2568. arg += strlen("private");
  2569. arg = (char*) eat_whitespace(arg);
  2570. if (!arg || *arg != ':')
  2571. return NULL;
  2572. if (parse_port_range(arg+1, &port_min, &port_max)<0)
  2573. return NULL;
  2574. memset(&result, 0, sizeof(result));
  2575. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  2576. result.policy_type = ADDR_POLICY_REJECT;
  2577. else
  2578. result.policy_type = ADDR_POLICY_ACCEPT;
  2579. result.is_private = 1;
  2580. result.prt_min = port_min;
  2581. result.prt_max = port_max;
  2582. return addr_policy_get_canonical_entry(&result);
  2583. }
  2584. /** Log and exit if <b>t</b> is malformed */
  2585. void
  2586. assert_addr_policy_ok(smartlist_t *lst)
  2587. {
  2588. if (!lst) return;
  2589. SMARTLIST_FOREACH(lst, addr_policy_t *, t, {
  2590. tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
  2591. t->policy_type == ADDR_POLICY_ACCEPT);
  2592. tor_assert(t->prt_min <= t->prt_max);
  2593. });
  2594. }
  2595. /*
  2596. * Low-level tokenizer for router descriptors and directories.
  2597. */
  2598. /** Free all resources allocated for <b>tok</b> */
  2599. static void
  2600. token_free(directory_token_t *tok)
  2601. {
  2602. tor_assert(tok);
  2603. if (tok->key)
  2604. crypto_free_pk_env(tok->key);
  2605. }
  2606. #define ALLOC_ZERO(sz) memarea_alloc_zero(area,sz)
  2607. #define ALLOC(sz) memarea_alloc(area,sz)
  2608. #define STRDUP(str) memarea_strdup(area,str)
  2609. #define STRNDUP(str,n) memarea_strndup(area,(str),(n))
  2610. #define RET_ERR(msg) \
  2611. STMT_BEGIN \
  2612. if (tok) token_free(tok); \
  2613. tok = ALLOC_ZERO(sizeof(directory_token_t)); \
  2614. tok->tp = _ERR; \
  2615. tok->error = STRDUP(msg); \
  2616. goto done_tokenizing; \
  2617. STMT_END
  2618. /** Helper: make sure that the token <b>tok</b> with keyword <b>kwd</b> obeys
  2619. * the object syntax of <b>o_syn</b>. Allocate all storage in <b>area</b>.
  2620. * Return <b>tok</b> on success, or a new _ERR token if the token didn't
  2621. * conform to the syntax we wanted.
  2622. **/
  2623. static INLINE directory_token_t *
  2624. token_check_object(memarea_t *area, const char *kwd,
  2625. directory_token_t *tok, obj_syntax o_syn)
  2626. {
  2627. char ebuf[128];
  2628. switch (o_syn) {
  2629. case NO_OBJ:
  2630. /* No object is allowed for this token. */
  2631. if (tok->object_body) {
  2632. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected object for %s", kwd);
  2633. RET_ERR(ebuf);
  2634. }
  2635. if (tok->key) {
  2636. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected public key for %s", kwd);
  2637. RET_ERR(ebuf);
  2638. }
  2639. break;
  2640. case NEED_OBJ:
  2641. /* There must be a (non-key) object. */
  2642. if (!tok->object_body) {
  2643. tor_snprintf(ebuf, sizeof(ebuf), "Missing object for %s", kwd);
  2644. RET_ERR(ebuf);
  2645. }
  2646. break;
  2647. case NEED_KEY_1024: /* There must be a 1024-bit public key. */
  2648. case NEED_SKEY_1024: /* There must be a 1024-bit private key. */
  2649. if (tok->key && crypto_pk_keysize(tok->key) != PK_BYTES) {
  2650. tor_snprintf(ebuf, sizeof(ebuf), "Wrong size on key for %s: %d bits",
  2651. kwd, (int)crypto_pk_keysize(tok->key));
  2652. RET_ERR(ebuf);
  2653. }
  2654. /* fall through */
  2655. case NEED_KEY: /* There must be some kind of key. */
  2656. if (!tok->key) {
  2657. tor_snprintf(ebuf, sizeof(ebuf), "Missing public key for %s", kwd);
  2658. RET_ERR(ebuf);
  2659. }
  2660. if (o_syn != NEED_SKEY_1024) {
  2661. if (crypto_pk_key_is_private(tok->key)) {
  2662. tor_snprintf(ebuf, sizeof(ebuf),
  2663. "Private key given for %s, which wants a public key", kwd);
  2664. RET_ERR(ebuf);
  2665. }
  2666. } else { /* o_syn == NEED_SKEY_1024 */
  2667. if (!crypto_pk_key_is_private(tok->key)) {
  2668. tor_snprintf(ebuf, sizeof(ebuf),
  2669. "Public key given for %s, which wants a private key", kwd);
  2670. RET_ERR(ebuf);
  2671. }
  2672. }
  2673. break;
  2674. case OBJ_OK:
  2675. /* Anything goes with this token. */
  2676. break;
  2677. }
  2678. done_tokenizing:
  2679. return tok;
  2680. }
  2681. /** Helper: parse space-separated arguments from the string <b>s</b> ending at
  2682. * <b>eol</b>, and store them in the args field of <b>tok</b>. Store the
  2683. * number of parsed elements into the n_args field of <b>tok</b>. Allocate
  2684. * all storage in <b>area</b>. Return the number of arguments parsed, or
  2685. * return -1 if there was an insanely high number of arguments. */
  2686. static INLINE int
  2687. get_token_arguments(memarea_t *area, directory_token_t *tok,
  2688. const char *s, const char *eol)
  2689. {
  2690. /** Largest number of arguments we'll accept to any token, ever. */
  2691. #define MAX_ARGS 512
  2692. char *mem = memarea_strndup(area, s, eol-s);
  2693. char *cp = mem;
  2694. int j = 0;
  2695. char *args[MAX_ARGS];
  2696. while (*cp) {
  2697. if (j == MAX_ARGS)
  2698. return -1;
  2699. args[j++] = cp;
  2700. cp = (char*)find_whitespace(cp);
  2701. if (!cp || !*cp)
  2702. break; /* End of the line. */
  2703. *cp++ = '\0';
  2704. cp = (char*)eat_whitespace(cp);
  2705. }
  2706. tok->n_args = j;
  2707. tok->args = memarea_memdup(area, args, j*sizeof(char*));
  2708. return j;
  2709. #undef MAX_ARGS
  2710. }
  2711. /** Helper function: read the next token from *s, advance *s to the end of the
  2712. * token, and return the parsed token. Parse *<b>s</b> according to the list
  2713. * of tokens in <b>table</b>.
  2714. */
  2715. static directory_token_t *
  2716. get_next_token(memarea_t *area,
  2717. const char **s, const char *eos, token_rule_t *table)
  2718. {
  2719. const char *next, *eol, *obstart;
  2720. size_t obname_len;
  2721. int i;
  2722. directory_token_t *tok;
  2723. obj_syntax o_syn = NO_OBJ;
  2724. char ebuf[128];
  2725. const char *kwd = "";
  2726. tor_assert(area);
  2727. tok = ALLOC_ZERO(sizeof(directory_token_t));
  2728. tok->tp = _ERR;
  2729. /* Set *s to first token, eol to end-of-line, next to after first token */
  2730. *s = eat_whitespace_eos(*s, eos); /* eat multi-line whitespace */
  2731. tor_assert(eos >= *s);
  2732. eol = memchr(*s, '\n', eos-*s);
  2733. if (!eol)
  2734. eol = eos;
  2735. next = find_whitespace_eos(*s, eol);
  2736. if (!strcmp_len(*s, "opt", next-*s)) {
  2737. /* Skip past an "opt" at the start of the line. */
  2738. *s = eat_whitespace_eos_no_nl(next, eol);
  2739. next = find_whitespace_eos(*s, eol);
  2740. } else if (*s == eos) { /* If no "opt", and end-of-line, line is invalid */
  2741. RET_ERR("Unexpected EOF");
  2742. }
  2743. /* Search the table for the appropriate entry. (I tried a binary search
  2744. * instead, but it wasn't any faster.) */
  2745. for (i = 0; table[i].t ; ++i) {
  2746. if (!strcmp_len(*s, table[i].t, next-*s)) {
  2747. /* We've found the keyword. */
  2748. kwd = table[i].t;
  2749. tok->tp = table[i].v;
  2750. o_syn = table[i].os;
  2751. *s = eat_whitespace_eos_no_nl(next, eol);
  2752. /* We go ahead whether there are arguments or not, so that tok->args is
  2753. * always set if we want arguments. */
  2754. if (table[i].concat_args) {
  2755. /* The keyword takes the line as a single argument */
  2756. tok->args = ALLOC(sizeof(char*));
  2757. tok->args[0] = STRNDUP(*s,eol-*s); /* Grab everything on line */
  2758. tok->n_args = 1;
  2759. } else {
  2760. /* This keyword takes multiple arguments. */
  2761. if (get_token_arguments(area, tok, *s, eol)<0) {
  2762. tor_snprintf(ebuf, sizeof(ebuf),"Far too many arguments to %s", kwd);
  2763. RET_ERR(ebuf);
  2764. }
  2765. *s = eol;
  2766. }
  2767. if (tok->n_args < table[i].min_args) {
  2768. tor_snprintf(ebuf, sizeof(ebuf), "Too few arguments to %s", kwd);
  2769. RET_ERR(ebuf);
  2770. } else if (tok->n_args > table[i].max_args) {
  2771. tor_snprintf(ebuf, sizeof(ebuf), "Too many arguments to %s", kwd);
  2772. RET_ERR(ebuf);
  2773. }
  2774. break;
  2775. }
  2776. }
  2777. if (tok->tp == _ERR) {
  2778. /* No keyword matched; call it an "K_opt" or "A_unrecognized" */
  2779. if (**s == '@')
  2780. tok->tp = _A_UNKNOWN;
  2781. else
  2782. tok->tp = K_OPT;
  2783. tok->args = ALLOC(sizeof(char*));
  2784. tok->args[0] = STRNDUP(*s, eol-*s);
  2785. tok->n_args = 1;
  2786. o_syn = OBJ_OK;
  2787. }
  2788. /* Check whether there's an object present */
  2789. *s = eat_whitespace_eos(eol, eos); /* Scan from end of first line */
  2790. tor_assert(eos >= *s);
  2791. eol = memchr(*s, '\n', eos-*s);
  2792. if (!eol || eol-*s<11 || strcmpstart(*s, "-----BEGIN ")) /* No object. */
  2793. goto check_object;
  2794. obstart = *s; /* Set obstart to start of object spec */
  2795. if (*s+16 >= eol || memchr(*s+11,'\0',eol-*s-16) || /* no short lines, */
  2796. strcmp_len(eol-5, "-----", 5)) { /* nuls or invalid endings */
  2797. RET_ERR("Malformed object: bad begin line");
  2798. }
  2799. tok->object_type = STRNDUP(*s+11, eol-*s-16);
  2800. obname_len = eol-*s-16; /* store objname length here to avoid a strlen() */
  2801. *s = eol+1; /* Set *s to possible start of object data (could be eos) */
  2802. /* Go to the end of the object */
  2803. next = tor_memstr(*s, eos-*s, "-----END ");
  2804. if (!next) {
  2805. RET_ERR("Malformed object: missing object end line");
  2806. }
  2807. tor_assert(eos >= next);
  2808. eol = memchr(next, '\n', eos-next);
  2809. if (!eol) /* end-of-line marker, or eos if there's no '\n' */
  2810. eol = eos;
  2811. /* Validate the ending tag, which should be 9 + NAME + 5 + eol */
  2812. if ((size_t)(eol-next) != 9+obname_len+5 ||
  2813. strcmp_len(next+9, tok->object_type, obname_len) ||
  2814. strcmp_len(eol-5, "-----", 5)) {
  2815. snprintf(ebuf, sizeof(ebuf), "Malformed object: mismatched end tag %s",
  2816. tok->object_type);
  2817. ebuf[sizeof(ebuf)-1] = '\0';
  2818. RET_ERR(ebuf);
  2819. }
  2820. if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) { /* If it's a public key */
  2821. tok->key = crypto_new_pk_env();
  2822. if (crypto_pk_read_public_key_from_string(tok->key, obstart, eol-obstart))
  2823. RET_ERR("Couldn't parse public key.");
  2824. } else if (!strcmp(tok->object_type, "RSA PRIVATE KEY")) { /* private key */
  2825. tok->key = crypto_new_pk_env();
  2826. if (crypto_pk_read_private_key_from_string(tok->key, obstart))
  2827. RET_ERR("Couldn't parse private key.");
  2828. } else { /* If it's something else, try to base64-decode it */
  2829. int r;
  2830. tok->object_body = ALLOC(next-*s); /* really, this is too much RAM. */
  2831. r = base64_decode(tok->object_body, next-*s, *s, next-*s);
  2832. if (r<0)
  2833. RET_ERR("Malformed object: bad base64-encoded data");
  2834. tok->object_size = r;
  2835. }
  2836. *s = eol;
  2837. check_object:
  2838. tok = token_check_object(area, kwd, tok, o_syn);
  2839. done_tokenizing:
  2840. return tok;
  2841. #undef RET_ERR
  2842. #undef ALLOC
  2843. #undef ALLOC_ZERO
  2844. #undef STRDUP
  2845. #undef STRNDUP
  2846. }
  2847. /** Read all tokens from a string between <b>start</b> and <b>end</b>, and add
  2848. * them to <b>out</b>. Parse according to the token rules in <b>table</b>.
  2849. * Caller must free tokens in <b>out</b>. If <b>end</b> is NULL, use the
  2850. * entire string.
  2851. */
  2852. static int
  2853. tokenize_string(memarea_t *area,
  2854. const char *start, const char *end, smartlist_t *out,
  2855. token_rule_t *table, int flags)
  2856. {
  2857. const char **s;
  2858. directory_token_t *tok = NULL;
  2859. int counts[_NIL];
  2860. int i;
  2861. int first_nonannotation;
  2862. int prev_len = smartlist_len(out);
  2863. tor_assert(area);
  2864. s = &start;
  2865. if (!end)
  2866. end = start+strlen(start);
  2867. for (i = 0; i < _NIL; ++i)
  2868. counts[i] = 0;
  2869. while (*s < end && (!tok || tok->tp != _EOF)) {
  2870. tok = get_next_token(area, s, end, table);
  2871. if (tok->tp == _ERR) {
  2872. log_warn(LD_DIR, "parse error: %s", tok->error);
  2873. token_free(tok);
  2874. return -1;
  2875. }
  2876. ++counts[tok->tp];
  2877. smartlist_add(out, tok);
  2878. *s = eat_whitespace_eos(*s, end);
  2879. }
  2880. if (flags & TS_NOCHECK)
  2881. return 0;
  2882. if ((flags & TS_ANNOTATIONS_OK)) {
  2883. first_nonannotation = -1;
  2884. for (i = 0; i < smartlist_len(out); ++i) {
  2885. tok = smartlist_get(out, i);
  2886. if (tok->tp < MIN_ANNOTATION || tok->tp > MAX_ANNOTATION) {
  2887. first_nonannotation = i;
  2888. break;
  2889. }
  2890. }
  2891. if (first_nonannotation < 0) {
  2892. log_warn(LD_DIR, "parse error: item contains only annotations");
  2893. return -1;
  2894. }
  2895. for (i=first_nonannotation; i < smartlist_len(out); ++i) {
  2896. tok = smartlist_get(out, i);
  2897. if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
  2898. log_warn(LD_DIR, "parse error: Annotations mixed with keywords");
  2899. return -1;
  2900. }
  2901. }
  2902. if ((flags & TS_NO_NEW_ANNOTATIONS)) {
  2903. if (first_nonannotation != prev_len) {
  2904. log_warn(LD_DIR, "parse error: Unexpected annotations.");
  2905. return -1;
  2906. }
  2907. }
  2908. } else {
  2909. for (i=0; i < smartlist_len(out); ++i) {
  2910. tok = smartlist_get(out, i);
  2911. if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
  2912. log_warn(LD_DIR, "parse error: no annotations allowed.");
  2913. return -1;
  2914. }
  2915. }
  2916. first_nonannotation = 0;
  2917. }
  2918. for (i = 0; table[i].t; ++i) {
  2919. if (counts[table[i].v] < table[i].min_cnt) {
  2920. log_warn(LD_DIR, "Parse error: missing %s element.", table[i].t);
  2921. return -1;
  2922. }
  2923. if (counts[table[i].v] > table[i].max_cnt) {
  2924. log_warn(LD_DIR, "Parse error: too many %s elements.", table[i].t);
  2925. return -1;
  2926. }
  2927. if (table[i].pos & AT_START) {
  2928. if (smartlist_len(out) < 1 ||
  2929. (tok = smartlist_get(out, first_nonannotation))->tp != table[i].v) {
  2930. log_warn(LD_DIR, "Parse error: first item is not %s.", table[i].t);
  2931. return -1;
  2932. }
  2933. }
  2934. if (table[i].pos & AT_END) {
  2935. if (smartlist_len(out) < 1 ||
  2936. (tok = smartlist_get(out, smartlist_len(out)-1))->tp != table[i].v) {
  2937. log_warn(LD_DIR, "Parse error: last item is not %s.", table[i].t);
  2938. return -1;
  2939. }
  2940. }
  2941. }
  2942. return 0;
  2943. }
  2944. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
  2945. * NULL if no such keyword is found.
  2946. */
  2947. static directory_token_t *
  2948. find_opt_by_keyword(smartlist_t *s, directory_keyword keyword)
  2949. {
  2950. SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
  2951. return NULL;
  2952. }
  2953. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; fail
  2954. * with an assert if no such keyword is found.
  2955. */
  2956. static directory_token_t *
  2957. _find_by_keyword(smartlist_t *s, directory_keyword keyword,
  2958. const char *keyword_as_string)
  2959. {
  2960. directory_token_t *tok = find_opt_by_keyword(s, keyword);
  2961. if (PREDICT_UNLIKELY(!tok)) {
  2962. log_err(LD_BUG, "Missing %s [%d] in directory object that should have "
  2963. "been validated. Internal error.", keyword_as_string, (int)keyword);
  2964. tor_assert(tok);
  2965. }
  2966. return tok;
  2967. }
  2968. /** Return a newly allocated smartlist of all accept or reject tokens in
  2969. * <b>s</b>.
  2970. */
  2971. static smartlist_t *
  2972. find_all_exitpolicy(smartlist_t *s)
  2973. {
  2974. smartlist_t *out = smartlist_create();
  2975. SMARTLIST_FOREACH(s, directory_token_t *, t,
  2976. if (t->tp == K_ACCEPT || t->tp == K_ACCEPT6 ||
  2977. t->tp == K_REJECT || t->tp == K_REJECT6)
  2978. smartlist_add(out,t));
  2979. return out;
  2980. }
  2981. /** Compute the SHA-1 digest of the substring of <b>s</b> taken from the first
  2982. * occurrence of <b>start_str</b> through the first instance of c after the
  2983. * first subsequent occurrence of <b>end_str</b>; store the 20-byte result in
  2984. * <b>digest</b>; return 0 on success.
  2985. *
  2986. * If no such substring exists, return -1.
  2987. */
  2988. static int
  2989. router_get_hash_impl(const char *s, char *digest,
  2990. const char *start_str,
  2991. const char *end_str, char end_c)
  2992. {
  2993. char *start, *end;
  2994. start = strstr(s, start_str);
  2995. if (!start) {
  2996. log_warn(LD_DIR,"couldn't find start of hashed material \"%s\"",start_str);
  2997. return -1;
  2998. }
  2999. if (start != s && *(start-1) != '\n') {
  3000. log_warn(LD_DIR,
  3001. "first occurrence of \"%s\" is not at the start of a line",
  3002. start_str);
  3003. return -1;
  3004. }
  3005. end = strstr(start+strlen(start_str), end_str);
  3006. if (!end) {
  3007. log_warn(LD_DIR,"couldn't find end of hashed material \"%s\"",end_str);
  3008. return -1;
  3009. }
  3010. end = strchr(end+strlen(end_str), end_c);
  3011. if (!end) {
  3012. log_warn(LD_DIR,"couldn't find EOL");
  3013. return -1;
  3014. }
  3015. ++end;
  3016. if (crypto_digest(digest, start, end-start)) {
  3017. log_warn(LD_BUG,"couldn't compute digest");
  3018. return -1;
  3019. }
  3020. return 0;
  3021. }
  3022. /** Parse the Tor version of the platform string <b>platform</b>,
  3023. * and compare it to the version in <b>cutoff</b>. Return 1 if
  3024. * the router is at least as new as the cutoff, else return 0.
  3025. */
  3026. int
  3027. tor_version_as_new_as(const char *platform, const char *cutoff)
  3028. {
  3029. tor_version_t cutoff_version, router_version;
  3030. char *s, *s2, *start;
  3031. char tmp[128];
  3032. tor_assert(platform);
  3033. if (tor_version_parse(cutoff, &cutoff_version)<0) {
  3034. log_warn(LD_BUG,"cutoff version '%s' unparseable.",cutoff);
  3035. return 0;
  3036. }
  3037. if (strcmpstart(platform,"Tor ")) /* nonstandard Tor; be safe and say yes */
  3038. return 1;
  3039. start = (char *)eat_whitespace(platform+3);
  3040. if (!*start) return 0;
  3041. s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
  3042. s2 = (char*)eat_whitespace(s);
  3043. if (!strcmpstart(s2, "(r") || !strcmpstart(s2, "(git-"))
  3044. s = (char*)find_whitespace(s2);
  3045. if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
  3046. return 0;
  3047. strlcpy(tmp, start, s-start+1);
  3048. if (tor_version_parse(tmp, &router_version)<0) {
  3049. log_info(LD_DIR,"Router version '%s' unparseable.",tmp);
  3050. return 1; /* be safe and say yes */
  3051. }
  3052. /* Here's why we don't need to do any special handling for svn revisions:
  3053. * - If neither has an svn revision, we're fine.
  3054. * - If the router doesn't have an svn revision, we can't assume that it
  3055. * is "at least" any svn revision, so we need to return 0.
  3056. * - If the target version doesn't have an svn revision, any svn revision
  3057. * (or none at all) is good enough, so return 1.
  3058. * - If both target and router have an svn revision, we compare them.
  3059. */
  3060. return tor_version_compare(&router_version, &cutoff_version) >= 0;
  3061. }
  3062. /** Parse a tor version from <b>s</b>, and store the result in <b>out</b>.
  3063. * Return 0 on success, -1 on failure. */
  3064. int
  3065. tor_version_parse(const char *s, tor_version_t *out)
  3066. {
  3067. char *eos=NULL;
  3068. const char *cp=NULL;
  3069. /* Format is:
  3070. * "Tor " ? NUM dot NUM dot NUM [ ( pre | rc | dot ) NUM [ - tag ] ]
  3071. */
  3072. tor_assert(s);
  3073. tor_assert(out);
  3074. memset(out, 0, sizeof(tor_version_t));
  3075. if (!strcasecmpstart(s, "Tor "))
  3076. s += 4;
  3077. /* Get major. */
  3078. out->major = (int)strtol(s,&eos,10);
  3079. if (!eos || eos==s || *eos != '.') return -1;
  3080. cp = eos+1;
  3081. /* Get minor */
  3082. out->minor = (int) strtol(cp,&eos,10);
  3083. if (!eos || eos==cp || *eos != '.') return -1;
  3084. cp = eos+1;
  3085. /* Get micro */
  3086. out->micro = (int) strtol(cp,&eos,10);
  3087. if (!eos || eos==cp) return -1;
  3088. if (!*eos) {
  3089. out->status = VER_RELEASE;
  3090. out->patchlevel = 0;
  3091. return 0;
  3092. }
  3093. cp = eos;
  3094. /* Get status */
  3095. if (*cp == '.') {
  3096. out->status = VER_RELEASE;
  3097. ++cp;
  3098. } else if (0==strncmp(cp, "pre", 3)) {
  3099. out->status = VER_PRE;
  3100. cp += 3;
  3101. } else if (0==strncmp(cp, "rc", 2)) {
  3102. out->status = VER_RC;
  3103. cp += 2;
  3104. } else {
  3105. return -1;
  3106. }
  3107. /* Get patchlevel */
  3108. out->patchlevel = (int) strtol(cp,&eos,10);
  3109. if (!eos || eos==cp) return -1;
  3110. cp = eos;
  3111. /* Get status tag. */
  3112. if (*cp == '-' || *cp == '.')
  3113. ++cp;
  3114. eos = (char*) find_whitespace(cp);
  3115. if (eos-cp >= (int)sizeof(out->status_tag))
  3116. strlcpy(out->status_tag, cp, sizeof(out->status_tag));
  3117. else {
  3118. memcpy(out->status_tag, cp, eos-cp);
  3119. out->status_tag[eos-cp] = 0;
  3120. }
  3121. cp = eat_whitespace(eos);
  3122. if (!strcmpstart(cp, "(r")) {
  3123. cp += 2;
  3124. out->svn_revision = (int) strtol(cp,&eos,10);
  3125. } else if (!strcmpstart(cp, "(git-")) {
  3126. char *close_paren = strchr(cp, ')');
  3127. int hexlen;
  3128. char digest[DIGEST_LEN];
  3129. if (! close_paren)
  3130. return -1;
  3131. cp += 5;
  3132. hexlen = (close_paren-cp);
  3133. memset(digest, 0, sizeof(digest));
  3134. if (hexlen > HEX_DIGEST_LEN || hexlen == 0 || (hexlen % 2) == 1)
  3135. return -1;
  3136. if (base16_decode(digest, hexlen/2, cp, hexlen))
  3137. return -1;
  3138. memcpy(out->git_tag, digest, hexlen/2);
  3139. out->git_tag_len = hexlen/2;
  3140. }
  3141. return 0;
  3142. }
  3143. /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
  3144. * b. */
  3145. int
  3146. tor_version_compare(tor_version_t *a, tor_version_t *b)
  3147. {
  3148. int i;
  3149. tor_assert(a);
  3150. tor_assert(b);
  3151. if ((i = a->major - b->major))
  3152. return i;
  3153. else if ((i = a->minor - b->minor))
  3154. return i;
  3155. else if ((i = a->micro - b->micro))
  3156. return i;
  3157. else if ((i = a->status - b->status))
  3158. return i;
  3159. else if ((i = a->patchlevel - b->patchlevel))
  3160. return i;
  3161. else if ((i = strcmp(a->status_tag, b->status_tag)))
  3162. return i;
  3163. else if ((i = a->svn_revision - b->svn_revision))
  3164. return i;
  3165. else if ((i = a->git_tag_len - b->git_tag_len))
  3166. return i;
  3167. else if (a->git_tag_len)
  3168. return memcmp(a->git_tag, b->git_tag, a->git_tag_len);
  3169. else
  3170. return 0;
  3171. }
  3172. /** Return true iff versions <b>a</b> and <b>b</b> belong to the same series.
  3173. */
  3174. static int
  3175. tor_version_same_series(tor_version_t *a, tor_version_t *b)
  3176. {
  3177. tor_assert(a);
  3178. tor_assert(b);
  3179. return ((a->major == b->major) &&
  3180. (a->minor == b->minor) &&
  3181. (a->micro == b->micro));
  3182. }
  3183. /** Helper: Given pointers to two strings describing tor versions, return -1
  3184. * if _a precedes _b, 1 if _b precedes _a, and 0 if they are equivalent.
  3185. * Used to sort a list of versions. */
  3186. static int
  3187. _compare_tor_version_str_ptr(const void **_a, const void **_b)
  3188. {
  3189. const char *a = *_a, *b = *_b;
  3190. int ca, cb;
  3191. tor_version_t va, vb;
  3192. ca = tor_version_parse(a, &va);
  3193. cb = tor_version_parse(b, &vb);
  3194. /* If they both parse, compare them. */
  3195. if (!ca && !cb)
  3196. return tor_version_compare(&va,&vb);
  3197. /* If one parses, it comes first. */
  3198. if (!ca && cb)
  3199. return -1;
  3200. if (ca && !cb)
  3201. return 1;
  3202. /* If neither parses, compare strings. Also, the directory server admin
  3203. ** needs to be smacked upside the head. But Tor is tolerant and gentle. */
  3204. return strcmp(a,b);
  3205. }
  3206. /** Sort a list of string-representations of versions in ascending order. */
  3207. void
  3208. sort_version_list(smartlist_t *versions, int remove_duplicates)
  3209. {
  3210. smartlist_sort(versions, _compare_tor_version_str_ptr);
  3211. if (remove_duplicates)
  3212. smartlist_uniq(versions, _compare_tor_version_str_ptr, _tor_free);
  3213. }
  3214. /** Parse and validate the ASCII-encoded v2 descriptor in <b>desc</b>,
  3215. * write the parsed descriptor to the newly allocated *<b>parsed_out</b>, the
  3216. * binary descriptor ID of length DIGEST_LEN to <b>desc_id_out</b>, the
  3217. * encrypted introduction points to the newly allocated
  3218. * *<b>intro_points_encrypted_out</b>, their encrypted size to
  3219. * *<b>intro_points_encrypted_size_out</b>, the size of the encoded descriptor
  3220. * to *<b>encoded_size_out</b>, and a pointer to the possibly next
  3221. * descriptor to *<b>next_out</b>; return 0 for success (including validation)
  3222. * and -1 for failure.
  3223. */
  3224. int
  3225. rend_parse_v2_service_descriptor(rend_service_descriptor_t **parsed_out,
  3226. char *desc_id_out,
  3227. char **intro_points_encrypted_out,
  3228. size_t *intro_points_encrypted_size_out,
  3229. size_t *encoded_size_out,
  3230. const char **next_out, const char *desc)
  3231. {
  3232. rend_service_descriptor_t *result =
  3233. tor_malloc_zero(sizeof(rend_service_descriptor_t));
  3234. char desc_hash[DIGEST_LEN];
  3235. const char *eos;
  3236. smartlist_t *tokens = smartlist_create();
  3237. directory_token_t *tok;
  3238. char secret_id_part[DIGEST_LEN];
  3239. int i, version, num_ok=1;
  3240. smartlist_t *versions;
  3241. char public_key_hash[DIGEST_LEN];
  3242. char test_desc_id[DIGEST_LEN];
  3243. memarea_t *area = NULL;
  3244. tor_assert(desc);
  3245. /* Check if desc starts correctly. */
  3246. if (strncmp(desc, "rendezvous-service-descriptor ",
  3247. strlen("rendezvous-service-descriptor "))) {
  3248. log_info(LD_REND, "Descriptor does not start correctly.");
  3249. goto err;
  3250. }
  3251. /* Compute descriptor hash for later validation. */
  3252. if (router_get_hash_impl(desc, desc_hash,
  3253. "rendezvous-service-descriptor ",
  3254. "\nsignature", '\n') < 0) {
  3255. log_warn(LD_REND, "Couldn't compute descriptor hash.");
  3256. goto err;
  3257. }
  3258. /* Determine end of string. */
  3259. eos = strstr(desc, "\nrendezvous-service-descriptor ");
  3260. if (!eos)
  3261. eos = desc + strlen(desc);
  3262. else
  3263. eos = eos + 1;
  3264. /* Check length. */
  3265. if (strlen(desc) > REND_DESC_MAX_SIZE) {
  3266. log_warn(LD_REND, "Descriptor length is %i which exceeds "
  3267. "maximum rendezvous descriptor size of %i kilobytes.",
  3268. (int)strlen(desc), REND_DESC_MAX_SIZE);
  3269. goto err;
  3270. }
  3271. /* Tokenize descriptor. */
  3272. area = memarea_new();
  3273. if (tokenize_string(area, desc, eos, tokens, desc_token_table, 0)) {
  3274. log_warn(LD_REND, "Error tokenizing descriptor.");
  3275. goto err;
  3276. }
  3277. /* Set next to next descriptor, if available. */
  3278. *next_out = eos;
  3279. /* Set length of encoded descriptor. */
  3280. *encoded_size_out = eos - desc;
  3281. /* Check min allowed length of token list. */
  3282. if (smartlist_len(tokens) < 7) {
  3283. log_warn(LD_REND, "Impossibly short descriptor.");
  3284. goto err;
  3285. }
  3286. /* Parse base32-encoded descriptor ID. */
  3287. tok = find_by_keyword(tokens, R_RENDEZVOUS_SERVICE_DESCRIPTOR);
  3288. tor_assert(tok == smartlist_get(tokens, 0));
  3289. tor_assert(tok->n_args == 1);
  3290. if (strlen(tok->args[0]) != REND_DESC_ID_V2_LEN_BASE32 ||
  3291. strspn(tok->args[0], BASE32_CHARS) != REND_DESC_ID_V2_LEN_BASE32) {
  3292. log_warn(LD_REND, "Invalid descriptor ID: '%s'", tok->args[0]);
  3293. goto err;
  3294. }
  3295. if (base32_decode(desc_id_out, DIGEST_LEN,
  3296. tok->args[0], REND_DESC_ID_V2_LEN_BASE32) < 0) {
  3297. log_warn(LD_REND, "Descriptor ID contains illegal characters: %s",
  3298. tok->args[0]);
  3299. goto err;
  3300. }
  3301. /* Parse descriptor version. */
  3302. tok = find_by_keyword(tokens, R_VERSION);
  3303. tor_assert(tok->n_args == 1);
  3304. result->version =
  3305. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &num_ok, NULL);
  3306. if (result->version != 2 || !num_ok) {
  3307. /* If it's <2, it shouldn't be under this format. If the number
  3308. * is greater than 2, we bumped it because we broke backward
  3309. * compatibility. See how version numbers in our other formats
  3310. * work. */
  3311. log_warn(LD_REND, "Unrecognized descriptor version: %s",
  3312. escaped(tok->args[0]));
  3313. goto err;
  3314. }
  3315. /* Parse public key. */
  3316. tok = find_by_keyword(tokens, R_PERMANENT_KEY);
  3317. result->pk = tok->key;
  3318. tok->key = NULL; /* Prevent free */
  3319. /* Parse secret ID part. */
  3320. tok = find_by_keyword(tokens, R_SECRET_ID_PART);
  3321. tor_assert(tok->n_args == 1);
  3322. if (strlen(tok->args[0]) != REND_SECRET_ID_PART_LEN_BASE32 ||
  3323. strspn(tok->args[0], BASE32_CHARS) != REND_SECRET_ID_PART_LEN_BASE32) {
  3324. log_warn(LD_REND, "Invalid secret ID part: '%s'", tok->args[0]);
  3325. goto err;
  3326. }
  3327. if (base32_decode(secret_id_part, DIGEST_LEN, tok->args[0], 32) < 0) {
  3328. log_warn(LD_REND, "Secret ID part contains illegal characters: %s",
  3329. tok->args[0]);
  3330. goto err;
  3331. }
  3332. /* Parse publication time -- up-to-date check is done when storing the
  3333. * descriptor. */
  3334. tok = find_by_keyword(tokens, R_PUBLICATION_TIME);
  3335. tor_assert(tok->n_args == 1);
  3336. if (parse_iso_time(tok->args[0], &result->timestamp) < 0) {
  3337. log_warn(LD_REND, "Invalid publication time: '%s'", tok->args[0]);
  3338. goto err;
  3339. }
  3340. /* Parse protocol versions. */
  3341. tok = find_by_keyword(tokens, R_PROTOCOL_VERSIONS);
  3342. tor_assert(tok->n_args == 1);
  3343. versions = smartlist_create();
  3344. smartlist_split_string(versions, tok->args[0], ",",
  3345. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3346. for (i = 0; i < smartlist_len(versions); i++) {
  3347. version = (int) tor_parse_long(smartlist_get(versions, i),
  3348. 10, 0, INT_MAX, &num_ok, NULL);
  3349. if (!num_ok) /* It's a string; let's ignore it. */
  3350. continue;
  3351. result->protocols |= 1 << version;
  3352. }
  3353. SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
  3354. smartlist_free(versions);
  3355. /* Parse encrypted introduction points. Don't verify. */
  3356. tok = find_opt_by_keyword(tokens, R_INTRODUCTION_POINTS);
  3357. if (tok) {
  3358. if (strcmp(tok->object_type, "MESSAGE")) {
  3359. log_warn(LD_DIR, "Bad object type: introduction points should be of "
  3360. "type MESSAGE");
  3361. goto err;
  3362. }
  3363. *intro_points_encrypted_out = tor_memdup(tok->object_body,
  3364. tok->object_size);
  3365. *intro_points_encrypted_size_out = tok->object_size;
  3366. } else {
  3367. *intro_points_encrypted_out = NULL;
  3368. *intro_points_encrypted_size_out = 0;
  3369. }
  3370. /* Parse and verify signature. */
  3371. tok = find_by_keyword(tokens, R_SIGNATURE);
  3372. note_crypto_pk_op(VERIFY_RTR);
  3373. if (check_signature_token(desc_hash, tok, result->pk, 0,
  3374. "v2 rendezvous service descriptor") < 0)
  3375. goto err;
  3376. /* Verify that descriptor ID belongs to public key and secret ID part. */
  3377. crypto_pk_get_digest(result->pk, public_key_hash);
  3378. rend_get_descriptor_id_bytes(test_desc_id, public_key_hash,
  3379. secret_id_part);
  3380. if (memcmp(desc_id_out, test_desc_id, DIGEST_LEN)) {
  3381. log_warn(LD_REND, "Parsed descriptor ID does not match "
  3382. "computed descriptor ID.");
  3383. goto err;
  3384. }
  3385. goto done;
  3386. err:
  3387. if (result)
  3388. rend_service_descriptor_free(result);
  3389. result = NULL;
  3390. done:
  3391. if (tokens) {
  3392. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  3393. smartlist_free(tokens);
  3394. }
  3395. if (area)
  3396. memarea_drop_all(area);
  3397. *parsed_out = result;
  3398. if (result)
  3399. return 0;
  3400. return -1;
  3401. }
  3402. /** Decrypt the encrypted introduction points in <b>ipos_encrypted</b> of
  3403. * length <b>ipos_encrypted_size</b> using <b>descriptor_cookie</b> and
  3404. * write the result to a newly allocated string that is pointed to by
  3405. * <b>ipos_decrypted</b> and its length to <b>ipos_decrypted_size</b>.
  3406. * Return 0 if decryption was successful and -1 otherwise. */
  3407. int
  3408. rend_decrypt_introduction_points(char **ipos_decrypted,
  3409. size_t *ipos_decrypted_size,
  3410. const char *descriptor_cookie,
  3411. const char *ipos_encrypted,
  3412. size_t ipos_encrypted_size)
  3413. {
  3414. tor_assert(ipos_encrypted);
  3415. tor_assert(descriptor_cookie);
  3416. if (ipos_encrypted_size < 2) {
  3417. log_warn(LD_REND, "Size of encrypted introduction points is too "
  3418. "small.");
  3419. return -1;
  3420. }
  3421. if (ipos_encrypted[0] == (int)REND_BASIC_AUTH) {
  3422. char iv[CIPHER_IV_LEN], client_id[REND_BASIC_AUTH_CLIENT_ID_LEN],
  3423. session_key[CIPHER_KEY_LEN], *dec;
  3424. int declen, client_blocks;
  3425. size_t pos = 0, len, client_entries_len;
  3426. crypto_digest_env_t *digest;
  3427. crypto_cipher_env_t *cipher;
  3428. client_blocks = (int) ipos_encrypted[1];
  3429. client_entries_len = client_blocks * REND_BASIC_AUTH_CLIENT_MULTIPLE *
  3430. REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
  3431. if (ipos_encrypted_size < 2 + client_entries_len + CIPHER_IV_LEN + 1) {
  3432. log_warn(LD_REND, "Size of encrypted introduction points is too "
  3433. "small.");
  3434. return -1;
  3435. }
  3436. memcpy(iv, ipos_encrypted + 2 + client_entries_len, CIPHER_IV_LEN);
  3437. digest = crypto_new_digest_env();
  3438. crypto_digest_add_bytes(digest, descriptor_cookie, REND_DESC_COOKIE_LEN);
  3439. crypto_digest_add_bytes(digest, iv, CIPHER_IV_LEN);
  3440. crypto_digest_get_digest(digest, client_id,
  3441. REND_BASIC_AUTH_CLIENT_ID_LEN);
  3442. crypto_free_digest_env(digest);
  3443. for (pos = 2; pos < 2 + client_entries_len;
  3444. pos += REND_BASIC_AUTH_CLIENT_ENTRY_LEN) {
  3445. if (!memcmp(ipos_encrypted + pos, client_id,
  3446. REND_BASIC_AUTH_CLIENT_ID_LEN)) {
  3447. /* Attempt to decrypt introduction points. */
  3448. cipher = crypto_create_init_cipher(descriptor_cookie, 0);
  3449. if (crypto_cipher_decrypt(cipher, session_key, ipos_encrypted
  3450. + pos + REND_BASIC_AUTH_CLIENT_ID_LEN,
  3451. CIPHER_KEY_LEN) < 0) {
  3452. log_warn(LD_REND, "Could not decrypt session key for client.");
  3453. crypto_free_cipher_env(cipher);
  3454. return -1;
  3455. }
  3456. crypto_free_cipher_env(cipher);
  3457. cipher = crypto_create_init_cipher(session_key, 0);
  3458. len = ipos_encrypted_size - 2 - client_entries_len - CIPHER_IV_LEN;
  3459. dec = tor_malloc(len);
  3460. declen = crypto_cipher_decrypt_with_iv(cipher, dec, len,
  3461. ipos_encrypted + 2 + client_entries_len,
  3462. ipos_encrypted_size - 2 - client_entries_len);
  3463. crypto_free_cipher_env(cipher);
  3464. if (declen < 0) {
  3465. log_warn(LD_REND, "Could not decrypt introduction point string.");
  3466. tor_free(dec);
  3467. return -1;
  3468. }
  3469. if (memcmpstart(dec, declen, "introduction-point ")) {
  3470. log_warn(LD_REND, "Decrypted introduction points don't "
  3471. "look like we could parse them.");
  3472. tor_free(dec);
  3473. continue;
  3474. }
  3475. *ipos_decrypted = dec;
  3476. *ipos_decrypted_size = declen;
  3477. return 0;
  3478. }
  3479. }
  3480. log_warn(LD_REND, "Could not decrypt introduction points. Please "
  3481. "check your authorization for this service!");
  3482. return -1;
  3483. } else if (ipos_encrypted[0] == (int)REND_STEALTH_AUTH) {
  3484. crypto_cipher_env_t *cipher;
  3485. char *dec;
  3486. int declen;
  3487. dec = tor_malloc_zero(ipos_encrypted_size - CIPHER_IV_LEN - 1);
  3488. cipher = crypto_create_init_cipher(descriptor_cookie, 0);
  3489. declen = crypto_cipher_decrypt_with_iv(cipher, dec,
  3490. ipos_encrypted_size -
  3491. CIPHER_IV_LEN - 1,
  3492. ipos_encrypted + 1,
  3493. ipos_encrypted_size - 1);
  3494. crypto_free_cipher_env(cipher);
  3495. if (declen < 0) {
  3496. log_warn(LD_REND, "Decrypting introduction points failed!");
  3497. tor_free(dec);
  3498. return -1;
  3499. }
  3500. *ipos_decrypted = dec;
  3501. *ipos_decrypted_size = declen;
  3502. return 0;
  3503. } else {
  3504. log_warn(LD_REND, "Unknown authorization type number: %d",
  3505. ipos_encrypted[0]);
  3506. return -1;
  3507. }
  3508. }
  3509. /** Parse the encoded introduction points in <b>intro_points_encoded</b> of
  3510. * length <b>intro_points_encoded_size</b> and write the result to the
  3511. * descriptor in <b>parsed</b>; return the number of successfully parsed
  3512. * introduction points or -1 in case of a failure. */
  3513. int
  3514. rend_parse_introduction_points(rend_service_descriptor_t *parsed,
  3515. const char *intro_points_encoded,
  3516. size_t intro_points_encoded_size)
  3517. {
  3518. const char *current_ipo, *end_of_intro_points;
  3519. smartlist_t *tokens;
  3520. directory_token_t *tok;
  3521. rend_intro_point_t *intro;
  3522. extend_info_t *info;
  3523. int result, num_ok=1;
  3524. memarea_t *area = NULL;
  3525. tor_assert(parsed);
  3526. /** Function may only be invoked once. */
  3527. tor_assert(!parsed->intro_nodes);
  3528. tor_assert(intro_points_encoded);
  3529. tor_assert(intro_points_encoded_size > 0);
  3530. /* Consider one intro point after the other. */
  3531. current_ipo = intro_points_encoded;
  3532. end_of_intro_points = intro_points_encoded + intro_points_encoded_size;
  3533. tokens = smartlist_create();
  3534. parsed->intro_nodes = smartlist_create();
  3535. area = memarea_new();
  3536. while (!memcmpstart(current_ipo, end_of_intro_points-current_ipo,
  3537. "introduction-point ")) {
  3538. /* Determine end of string. */
  3539. const char *eos = tor_memstr(current_ipo, end_of_intro_points-current_ipo,
  3540. "\nintroduction-point ");
  3541. if (!eos)
  3542. eos = end_of_intro_points;
  3543. else
  3544. eos = eos+1;
  3545. tor_assert(eos <= intro_points_encoded+intro_points_encoded_size);
  3546. /* Free tokens and clear token list. */
  3547. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  3548. smartlist_clear(tokens);
  3549. memarea_clear(area);
  3550. /* Tokenize string. */
  3551. if (tokenize_string(area, current_ipo, eos, tokens, ipo_token_table, 0)) {
  3552. log_warn(LD_REND, "Error tokenizing introduction point");
  3553. goto err;
  3554. }
  3555. /* Advance to next introduction point, if available. */
  3556. current_ipo = eos;
  3557. /* Check minimum allowed length of introduction point. */
  3558. if (smartlist_len(tokens) < 5) {
  3559. log_warn(LD_REND, "Impossibly short introduction point.");
  3560. goto err;
  3561. }
  3562. /* Allocate new intro point and extend info. */
  3563. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  3564. info = intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  3565. /* Parse identifier. */
  3566. tok = find_by_keyword(tokens, R_IPO_IDENTIFIER);
  3567. if (base32_decode(info->identity_digest, DIGEST_LEN,
  3568. tok->args[0], REND_INTRO_POINT_ID_LEN_BASE32) < 0) {
  3569. log_warn(LD_REND, "Identity digest contains illegal characters: %s",
  3570. tok->args[0]);
  3571. rend_intro_point_free(intro);
  3572. goto err;
  3573. }
  3574. /* Write identifier to nickname. */
  3575. info->nickname[0] = '$';
  3576. base16_encode(info->nickname + 1, sizeof(info->nickname) - 1,
  3577. info->identity_digest, DIGEST_LEN);
  3578. /* Parse IP address. */
  3579. tok = find_by_keyword(tokens, R_IPO_IP_ADDRESS);
  3580. if (tor_addr_from_str(&info->addr, tok->args[0])<0) {
  3581. log_warn(LD_REND, "Could not parse introduction point address.");
  3582. rend_intro_point_free(intro);
  3583. goto err;
  3584. }
  3585. if (tor_addr_family(&info->addr) != AF_INET) {
  3586. log_warn(LD_REND, "Introduction point address was not ipv4.");
  3587. rend_intro_point_free(intro);
  3588. goto err;
  3589. }
  3590. /* Parse onion port. */
  3591. tok = find_by_keyword(tokens, R_IPO_ONION_PORT);
  3592. info->port = (uint16_t) tor_parse_long(tok->args[0],10,1,65535,
  3593. &num_ok,NULL);
  3594. if (!info->port || !num_ok) {
  3595. log_warn(LD_REND, "Introduction point onion port %s is invalid",
  3596. escaped(tok->args[0]));
  3597. rend_intro_point_free(intro);
  3598. goto err;
  3599. }
  3600. /* Parse onion key. */
  3601. tok = find_by_keyword(tokens, R_IPO_ONION_KEY);
  3602. info->onion_key = tok->key;
  3603. tok->key = NULL; /* Prevent free */
  3604. /* Parse service key. */
  3605. tok = find_by_keyword(tokens, R_IPO_SERVICE_KEY);
  3606. intro->intro_key = tok->key;
  3607. tok->key = NULL; /* Prevent free */
  3608. /* Add extend info to list of introduction points. */
  3609. smartlist_add(parsed->intro_nodes, intro);
  3610. }
  3611. result = smartlist_len(parsed->intro_nodes);
  3612. goto done;
  3613. err:
  3614. result = -1;
  3615. done:
  3616. /* Free tokens and clear token list. */
  3617. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  3618. smartlist_free(tokens);
  3619. if (area)
  3620. memarea_drop_all(area);
  3621. return result;
  3622. }
  3623. /** Parse the content of a client_key file in <b>ckstr</b> and add
  3624. * rend_authorized_client_t's for each parsed client to
  3625. * <b>parsed_clients</b>. Return the number of parsed clients as result
  3626. * or -1 for failure. */
  3627. int
  3628. rend_parse_client_keys(strmap_t *parsed_clients, const char *ckstr)
  3629. {
  3630. int result = -1;
  3631. smartlist_t *tokens;
  3632. directory_token_t *tok;
  3633. const char *current_entry = NULL;
  3634. memarea_t *area = NULL;
  3635. if (!ckstr || strlen(ckstr) == 0)
  3636. return -1;
  3637. tokens = smartlist_create();
  3638. /* Begin parsing with first entry, skipping comments or whitespace at the
  3639. * beginning. */
  3640. area = memarea_new();
  3641. current_entry = eat_whitespace(ckstr);
  3642. while (!strcmpstart(current_entry, "client-name ")) {
  3643. rend_authorized_client_t *parsed_entry;
  3644. size_t len;
  3645. char descriptor_cookie_base64[REND_DESC_COOKIE_LEN_BASE64+2+1];
  3646. char descriptor_cookie_tmp[REND_DESC_COOKIE_LEN+2];
  3647. /* Determine end of string. */
  3648. const char *eos = strstr(current_entry, "\nclient-name ");
  3649. if (!eos)
  3650. eos = current_entry + strlen(current_entry);
  3651. else
  3652. eos = eos + 1;
  3653. /* Free tokens and clear token list. */
  3654. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  3655. smartlist_clear(tokens);
  3656. memarea_clear(area);
  3657. /* Tokenize string. */
  3658. if (tokenize_string(area, current_entry, eos, tokens,
  3659. client_keys_token_table, 0)) {
  3660. log_warn(LD_REND, "Error tokenizing client keys file.");
  3661. goto err;
  3662. }
  3663. /* Advance to next entry, if available. */
  3664. current_entry = eos;
  3665. /* Check minimum allowed length of token list. */
  3666. if (smartlist_len(tokens) < 2) {
  3667. log_warn(LD_REND, "Impossibly short client key entry.");
  3668. goto err;
  3669. }
  3670. /* Parse client name. */
  3671. tok = find_by_keyword(tokens, C_CLIENT_NAME);
  3672. tor_assert(tok == smartlist_get(tokens, 0));
  3673. tor_assert(tok->n_args == 1);
  3674. len = strlen(tok->args[0]);
  3675. if (len < 1 || len > 19 ||
  3676. strspn(tok->args[0], REND_LEGAL_CLIENTNAME_CHARACTERS) != len) {
  3677. log_warn(LD_CONFIG, "Illegal client name: %s. (Length must be "
  3678. "between 1 and 19, and valid characters are "
  3679. "[A-Za-z0-9+-_].)", tok->args[0]);
  3680. goto err;
  3681. }
  3682. /* Check if client name is duplicate. */
  3683. if (strmap_get(parsed_clients, tok->args[0])) {
  3684. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains a "
  3685. "duplicate client name: '%s'. Ignoring.", tok->args[0]);
  3686. goto err;
  3687. }
  3688. parsed_entry = tor_malloc_zero(sizeof(rend_authorized_client_t));
  3689. parsed_entry->client_name = tor_strdup(tok->args[0]);
  3690. strmap_set(parsed_clients, parsed_entry->client_name, parsed_entry);
  3691. /* Parse client key. */
  3692. tok = find_opt_by_keyword(tokens, C_CLIENT_KEY);
  3693. if (tok) {
  3694. parsed_entry->client_key = tok->key;
  3695. tok->key = NULL; /* Prevent free */
  3696. }
  3697. /* Parse descriptor cookie. */
  3698. tok = find_by_keyword(tokens, C_DESCRIPTOR_COOKIE);
  3699. tor_assert(tok->n_args == 1);
  3700. if (strlen(tok->args[0]) != REND_DESC_COOKIE_LEN_BASE64 + 2) {
  3701. log_warn(LD_REND, "Descriptor cookie has illegal length: %s",
  3702. escaped(tok->args[0]));
  3703. goto err;
  3704. }
  3705. /* The size of descriptor_cookie_tmp needs to be REND_DESC_COOKIE_LEN+2,
  3706. * because a base64 encoding of length 24 does not fit into 16 bytes in all
  3707. * cases. */
  3708. if ((base64_decode(descriptor_cookie_tmp, REND_DESC_COOKIE_LEN+2,
  3709. tok->args[0], REND_DESC_COOKIE_LEN_BASE64+2+1)
  3710. != REND_DESC_COOKIE_LEN)) {
  3711. log_warn(LD_REND, "Descriptor cookie contains illegal characters: "
  3712. "%s", descriptor_cookie_base64);
  3713. goto err;
  3714. }
  3715. memcpy(parsed_entry->descriptor_cookie, descriptor_cookie_tmp,
  3716. REND_DESC_COOKIE_LEN);
  3717. }
  3718. result = strmap_size(parsed_clients);
  3719. goto done;
  3720. err:
  3721. result = -1;
  3722. done:
  3723. /* Free tokens and clear token list. */
  3724. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  3725. smartlist_free(tokens);
  3726. if (area)
  3727. memarea_drop_all(area);
  3728. return result;
  3729. }