routerparse.c 99 KB

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