routerparse.c 115 KB

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