routerparse.c 115 KB

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