routerparse.c 139 KB

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