routerparse.c 137 KB

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