routerparse.c 78 KB

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