routerparse.c 132 KB

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