routerparse.c 100 KB

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