routerparse.c 140 KB

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