routerparse.c 115 KB

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