routerparse.c 114 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499
  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. int 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. memcpy(cp, start_of_annotations, end-start_of_annotations);
  1007. router->cache_info.signed_descriptor_body[len] = '\0';
  1008. tor_assert(strlen(router->cache_info.signed_descriptor_body) == len);
  1009. }
  1010. memcpy(router->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1011. router->nickname = tor_strdup(tok->args[0]);
  1012. if (!is_legal_nickname(router->nickname)) {
  1013. log_warn(LD_DIR,"Router nickname is invalid");
  1014. goto err;
  1015. }
  1016. router->address = tor_strdup(tok->args[1]);
  1017. if (!tor_inet_aton(router->address, &in)) {
  1018. log_warn(LD_DIR,"Router address is not an IP address.");
  1019. goto err;
  1020. }
  1021. router->addr = ntohl(in.s_addr);
  1022. router->or_port =
  1023. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,&ok,NULL);
  1024. if (!ok) {
  1025. log_warn(LD_DIR,"Invalid OR port %s", escaped(tok->args[2]));
  1026. goto err;
  1027. }
  1028. router->dir_port =
  1029. (uint16_t) tor_parse_long(tok->args[4],10,0,65535,&ok,NULL);
  1030. if (!ok) {
  1031. log_warn(LD_DIR,"Invalid dir port %s", escaped(tok->args[4]));
  1032. goto err;
  1033. }
  1034. tok = find_first_by_keyword(tokens, K_BANDWIDTH);
  1035. tor_assert(tok && tok->n_args >= 3);
  1036. router->bandwidthrate =
  1037. tor_parse_long(tok->args[0],10,1,INT_MAX,&ok,NULL);
  1038. if (!ok) {
  1039. log_warn(LD_DIR, "bandwidthrate %s unreadable or 0. Failing.",
  1040. escaped(tok->args[0]));
  1041. goto err;
  1042. }
  1043. router->bandwidthburst = tor_parse_long(tok->args[1],10,0,INT_MAX,&ok,NULL);
  1044. if (!ok) {
  1045. log_warn(LD_DIR, "Invalid bandwidthburst %s", escaped(tok->args[1]));
  1046. goto err;
  1047. }
  1048. router->bandwidthcapacity =
  1049. tor_parse_long(tok->args[2],10,0,INT_MAX,&ok,NULL);
  1050. if (!ok) {
  1051. log_warn(LD_DIR, "Invalid bandwidthcapacity %s", escaped(tok->args[1]));
  1052. goto err;
  1053. }
  1054. if ((tok = find_first_by_keyword(tokens, A_PURPOSE))) {
  1055. tor_assert(tok->n_args);
  1056. router->purpose = router_purpose_from_string(tok->args[0]);
  1057. } else {
  1058. router->purpose = ROUTER_PURPOSE_GENERAL;
  1059. }
  1060. router->cache_info.send_unencrypted =
  1061. (router->purpose == ROUTER_PURPOSE_GENERAL) ? 1 : 0;
  1062. if ((tok = find_first_by_keyword(tokens, K_UPTIME))) {
  1063. tor_assert(tok->n_args >= 1);
  1064. router->uptime = tor_parse_long(tok->args[0],10,0,LONG_MAX,&ok,NULL);
  1065. if (!ok) {
  1066. log_warn(LD_DIR, "Invalid uptime %s", escaped(tok->args[0]));
  1067. goto err;
  1068. }
  1069. }
  1070. if ((tok = find_first_by_keyword(tokens, K_HIBERNATING))) {
  1071. tor_assert(tok->n_args >= 1);
  1072. router->is_hibernating
  1073. = (tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL) != 0);
  1074. }
  1075. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  1076. tor_assert(tok);
  1077. tor_assert(tok->n_args == 1);
  1078. if (parse_iso_time(tok->args[0], &router->cache_info.published_on) < 0)
  1079. goto err;
  1080. tok = find_first_by_keyword(tokens, K_ONION_KEY);
  1081. tor_assert(tok);
  1082. router->onion_pkey = tok->key;
  1083. tok->key = NULL; /* Prevent free */
  1084. tok = find_first_by_keyword(tokens, K_SIGNING_KEY);
  1085. tor_assert(tok);
  1086. router->identity_pkey = tok->key;
  1087. tok->key = NULL; /* Prevent free */
  1088. if (crypto_pk_get_digest(router->identity_pkey,
  1089. router->cache_info.identity_digest)) {
  1090. log_warn(LD_DIR, "Couldn't calculate key digest"); goto err;
  1091. }
  1092. if ((tok = find_first_by_keyword(tokens, K_FINGERPRINT))) {
  1093. /* If there's a fingerprint line, it must match the identity digest. */
  1094. char d[DIGEST_LEN];
  1095. tor_assert(tok->n_args == 1);
  1096. tor_strstrip(tok->args[0], " ");
  1097. if (base16_decode(d, DIGEST_LEN, tok->args[0], strlen(tok->args[0]))) {
  1098. log_warn(LD_DIR, "Couldn't decode router fingerprint %s",
  1099. escaped(tok->args[0]));
  1100. goto err;
  1101. }
  1102. if (memcmp(d,router->cache_info.identity_digest, DIGEST_LEN)!=0) {
  1103. log_warn(LD_DIR, "Fingerprint '%s' does not match identity digest.",
  1104. tok->args[0]);
  1105. goto err;
  1106. }
  1107. }
  1108. if ((tok = find_first_by_keyword(tokens, K_PLATFORM))) {
  1109. router->platform = tor_strdup(tok->args[0]);
  1110. }
  1111. if ((tok = find_first_by_keyword(tokens, K_CONTACT))) {
  1112. router->contact_info = tor_strdup(tok->args[0]);
  1113. }
  1114. if ((tok = find_first_by_keyword(tokens, K_EVENTDNS))) {
  1115. router->has_old_dnsworkers = tok->n_args && !strcmp(tok->args[0], "0");
  1116. } else if (router->platform) {
  1117. if (! tor_version_as_new_as(router->platform, "0.1.2.2-alpha"))
  1118. router->has_old_dnsworkers = 1;
  1119. }
  1120. exit_policy_tokens = find_all_exitpolicy(tokens);
  1121. SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
  1122. if (router_add_exit_policy(router,t)<0) {
  1123. log_warn(LD_DIR,"Error in exit policy");
  1124. goto err;
  1125. });
  1126. policy_expand_private(&router->exit_policy);
  1127. if ((tok = find_first_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
  1128. int i;
  1129. router->declared_family = smartlist_create();
  1130. for (i=0;i<tok->n_args;++i) {
  1131. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  1132. log_warn(LD_DIR, "Illegal nickname %s in family line",
  1133. escaped(tok->args[i]));
  1134. goto err;
  1135. }
  1136. smartlist_add(router->declared_family, tor_strdup(tok->args[i]));
  1137. }
  1138. }
  1139. if ((tok = find_first_by_keyword(tokens, K_CACHES_EXTRA_INFO)))
  1140. router->caches_extra_info = 1;
  1141. if ((tok = find_first_by_keyword(tokens, K_EXTRA_INFO_DIGEST))) {
  1142. tor_assert(tok->n_args >= 1);
  1143. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  1144. base16_decode(router->cache_info.extra_info_digest,
  1145. DIGEST_LEN, tok->args[0], HEX_DIGEST_LEN);
  1146. } else {
  1147. log_warn(LD_DIR, "Invalid extra info digest %s", escaped(tok->args[0]));
  1148. }
  1149. }
  1150. if ((tok = find_first_by_keyword(tokens, K_HIDDEN_SERVICE_DIR))) {
  1151. router->wants_to_be_hs_dir = 1;
  1152. }
  1153. tok = find_first_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1154. tor_assert(tok);
  1155. note_crypto_pk_op(VERIFY_RTR);
  1156. #ifdef COUNT_DISTINCT_DIGESTS
  1157. if (!verified_digests)
  1158. verified_digests = digestmap_new();
  1159. digestmap_set(verified_digests, signed_digest, (void*)(uintptr_t)1);
  1160. #endif
  1161. if (check_signature_token(digest, tok, router->identity_pkey, 0,
  1162. "router descriptor") < 0)
  1163. goto err;
  1164. if (!router->or_port) {
  1165. log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
  1166. goto err;
  1167. }
  1168. if (!router->platform) {
  1169. router->platform = tor_strdup("<unknown>");
  1170. }
  1171. goto done;
  1172. err:
  1173. routerinfo_free(router);
  1174. router = NULL;
  1175. done:
  1176. if (tokens) {
  1177. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1178. smartlist_free(tokens);
  1179. }
  1180. if (exit_policy_tokens) {
  1181. smartlist_free(exit_policy_tokens);
  1182. }
  1183. return router;
  1184. }
  1185. /** Parse a single extrainfo entry from the string <b>s</b>, ending at
  1186. * <b>end</b>. (If <b>end</b> is NULL, parse up to the end of <b>s</b>.) If
  1187. * <b>cache_copy</b> is true, make a copy of the extra-info document in the
  1188. * cache_info fields of the result. If <b>routermap</b> is provided, use it
  1189. * as a map from router identity to routerinfo_t when looking up signing keys.
  1190. */
  1191. extrainfo_t *
  1192. extrainfo_parse_entry_from_string(const char *s, const char *end,
  1193. int cache_copy, struct digest_ri_map_t *routermap)
  1194. {
  1195. extrainfo_t *extrainfo = NULL;
  1196. char digest[128];
  1197. smartlist_t *tokens = NULL;
  1198. directory_token_t *tok;
  1199. crypto_pk_env_t *key = NULL;
  1200. routerinfo_t *router = NULL;
  1201. if (!end) {
  1202. end = s + strlen(s);
  1203. }
  1204. /* point 'end' to a point immediately after the final newline. */
  1205. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  1206. --end;
  1207. if (router_get_extrainfo_hash(s, digest) < 0) {
  1208. log_warn(LD_DIR, "Couldn't compute router hash.");
  1209. return NULL;
  1210. }
  1211. tokens = smartlist_create();
  1212. if (tokenize_string(s,end,tokens,extrainfo_token_table,0)) {
  1213. log_warn(LD_DIR, "Error tokenizing extra-info document.");
  1214. goto err;
  1215. }
  1216. if (smartlist_len(tokens) < 2) {
  1217. log_warn(LD_DIR, "Impossibly short extra-info document.");
  1218. goto err;
  1219. }
  1220. tok = smartlist_get(tokens,0);
  1221. if (tok->tp != K_EXTRA_INFO) {
  1222. log_warn(LD_DIR,"Entry does not start with \"extra-info\"");
  1223. goto err;
  1224. }
  1225. extrainfo = tor_malloc_zero(sizeof(extrainfo_t));
  1226. extrainfo->cache_info.is_extrainfo = 1;
  1227. if (cache_copy)
  1228. extrainfo->cache_info.signed_descriptor_body = tor_strndup(s, end-s);
  1229. extrainfo->cache_info.signed_descriptor_len = end-s;
  1230. memcpy(extrainfo->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1231. tor_assert(tok->n_args >= 2);
  1232. if (!is_legal_nickname(tok->args[0])) {
  1233. log_warn(LD_DIR,"Bad nickname %s on \"extra-info\"",escaped(tok->args[0]));
  1234. goto err;
  1235. }
  1236. strlcpy(extrainfo->nickname, tok->args[0], sizeof(extrainfo->nickname));
  1237. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  1238. base16_decode(extrainfo->cache_info.identity_digest, DIGEST_LEN,
  1239. tok->args[1], HEX_DIGEST_LEN)) {
  1240. log_warn(LD_DIR,"Invalid fingerprint %s on \"extra-info\"",
  1241. escaped(tok->args[1]));
  1242. goto err;
  1243. }
  1244. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  1245. tor_assert(tok);
  1246. if (parse_iso_time(tok->args[0], &extrainfo->cache_info.published_on)) {
  1247. log_warn(LD_DIR,"Invalid published time %s on \"extra-info\"",
  1248. escaped(tok->args[0]));
  1249. goto err;
  1250. }
  1251. if (routermap &&
  1252. (router = digestmap_get((digestmap_t*)routermap,
  1253. extrainfo->cache_info.identity_digest))) {
  1254. key = router->identity_pkey;
  1255. }
  1256. tok = find_first_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1257. tor_assert(tok);
  1258. if (strcmp(tok->object_type, "SIGNATURE") ||
  1259. tok->object_size < 128 || tok->object_size > 512) {
  1260. log_warn(LD_DIR, "Bad object type or length on extra-info signature");
  1261. goto err;
  1262. }
  1263. if (key) {
  1264. note_crypto_pk_op(VERIFY_RTR);
  1265. if (check_signature_token(digest, tok, key, 0, "extra-info") < 0)
  1266. goto err;
  1267. if (router)
  1268. extrainfo->cache_info.send_unencrypted =
  1269. router->cache_info.send_unencrypted;
  1270. } else {
  1271. extrainfo->pending_sig = tor_memdup(tok->object_body,
  1272. tok->object_size);
  1273. extrainfo->pending_sig_len = tok->object_size;
  1274. }
  1275. goto done;
  1276. err:
  1277. if (extrainfo)
  1278. extrainfo_free(extrainfo);
  1279. extrainfo = NULL;
  1280. done:
  1281. if (tokens) {
  1282. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1283. smartlist_free(tokens);
  1284. }
  1285. return extrainfo;
  1286. }
  1287. /** Parse a key certificate from <b>s</b>; point <b>end-of-string</b> to
  1288. * the first character after the certificate. */
  1289. authority_cert_t *
  1290. authority_cert_parse_from_string(const char *s, const char **end_of_string)
  1291. {
  1292. authority_cert_t *cert = NULL, *old_cert;
  1293. smartlist_t *tokens = NULL;
  1294. char digest[DIGEST_LEN];
  1295. directory_token_t *tok;
  1296. char fp_declared[DIGEST_LEN];
  1297. char *eos;
  1298. size_t len;
  1299. int found;
  1300. s = eat_whitespace(s);
  1301. eos = strstr(s, "\n-----END SIGNATURE-----\n");
  1302. if (! eos) {
  1303. log_warn(LD_DIR, "No end-of-signature found on key certificate");
  1304. return NULL;
  1305. }
  1306. eos = strchr(eos+2, '\n');
  1307. tor_assert(eos);
  1308. ++eos;
  1309. len = eos - s;
  1310. tokens = smartlist_create();
  1311. if (tokenize_string(s, eos, tokens, dir_key_certificate_table, 0) < 0) {
  1312. log_warn(LD_DIR, "Error tokenizing key certificate");
  1313. goto err;
  1314. }
  1315. if (router_get_hash_impl(s, digest, "dir-key-certificate-version",
  1316. "\ndir-key-certification", '\n') < 0)
  1317. goto err;
  1318. tok = smartlist_get(tokens, 0);
  1319. if (tok->tp != K_DIR_KEY_CERTIFICATE_VERSION || strcmp(tok->args[0], "3")) {
  1320. log_warn(LD_DIR,
  1321. "Key certificate does not begin with a recognized version (3).");
  1322. goto err;
  1323. }
  1324. cert = tor_malloc_zero(sizeof(authority_cert_t));
  1325. memcpy(cert->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1326. tok = find_first_by_keyword(tokens, K_DIR_SIGNING_KEY);
  1327. tor_assert(tok && tok->key);
  1328. cert->signing_key = tok->key;
  1329. tok->key = NULL;
  1330. if (crypto_pk_get_digest(cert->signing_key, cert->signing_key_digest))
  1331. goto err;
  1332. tok = find_first_by_keyword(tokens, K_DIR_IDENTITY_KEY);
  1333. tor_assert(tok && tok->key);
  1334. cert->identity_key = tok->key;
  1335. tok->key = NULL;
  1336. tok = find_first_by_keyword(tokens, K_FINGERPRINT);
  1337. tor_assert(tok && tok->n_args);
  1338. if (base16_decode(fp_declared, DIGEST_LEN, tok->args[0],
  1339. strlen(tok->args[0]))) {
  1340. log_warn(LD_DIR, "Couldn't decode key certificate fingerprint %s",
  1341. escaped(tok->args[0]));
  1342. goto err;
  1343. }
  1344. if (crypto_pk_get_digest(cert->identity_key,
  1345. cert->cache_info.identity_digest))
  1346. goto err;
  1347. if (memcmp(cert->cache_info.identity_digest, fp_declared, DIGEST_LEN)) {
  1348. log_warn(LD_DIR, "Digest of certificate key didn't match declared "
  1349. "fingerprint");
  1350. goto err;
  1351. }
  1352. tok = find_first_by_keyword(tokens, K_DIR_ADDRESS);
  1353. if (tok) {
  1354. tor_assert(tok->n_args);
  1355. if (parse_addr_port(LOG_WARN, tok->args[0], NULL, &cert->addr,
  1356. &cert->dir_port)<0) {
  1357. log_warn(LD_DIR, "Couldn't parse dir-address in certificate");
  1358. goto err;
  1359. }
  1360. }
  1361. tok = find_first_by_keyword(tokens, K_DIR_KEY_PUBLISHED);
  1362. tor_assert(tok);
  1363. if (parse_iso_time(tok->args[0], &cert->cache_info.published_on) < 0) {
  1364. goto err;
  1365. }
  1366. tok = find_first_by_keyword(tokens, K_DIR_KEY_EXPIRES);
  1367. tor_assert(tok);
  1368. if (parse_iso_time(tok->args[0], &cert->expires) < 0) {
  1369. goto err;
  1370. }
  1371. tok = smartlist_get(tokens, smartlist_len(tokens)-1);
  1372. if (tok->tp != K_DIR_KEY_CERTIFICATION) {
  1373. log_warn(LD_DIR, "Certificate didn't end with dir-key-certification.");
  1374. goto err;
  1375. }
  1376. /* If we already have this cert, don't bother checking the signature. */
  1377. old_cert = authority_cert_get_by_digests(
  1378. cert->cache_info.identity_digest,
  1379. cert->signing_key_digest);
  1380. found = 0;
  1381. if (old_cert) {
  1382. /* XXXX We could just compare signed_descriptor_digest, but that wouldn't
  1383. * buy us much. */
  1384. if (old_cert->cache_info.signed_descriptor_len == len &&
  1385. old_cert->cache_info.signed_descriptor_body &&
  1386. !memcmp(s, old_cert->cache_info.signed_descriptor_body, len)) {
  1387. log_debug(LD_DIR, "We already checked the signature on this "
  1388. "certificate; no need to do so again.");
  1389. found = 1;
  1390. }
  1391. }
  1392. if (!found) {
  1393. if (check_signature_token(digest, tok, cert->identity_key, 0,
  1394. "key certificate")) {
  1395. goto err;
  1396. }
  1397. }
  1398. cert->cache_info.signed_descriptor_len = len;
  1399. cert->cache_info.signed_descriptor_body = tor_malloc(len+1);
  1400. memcpy(cert->cache_info.signed_descriptor_body, s, len);
  1401. cert->cache_info.signed_descriptor_body[len] = 0;
  1402. cert->cache_info.saved_location = SAVED_NOWHERE;
  1403. if (end_of_string) {
  1404. *end_of_string = eat_whitespace(eos);
  1405. }
  1406. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1407. smartlist_free(tokens);
  1408. return cert;
  1409. err:
  1410. authority_cert_free(cert);
  1411. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1412. smartlist_free(tokens);
  1413. return NULL;
  1414. }
  1415. /** Helper: given a string <b>s</b>, return the start of the next router-status
  1416. * object (starting with "r " at the start of a line). If none is found,
  1417. * return the start of the next directory signature. If none is found, return
  1418. * the end of the string. */
  1419. static INLINE const char *
  1420. find_start_of_next_routerstatus(const char *s)
  1421. {
  1422. const char *eos = strstr(s, "\nr ");
  1423. if (eos) {
  1424. const char *eos2 = tor_memstr(s, eos-s, "\ndirectory-signature");
  1425. if (eos2 && eos2 < eos)
  1426. return eos2;
  1427. else
  1428. return eos+1;
  1429. } else {
  1430. if ((eos = strstr(s, "\ndirectory-signature")))
  1431. return eos+1;
  1432. return s + strlen(s);
  1433. }
  1434. }
  1435. /** Given a string at *<b>s</b>, containing a routerstatus object, and an
  1436. * empty smartlist at <b>tokens</b>, parse and return the first router status
  1437. * object in the string, and advance *<b>s</b> to just after the end of the
  1438. * router status. Return NULL and advance *<b>s</b> on error.
  1439. *
  1440. * If <b>vote</b> and <b>vote_rs</b> are provided, don't allocate a fresh
  1441. * routerstatus but use <b>vote_rs</b> instead.
  1442. *
  1443. * If <b>consensus_method</b> is nonzero, this routerstatus is part of a
  1444. * consensus, and we should parse it according to the method used to
  1445. * make that consensus.
  1446. **/
  1447. static routerstatus_t *
  1448. routerstatus_parse_entry_from_string(const char **s, smartlist_t *tokens,
  1449. networkstatus_t *vote,
  1450. vote_routerstatus_t *vote_rs,
  1451. int consensus_method)
  1452. {
  1453. const char *eos;
  1454. routerstatus_t *rs = NULL;
  1455. directory_token_t *tok;
  1456. char timebuf[ISO_TIME_LEN+1];
  1457. struct in_addr in;
  1458. tor_assert(tokens);
  1459. tor_assert(bool_eq(vote, vote_rs));
  1460. eos = find_start_of_next_routerstatus(*s);
  1461. if (tokenize_string(*s, eos, tokens, rtrstatus_token_table,0)) {
  1462. log_warn(LD_DIR, "Error tokenizing router status");
  1463. goto err;
  1464. }
  1465. if (smartlist_len(tokens) < 1) {
  1466. log_warn(LD_DIR, "Impossibly short router status");
  1467. goto err;
  1468. }
  1469. tok = find_first_by_keyword(tokens, K_R);
  1470. tor_assert(tok);
  1471. tor_assert(tok->n_args >= 8);
  1472. if (vote_rs) {
  1473. rs = &vote_rs->status;
  1474. } else {
  1475. rs = tor_malloc_zero(sizeof(routerstatus_t));
  1476. }
  1477. if (!is_legal_nickname(tok->args[0])) {
  1478. log_warn(LD_DIR,
  1479. "Invalid nickname %s in router status; skipping.",
  1480. escaped(tok->args[0]));
  1481. goto err;
  1482. }
  1483. strlcpy(rs->nickname, tok->args[0], sizeof(rs->nickname));
  1484. if (digest_from_base64(rs->identity_digest, tok->args[1])) {
  1485. log_warn(LD_DIR, "Error decoding identity digest %s",
  1486. escaped(tok->args[1]));
  1487. goto err;
  1488. }
  1489. if (digest_from_base64(rs->descriptor_digest, tok->args[2])) {
  1490. log_warn(LD_DIR, "Error decoding descriptor digest %s",
  1491. escaped(tok->args[2]));
  1492. goto err;
  1493. }
  1494. if (tor_snprintf(timebuf, sizeof(timebuf), "%s %s",
  1495. tok->args[3], tok->args[4]) < 0 ||
  1496. parse_iso_time(timebuf, &rs->published_on)<0) {
  1497. log_warn(LD_DIR, "Error parsing time '%s %s'",
  1498. tok->args[3], tok->args[4]);
  1499. goto err;
  1500. }
  1501. if (tor_inet_aton(tok->args[5], &in) == 0) {
  1502. log_warn(LD_DIR, "Error parsing router address in network-status %s",
  1503. escaped(tok->args[5]));
  1504. goto err;
  1505. }
  1506. rs->addr = ntohl(in.s_addr);
  1507. rs->or_port =(uint16_t) tor_parse_long(tok->args[6],10,0,65535,NULL,NULL);
  1508. rs->dir_port = (uint16_t) tor_parse_long(tok->args[7],10,0,65535,NULL,NULL);
  1509. tok = find_first_by_keyword(tokens, K_S);
  1510. if (tok && vote) {
  1511. int i;
  1512. vote_rs->flags = 0;
  1513. for (i=0; i < tok->n_args; ++i) {
  1514. int p = smartlist_string_pos(vote->known_flags, tok->args[i]);
  1515. if (p >= 0) {
  1516. vote_rs->flags |= (1<<p);
  1517. } else {
  1518. log_warn(LD_DIR, "Flags line had a flag %s not listed in known_flags.",
  1519. escaped(tok->args[i]));
  1520. goto err;
  1521. }
  1522. }
  1523. } else if (tok) {
  1524. int i;
  1525. for (i=0; i < tok->n_args; ++i) {
  1526. if (!strcmp(tok->args[i], "Exit"))
  1527. rs->is_exit = 1;
  1528. else if (!strcmp(tok->args[i], "Stable"))
  1529. rs->is_stable = 1;
  1530. else if (!strcmp(tok->args[i], "Fast"))
  1531. rs->is_fast = 1;
  1532. else if (!strcmp(tok->args[i], "Running"))
  1533. rs->is_running = 1;
  1534. else if (!strcmp(tok->args[i], "Named"))
  1535. rs->is_named = 1;
  1536. else if (!strcmp(tok->args[i], "Valid"))
  1537. rs->is_valid = 1;
  1538. else if (!strcmp(tok->args[i], "V2Dir"))
  1539. rs->is_v2_dir = 1;
  1540. else if (!strcmp(tok->args[i], "Guard"))
  1541. rs->is_possible_guard = 1;
  1542. else if (!strcmp(tok->args[i], "BadExit"))
  1543. rs->is_bad_exit = 1;
  1544. else if (!strcmp(tok->args[i], "BadDirectory"))
  1545. rs->is_bad_directory = 1;
  1546. else if (!strcmp(tok->args[i], "Authority"))
  1547. rs->is_authority = 1;
  1548. else if (!strcmp(tok->args[i], "Unnamed") &&
  1549. consensus_method >= 2) {
  1550. /* Unnamed is computed right by consensus method 2 and later. */
  1551. rs->is_unnamed = 1;
  1552. } else if (!strcmp(tok->args[i], "HSDir")) {
  1553. rs->is_hs_dir = 1;
  1554. }
  1555. }
  1556. }
  1557. if ((tok = find_first_by_keyword(tokens, K_V))) {
  1558. tor_assert(tok->n_args == 1);
  1559. rs->version_known = 1;
  1560. if (strcmpstart(tok->args[0], "Tor ")) {
  1561. rs->version_supports_begindir = 1;
  1562. rs->version_supports_extrainfo_upload = 1;
  1563. } else {
  1564. rs->version_supports_begindir =
  1565. tor_version_as_new_as(tok->args[0], "0.2.0.1-alpha");
  1566. rs->version_supports_extrainfo_upload =
  1567. tor_version_as_new_as(tok->args[0], "0.2.0.0-alpha-dev (r10070)");
  1568. rs->version_supports_v3_dir =
  1569. tor_version_as_new_as(tok->args[0], "0.2.0.8-alpha");
  1570. }
  1571. if (vote_rs) {
  1572. vote_rs->version = tok->args[0];
  1573. tok->args[0] = NULL; /* suppress free() */
  1574. }
  1575. }
  1576. if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME))
  1577. rs->is_named = 0;
  1578. goto done;
  1579. err:
  1580. if (rs && !vote_rs)
  1581. routerstatus_free(rs);
  1582. rs = NULL;
  1583. done:
  1584. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1585. smartlist_clear(tokens);
  1586. *s = eos;
  1587. return rs;
  1588. }
  1589. /** Helper to sort a smartlist of pointers to routerstatus_t */
  1590. static int
  1591. _compare_routerstatus_entries(const void **_a, const void **_b)
  1592. {
  1593. const routerstatus_t *a = *_a, *b = *_b;
  1594. return memcmp(a->identity_digest, b->identity_digest, DIGEST_LEN);
  1595. }
  1596. /** Helper: used in call to _smartlist_uniq to clear out duplicate entries. */
  1597. static void
  1598. _free_duplicate_routerstatus_entry(void *e)
  1599. {
  1600. log_warn(LD_DIR,
  1601. "Network-status has two entries for the same router. "
  1602. "Dropping one.");
  1603. routerstatus_free(e);
  1604. }
  1605. /** Given a v2 network-status object in <b>s</b>, try to
  1606. * parse it and return the result. Return NULL on failure. Check the
  1607. * signature of the network status, but do not (yet) check the signing key for
  1608. * authority.
  1609. */
  1610. networkstatus_v2_t *
  1611. networkstatus_v2_parse_from_string(const char *s)
  1612. {
  1613. const char *eos;
  1614. smartlist_t *tokens = smartlist_create();
  1615. smartlist_t *footer_tokens = smartlist_create();
  1616. networkstatus_v2_t *ns = NULL;
  1617. char ns_digest[DIGEST_LEN];
  1618. char tmp_digest[DIGEST_LEN];
  1619. struct in_addr in;
  1620. directory_token_t *tok;
  1621. int i;
  1622. if (router_get_networkstatus_v2_hash(s, ns_digest)) {
  1623. log_warn(LD_DIR, "Unable to compute digest of network-status");
  1624. goto err;
  1625. }
  1626. eos = find_start_of_next_routerstatus(s);
  1627. if (tokenize_string(s, eos, tokens, netstatus_token_table,0)) {
  1628. log_warn(LD_DIR, "Error tokenizing network-status header.");
  1629. goto err;
  1630. }
  1631. ns = tor_malloc_zero(sizeof(networkstatus_v2_t));
  1632. memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN);
  1633. tok = find_first_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
  1634. tor_assert(tok && tok->n_args >= 1);
  1635. if (strcmp(tok->args[0], "2")) {
  1636. log_warn(LD_BUG, "Got a non-v2 networkstatus. Version was "
  1637. "%s", escaped(tok->args[0]));
  1638. goto err;
  1639. }
  1640. tok = find_first_by_keyword(tokens, K_DIR_SOURCE);
  1641. tor_assert(tok);
  1642. tor_assert(tok->n_args >= 3);
  1643. ns->source_address = tok->args[0]; tok->args[0] = NULL;
  1644. if (tor_inet_aton(tok->args[1], &in) == 0) {
  1645. log_warn(LD_DIR, "Error parsing network-status source address %s",
  1646. escaped(tok->args[1]));
  1647. goto err;
  1648. }
  1649. ns->source_addr = ntohl(in.s_addr);
  1650. ns->source_dirport =
  1651. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
  1652. if (ns->source_dirport == 0) {
  1653. log_warn(LD_DIR, "Directory source without dirport; skipping.");
  1654. goto err;
  1655. }
  1656. tok = find_first_by_keyword(tokens, K_FINGERPRINT);
  1657. tor_assert(tok);
  1658. tor_assert(tok->n_args);
  1659. if (base16_decode(ns->identity_digest, DIGEST_LEN, tok->args[0],
  1660. strlen(tok->args[0]))) {
  1661. log_warn(LD_DIR, "Couldn't decode networkstatus fingerprint %s",
  1662. escaped(tok->args[0]));
  1663. goto err;
  1664. }
  1665. if ((tok = find_first_by_keyword(tokens, K_CONTACT))) {
  1666. tor_assert(tok->n_args);
  1667. ns->contact = tok->args[0];
  1668. tok->args[0] = NULL;
  1669. }
  1670. tok = find_first_by_keyword(tokens, K_DIR_SIGNING_KEY);
  1671. tor_assert(tok && tok->key);
  1672. ns->signing_key = tok->key;
  1673. tok->key = NULL;
  1674. if (crypto_pk_get_digest(ns->signing_key, tmp_digest)<0) {
  1675. log_warn(LD_DIR, "Couldn't compute signing key digest");
  1676. goto err;
  1677. }
  1678. if (memcmp(tmp_digest, ns->identity_digest, DIGEST_LEN)) {
  1679. log_warn(LD_DIR,
  1680. "network-status fingerprint did not match dir-signing-key");
  1681. goto err;
  1682. }
  1683. if ((tok = find_first_by_keyword(tokens, K_DIR_OPTIONS))) {
  1684. for (i=0; i < tok->n_args; ++i) {
  1685. if (!strcmp(tok->args[i], "Names"))
  1686. ns->binds_names = 1;
  1687. if (!strcmp(tok->args[i], "Versions"))
  1688. ns->recommends_versions = 1;
  1689. if (!strcmp(tok->args[i], "BadExits"))
  1690. ns->lists_bad_exits = 1;
  1691. if (!strcmp(tok->args[i], "BadDirectories"))
  1692. ns->lists_bad_directories = 1;
  1693. }
  1694. }
  1695. if (ns->recommends_versions) {
  1696. if (!(tok = find_first_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  1697. log_warn(LD_DIR, "Missing client-versions on versioning directory");
  1698. goto err;
  1699. }
  1700. ns->client_versions = tok->args[0];
  1701. tok->args[0] = NULL;
  1702. if (!(tok = find_first_by_keyword(tokens, K_SERVER_VERSIONS)) ||
  1703. tok->n_args<1) {
  1704. log_warn(LD_DIR, "Missing server-versions on versioning directory");
  1705. goto err;
  1706. }
  1707. ns->server_versions = tok->args[0];
  1708. tok->args[0] = NULL;
  1709. }
  1710. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  1711. tor_assert(tok);
  1712. tor_assert(tok->n_args == 1);
  1713. if (parse_iso_time(tok->args[0], &ns->published_on) < 0) {
  1714. goto err;
  1715. }
  1716. ns->entries = smartlist_create();
  1717. s = eos;
  1718. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1719. smartlist_clear(tokens);
  1720. while (!strcmpstart(s, "r ")) {
  1721. routerstatus_t *rs;
  1722. if ((rs = routerstatus_parse_entry_from_string(&s, tokens, NULL, NULL, 0)))
  1723. smartlist_add(ns->entries, rs);
  1724. }
  1725. smartlist_sort(ns->entries, _compare_routerstatus_entries);
  1726. smartlist_uniq(ns->entries, _compare_routerstatus_entries,
  1727. _free_duplicate_routerstatus_entry);
  1728. if (tokenize_string(s, NULL, footer_tokens, dir_footer_token_table,0)) {
  1729. log_warn(LD_DIR, "Error tokenizing network-status footer.");
  1730. goto err;
  1731. }
  1732. if (smartlist_len(footer_tokens) < 1) {
  1733. log_warn(LD_DIR, "Too few items in network-status footer.");
  1734. goto err;
  1735. }
  1736. tok = smartlist_get(footer_tokens, smartlist_len(footer_tokens)-1);
  1737. if (tok->tp != K_DIRECTORY_SIGNATURE) {
  1738. log_warn(LD_DIR,
  1739. "Expected network-status footer to end with a signature.");
  1740. goto err;
  1741. }
  1742. note_crypto_pk_op(VERIFY_DIR);
  1743. if (check_signature_token(ns_digest, tok, ns->signing_key, 0,
  1744. "network-status") < 0)
  1745. goto err;
  1746. goto done;
  1747. err:
  1748. if (ns)
  1749. networkstatus_v2_free(ns);
  1750. ns = NULL;
  1751. done:
  1752. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1753. smartlist_free(tokens);
  1754. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_free(t));
  1755. smartlist_free(footer_tokens);
  1756. return ns;
  1757. }
  1758. /** Parse a v3 networkstatus vote (if <b>is_vote</b> is true) or a v3
  1759. * networkstatus consensus (if <b>is_vote</b> is false) from <b>s</b>, and
  1760. * return the result. Return NULL on failure. */
  1761. networkstatus_t *
  1762. networkstatus_parse_vote_from_string(const char *s, const char **eos_out,
  1763. int is_vote)
  1764. {
  1765. smartlist_t *tokens = smartlist_create();
  1766. smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;
  1767. networkstatus_voter_info_t *voter = NULL;
  1768. networkstatus_t *ns = NULL;
  1769. char ns_digest[DIGEST_LEN];
  1770. const char *cert, *end_of_header, *end_of_footer;
  1771. directory_token_t *tok;
  1772. int ok;
  1773. struct in_addr in;
  1774. int i, inorder, n_signatures = 0;
  1775. if (router_get_networkstatus_v3_hash(s, ns_digest)) {
  1776. log_warn(LD_DIR, "Unable to compute digest of network-status");
  1777. goto err;
  1778. }
  1779. end_of_header = find_start_of_next_routerstatus(s);
  1780. if (tokenize_string(s, end_of_header, tokens,
  1781. is_vote ? networkstatus_token_table :
  1782. networkstatus_consensus_token_table, 0)) {
  1783. log_warn(LD_DIR, "Error tokenizing network-status vote header.");
  1784. goto err;
  1785. }
  1786. ns = tor_malloc_zero(sizeof(networkstatus_t));
  1787. memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN);
  1788. if (is_vote) {
  1789. const char *end_of_cert = NULL;
  1790. if (!(cert = strstr(s, "\ndir-key-certificate-version")))
  1791. goto err;
  1792. ++cert;
  1793. ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);
  1794. if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)
  1795. goto err;
  1796. }
  1797. tok = find_first_by_keyword(tokens, K_VOTE_STATUS);
  1798. tor_assert(tok);
  1799. tor_assert(tok->n_args);
  1800. if (!strcmp(tok->args[0], "vote")) {
  1801. ns->is_vote = 1;
  1802. } else if (!strcmp(tok->args[0], "consensus")) {
  1803. ns->is_vote = 0;
  1804. } else {
  1805. log_warn(LD_DIR, "Unrecognized vote status %s in network-status",
  1806. escaped(tok->args[0]));
  1807. goto err;
  1808. }
  1809. if (!bool_eq(ns->is_vote, is_vote)) {
  1810. log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus.");
  1811. goto err;
  1812. }
  1813. if (ns->is_vote) {
  1814. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  1815. if (parse_iso_time(tok->args[0], &ns->published))
  1816. goto err;
  1817. ns->supported_methods = smartlist_create();
  1818. tok = find_first_by_keyword(tokens, K_CONSENSUS_METHODS);
  1819. if (tok) {
  1820. for (i=0; i < tok->n_args; ++i)
  1821. smartlist_add(ns->supported_methods, tok->args[i]);
  1822. tok->n_args = 0; /* Prevent double free. */
  1823. } else {
  1824. smartlist_add(ns->supported_methods, tor_strdup("1"));
  1825. }
  1826. } else {
  1827. tok = find_first_by_keyword(tokens, K_CONSENSUS_METHOD);
  1828. if (tok) {
  1829. ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX,
  1830. &ok, NULL);
  1831. if (!ok)
  1832. goto err;
  1833. } else {
  1834. ns->consensus_method = 1;
  1835. }
  1836. }
  1837. tok = find_first_by_keyword(tokens, K_VALID_AFTER);
  1838. if (parse_iso_time(tok->args[0], &ns->valid_after))
  1839. goto err;
  1840. tok = find_first_by_keyword(tokens, K_FRESH_UNTIL);
  1841. if (parse_iso_time(tok->args[0], &ns->fresh_until))
  1842. goto err;
  1843. tok = find_first_by_keyword(tokens, K_VALID_UNTIL);
  1844. if (parse_iso_time(tok->args[0], &ns->valid_until))
  1845. goto err;
  1846. tok = find_first_by_keyword(tokens, K_VOTING_DELAY);
  1847. tor_assert(tok->n_args >= 2);
  1848. ns->vote_seconds =
  1849. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);
  1850. if (!ok)
  1851. goto err;
  1852. ns->dist_seconds =
  1853. (int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL);
  1854. if (!ok)
  1855. goto err;
  1856. if (ns->valid_after + MIN_VOTE_INTERVAL > ns->fresh_until) {
  1857. log_warn(LD_DIR, "Vote/consensus freshness interval is too short");
  1858. goto err;
  1859. }
  1860. if (ns->valid_after + MIN_VOTE_INTERVAL*2 > ns->valid_until) {
  1861. log_warn(LD_DIR, "Vote/consensus liveness interval is too short");
  1862. goto err;
  1863. }
  1864. if (ns->vote_seconds < MIN_VOTE_SECONDS) {
  1865. log_warn(LD_DIR, "Vote seconds is too short");
  1866. goto err;
  1867. }
  1868. if (ns->dist_seconds < MIN_DIST_SECONDS) {
  1869. log_warn(LD_DIR, "Dist seconds is too short");
  1870. goto err;
  1871. }
  1872. if ((tok = find_first_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  1873. ns->client_versions = tok->args[0];
  1874. tok->args[0] = NULL;
  1875. }
  1876. if ((tok = find_first_by_keyword(tokens, K_SERVER_VERSIONS))) {
  1877. ns->server_versions = tok->args[0];
  1878. tok->args[0] = NULL;
  1879. }
  1880. tok = find_first_by_keyword(tokens, K_KNOWN_FLAGS);
  1881. ns->known_flags = smartlist_create();
  1882. inorder = 1;
  1883. for (i = 0; i < tok->n_args; ++i) {
  1884. smartlist_add(ns->known_flags, tok->args[i]);
  1885. if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) {
  1886. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  1887. inorder = 0;
  1888. }
  1889. }
  1890. tok->n_args = 0; /* suppress free of args members, but not of args itself. */
  1891. if (!inorder) {
  1892. log_warn(LD_DIR, "known-flags not in order");
  1893. goto err;
  1894. }
  1895. ns->voters = smartlist_create();
  1896. SMARTLIST_FOREACH(tokens, directory_token_t *, _tok,
  1897. {
  1898. tok = _tok;
  1899. if (tok->tp == K_DIR_SOURCE) {
  1900. tor_assert(tok->n_args >= 6);
  1901. if (voter)
  1902. smartlist_add(ns->voters, voter);
  1903. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  1904. if (is_vote)
  1905. memcpy(voter->vote_digest, ns_digest, DIGEST_LEN);
  1906. voter->nickname = tor_strdup(tok->args[0]);
  1907. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  1908. base16_decode(voter->identity_digest, sizeof(voter->identity_digest),
  1909. tok->args[1], HEX_DIGEST_LEN) < 0) {
  1910. log_warn(LD_DIR, "Error decoding identity digest %s in "
  1911. "network-status vote.", escaped(tok->args[1]));
  1912. goto err;
  1913. }
  1914. if (is_vote && memcmp(ns->cert->cache_info.identity_digest,
  1915. voter->identity_digest, DIGEST_LEN)) {
  1916. log_warn(LD_DIR,"Mismatch between identities in certificate and vote");
  1917. goto err;
  1918. }
  1919. voter->address = tor_strdup(tok->args[2]);
  1920. if (!tor_inet_aton(tok->args[3], &in)) {
  1921. log_warn(LD_DIR, "Error decoding IP address %s in network-status.",
  1922. escaped(tok->args[3]));
  1923. goto err;
  1924. }
  1925. voter->addr = ntohl(in.s_addr);
  1926. voter->dir_port = (uint64_t)
  1927. (int) tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);
  1928. if (!ok)
  1929. goto err;
  1930. voter->or_port = (uint64_t)
  1931. (int) tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);
  1932. if (!ok)
  1933. goto err;
  1934. } else if (tok->tp == K_CONTACT) {
  1935. if (!voter || voter->contact) {
  1936. log_warn(LD_DIR, "contact element is out of place.");
  1937. goto err;
  1938. }
  1939. voter->contact = tor_strdup(tok->args[0]);
  1940. } else if (tok->tp == K_VOTE_DIGEST) {
  1941. tor_assert(!is_vote);
  1942. tor_assert(tok->n_args >= 1);
  1943. if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {
  1944. log_warn(LD_DIR, "vote-digest element is out of place.");
  1945. goto err;
  1946. }
  1947. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  1948. base16_decode(voter->vote_digest, sizeof(voter->vote_digest),
  1949. tok->args[0], HEX_DIGEST_LEN) < 0) {
  1950. log_warn(LD_DIR, "Error decoding vote digest %s in "
  1951. "network-status consensus.", escaped(tok->args[1]));
  1952. goto err;
  1953. }
  1954. }
  1955. });
  1956. if (voter) {
  1957. smartlist_add(ns->voters, voter);
  1958. voter = NULL;
  1959. }
  1960. if (smartlist_len(ns->voters) == 0) {
  1961. log_warn(LD_DIR, "Missing dir-source elements in a vote networkstatus.");
  1962. goto err;
  1963. } else if (is_vote && smartlist_len(ns->voters) != 1) {
  1964. log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus.");
  1965. goto err;
  1966. }
  1967. /* Parse routerstatus lines. */
  1968. rs_tokens = smartlist_create();
  1969. s = end_of_header;
  1970. ns->routerstatus_list = smartlist_create();
  1971. while (!strcmpstart(s, "r ")) {
  1972. if (is_vote) {
  1973. vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  1974. if (routerstatus_parse_entry_from_string(&s, tokens, ns, rs, 0))
  1975. smartlist_add(ns->routerstatus_list, rs);
  1976. else {
  1977. tor_free(rs->version);
  1978. tor_free(rs);
  1979. }
  1980. } else {
  1981. routerstatus_t *rs;
  1982. if ((rs = routerstatus_parse_entry_from_string(&s, tokens, NULL, NULL,
  1983. ns->consensus_method)))
  1984. smartlist_add(ns->routerstatus_list, rs);
  1985. }
  1986. }
  1987. for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {
  1988. routerstatus_t *rs1, *rs2;
  1989. if (is_vote) {
  1990. vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);
  1991. vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);
  1992. rs1 = &a->status; rs2 = &b->status;
  1993. } else {
  1994. rs1 = smartlist_get(ns->routerstatus_list, i-1);
  1995. rs2 = smartlist_get(ns->routerstatus_list, i);
  1996. }
  1997. if (memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN) >= 0) {
  1998. log_warn(LD_DIR, "Vote networkstatus entries not sorted by identity "
  1999. "digest");
  2000. goto err;
  2001. }
  2002. }
  2003. /* Parse footer; check signature. */
  2004. footer_tokens = smartlist_create();
  2005. if ((end_of_footer = strstr(s, "\nnetwork-status-version ")))
  2006. ++end_of_footer;
  2007. else
  2008. end_of_footer = s + strlen(s);
  2009. if (tokenize_string(s, end_of_footer, footer_tokens,
  2010. networkstatus_vote_footer_token_table, 0)) {
  2011. log_warn(LD_DIR, "Error tokenizing network-status vote footer.");
  2012. goto err;
  2013. }
  2014. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, _tok,
  2015. {
  2016. char declared_identity[DIGEST_LEN];
  2017. networkstatus_voter_info_t *v;
  2018. tok = _tok;
  2019. if (tok->tp != K_DIRECTORY_SIGNATURE)
  2020. continue;
  2021. tor_assert(tok->n_args >= 2);
  2022. if (!tok->object_type ||
  2023. strcmp(tok->object_type, "SIGNATURE") ||
  2024. tok->object_size < 128 || tok->object_size > 512) {
  2025. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  2026. goto err;
  2027. }
  2028. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  2029. base16_decode(declared_identity, sizeof(declared_identity),
  2030. tok->args[0], HEX_DIGEST_LEN) < 0) {
  2031. log_warn(LD_DIR, "Error decoding declared identity %s in "
  2032. "network-status vote.", escaped(tok->args[0]));
  2033. goto err;
  2034. }
  2035. if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {
  2036. log_warn(LD_DIR, "ID on signature on network-status vote does not match "
  2037. "any declared directory source.");
  2038. goto err;
  2039. }
  2040. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  2041. base16_decode(v->signing_key_digest, sizeof(v->signing_key_digest),
  2042. tok->args[1], HEX_DIGEST_LEN) < 0) {
  2043. log_warn(LD_DIR, "Error decoding declared digest %s in "
  2044. "network-status vote.", escaped(tok->args[1]));
  2045. goto err;
  2046. }
  2047. if (is_vote) {
  2048. if (memcmp(declared_identity, ns->cert->cache_info.identity_digest,
  2049. DIGEST_LEN)) {
  2050. log_warn(LD_DIR, "Digest mismatch between declared and actual on "
  2051. "network-status vote.");
  2052. goto err;
  2053. }
  2054. }
  2055. if (is_vote) {
  2056. if (check_signature_token(ns_digest, tok, ns->cert->signing_key, 0,
  2057. "network-status vote"))
  2058. goto err;
  2059. v->good_signature = 1;
  2060. } else {
  2061. v->signature = tor_memdup(tok->object_body, tok->object_size);
  2062. v->signature_len = tok->object_size;
  2063. }
  2064. ++n_signatures;
  2065. });
  2066. if (! n_signatures) {
  2067. log_warn(LD_DIR, "No signatures on networkstatus vote.");
  2068. goto err;
  2069. }
  2070. if (eos_out)
  2071. *eos_out = end_of_footer;
  2072. goto done;
  2073. err:
  2074. if (ns)
  2075. networkstatus_vote_free(ns);
  2076. ns = NULL;
  2077. done:
  2078. if (tokens) {
  2079. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  2080. smartlist_free(tokens);
  2081. }
  2082. if (voter) {
  2083. tor_free(voter->nickname);
  2084. tor_free(voter->address);
  2085. tor_free(voter->contact);
  2086. tor_free(voter->signature);
  2087. tor_free(voter);
  2088. }
  2089. if (rs_tokens) {
  2090. SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_free(t));
  2091. smartlist_free(rs_tokens);
  2092. }
  2093. if (footer_tokens) {
  2094. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_free(t));
  2095. smartlist_free(footer_tokens);
  2096. }
  2097. return ns;
  2098. }
  2099. /** Parse a detached v3 networkstatus signature document between <b>s</b> and
  2100. * <b>eos</b> and return the result. Return -1 on failure. */
  2101. ns_detached_signatures_t *
  2102. networkstatus_parse_detached_signatures(const char *s, const char *eos)
  2103. {
  2104. /* XXXX there is too much duplicate code here. */
  2105. directory_token_t *tok;
  2106. smartlist_t *tokens = smartlist_create();
  2107. ns_detached_signatures_t *sigs =
  2108. tor_malloc_zero(sizeof(ns_detached_signatures_t));
  2109. if (!eos)
  2110. eos = s + strlen(s);
  2111. if (tokenize_string(s, eos, tokens,
  2112. networkstatus_detached_signature_token_table, 0)) {
  2113. log_warn(LD_DIR, "Error tokenizing detached networkstatus signatures");
  2114. goto err;
  2115. }
  2116. tok = find_first_by_keyword(tokens, K_CONSENSUS_DIGEST);
  2117. if (strlen(tok->args[0]) != HEX_DIGEST_LEN) {
  2118. log_warn(LD_DIR, "Wrong length on consensus-digest in detached "
  2119. "networkstatus signatures");
  2120. goto err;
  2121. }
  2122. if (base16_decode(sigs->networkstatus_digest, DIGEST_LEN,
  2123. tok->args[0], strlen(tok->args[0])) < 0) {
  2124. log_warn(LD_DIR, "Bad encoding on on consensus-digest in detached "
  2125. "networkstatus signatures");
  2126. goto err;
  2127. }
  2128. tok = find_first_by_keyword(tokens, K_VALID_AFTER);
  2129. if (parse_iso_time(tok->args[0], &sigs->valid_after)) {
  2130. log_warn(LD_DIR, "Bad valid-after in detached networkstatus signatures");
  2131. goto err;
  2132. }
  2133. tok = find_first_by_keyword(tokens, K_FRESH_UNTIL);
  2134. if (parse_iso_time(tok->args[0], &sigs->fresh_until)) {
  2135. log_warn(LD_DIR, "Bad fresh-until in detached networkstatus signatures");
  2136. goto err;
  2137. }
  2138. tok = find_first_by_keyword(tokens, K_VALID_UNTIL);
  2139. if (parse_iso_time(tok->args[0], &sigs->valid_until)) {
  2140. log_warn(LD_DIR, "Bad valid-until in detached networkstatus signatures");
  2141. goto err;
  2142. }
  2143. sigs->signatures = smartlist_create();
  2144. SMARTLIST_FOREACH(tokens, directory_token_t *, _tok,
  2145. {
  2146. char id_digest[DIGEST_LEN];
  2147. char sk_digest[DIGEST_LEN];
  2148. networkstatus_voter_info_t *voter;
  2149. tok = _tok;
  2150. if (tok->tp != K_DIRECTORY_SIGNATURE)
  2151. continue;
  2152. tor_assert(tok->n_args >= 2);
  2153. if (!tok->object_type ||
  2154. strcmp(tok->object_type, "SIGNATURE") ||
  2155. tok->object_size < 128 || tok->object_size > 512) {
  2156. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  2157. goto err;
  2158. }
  2159. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  2160. base16_decode(id_digest, sizeof(id_digest),
  2161. tok->args[0], HEX_DIGEST_LEN) < 0) {
  2162. log_warn(LD_DIR, "Error decoding declared identity %s in "
  2163. "network-status vote.", escaped(tok->args[0]));
  2164. goto err;
  2165. }
  2166. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  2167. base16_decode(sk_digest, sizeof(sk_digest),
  2168. tok->args[1], HEX_DIGEST_LEN) < 0) {
  2169. log_warn(LD_DIR, "Error decoding declared digest %s in "
  2170. "network-status vote.", escaped(tok->args[1]));
  2171. goto err;
  2172. }
  2173. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  2174. memcpy(voter->identity_digest, id_digest, DIGEST_LEN);
  2175. memcpy(voter->signing_key_digest, sk_digest, DIGEST_LEN);
  2176. voter->signature = tor_memdup(tok->object_body, tok->object_size);
  2177. voter->signature_len = tok->object_size;
  2178. smartlist_add(sigs->signatures, voter);
  2179. });
  2180. goto done;
  2181. err:
  2182. ns_detached_signatures_free(sigs);
  2183. sigs = NULL;
  2184. done:
  2185. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  2186. smartlist_free(tokens);
  2187. return sigs;
  2188. }
  2189. /** Parse the addr policy in the string <b>s</b> and return it. If
  2190. * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
  2191. * ADDR_POLICY_REJECT) for items that specify no action.
  2192. */
  2193. addr_policy_t *
  2194. router_parse_addr_policy_item_from_string(const char *s, int assume_action)
  2195. {
  2196. directory_token_t *tok = NULL;
  2197. const char *cp, *eos;
  2198. /* Longest possible policy is "accept ffff:ffff:..255/ffff:...255:0-65535".
  2199. * But note that there can be an arbitrary amount of space between the
  2200. * accept and the address:mask/port element. */
  2201. char line[TOR_ADDR_BUF_LEN*2 + 32];
  2202. addr_policy_t *r;
  2203. s = eat_whitespace(s);
  2204. if ((*s == '*' || TOR_ISDIGIT(*s)) && assume_action >= 0) {
  2205. if (tor_snprintf(line, sizeof(line), "%s %s",
  2206. assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", s)<0) {
  2207. log_warn(LD_DIR, "Policy %s is too long.", escaped(s));
  2208. return NULL;
  2209. }
  2210. cp = line;
  2211. tor_strlower(line);
  2212. } else { /* assume an already well-formed address policy line */
  2213. cp = s;
  2214. }
  2215. eos = cp + strlen(cp);
  2216. tok = get_next_token(&cp, eos, routerdesc_token_table);
  2217. if (tok->tp == _ERR) {
  2218. log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
  2219. goto err;
  2220. }
  2221. if (tok->tp != K_ACCEPT && tok->tp != K_REJECT) {
  2222. log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
  2223. goto err;
  2224. }
  2225. /* Now that we've gotten an addr policy, add it to the router. */
  2226. r = router_parse_addr_policy(tok);
  2227. goto done;
  2228. err:
  2229. r = NULL;
  2230. done:
  2231. token_free(tok);
  2232. return r;
  2233. }
  2234. /** Add an exit policy stored in the token <b>tok</b> to the router info in
  2235. * <b>router</b>. Return 0 on success, -1 on failure. */
  2236. static int
  2237. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
  2238. {
  2239. addr_policy_t *newe;
  2240. newe = router_parse_addr_policy(tok);
  2241. if (!newe)
  2242. return -1;
  2243. if (! router->exit_policy)
  2244. router->exit_policy = smartlist_create();
  2245. smartlist_add(router->exit_policy, newe);
  2246. return 0;
  2247. }
  2248. /** Given a K_ACCEPT or K_REJECT token and a router, create and return
  2249. * a new exit_policy_t corresponding to the token. */
  2250. static addr_policy_t *
  2251. router_parse_addr_policy(directory_token_t *tok)
  2252. {
  2253. addr_policy_t newe;
  2254. char *arg;
  2255. tor_assert(tok->tp == K_REJECT || tok->tp == K_ACCEPT);
  2256. if (tok->n_args != 1)
  2257. return NULL;
  2258. arg = tok->args[0];
  2259. if (!strcmpstart(arg,"private"))
  2260. return router_parse_addr_policy_private(tok);
  2261. memset(&newe, 0, sizeof(newe));
  2262. newe.policy_type = (tok->tp == K_REJECT) ? ADDR_POLICY_REJECT
  2263. : ADDR_POLICY_ACCEPT;
  2264. if (parse_addr_and_port_range(arg, &newe.addr, &newe.maskbits,
  2265. &newe.prt_min, &newe.prt_max))
  2266. goto policy_read_failed;
  2267. return addr_policy_get_canonical_entry(&newe);
  2268. policy_read_failed:
  2269. log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
  2270. return NULL;
  2271. }
  2272. /** Parse an exit policy line of the format "accept/reject private:...".
  2273. * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
  2274. * router descriptors until earlier versions are obsolete.
  2275. */
  2276. static addr_policy_t *
  2277. router_parse_addr_policy_private(directory_token_t *tok)
  2278. {
  2279. const char *arg;
  2280. uint16_t port_min, port_max;
  2281. addr_policy_t result;
  2282. arg = tok->args[0];
  2283. if (strcmpstart(arg, "private"))
  2284. return NULL;
  2285. arg += strlen("private");
  2286. arg = (char*) eat_whitespace(arg);
  2287. if (!arg || *arg != ':')
  2288. return NULL;
  2289. if (parse_port_range(arg+1, &port_min, &port_max)<0)
  2290. return NULL;
  2291. memset(&result, 0, sizeof(result));
  2292. result.policy_type = (tok->tp == K_REJECT) ? ADDR_POLICY_REJECT
  2293. : ADDR_POLICY_ACCEPT;
  2294. result.is_private = 1;
  2295. result.prt_min = port_min;
  2296. result.prt_max = port_max;
  2297. return addr_policy_get_canonical_entry(&result);
  2298. }
  2299. /** Log and exit if <b>t</b> is malformed */
  2300. void
  2301. assert_addr_policy_ok(smartlist_t *lst)
  2302. {
  2303. if (!lst) return;
  2304. SMARTLIST_FOREACH(lst, addr_policy_t *, t, {
  2305. tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
  2306. t->policy_type == ADDR_POLICY_ACCEPT);
  2307. tor_assert(t->prt_min <= t->prt_max);
  2308. });
  2309. }
  2310. /*
  2311. * Low-level tokenizer for router descriptors and directories.
  2312. */
  2313. /** Free all resources allocated for <b>tok</b> */
  2314. static void
  2315. token_free(directory_token_t *tok)
  2316. {
  2317. int i;
  2318. tor_assert(tok);
  2319. if (tok->args) {
  2320. for (i = 0; i < tok->n_args; ++i) {
  2321. tor_free(tok->args[i]);
  2322. }
  2323. tor_free(tok->args);
  2324. }
  2325. tor_free(tok->object_type);
  2326. tor_free(tok->object_body);
  2327. tor_free(tok->error);
  2328. if (tok->key)
  2329. crypto_free_pk_env(tok->key);
  2330. tor_free(tok);
  2331. }
  2332. #define RET_ERR(msg) \
  2333. STMT_BEGIN \
  2334. if (tok) token_free(tok); \
  2335. tok = tor_malloc_zero(sizeof(directory_token_t)); \
  2336. tok->tp = _ERR; \
  2337. tok->error = tor_strdup(msg); \
  2338. goto done_tokenizing; \
  2339. STMT_END
  2340. static INLINE directory_token_t *
  2341. token_check_object(const char *kwd,
  2342. directory_token_t *tok, obj_syntax o_syn)
  2343. {
  2344. char ebuf[128];
  2345. switch (o_syn) {
  2346. case NO_OBJ:
  2347. if (tok->object_body) {
  2348. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected object for %s", kwd);
  2349. RET_ERR(ebuf);
  2350. }
  2351. if (tok->key) {
  2352. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected public key for %s", kwd);
  2353. RET_ERR(ebuf);
  2354. }
  2355. break;
  2356. case NEED_OBJ:
  2357. if (!tok->object_body) {
  2358. tor_snprintf(ebuf, sizeof(ebuf), "Missing object for %s", kwd);
  2359. RET_ERR(ebuf);
  2360. }
  2361. break;
  2362. case NEED_KEY_1024:
  2363. if (tok->key && crypto_pk_keysize(tok->key) != PK_BYTES) {
  2364. tor_snprintf(ebuf, sizeof(ebuf), "Wrong size on key for %s: %d bits",
  2365. kwd, (int)crypto_pk_keysize(tok->key));
  2366. RET_ERR(ebuf);
  2367. }
  2368. /* fall through */
  2369. case NEED_KEY:
  2370. if (!tok->key) {
  2371. tor_snprintf(ebuf, sizeof(ebuf), "Missing public key for %s", kwd);
  2372. }
  2373. break;
  2374. case OBJ_OK:
  2375. break;
  2376. }
  2377. done_tokenizing:
  2378. return tok;
  2379. }
  2380. /** Helper function: read the next token from *s, advance *s to the end of the
  2381. * token, and return the parsed token. Parse *<b>s</b> according to the list
  2382. * of tokens in <b>table</b>.
  2383. */
  2384. static directory_token_t *
  2385. get_next_token(const char **s, const char *eos, token_rule_t *table)
  2386. {
  2387. const char *next, *eol, *obstart;
  2388. int i, j, allocated, obname_len;
  2389. directory_token_t *tok;
  2390. obj_syntax o_syn = NO_OBJ;
  2391. char ebuf[128];
  2392. const char *kwd = "";
  2393. #define RET_ERR(msg) \
  2394. STMT_BEGIN \
  2395. if (tok) token_free(tok); \
  2396. tok = tor_malloc_zero(sizeof(directory_token_t)); \
  2397. tok->tp = _ERR; \
  2398. tok->error = tor_strdup(msg); \
  2399. goto done_tokenizing; \
  2400. STMT_END
  2401. tok = tor_malloc_zero(sizeof(directory_token_t));
  2402. tok->tp = _ERR;
  2403. /* Set *s to first token, eol to end-of-line, next to after first token */
  2404. *s = eat_whitespace_eos(*s, eos); /* eat multi-line whitespace */
  2405. eol = memchr(*s, '\n', eos-*s);
  2406. if (!eol)
  2407. eol = eos;
  2408. next = find_whitespace_eos(*s, eol);
  2409. if (!strcmp_len(*s, "opt", next-*s)) {
  2410. /* Skip past an "opt" at the start of the line. */
  2411. *s = eat_whitespace_eos_no_nl(next, eol);
  2412. next = find_whitespace_eos(*s, eol);
  2413. } else if (*s == eos) { /* If no "opt", and end-of-line, line is invalid */
  2414. RET_ERR("Unexpected EOF");
  2415. }
  2416. /* Search the table for the appropriate entry. (I tried a binary search
  2417. * instead, but it wasn't any faster.) */
  2418. for (i = 0; table[i].t ; ++i) {
  2419. if (!strcmp_len(*s, table[i].t, next-*s)) {
  2420. /* We've found the keyword. */
  2421. kwd = table[i].t;
  2422. tok->tp = table[i].v;
  2423. o_syn = table[i].os;
  2424. *s = eat_whitespace_eos_no_nl(next, eol);
  2425. next = find_whitespace_eos(*s, eol);
  2426. /* We go ahead whether there are arguments or not, so that tok->args is
  2427. * always set if we want arguments. */
  2428. if (table[i].concat_args) {
  2429. /* The keyword takes the line as a single argument */
  2430. tok->args = tor_malloc(sizeof(char*));
  2431. tok->args[0] = tor_strndup(*s,eol-*s); /* Grab everything on line */
  2432. tok->n_args = 1;
  2433. } else {
  2434. /* This keyword takes multiple arguments. */
  2435. j = 0;
  2436. allocated = 16;
  2437. tok->args = tor_malloc(sizeof(char*)*allocated);
  2438. while (*s < eol) { /* While not at eol, store the next token */
  2439. if (j == allocated) {
  2440. allocated *= 2;
  2441. tok->args = tor_realloc(tok->args,sizeof(char*)*allocated);
  2442. }
  2443. tok->args[j++] = tor_strndup(*s, next-*s);
  2444. *s = eat_whitespace_eos_no_nl(next, eol); /* eat intra-line ws */
  2445. next = find_whitespace_eos(*s, eol); /* find end of token at *s */
  2446. }
  2447. tok->n_args = j;
  2448. }
  2449. if (tok->n_args < table[i].min_args) {
  2450. tor_snprintf(ebuf, sizeof(ebuf), "Too few arguments to %s", kwd);
  2451. RET_ERR(ebuf);
  2452. } else if (tok->n_args > table[i].max_args) {
  2453. tor_snprintf(ebuf, sizeof(ebuf), "Too many arguments to %s", kwd);
  2454. RET_ERR(ebuf);
  2455. }
  2456. break;
  2457. }
  2458. }
  2459. if (tok->tp == _ERR) {
  2460. /* No keyword matched; call it an "K_opt" or "A_unrecognized" */
  2461. if (**s == '@')
  2462. tok->tp = _A_UNKNOWN;
  2463. else
  2464. tok->tp = K_OPT;
  2465. tok->args = tor_malloc(sizeof(char*));
  2466. tok->args[0] = tor_strndup(*s, eol-*s);
  2467. tok->n_args = 1;
  2468. o_syn = OBJ_OK;
  2469. }
  2470. /* Check whether there's an object present */
  2471. *s = eat_whitespace_eos(eol, eos); /* Scan from end of first line */
  2472. eol = memchr(*s, '\n', eos-*s);
  2473. if (!eol || eol-*s<11 || strcmpstart(*s, "-----BEGIN ")) /* No object. */
  2474. goto check_object;
  2475. obstart = *s; /* Set obstart to start of object spec */
  2476. if (*s+11 >= eol-5 || memchr(*s+11,'\0',eol-*s-16) || /* no short lines, */
  2477. strcmp_len(eol-5, "-----", 5)) { /* nuls or invalid endings */
  2478. RET_ERR("Malformed object: bad begin line");
  2479. }
  2480. tok->object_type = tor_strndup(*s+11, eol-*s-16);
  2481. obname_len = eol-*s-16; /* store objname length here to avoid a strlen() */
  2482. *s = eol+1; /* Set *s to possible start of object data (could be eos) */
  2483. /* Go to the end of the object */
  2484. next = tor_memstr(*s, eos-*s, "-----END ");
  2485. if (!next) {
  2486. RET_ERR("Malformed object: missing object end line");
  2487. }
  2488. eol = memchr(next, '\n', eos-next);
  2489. if (!eol) /* end-of-line marker, or eos if there's no '\n' */
  2490. eol = eos;
  2491. /* Validate the ending tag, which should be 9 + NAME + 5 + eol */
  2492. if (eol-next != 9+obname_len+5 ||
  2493. strcmp_len(next+9, tok->object_type, obname_len) ||
  2494. strcmp_len(eol-5, "-----", 5)) {
  2495. snprintf(ebuf, sizeof(ebuf), "Malformed object: mismatched end tag %s",
  2496. tok->object_type);
  2497. ebuf[sizeof(ebuf)-1] = '\0';
  2498. RET_ERR(ebuf);
  2499. }
  2500. if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) { /* If it's a key... */
  2501. tok->key = crypto_new_pk_env();
  2502. if (crypto_pk_read_public_key_from_string(tok->key, obstart, eol-obstart))
  2503. RET_ERR("Couldn't parse public key.");
  2504. } else { /* If it's something else, try to base64-decode it */
  2505. int r;
  2506. tok->object_body = tor_malloc(next-*s); /* really, this is too much RAM. */
  2507. r = base64_decode(tok->object_body, next-*s, *s, next-*s);
  2508. if (r<0)
  2509. RET_ERR("Malformed object: bad base64-encoded data");
  2510. tok->object_size = r;
  2511. }
  2512. *s = eol;
  2513. check_object:
  2514. tok = token_check_object(kwd, tok, o_syn);
  2515. done_tokenizing:
  2516. return tok;
  2517. #undef RET_ERR
  2518. }
  2519. /** Read all tokens from a string between <b>start</b> and <b>end</b>, and add
  2520. * them to <b>out</b>. Parse according to the token rules in <b>table</b>.
  2521. * Caller must free tokens in <b>out</b>. If <b>end</b> is NULL, use the
  2522. * entire string.
  2523. */
  2524. static int
  2525. tokenize_string(const char *start, const char *end, smartlist_t *out,
  2526. token_rule_t *table, int flags)
  2527. {
  2528. const char **s;
  2529. directory_token_t *tok = NULL;
  2530. int counts[_NIL];
  2531. int i;
  2532. int first_nonannotation;
  2533. int prev_len = smartlist_len(out);
  2534. s = &start;
  2535. if (!end)
  2536. end = start+strlen(start);
  2537. for (i = 0; i < _NIL; ++i)
  2538. counts[i] = 0;
  2539. while (*s < end && (!tok || tok->tp != _EOF)) {
  2540. tok = get_next_token(s, end, table);
  2541. if (tok->tp == _ERR) {
  2542. log_warn(LD_DIR, "parse error: %s", tok->error);
  2543. token_free(tok);
  2544. return -1;
  2545. }
  2546. ++counts[tok->tp];
  2547. smartlist_add(out, tok);
  2548. *s = eat_whitespace_eos(*s, end);
  2549. }
  2550. if (flags & TS_NOCHECK)
  2551. return 0;
  2552. if ((flags & TS_ANNOTATIONS_OK)) {
  2553. first_nonannotation = -1;
  2554. for (i = 0; i < smartlist_len(out); ++i) {
  2555. tok = smartlist_get(out, i);
  2556. if (tok->tp < MIN_ANNOTATION || tok->tp > MAX_ANNOTATION) {
  2557. first_nonannotation = i;
  2558. break;
  2559. }
  2560. }
  2561. if (first_nonannotation < 0) {
  2562. log_warn(LD_DIR, "parse error: item contains only annotations");
  2563. return -1;
  2564. }
  2565. for (i=first_nonannotation; i < smartlist_len(out); ++i) {
  2566. tok = smartlist_get(out, i);
  2567. if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
  2568. log_warn(LD_DIR, "parse error: Annotations mixed with keywords");
  2569. return -1;
  2570. }
  2571. }
  2572. if ((flags & TS_NO_NEW_ANNOTATIONS)) {
  2573. if (first_nonannotation != prev_len) {
  2574. log_warn(LD_DIR, "parse error: Unexpectd annotations.");
  2575. return -1;
  2576. }
  2577. }
  2578. } else {
  2579. for (i=0; i < smartlist_len(out); ++i) {
  2580. tok = smartlist_get(out, i);
  2581. if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
  2582. log_warn(LD_DIR, "parse error: no annotations allowed.");
  2583. return -1;
  2584. }
  2585. }
  2586. first_nonannotation = 0;
  2587. }
  2588. for (i = 0; table[i].t; ++i) {
  2589. if (counts[table[i].v] < table[i].min_cnt) {
  2590. log_warn(LD_DIR, "Parse error: missing %s element.", table[i].t);
  2591. return -1;
  2592. }
  2593. if (counts[table[i].v] > table[i].max_cnt) {
  2594. log_warn(LD_DIR, "Parse error: too many %s elements.", table[i].t);
  2595. return -1;
  2596. }
  2597. if (table[i].pos & AT_START) {
  2598. if (smartlist_len(out) < 1 ||
  2599. (tok = smartlist_get(out, first_nonannotation))->tp != table[i].v) {
  2600. log_warn(LD_DIR, "Parse error: first item is not %s.", table[i].t);
  2601. return -1;
  2602. }
  2603. }
  2604. if (table[i].pos & AT_END) {
  2605. if (smartlist_len(out) < 1 ||
  2606. (tok = smartlist_get(out, smartlist_len(out)-1))->tp != table[i].v) {
  2607. log_warn(LD_DIR, "Parse error: last item is not %s.", table[i].t);
  2608. return -1;
  2609. }
  2610. }
  2611. }
  2612. return 0;
  2613. }
  2614. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
  2615. * NULL if no such keyword is found.
  2616. */
  2617. static directory_token_t *
  2618. find_first_by_keyword(smartlist_t *s, directory_keyword keyword)
  2619. {
  2620. SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
  2621. return NULL;
  2622. }
  2623. /** Return a newly allocated smartlist of all accept or reject tokens in
  2624. * <b>s</b>.
  2625. */
  2626. static smartlist_t *
  2627. find_all_exitpolicy(smartlist_t *s)
  2628. {
  2629. smartlist_t *out = smartlist_create();
  2630. SMARTLIST_FOREACH(s, directory_token_t *, t,
  2631. if (t->tp == K_ACCEPT || t->tp == K_REJECT)
  2632. smartlist_add(out,t));
  2633. return out;
  2634. }
  2635. /** Compute the SHA-1 digest of the substring of <b>s</b> taken from the first
  2636. * occurrence of <b>start_str</b> through the first instance of c after the
  2637. * first subsequent occurrence of <b>end_str</b>; store the 20-byte result in
  2638. * <b>digest</b>; return 0 on success.
  2639. *
  2640. * If no such substring exists, return -1.
  2641. */
  2642. static int
  2643. router_get_hash_impl(const char *s, char *digest,
  2644. const char *start_str,
  2645. const char *end_str, char end_c)
  2646. {
  2647. char *start, *end;
  2648. start = strstr(s, start_str);
  2649. if (!start) {
  2650. log_warn(LD_DIR,"couldn't find start of hashed material \"%s\"",start_str);
  2651. return -1;
  2652. }
  2653. if (start != s && *(start-1) != '\n') {
  2654. log_warn(LD_DIR,
  2655. "first occurrence of \"%s\" is not at the start of a line",
  2656. start_str);
  2657. return -1;
  2658. }
  2659. end = strstr(start+strlen(start_str), end_str);
  2660. if (!end) {
  2661. log_warn(LD_DIR,"couldn't find end of hashed material \"%s\"",end_str);
  2662. return -1;
  2663. }
  2664. end = strchr(end+strlen(end_str), end_c);
  2665. if (!end) {
  2666. log_warn(LD_DIR,"couldn't find EOL");
  2667. return -1;
  2668. }
  2669. ++end;
  2670. if (crypto_digest(digest, start, end-start)) {
  2671. log_warn(LD_BUG,"couldn't compute digest");
  2672. return -1;
  2673. }
  2674. return 0;
  2675. }
  2676. /** Parse the Tor version of the platform string <b>platform</b>,
  2677. * and compare it to the version in <b>cutoff</b>. Return 1 if
  2678. * the router is at least as new as the cutoff, else return 0.
  2679. */
  2680. int
  2681. tor_version_as_new_as(const char *platform, const char *cutoff)
  2682. {
  2683. tor_version_t cutoff_version, router_version;
  2684. char *s, *s2, *start;
  2685. char tmp[128];
  2686. tor_assert(platform);
  2687. if (tor_version_parse(cutoff, &cutoff_version)<0) {
  2688. log_warn(LD_BUG,"cutoff version '%s' unparseable.",cutoff);
  2689. return 0;
  2690. }
  2691. if (strcmpstart(platform,"Tor ")) /* nonstandard Tor; be safe and say yes */
  2692. return 1;
  2693. start = (char *)eat_whitespace(platform+3);
  2694. if (!*start) return 0;
  2695. s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
  2696. s2 = (char*)eat_whitespace(s);
  2697. if (!strcmpstart(s2, "(r"))
  2698. s = (char*)find_whitespace(s2);
  2699. if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
  2700. return 0;
  2701. strlcpy(tmp, start, s-start+1);
  2702. if (tor_version_parse(tmp, &router_version)<0) {
  2703. log_info(LD_DIR,"Router version '%s' unparseable.",tmp);
  2704. return 1; /* be safe and say yes */
  2705. }
  2706. /* Here's why we don't need to do any special handling for svn revisions:
  2707. * - If neither has an svn revision, we're fine.
  2708. * - If the router doesn't have an svn revision, we can't assume that it
  2709. * is "at least" any svn revision, so we need to return 0.
  2710. * - If the target version doesn't have an svn revision, any svn revision
  2711. * (or none at all) is good enough, so return 1.
  2712. * - If both target and router have an svn revision, we compare them.
  2713. */
  2714. return tor_version_compare(&router_version, &cutoff_version) >= 0;
  2715. }
  2716. /** Parse a tor version from <b>s</b>, and store the result in <b>out</b>.
  2717. * Return 0 on success, -1 on failure. */
  2718. int
  2719. tor_version_parse(const char *s, tor_version_t *out)
  2720. {
  2721. char *eos=NULL;
  2722. const char *cp=NULL;
  2723. /* Format is:
  2724. * "Tor " ? NUM dot NUM dot NUM [ ( pre | rc | dot ) NUM [ - tag ] ]
  2725. */
  2726. tor_assert(s);
  2727. tor_assert(out);
  2728. memset(out, 0, sizeof(tor_version_t));
  2729. if (!strcasecmpstart(s, "Tor "))
  2730. s += 4;
  2731. /* Get major. */
  2732. out->major = strtol(s,&eos,10);
  2733. if (!eos || eos==s || *eos != '.') return -1;
  2734. cp = eos+1;
  2735. /* Get minor */
  2736. out->minor = strtol(cp,&eos,10);
  2737. if (!eos || eos==cp || *eos != '.') return -1;
  2738. cp = eos+1;
  2739. /* Get micro */
  2740. out->micro = strtol(cp,&eos,10);
  2741. if (!eos || eos==cp) return -1;
  2742. if (!*eos) {
  2743. out->status = VER_RELEASE;
  2744. out->patchlevel = 0;
  2745. return 0;
  2746. }
  2747. cp = eos;
  2748. /* Get status */
  2749. if (*cp == '.') {
  2750. out->status = VER_RELEASE;
  2751. ++cp;
  2752. } else if (0==strncmp(cp, "pre", 3)) {
  2753. out->status = VER_PRE;
  2754. cp += 3;
  2755. } else if (0==strncmp(cp, "rc", 2)) {
  2756. out->status = VER_RC;
  2757. cp += 2;
  2758. } else {
  2759. return -1;
  2760. }
  2761. /* Get patchlevel */
  2762. out->patchlevel = strtol(cp,&eos,10);
  2763. if (!eos || eos==cp) return -1;
  2764. cp = eos;
  2765. /* Get status tag. */
  2766. if (*cp == '-' || *cp == '.')
  2767. ++cp;
  2768. eos = (char*) find_whitespace(cp);
  2769. if (eos-cp >= (int)sizeof(out->status_tag))
  2770. strlcpy(out->status_tag, cp, sizeof(out->status_tag));
  2771. else {
  2772. memcpy(out->status_tag, cp, eos-cp);
  2773. out->status_tag[eos-cp] = 0;
  2774. }
  2775. cp = eat_whitespace(eos);
  2776. if (!strcmpstart(cp, "(r")) {
  2777. cp += 2;
  2778. out->svn_revision = strtol(cp,&eos,10);
  2779. }
  2780. return 0;
  2781. }
  2782. /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
  2783. * b. */
  2784. int
  2785. tor_version_compare(tor_version_t *a, tor_version_t *b)
  2786. {
  2787. int i;
  2788. tor_assert(a);
  2789. tor_assert(b);
  2790. if ((i = a->major - b->major))
  2791. return i;
  2792. else if ((i = a->minor - b->minor))
  2793. return i;
  2794. else if ((i = a->micro - b->micro))
  2795. return i;
  2796. else if ((i = a->status - b->status))
  2797. return i;
  2798. else if ((i = a->patchlevel - b->patchlevel))
  2799. return i;
  2800. else if ((i = strcmp(a->status_tag, b->status_tag)))
  2801. return i;
  2802. else
  2803. return a->svn_revision - b->svn_revision;
  2804. }
  2805. /** Return true iff versions <b>a</b> and <b>b</b> belong to the same series.
  2806. */
  2807. static int
  2808. tor_version_same_series(tor_version_t *a, tor_version_t *b)
  2809. {
  2810. tor_assert(a);
  2811. tor_assert(b);
  2812. return ((a->major == b->major) &&
  2813. (a->minor == b->minor) &&
  2814. (a->micro == b->micro));
  2815. }
  2816. /** Helper: Given pointers to two strings describing tor versions, return -1
  2817. * if _a precedes _b, 1 if _b preceeds _a, and 0 if they are equivalent.
  2818. * Used to sort a list of versions. */
  2819. static int
  2820. _compare_tor_version_str_ptr(const void **_a, const void **_b)
  2821. {
  2822. const char *a = *_a, *b = *_b;
  2823. int ca, cb;
  2824. tor_version_t va, vb;
  2825. ca = tor_version_parse(a, &va);
  2826. cb = tor_version_parse(b, &vb);
  2827. /* If they both parse, compare them. */
  2828. if (!ca && !cb)
  2829. return tor_version_compare(&va,&vb);
  2830. /* If one parses, it comes first. */
  2831. if (!ca && cb)
  2832. return -1;
  2833. if (ca && !cb)
  2834. return 1;
  2835. /* If neither parses, compare strings. Also, the directory server admin
  2836. ** needs to be smacked upside the head. But Tor is tolerant and gentle. */
  2837. return strcmp(a,b);
  2838. }
  2839. /** Sort a list of string-representations of versions in ascending order. */
  2840. void
  2841. sort_version_list(smartlist_t *versions, int remove_duplicates)
  2842. {
  2843. smartlist_sort(versions, _compare_tor_version_str_ptr);
  2844. if (remove_duplicates)
  2845. smartlist_uniq(versions, _compare_tor_version_str_ptr, _tor_free);
  2846. }
  2847. /** Parse and validate the ASCII-encoded v2 descriptor in <b>desc</b>,
  2848. * write the parsed descriptor to the newly allocated *<b>parsed_out</b>, the
  2849. * binary descriptor ID of length DIGEST_LEN to <b>desc_id_out</b>, the
  2850. * encrypted introduction points to the newly allocated
  2851. * *<b>intro_points_encrypted_out</b>, their encrypted size to
  2852. * *<b>intro_points_encrypted_size_out</b>, the size of the encoded descriptor
  2853. * to *<b>encoded_size_out</b>, and a pointer to the possibly next
  2854. * descriptor to *<b>next_out</b>; return 0 for success (including validation)
  2855. * and -1 for failure.
  2856. */
  2857. int
  2858. rend_parse_v2_service_descriptor(rend_service_descriptor_t **parsed_out,
  2859. char *desc_id_out,
  2860. char **intro_points_encrypted_out,
  2861. size_t *intro_points_encrypted_size_out,
  2862. size_t *encoded_size_out,
  2863. const char **next_out, const char *desc)
  2864. {
  2865. rend_service_descriptor_t *result =
  2866. tor_malloc_zero(sizeof(rend_service_descriptor_t));
  2867. char desc_hash[DIGEST_LEN];
  2868. const char *eos;
  2869. smartlist_t *tokens = smartlist_create();
  2870. directory_token_t *tok;
  2871. char secret_id_part[DIGEST_LEN];
  2872. int i, version, num_ok=1;
  2873. smartlist_t *versions;
  2874. char public_key_hash[DIGEST_LEN];
  2875. char test_desc_id[DIGEST_LEN];
  2876. tor_assert(desc);
  2877. /* Check if desc starts correctly. */
  2878. if (strncmp(desc, "rendezvous-service-descriptor ",
  2879. strlen("rendezvous-service-descriptor "))) {
  2880. log_info(LD_REND, "Descriptor does not start correctly.");
  2881. goto err;
  2882. }
  2883. /* Compute descriptor hash for later validation. */
  2884. if (router_get_hash_impl(desc, desc_hash,
  2885. "rendezvous-service-descriptor ",
  2886. "\nsignature", '\n') < 0) {
  2887. log_warn(LD_REND, "Couldn't compute descriptor hash.");
  2888. goto err;
  2889. }
  2890. /* Determine end of string. */
  2891. eos = strstr(desc, "\nrendezvous-service-descriptor ");
  2892. if (!eos)
  2893. eos = desc + strlen(desc);
  2894. else
  2895. eos = eos + 1;
  2896. /* Tokenize descriptor. */
  2897. if (tokenize_string(desc, eos, tokens, desc_token_table, 0)) {
  2898. log_warn(LD_REND, "Error tokenizing descriptor.");
  2899. goto err;
  2900. }
  2901. /* Set next to next descriptor, if available. */
  2902. *next_out = eos;
  2903. /* Set length of encoded descriptor. */
  2904. *encoded_size_out = eos - desc;
  2905. /* Check min allowed length of token list. */
  2906. if (smartlist_len(tokens) < 7) {
  2907. log_warn(LD_REND, "Impossibly short descriptor.");
  2908. goto err;
  2909. }
  2910. /* Parse base32-encoded descriptor ID. */
  2911. tok = find_first_by_keyword(tokens, R_RENDEZVOUS_SERVICE_DESCRIPTOR);
  2912. tor_assert(tok);
  2913. tor_assert(tok == smartlist_get(tokens, 0));
  2914. tor_assert(tok->n_args == 1);
  2915. if (strlen(tok->args[0]) != REND_DESC_ID_V2_LEN_BASE32 ||
  2916. strspn(tok->args[0], BASE32_CHARS) != REND_DESC_ID_V2_LEN_BASE32) {
  2917. log_warn(LD_REND, "Invalid descriptor ID: '%s'", tok->args[0]);
  2918. goto err;
  2919. }
  2920. if (base32_decode(desc_id_out, DIGEST_LEN,
  2921. tok->args[0], REND_DESC_ID_V2_LEN_BASE32) < 0) {
  2922. log_warn(LD_REND, "Descriptor ID contains illegal characters: %s",
  2923. tok->args[0]);
  2924. goto err;
  2925. }
  2926. /* Parse descriptor version. */
  2927. tok = find_first_by_keyword(tokens, R_VERSION);
  2928. tor_assert(tok);
  2929. tor_assert(tok->n_args == 1);
  2930. result->version =
  2931. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &num_ok, NULL);
  2932. if (result->version != 2 || !num_ok) {
  2933. /* If it's <2, it shouldn't be under this format. If the number
  2934. * is greater than 2, we bumped it because we broke backward
  2935. * compatibility. See how version numbers in our other formats
  2936. * work. */
  2937. log_warn(LD_REND, "Unrecognized descriptor version: %s",
  2938. escaped(tok->args[0]));
  2939. goto err;
  2940. }
  2941. /* Parse public key. */
  2942. tok = find_first_by_keyword(tokens, R_PERMANENT_KEY);
  2943. tor_assert(tok);
  2944. result->pk = tok->key;
  2945. tok->key = NULL; /* Prevent free */
  2946. /* Parse secret ID part. */
  2947. tok = find_first_by_keyword(tokens, R_SECRET_ID_PART);
  2948. tor_assert(tok);
  2949. tor_assert(tok->n_args == 1);
  2950. if (strlen(tok->args[0]) != REND_SECRET_ID_PART_LEN_BASE32 ||
  2951. strspn(tok->args[0], BASE32_CHARS) != REND_SECRET_ID_PART_LEN_BASE32) {
  2952. log_warn(LD_REND, "Invalid secret ID part: '%s'", tok->args[0]);
  2953. goto err;
  2954. }
  2955. if (base32_decode(secret_id_part, DIGEST_LEN, tok->args[0], 32) < 0) {
  2956. log_warn(LD_REND, "Secret ID part contains illegal characters: %s",
  2957. tok->args[0]);
  2958. goto err;
  2959. }
  2960. /* Parse publication time -- up-to-date check is done when storing the
  2961. * descriptor. */
  2962. tok = find_first_by_keyword(tokens, R_PUBLICATION_TIME);
  2963. tor_assert(tok);
  2964. tor_assert(tok->n_args == 1);
  2965. if (parse_iso_time(tok->args[0], &result->timestamp) < 0) {
  2966. log_warn(LD_REND, "Invalid publication time: '%s'", tok->args[0]);
  2967. goto err;
  2968. }
  2969. /* Parse protocol versions. */
  2970. tok = find_first_by_keyword(tokens, R_PROTOCOL_VERSIONS);
  2971. tor_assert(tok);
  2972. tor_assert(tok->n_args == 1);
  2973. versions = smartlist_create();
  2974. smartlist_split_string(versions, tok->args[0], ",",
  2975. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2976. for (i = 0; i < smartlist_len(versions); i++) {
  2977. version = (int) tor_parse_long(smartlist_get(versions, i),
  2978. 10, 0, INT_MAX, &num_ok, NULL);
  2979. if (!num_ok) /* It's a string; let's ignore it. */
  2980. continue;
  2981. result->protocols |= 1 << version;
  2982. }
  2983. SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
  2984. smartlist_free(versions);
  2985. /* Parse encrypted introduction points. Don't verify. */
  2986. tok = find_first_by_keyword(tokens, R_INTRODUCTION_POINTS);
  2987. if (tok) {
  2988. if (strcmp(tok->object_type, "MESSAGE")) {
  2989. log_warn(LD_DIR, "Bad object type: introduction points should be of "
  2990. "type MESSAGE");
  2991. goto err;
  2992. }
  2993. *intro_points_encrypted_out = tok->object_body;
  2994. *intro_points_encrypted_size_out = tok->object_size;
  2995. tok->object_body = NULL; /* Prevent free. */
  2996. } else {
  2997. *intro_points_encrypted_out = NULL;
  2998. *intro_points_encrypted_size_out = 0;
  2999. }
  3000. /* Parse and verify signature. */
  3001. tok = find_first_by_keyword(tokens, R_SIGNATURE);
  3002. tor_assert(tok);
  3003. note_crypto_pk_op(VERIFY_RTR);
  3004. if (check_signature_token(desc_hash, tok, result->pk, 0,
  3005. "v2 rendezvous service descriptor") < 0)
  3006. goto err;
  3007. /* Verify that descriptor ID belongs to public key and secret ID part. */
  3008. crypto_pk_get_digest(result->pk, public_key_hash);
  3009. rend_get_descriptor_id_bytes(test_desc_id, public_key_hash,
  3010. secret_id_part);
  3011. if (memcmp(desc_id_out, test_desc_id, DIGEST_LEN)) {
  3012. log_warn(LD_REND, "Parsed descriptor ID does not match "
  3013. "computed descriptor ID.");
  3014. goto err;
  3015. }
  3016. goto done;
  3017. err:
  3018. if (result)
  3019. rend_service_descriptor_free(result);
  3020. result = NULL;
  3021. done:
  3022. if (tokens) {
  3023. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  3024. smartlist_free(tokens);
  3025. }
  3026. *parsed_out = result;
  3027. if (result)
  3028. return 0;
  3029. return -1;
  3030. }
  3031. /** Decrypt and decode the introduction points in
  3032. * <b>intro_points_encrypted</b> of length
  3033. * <b>intro_points_encrypted_size</b> using <b>descriptor_cookie</b>
  3034. * (which may also be <b>NULL</b> if no decryption, but only parsing is
  3035. * required), parse the introduction points, and write the result to
  3036. * <b>parsed</b>; return the number of successfully parsed introduction
  3037. * points or -1 in case of a failure.
  3038. */
  3039. int
  3040. rend_decrypt_introduction_points(rend_service_descriptor_t *parsed,
  3041. const char *descriptor_cookie,
  3042. const char *intro_points_encrypted,
  3043. size_t intro_points_encrypted_size)
  3044. {
  3045. char *ipos_decrypted = NULL;
  3046. const char **current_ipo;
  3047. smartlist_t *tokens;
  3048. directory_token_t *tok;
  3049. rend_intro_point_t *intro;
  3050. extend_info_t *info;
  3051. struct in_addr ip;
  3052. int result, num_ok=1;
  3053. tor_assert(parsed);
  3054. /** Function may only be invoked once. */
  3055. tor_assert(!parsed->intro_nodes);
  3056. tor_assert(intro_points_encrypted);
  3057. tor_assert(intro_points_encrypted_size > 0);
  3058. /* Decrypt introduction points, if required. */
  3059. if (descriptor_cookie) {
  3060. crypto_cipher_env_t *cipher;
  3061. int unenclen;
  3062. ipos_decrypted = tor_malloc_zero(intro_points_encrypted_size - 16);
  3063. cipher = crypto_create_init_cipher(descriptor_cookie, 0);
  3064. unenclen = crypto_cipher_decrypt_with_iv(cipher, ipos_decrypted,
  3065. intro_points_encrypted_size - 16,
  3066. intro_points_encrypted,
  3067. intro_points_encrypted_size);
  3068. crypto_free_cipher_env(cipher);
  3069. if (unenclen < 0) {
  3070. tor_free(ipos_decrypted);
  3071. return -1;
  3072. }
  3073. intro_points_encrypted = ipos_decrypted;
  3074. intro_points_encrypted_size = unenclen;
  3075. }
  3076. /* Consider one intro point after the other. */
  3077. current_ipo = &intro_points_encrypted;
  3078. tokens = smartlist_create();
  3079. parsed->intro_nodes = smartlist_create();
  3080. while (!strcmpstart(*current_ipo, "introduction-point ")) {
  3081. /* Determine end of string. */
  3082. const char *eos = strstr(*current_ipo, "\nintroduction-point ");
  3083. if (!eos)
  3084. eos = *current_ipo+strlen(*current_ipo);
  3085. else
  3086. eos = eos+1;
  3087. /* Free tokens and clear token list. */
  3088. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  3089. smartlist_clear(tokens);
  3090. /* Tokenize string. */
  3091. if (tokenize_string(*current_ipo, eos, tokens, ipo_token_table, 0)) {
  3092. log_warn(LD_REND, "Error tokenizing introduction point.");
  3093. goto err;
  3094. }
  3095. /* Advance to next introduction point, if available. */
  3096. *current_ipo = eos;
  3097. /* Check minimum allowed length of introduction point. */
  3098. if (smartlist_len(tokens) < 5) {
  3099. log_warn(LD_REND, "Impossibly short introduction point.");
  3100. goto err;
  3101. }
  3102. /* Allocate new intro point and extend info. */
  3103. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  3104. info = intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  3105. /* Parse identifier. */
  3106. tok = find_first_by_keyword(tokens, R_IPO_IDENTIFIER);
  3107. tor_assert(tok);
  3108. if (base32_decode(info->identity_digest, DIGEST_LEN,
  3109. tok->args[0], REND_INTRO_POINT_ID_LEN_BASE32) < 0) {
  3110. log_warn(LD_REND, "Identity digest contains illegal characters: %s",
  3111. tok->args[0]);
  3112. rend_intro_point_free(intro);
  3113. goto err;
  3114. }
  3115. /* Write identifier to nickname. */
  3116. info->nickname[0] = '$';
  3117. base16_encode(info->nickname + 1, sizeof(info->nickname) - 1,
  3118. info->identity_digest, DIGEST_LEN);
  3119. /* Parse IP address. */
  3120. tok = find_first_by_keyword(tokens, R_IPO_IP_ADDRESS);
  3121. if (tor_inet_aton(tok->args[0], &ip) == 0) {
  3122. log_warn(LD_REND, "Could not parse IP address.");
  3123. rend_intro_point_free(intro);
  3124. goto err;
  3125. }
  3126. info->addr = ntohl(ip.s_addr);
  3127. /* Parse onion port. */
  3128. tok = find_first_by_keyword(tokens, R_IPO_ONION_PORT);
  3129. info->port = (uint16_t) tor_parse_long(tok->args[0],10,1,65535,
  3130. &num_ok,NULL);
  3131. if (!info->port || !num_ok) {
  3132. log_warn(LD_REND, "Introduction point onion port %s is invalid",
  3133. escaped(tok->args[0]));
  3134. rend_intro_point_free(intro);
  3135. goto err;
  3136. }
  3137. /* Parse onion key. */
  3138. tok = find_first_by_keyword(tokens, R_IPO_ONION_KEY);
  3139. info->onion_key = tok->key;
  3140. tok->key = NULL; /* Prevent free */
  3141. /* Parse service key. */
  3142. tok = find_first_by_keyword(tokens, R_IPO_SERVICE_KEY);
  3143. intro->intro_key = tok->key;
  3144. tok->key = NULL; /* Prevent free */
  3145. /* Add extend info to list of introduction points. */
  3146. smartlist_add(parsed->intro_nodes, intro);
  3147. }
  3148. result = smartlist_len(parsed->intro_nodes);
  3149. goto done;
  3150. err:
  3151. result = -1;
  3152. done:
  3153. /* Free tokens and clear token list. */
  3154. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  3155. smartlist_free(tokens);
  3156. return result;
  3157. }