routerparse.c 98 KB

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