routerparse.c 99 KB

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