routerparse.c 136 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108
  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. router->onion_pkey = tok->key;
  1181. tok->key = NULL; /* Prevent free */
  1182. tok = find_by_keyword(tokens, K_SIGNING_KEY);
  1183. router->identity_pkey = tok->key;
  1184. tok->key = NULL; /* Prevent free */
  1185. if (crypto_pk_get_digest(router->identity_pkey,
  1186. router->cache_info.identity_digest)) {
  1187. log_warn(LD_DIR, "Couldn't calculate key digest"); goto err;
  1188. }
  1189. if ((tok = find_opt_by_keyword(tokens, K_FINGERPRINT))) {
  1190. /* If there's a fingerprint line, it must match the identity digest. */
  1191. char d[DIGEST_LEN];
  1192. tor_assert(tok->n_args == 1);
  1193. tor_strstrip(tok->args[0], " ");
  1194. if (base16_decode(d, DIGEST_LEN, tok->args[0], strlen(tok->args[0]))) {
  1195. log_warn(LD_DIR, "Couldn't decode router fingerprint %s",
  1196. escaped(tok->args[0]));
  1197. goto err;
  1198. }
  1199. if (tor_memneq(d,router->cache_info.identity_digest, DIGEST_LEN)) {
  1200. log_warn(LD_DIR, "Fingerprint '%s' does not match identity digest.",
  1201. tok->args[0]);
  1202. goto err;
  1203. }
  1204. }
  1205. if ((tok = find_opt_by_keyword(tokens, K_PLATFORM))) {
  1206. router->platform = tor_strdup(tok->args[0]);
  1207. }
  1208. if ((tok = find_opt_by_keyword(tokens, K_CONTACT))) {
  1209. router->contact_info = tor_strdup(tok->args[0]);
  1210. }
  1211. if ((tok = find_opt_by_keyword(tokens, K_EVENTDNS))) {
  1212. router->has_old_dnsworkers = tok->n_args && !strcmp(tok->args[0], "0");
  1213. } else if (router->platform) {
  1214. if (! tor_version_as_new_as(router->platform, "0.1.2.2-alpha"))
  1215. router->has_old_dnsworkers = 1;
  1216. }
  1217. if (find_opt_by_keyword(tokens, K_REJECT6) ||
  1218. find_opt_by_keyword(tokens, K_ACCEPT6)) {
  1219. log_warn(LD_DIR, "Rejecting router with reject6/accept6 line: they crash "
  1220. "older Tors.");
  1221. goto err;
  1222. }
  1223. exit_policy_tokens = find_all_exitpolicy(tokens);
  1224. if (!smartlist_len(exit_policy_tokens)) {
  1225. log_warn(LD_DIR, "No exit policy tokens in descriptor.");
  1226. goto err;
  1227. }
  1228. SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
  1229. if (router_add_exit_policy(router,t)<0) {
  1230. log_warn(LD_DIR,"Error in exit policy");
  1231. goto err;
  1232. });
  1233. policy_expand_private(&router->exit_policy);
  1234. if (policy_is_reject_star(router->exit_policy))
  1235. router->policy_is_reject_star = 1;
  1236. if ((tok = find_opt_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
  1237. int i;
  1238. router->declared_family = smartlist_create();
  1239. for (i=0;i<tok->n_args;++i) {
  1240. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  1241. log_warn(LD_DIR, "Illegal nickname %s in family line",
  1242. escaped(tok->args[i]));
  1243. goto err;
  1244. }
  1245. smartlist_add(router->declared_family, tor_strdup(tok->args[i]));
  1246. }
  1247. }
  1248. if ((tok = find_opt_by_keyword(tokens, K_CACHES_EXTRA_INFO)))
  1249. router->caches_extra_info = 1;
  1250. if ((tok = find_opt_by_keyword(tokens, K_ALLOW_SINGLE_HOP_EXITS)))
  1251. router->allow_single_hop_exits = 1;
  1252. if ((tok = find_opt_by_keyword(tokens, K_EXTRA_INFO_DIGEST))) {
  1253. tor_assert(tok->n_args >= 1);
  1254. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  1255. base16_decode(router->cache_info.extra_info_digest,
  1256. DIGEST_LEN, tok->args[0], HEX_DIGEST_LEN);
  1257. } else {
  1258. log_warn(LD_DIR, "Invalid extra info digest %s", escaped(tok->args[0]));
  1259. }
  1260. }
  1261. if ((tok = find_opt_by_keyword(tokens, K_HIDDEN_SERVICE_DIR))) {
  1262. router->wants_to_be_hs_dir = 1;
  1263. }
  1264. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1265. note_crypto_pk_op(VERIFY_RTR);
  1266. #ifdef COUNT_DISTINCT_DIGESTS
  1267. if (!verified_digests)
  1268. verified_digests = digestmap_new();
  1269. digestmap_set(verified_digests, signed_digest, (void*)(uintptr_t)1);
  1270. #endif
  1271. if (check_signature_token(digest, tok, router->identity_pkey, 0,
  1272. "router descriptor") < 0)
  1273. goto err;
  1274. routerinfo_set_country(router);
  1275. if (!router->or_port) {
  1276. log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
  1277. goto err;
  1278. }
  1279. if (!router->platform) {
  1280. router->platform = tor_strdup("<unknown>");
  1281. }
  1282. goto done;
  1283. err:
  1284. routerinfo_free(router);
  1285. router = NULL;
  1286. done:
  1287. if (tokens) {
  1288. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1289. smartlist_free(tokens);
  1290. }
  1291. if (exit_policy_tokens) {
  1292. smartlist_free(exit_policy_tokens);
  1293. }
  1294. if (area) {
  1295. DUMP_AREA(area, "routerinfo");
  1296. memarea_drop_all(area);
  1297. }
  1298. return router;
  1299. }
  1300. /** Parse a single extrainfo entry from the string <b>s</b>, ending at
  1301. * <b>end</b>. (If <b>end</b> is NULL, parse up to the end of <b>s</b>.) If
  1302. * <b>cache_copy</b> is true, make a copy of the extra-info document in the
  1303. * cache_info fields of the result. If <b>routermap</b> is provided, use it
  1304. * as a map from router identity to routerinfo_t when looking up signing keys.
  1305. */
  1306. extrainfo_t *
  1307. extrainfo_parse_entry_from_string(const char *s, const char *end,
  1308. int cache_copy, struct digest_ri_map_t *routermap)
  1309. {
  1310. extrainfo_t *extrainfo = NULL;
  1311. char digest[128];
  1312. smartlist_t *tokens = NULL;
  1313. directory_token_t *tok;
  1314. crypto_pk_env_t *key = NULL;
  1315. routerinfo_t *router = NULL;
  1316. memarea_t *area = NULL;
  1317. if (!end) {
  1318. end = s + strlen(s);
  1319. }
  1320. /* point 'end' to a point immediately after the final newline. */
  1321. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  1322. --end;
  1323. if (router_get_extrainfo_hash(s, digest) < 0) {
  1324. log_warn(LD_DIR, "Couldn't compute router hash.");
  1325. goto err;
  1326. }
  1327. tokens = smartlist_create();
  1328. area = memarea_new();
  1329. if (tokenize_string(area,s,end,tokens,extrainfo_token_table,0)) {
  1330. log_warn(LD_DIR, "Error tokenizing extra-info document.");
  1331. goto err;
  1332. }
  1333. if (smartlist_len(tokens) < 2) {
  1334. log_warn(LD_DIR, "Impossibly short extra-info document.");
  1335. goto err;
  1336. }
  1337. tok = smartlist_get(tokens,0);
  1338. if (tok->tp != K_EXTRA_INFO) {
  1339. log_warn(LD_DIR,"Entry does not start with \"extra-info\"");
  1340. goto err;
  1341. }
  1342. extrainfo = tor_malloc_zero(sizeof(extrainfo_t));
  1343. extrainfo->cache_info.is_extrainfo = 1;
  1344. if (cache_copy)
  1345. extrainfo->cache_info.signed_descriptor_body = tor_strndup(s, end-s);
  1346. extrainfo->cache_info.signed_descriptor_len = end-s;
  1347. memcpy(extrainfo->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1348. tor_assert(tok->n_args >= 2);
  1349. if (!is_legal_nickname(tok->args[0])) {
  1350. log_warn(LD_DIR,"Bad nickname %s on \"extra-info\"",escaped(tok->args[0]));
  1351. goto err;
  1352. }
  1353. strlcpy(extrainfo->nickname, tok->args[0], sizeof(extrainfo->nickname));
  1354. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  1355. base16_decode(extrainfo->cache_info.identity_digest, DIGEST_LEN,
  1356. tok->args[1], HEX_DIGEST_LEN)) {
  1357. log_warn(LD_DIR,"Invalid fingerprint %s on \"extra-info\"",
  1358. escaped(tok->args[1]));
  1359. goto err;
  1360. }
  1361. tok = find_by_keyword(tokens, K_PUBLISHED);
  1362. if (parse_iso_time(tok->args[0], &extrainfo->cache_info.published_on)) {
  1363. log_warn(LD_DIR,"Invalid published time %s on \"extra-info\"",
  1364. escaped(tok->args[0]));
  1365. goto err;
  1366. }
  1367. if (routermap &&
  1368. (router = digestmap_get((digestmap_t*)routermap,
  1369. extrainfo->cache_info.identity_digest))) {
  1370. key = router->identity_pkey;
  1371. }
  1372. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1373. if (strcmp(tok->object_type, "SIGNATURE") ||
  1374. tok->object_size < 128 || tok->object_size > 512) {
  1375. log_warn(LD_DIR, "Bad object type or length on extra-info signature");
  1376. goto err;
  1377. }
  1378. if (key) {
  1379. note_crypto_pk_op(VERIFY_RTR);
  1380. if (check_signature_token(digest, tok, key, 0, "extra-info") < 0)
  1381. goto err;
  1382. if (router)
  1383. extrainfo->cache_info.send_unencrypted =
  1384. router->cache_info.send_unencrypted;
  1385. } else {
  1386. extrainfo->pending_sig = tor_memdup(tok->object_body,
  1387. tok->object_size);
  1388. extrainfo->pending_sig_len = tok->object_size;
  1389. }
  1390. goto done;
  1391. err:
  1392. if (extrainfo)
  1393. extrainfo_free(extrainfo);
  1394. extrainfo = NULL;
  1395. done:
  1396. if (tokens) {
  1397. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1398. smartlist_free(tokens);
  1399. }
  1400. if (area) {
  1401. DUMP_AREA(area, "extrainfo");
  1402. memarea_drop_all(area);
  1403. }
  1404. return extrainfo;
  1405. }
  1406. /** Parse a key certificate from <b>s</b>; point <b>end-of-string</b> to
  1407. * the first character after the certificate. */
  1408. authority_cert_t *
  1409. authority_cert_parse_from_string(const char *s, const char **end_of_string)
  1410. {
  1411. /** Reject any certificate at least this big; it is probably an overflow, an
  1412. * attack, a bug, or some other nonsense. */
  1413. #define MAX_CERT_SIZE (128*1024)
  1414. authority_cert_t *cert = NULL, *old_cert;
  1415. smartlist_t *tokens = NULL;
  1416. char digest[DIGEST_LEN];
  1417. directory_token_t *tok;
  1418. char fp_declared[DIGEST_LEN];
  1419. char *eos;
  1420. size_t len;
  1421. int found;
  1422. memarea_t *area = NULL;
  1423. s = eat_whitespace(s);
  1424. eos = strstr(s, "\ndir-key-certification");
  1425. if (! eos) {
  1426. log_warn(LD_DIR, "No signature found on key certificate");
  1427. return NULL;
  1428. }
  1429. eos = strstr(eos, "\n-----END SIGNATURE-----\n");
  1430. if (! eos) {
  1431. log_warn(LD_DIR, "No end-of-signature found on key certificate");
  1432. return NULL;
  1433. }
  1434. eos = strchr(eos+2, '\n');
  1435. tor_assert(eos);
  1436. ++eos;
  1437. len = eos - s;
  1438. if (len > MAX_CERT_SIZE) {
  1439. log_warn(LD_DIR, "Certificate is far too big (at %lu bytes long); "
  1440. "rejecting", (unsigned long)len);
  1441. return NULL;
  1442. }
  1443. tokens = smartlist_create();
  1444. area = memarea_new();
  1445. if (tokenize_string(area,s, eos, tokens, dir_key_certificate_table, 0) < 0) {
  1446. log_warn(LD_DIR, "Error tokenizing key certificate");
  1447. goto err;
  1448. }
  1449. if (router_get_hash_impl(s, strlen(s), digest, "dir-key-certificate-version",
  1450. "\ndir-key-certification", '\n') < 0)
  1451. goto err;
  1452. tok = smartlist_get(tokens, 0);
  1453. if (tok->tp != K_DIR_KEY_CERTIFICATE_VERSION || strcmp(tok->args[0], "3")) {
  1454. log_warn(LD_DIR,
  1455. "Key certificate does not begin with a recognized version (3).");
  1456. goto err;
  1457. }
  1458. cert = tor_malloc_zero(sizeof(authority_cert_t));
  1459. memcpy(cert->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1460. tok = find_by_keyword(tokens, K_DIR_SIGNING_KEY);
  1461. tor_assert(tok->key);
  1462. cert->signing_key = tok->key;
  1463. tok->key = NULL;
  1464. if (crypto_pk_get_digest(cert->signing_key, cert->signing_key_digest))
  1465. goto err;
  1466. tok = find_by_keyword(tokens, K_DIR_IDENTITY_KEY);
  1467. tor_assert(tok->key);
  1468. cert->identity_key = tok->key;
  1469. tok->key = NULL;
  1470. tok = find_by_keyword(tokens, K_FINGERPRINT);
  1471. tor_assert(tok->n_args);
  1472. if (base16_decode(fp_declared, DIGEST_LEN, tok->args[0],
  1473. strlen(tok->args[0]))) {
  1474. log_warn(LD_DIR, "Couldn't decode key certificate fingerprint %s",
  1475. escaped(tok->args[0]));
  1476. goto err;
  1477. }
  1478. if (crypto_pk_get_digest(cert->identity_key,
  1479. cert->cache_info.identity_digest))
  1480. goto err;
  1481. if (tor_memneq(cert->cache_info.identity_digest, fp_declared, DIGEST_LEN)) {
  1482. log_warn(LD_DIR, "Digest of certificate key didn't match declared "
  1483. "fingerprint");
  1484. goto err;
  1485. }
  1486. tok = find_opt_by_keyword(tokens, K_DIR_ADDRESS);
  1487. if (tok) {
  1488. struct in_addr in;
  1489. char *address = NULL;
  1490. tor_assert(tok->n_args);
  1491. /* XXX021 use tor_addr_port_parse() below instead. -RD */
  1492. if (parse_addr_port(LOG_WARN, tok->args[0], &address, NULL,
  1493. &cert->dir_port)<0 ||
  1494. tor_inet_aton(address, &in) == 0) {
  1495. log_warn(LD_DIR, "Couldn't parse dir-address in certificate");
  1496. tor_free(address);
  1497. goto err;
  1498. }
  1499. cert->addr = ntohl(in.s_addr);
  1500. tor_free(address);
  1501. }
  1502. tok = find_by_keyword(tokens, K_DIR_KEY_PUBLISHED);
  1503. if (parse_iso_time(tok->args[0], &cert->cache_info.published_on) < 0) {
  1504. goto err;
  1505. }
  1506. tok = find_by_keyword(tokens, K_DIR_KEY_EXPIRES);
  1507. if (parse_iso_time(tok->args[0], &cert->expires) < 0) {
  1508. goto err;
  1509. }
  1510. tok = smartlist_get(tokens, smartlist_len(tokens)-1);
  1511. if (tok->tp != K_DIR_KEY_CERTIFICATION) {
  1512. log_warn(LD_DIR, "Certificate didn't end with dir-key-certification.");
  1513. goto err;
  1514. }
  1515. /* If we already have this cert, don't bother checking the signature. */
  1516. old_cert = authority_cert_get_by_digests(
  1517. cert->cache_info.identity_digest,
  1518. cert->signing_key_digest);
  1519. found = 0;
  1520. if (old_cert) {
  1521. /* XXXX We could just compare signed_descriptor_digest, but that wouldn't
  1522. * buy us much. */
  1523. if (old_cert->cache_info.signed_descriptor_len == len &&
  1524. old_cert->cache_info.signed_descriptor_body &&
  1525. tor_memeq(s, old_cert->cache_info.signed_descriptor_body, len)) {
  1526. log_debug(LD_DIR, "We already checked the signature on this "
  1527. "certificate; no need to do so again.");
  1528. found = 1;
  1529. cert->is_cross_certified = old_cert->is_cross_certified;
  1530. }
  1531. }
  1532. if (!found) {
  1533. if (check_signature_token(digest, tok, cert->identity_key, 0,
  1534. "key certificate")) {
  1535. goto err;
  1536. }
  1537. if ((tok = find_opt_by_keyword(tokens, K_DIR_KEY_CROSSCERT))) {
  1538. /* XXXX Once all authorities generate cross-certified certificates,
  1539. * make this field mandatory. */
  1540. if (check_signature_token(cert->cache_info.identity_digest,
  1541. tok,
  1542. cert->signing_key,
  1543. CST_NO_CHECK_OBJTYPE,
  1544. "key cross-certification")) {
  1545. goto err;
  1546. }
  1547. cert->is_cross_certified = 1;
  1548. }
  1549. }
  1550. cert->cache_info.signed_descriptor_len = len;
  1551. cert->cache_info.signed_descriptor_body = tor_malloc(len+1);
  1552. memcpy(cert->cache_info.signed_descriptor_body, s, len);
  1553. cert->cache_info.signed_descriptor_body[len] = 0;
  1554. cert->cache_info.saved_location = SAVED_NOWHERE;
  1555. if (end_of_string) {
  1556. *end_of_string = eat_whitespace(eos);
  1557. }
  1558. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1559. smartlist_free(tokens);
  1560. if (area) {
  1561. DUMP_AREA(area, "authority cert");
  1562. memarea_drop_all(area);
  1563. }
  1564. return cert;
  1565. err:
  1566. authority_cert_free(cert);
  1567. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1568. smartlist_free(tokens);
  1569. if (area) {
  1570. DUMP_AREA(area, "authority cert");
  1571. memarea_drop_all(area);
  1572. }
  1573. return NULL;
  1574. }
  1575. /** Helper: given a string <b>s</b>, return the start of the next router-status
  1576. * object (starting with "r " at the start of a line). If none is found,
  1577. * return the start of the next directory signature. If none is found, return
  1578. * the end of the string. */
  1579. static INLINE const char *
  1580. find_start_of_next_routerstatus(const char *s)
  1581. {
  1582. const char *eos = strstr(s, "\nr ");
  1583. if (eos) {
  1584. const char *eos2 = tor_memstr(s, eos-s, "\ndirectory-signature");
  1585. if (eos2 && eos2 < eos)
  1586. return eos2;
  1587. else
  1588. return eos+1;
  1589. } else {
  1590. if ((eos = strstr(s, "\ndirectory-signature")))
  1591. return eos+1;
  1592. return s + strlen(s);
  1593. }
  1594. }
  1595. /** Given a string at *<b>s</b>, containing a routerstatus object, and an
  1596. * empty smartlist at <b>tokens</b>, parse and return the first router status
  1597. * object in the string, and advance *<b>s</b> to just after the end of the
  1598. * router status. Return NULL and advance *<b>s</b> on error.
  1599. *
  1600. * If <b>vote</b> and <b>vote_rs</b> are provided, don't allocate a fresh
  1601. * routerstatus but use <b>vote_rs</b> instead.
  1602. *
  1603. * If <b>consensus_method</b> is nonzero, this routerstatus is part of a
  1604. * consensus, and we should parse it according to the method used to
  1605. * make that consensus.
  1606. **/
  1607. static routerstatus_t *
  1608. routerstatus_parse_entry_from_string(memarea_t *area,
  1609. const char **s, smartlist_t *tokens,
  1610. networkstatus_t *vote,
  1611. vote_routerstatus_t *vote_rs,
  1612. int consensus_method)
  1613. {
  1614. const char *eos;
  1615. routerstatus_t *rs = NULL;
  1616. directory_token_t *tok;
  1617. char timebuf[ISO_TIME_LEN+1];
  1618. struct in_addr in;
  1619. tor_assert(tokens);
  1620. tor_assert(bool_eq(vote, vote_rs));
  1621. eos = find_start_of_next_routerstatus(*s);
  1622. if (tokenize_string(area,*s, eos, tokens, rtrstatus_token_table,0)) {
  1623. log_warn(LD_DIR, "Error tokenizing router status");
  1624. goto err;
  1625. }
  1626. if (smartlist_len(tokens) < 1) {
  1627. log_warn(LD_DIR, "Impossibly short router status");
  1628. goto err;
  1629. }
  1630. tok = find_by_keyword(tokens, K_R);
  1631. tor_assert(tok->n_args >= 8);
  1632. if (vote_rs) {
  1633. rs = &vote_rs->status;
  1634. } else {
  1635. rs = tor_malloc_zero(sizeof(routerstatus_t));
  1636. }
  1637. if (!is_legal_nickname(tok->args[0])) {
  1638. log_warn(LD_DIR,
  1639. "Invalid nickname %s in router status; skipping.",
  1640. escaped(tok->args[0]));
  1641. goto err;
  1642. }
  1643. strlcpy(rs->nickname, tok->args[0], sizeof(rs->nickname));
  1644. if (digest_from_base64(rs->identity_digest, tok->args[1])) {
  1645. log_warn(LD_DIR, "Error decoding identity digest %s",
  1646. escaped(tok->args[1]));
  1647. goto err;
  1648. }
  1649. if (digest_from_base64(rs->descriptor_digest, tok->args[2])) {
  1650. log_warn(LD_DIR, "Error decoding descriptor digest %s",
  1651. escaped(tok->args[2]));
  1652. goto err;
  1653. }
  1654. if (tor_snprintf(timebuf, sizeof(timebuf), "%s %s",
  1655. tok->args[3], tok->args[4]) < 0 ||
  1656. parse_iso_time(timebuf, &rs->published_on)<0) {
  1657. log_warn(LD_DIR, "Error parsing time '%s %s'",
  1658. tok->args[3], tok->args[4]);
  1659. goto err;
  1660. }
  1661. if (tor_inet_aton(tok->args[5], &in) == 0) {
  1662. log_warn(LD_DIR, "Error parsing router address in network-status %s",
  1663. escaped(tok->args[5]));
  1664. goto err;
  1665. }
  1666. rs->addr = ntohl(in.s_addr);
  1667. rs->or_port =(uint16_t) tor_parse_long(tok->args[6],10,0,65535,NULL,NULL);
  1668. rs->dir_port = (uint16_t) tor_parse_long(tok->args[7],10,0,65535,NULL,NULL);
  1669. tok = find_opt_by_keyword(tokens, K_S);
  1670. if (tok && vote) {
  1671. int i;
  1672. vote_rs->flags = 0;
  1673. for (i=0; i < tok->n_args; ++i) {
  1674. int p = smartlist_string_pos(vote->known_flags, tok->args[i]);
  1675. if (p >= 0) {
  1676. vote_rs->flags |= (1<<p);
  1677. } else {
  1678. log_warn(LD_DIR, "Flags line had a flag %s not listed in known_flags.",
  1679. escaped(tok->args[i]));
  1680. goto err;
  1681. }
  1682. }
  1683. } else if (tok) {
  1684. int i;
  1685. for (i=0; i < tok->n_args; ++i) {
  1686. if (!strcmp(tok->args[i], "Exit"))
  1687. rs->is_exit = 1;
  1688. else if (!strcmp(tok->args[i], "Stable"))
  1689. rs->is_stable = 1;
  1690. else if (!strcmp(tok->args[i], "Fast"))
  1691. rs->is_fast = 1;
  1692. else if (!strcmp(tok->args[i], "Running"))
  1693. rs->is_running = 1;
  1694. else if (!strcmp(tok->args[i], "Named"))
  1695. rs->is_named = 1;
  1696. else if (!strcmp(tok->args[i], "Valid"))
  1697. rs->is_valid = 1;
  1698. else if (!strcmp(tok->args[i], "V2Dir"))
  1699. rs->is_v2_dir = 1;
  1700. else if (!strcmp(tok->args[i], "Guard"))
  1701. rs->is_possible_guard = 1;
  1702. else if (!strcmp(tok->args[i], "BadExit"))
  1703. rs->is_bad_exit = 1;
  1704. else if (!strcmp(tok->args[i], "BadDirectory"))
  1705. rs->is_bad_directory = 1;
  1706. else if (!strcmp(tok->args[i], "Authority"))
  1707. rs->is_authority = 1;
  1708. else if (!strcmp(tok->args[i], "Unnamed") &&
  1709. consensus_method >= 2) {
  1710. /* Unnamed is computed right by consensus method 2 and later. */
  1711. rs->is_unnamed = 1;
  1712. } else if (!strcmp(tok->args[i], "HSDir")) {
  1713. rs->is_hs_dir = 1;
  1714. }
  1715. }
  1716. }
  1717. if ((tok = find_opt_by_keyword(tokens, K_V))) {
  1718. tor_assert(tok->n_args == 1);
  1719. rs->version_known = 1;
  1720. if (strcmpstart(tok->args[0], "Tor ")) {
  1721. rs->version_supports_begindir = 1;
  1722. rs->version_supports_extrainfo_upload = 1;
  1723. rs->version_supports_conditional_consensus = 1;
  1724. } else {
  1725. rs->version_supports_begindir =
  1726. tor_version_as_new_as(tok->args[0], "0.2.0.1-alpha");
  1727. rs->version_supports_extrainfo_upload =
  1728. tor_version_as_new_as(tok->args[0], "0.2.0.0-alpha-dev (r10070)");
  1729. rs->version_supports_v3_dir =
  1730. tor_version_as_new_as(tok->args[0], "0.2.0.8-alpha");
  1731. rs->version_supports_conditional_consensus =
  1732. tor_version_as_new_as(tok->args[0], "0.2.1.1-alpha");
  1733. }
  1734. if (vote_rs) {
  1735. vote_rs->version = tor_strdup(tok->args[0]);
  1736. }
  1737. }
  1738. /* handle weighting/bandwidth info */
  1739. if ((tok = find_opt_by_keyword(tokens, K_W))) {
  1740. int i;
  1741. for (i=0; i < tok->n_args; ++i) {
  1742. if (!strcmpstart(tok->args[i], "Bandwidth=")) {
  1743. int ok;
  1744. rs->bandwidth = (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
  1745. 10, 0, UINT32_MAX,
  1746. &ok, NULL);
  1747. if (!ok) {
  1748. log_warn(LD_DIR, "Invalid Bandwidth %s", escaped(tok->args[i]));
  1749. goto err;
  1750. }
  1751. rs->has_bandwidth = 1;
  1752. }
  1753. }
  1754. }
  1755. /* parse exit policy summaries */
  1756. if ((tok = find_opt_by_keyword(tokens, K_P))) {
  1757. tor_assert(tok->n_args == 1);
  1758. if (strcmpstart(tok->args[0], "accept ") &&
  1759. strcmpstart(tok->args[0], "reject ")) {
  1760. log_warn(LD_DIR, "Unknown exit policy summary type %s.",
  1761. escaped(tok->args[0]));
  1762. goto err;
  1763. }
  1764. /* XXX weasel: parse this into ports and represent them somehow smart,
  1765. * maybe not here but somewhere on if we need it for the client.
  1766. * we should still parse it here to check it's valid tho.
  1767. */
  1768. rs->exitsummary = tor_strdup(tok->args[0]);
  1769. rs->has_exitsummary = 1;
  1770. }
  1771. if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME))
  1772. rs->is_named = 0;
  1773. goto done;
  1774. err:
  1775. if (rs && !vote_rs)
  1776. routerstatus_free(rs);
  1777. rs = NULL;
  1778. done:
  1779. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1780. smartlist_clear(tokens);
  1781. if (area) {
  1782. DUMP_AREA(area, "routerstatus entry");
  1783. memarea_clear(area);
  1784. }
  1785. *s = eos;
  1786. return rs;
  1787. }
  1788. /** Helper to sort a smartlist of pointers to routerstatus_t */
  1789. static int
  1790. _compare_routerstatus_entries(const void **_a, const void **_b)
  1791. {
  1792. const routerstatus_t *a = *_a, *b = *_b;
  1793. return fast_memcmp(a->identity_digest, b->identity_digest, DIGEST_LEN);
  1794. }
  1795. /** Helper: used in call to _smartlist_uniq to clear out duplicate entries. */
  1796. static void
  1797. _free_duplicate_routerstatus_entry(void *e)
  1798. {
  1799. log_warn(LD_DIR,
  1800. "Network-status has two entries for the same router. "
  1801. "Dropping one.");
  1802. routerstatus_free(e);
  1803. }
  1804. /** Given a v2 network-status object in <b>s</b>, try to
  1805. * parse it and return the result. Return NULL on failure. Check the
  1806. * signature of the network status, but do not (yet) check the signing key for
  1807. * authority.
  1808. */
  1809. networkstatus_v2_t *
  1810. networkstatus_v2_parse_from_string(const char *s)
  1811. {
  1812. const char *eos;
  1813. smartlist_t *tokens = smartlist_create();
  1814. smartlist_t *footer_tokens = smartlist_create();
  1815. networkstatus_v2_t *ns = NULL;
  1816. char ns_digest[DIGEST_LEN];
  1817. char tmp_digest[DIGEST_LEN];
  1818. struct in_addr in;
  1819. directory_token_t *tok;
  1820. int i;
  1821. memarea_t *area = NULL;
  1822. if (router_get_networkstatus_v2_hash(s, ns_digest)) {
  1823. log_warn(LD_DIR, "Unable to compute digest of network-status");
  1824. goto err;
  1825. }
  1826. area = memarea_new();
  1827. eos = find_start_of_next_routerstatus(s);
  1828. if (tokenize_string(area, s, eos, tokens, netstatus_token_table,0)) {
  1829. log_warn(LD_DIR, "Error tokenizing network-status header.");
  1830. goto err;
  1831. }
  1832. ns = tor_malloc_zero(sizeof(networkstatus_v2_t));
  1833. memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN);
  1834. tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
  1835. tor_assert(tok->n_args >= 1);
  1836. if (strcmp(tok->args[0], "2")) {
  1837. log_warn(LD_BUG, "Got a non-v2 networkstatus. Version was "
  1838. "%s", escaped(tok->args[0]));
  1839. goto err;
  1840. }
  1841. tok = find_by_keyword(tokens, K_DIR_SOURCE);
  1842. tor_assert(tok->n_args >= 3);
  1843. ns->source_address = tor_strdup(tok->args[0]);
  1844. if (tor_inet_aton(tok->args[1], &in) == 0) {
  1845. log_warn(LD_DIR, "Error parsing network-status source address %s",
  1846. escaped(tok->args[1]));
  1847. goto err;
  1848. }
  1849. ns->source_addr = ntohl(in.s_addr);
  1850. ns->source_dirport =
  1851. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
  1852. if (ns->source_dirport == 0) {
  1853. log_warn(LD_DIR, "Directory source without dirport; skipping.");
  1854. goto err;
  1855. }
  1856. tok = find_by_keyword(tokens, K_FINGERPRINT);
  1857. tor_assert(tok->n_args);
  1858. if (base16_decode(ns->identity_digest, DIGEST_LEN, tok->args[0],
  1859. strlen(tok->args[0]))) {
  1860. log_warn(LD_DIR, "Couldn't decode networkstatus fingerprint %s",
  1861. escaped(tok->args[0]));
  1862. goto err;
  1863. }
  1864. if ((tok = find_opt_by_keyword(tokens, K_CONTACT))) {
  1865. tor_assert(tok->n_args);
  1866. ns->contact = tor_strdup(tok->args[0]);
  1867. }
  1868. tok = find_by_keyword(tokens, K_DIR_SIGNING_KEY);
  1869. tor_assert(tok->key);
  1870. ns->signing_key = tok->key;
  1871. tok->key = NULL;
  1872. if (crypto_pk_get_digest(ns->signing_key, tmp_digest)<0) {
  1873. log_warn(LD_DIR, "Couldn't compute signing key digest");
  1874. goto err;
  1875. }
  1876. if (tor_memneq(tmp_digest, ns->identity_digest, DIGEST_LEN)) {
  1877. log_warn(LD_DIR,
  1878. "network-status fingerprint did not match dir-signing-key");
  1879. goto err;
  1880. }
  1881. if ((tok = find_opt_by_keyword(tokens, K_DIR_OPTIONS))) {
  1882. for (i=0; i < tok->n_args; ++i) {
  1883. if (!strcmp(tok->args[i], "Names"))
  1884. ns->binds_names = 1;
  1885. if (!strcmp(tok->args[i], "Versions"))
  1886. ns->recommends_versions = 1;
  1887. if (!strcmp(tok->args[i], "BadExits"))
  1888. ns->lists_bad_exits = 1;
  1889. if (!strcmp(tok->args[i], "BadDirectories"))
  1890. ns->lists_bad_directories = 1;
  1891. }
  1892. }
  1893. if (ns->recommends_versions) {
  1894. if (!(tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  1895. log_warn(LD_DIR, "Missing client-versions on versioning directory");
  1896. goto err;
  1897. }
  1898. ns->client_versions = tor_strdup(tok->args[0]);
  1899. if (!(tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS)) ||
  1900. tok->n_args<1) {
  1901. log_warn(LD_DIR, "Missing server-versions on versioning directory");
  1902. goto err;
  1903. }
  1904. ns->server_versions = tor_strdup(tok->args[0]);
  1905. }
  1906. tok = find_by_keyword(tokens, K_PUBLISHED);
  1907. tor_assert(tok->n_args == 1);
  1908. if (parse_iso_time(tok->args[0], &ns->published_on) < 0) {
  1909. goto err;
  1910. }
  1911. ns->entries = smartlist_create();
  1912. s = eos;
  1913. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1914. smartlist_clear(tokens);
  1915. memarea_clear(area);
  1916. while (!strcmpstart(s, "r ")) {
  1917. routerstatus_t *rs;
  1918. if ((rs = routerstatus_parse_entry_from_string(area, &s, tokens,
  1919. NULL, NULL, 0)))
  1920. smartlist_add(ns->entries, rs);
  1921. }
  1922. smartlist_sort(ns->entries, _compare_routerstatus_entries);
  1923. smartlist_uniq(ns->entries, _compare_routerstatus_entries,
  1924. _free_duplicate_routerstatus_entry);
  1925. if (tokenize_string(area,s, NULL, footer_tokens, dir_footer_token_table,0)) {
  1926. log_warn(LD_DIR, "Error tokenizing network-status footer.");
  1927. goto err;
  1928. }
  1929. if (smartlist_len(footer_tokens) < 1) {
  1930. log_warn(LD_DIR, "Too few items in network-status footer.");
  1931. goto err;
  1932. }
  1933. tok = smartlist_get(footer_tokens, smartlist_len(footer_tokens)-1);
  1934. if (tok->tp != K_DIRECTORY_SIGNATURE) {
  1935. log_warn(LD_DIR,
  1936. "Expected network-status footer to end with a signature.");
  1937. goto err;
  1938. }
  1939. note_crypto_pk_op(VERIFY_DIR);
  1940. if (check_signature_token(ns_digest, tok, ns->signing_key, 0,
  1941. "network-status") < 0)
  1942. goto err;
  1943. goto done;
  1944. err:
  1945. if (ns)
  1946. networkstatus_v2_free(ns);
  1947. ns = NULL;
  1948. done:
  1949. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1950. smartlist_free(tokens);
  1951. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_free(t));
  1952. smartlist_free(footer_tokens);
  1953. if (area) {
  1954. DUMP_AREA(area, "v2 networkstatus");
  1955. memarea_drop_all(area);
  1956. }
  1957. return ns;
  1958. }
  1959. /** Parse a v3 networkstatus vote, opinion, or consensus (depending on
  1960. * ns_type), from <b>s</b>, and return the result. Return NULL on failure. */
  1961. networkstatus_t *
  1962. networkstatus_parse_vote_from_string(const char *s, const char **eos_out,
  1963. networkstatus_type_t ns_type)
  1964. {
  1965. smartlist_t *tokens = smartlist_create();
  1966. smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;
  1967. networkstatus_voter_info_t *voter = NULL;
  1968. networkstatus_t *ns = NULL;
  1969. char ns_digest[DIGEST_LEN];
  1970. const char *cert, *end_of_header, *end_of_footer;
  1971. directory_token_t *tok;
  1972. int ok;
  1973. struct in_addr in;
  1974. int i, inorder, n_signatures = 0;
  1975. memarea_t *area = NULL, *rs_area = NULL;
  1976. tor_assert(s);
  1977. if (eos_out)
  1978. *eos_out = NULL;
  1979. if (router_get_networkstatus_v3_hash(s, ns_digest)) {
  1980. log_warn(LD_DIR, "Unable to compute digest of network-status");
  1981. goto err;
  1982. }
  1983. area = memarea_new();
  1984. end_of_header = find_start_of_next_routerstatus(s);
  1985. if (tokenize_string(area, s, end_of_header, tokens,
  1986. (ns_type == NS_TYPE_CONSENSUS) ?
  1987. networkstatus_consensus_token_table :
  1988. networkstatus_token_table, 0)) {
  1989. log_warn(LD_DIR, "Error tokenizing network-status vote header");
  1990. goto err;
  1991. }
  1992. ns = tor_malloc_zero(sizeof(networkstatus_t));
  1993. memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN);
  1994. if (ns_type != NS_TYPE_CONSENSUS) {
  1995. const char *end_of_cert = NULL;
  1996. if (!(cert = strstr(s, "\ndir-key-certificate-version")))
  1997. goto err;
  1998. ++cert;
  1999. ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);
  2000. if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)
  2001. goto err;
  2002. }
  2003. tok = find_by_keyword(tokens, K_VOTE_STATUS);
  2004. tor_assert(tok->n_args);
  2005. if (!strcmp(tok->args[0], "vote")) {
  2006. ns->type = NS_TYPE_VOTE;
  2007. } else if (!strcmp(tok->args[0], "consensus")) {
  2008. ns->type = NS_TYPE_CONSENSUS;
  2009. } else if (!strcmp(tok->args[0], "opinion")) {
  2010. ns->type = NS_TYPE_OPINION;
  2011. } else {
  2012. log_warn(LD_DIR, "Unrecognized vote status %s in network-status",
  2013. escaped(tok->args[0]));
  2014. goto err;
  2015. }
  2016. if (ns_type != ns->type) {
  2017. log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus.");
  2018. goto err;
  2019. }
  2020. if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
  2021. tok = find_by_keyword(tokens, K_PUBLISHED);
  2022. if (parse_iso_time(tok->args[0], &ns->published))
  2023. goto err;
  2024. ns->supported_methods = smartlist_create();
  2025. tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHODS);
  2026. if (tok) {
  2027. for (i=0; i < tok->n_args; ++i)
  2028. smartlist_add(ns->supported_methods, tor_strdup(tok->args[i]));
  2029. } else {
  2030. smartlist_add(ns->supported_methods, tor_strdup("1"));
  2031. }
  2032. } else {
  2033. tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHOD);
  2034. if (tok) {
  2035. ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX,
  2036. &ok, NULL);
  2037. if (!ok)
  2038. goto err;
  2039. } else {
  2040. ns->consensus_method = 1;
  2041. }
  2042. }
  2043. tok = find_by_keyword(tokens, K_VALID_AFTER);
  2044. if (parse_iso_time(tok->args[0], &ns->valid_after))
  2045. goto err;
  2046. tok = find_by_keyword(tokens, K_FRESH_UNTIL);
  2047. if (parse_iso_time(tok->args[0], &ns->fresh_until))
  2048. goto err;
  2049. tok = find_by_keyword(tokens, K_VALID_UNTIL);
  2050. if (parse_iso_time(tok->args[0], &ns->valid_until))
  2051. goto err;
  2052. tok = find_by_keyword(tokens, K_VOTING_DELAY);
  2053. tor_assert(tok->n_args >= 2);
  2054. ns->vote_seconds =
  2055. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);
  2056. if (!ok)
  2057. goto err;
  2058. ns->dist_seconds =
  2059. (int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL);
  2060. if (!ok)
  2061. goto err;
  2062. if (ns->valid_after + MIN_VOTE_INTERVAL > ns->fresh_until) {
  2063. log_warn(LD_DIR, "Vote/consensus freshness interval is too short");
  2064. goto err;
  2065. }
  2066. if (ns->valid_after + MIN_VOTE_INTERVAL*2 > ns->valid_until) {
  2067. log_warn(LD_DIR, "Vote/consensus liveness interval is too short");
  2068. goto err;
  2069. }
  2070. if (ns->vote_seconds < MIN_VOTE_SECONDS) {
  2071. log_warn(LD_DIR, "Vote seconds is too short");
  2072. goto err;
  2073. }
  2074. if (ns->dist_seconds < MIN_DIST_SECONDS) {
  2075. log_warn(LD_DIR, "Dist seconds is too short");
  2076. goto err;
  2077. }
  2078. if ((tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  2079. ns->client_versions = tor_strdup(tok->args[0]);
  2080. }
  2081. if ((tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS))) {
  2082. ns->server_versions = tor_strdup(tok->args[0]);
  2083. }
  2084. tok = find_by_keyword(tokens, K_KNOWN_FLAGS);
  2085. ns->known_flags = smartlist_create();
  2086. inorder = 1;
  2087. for (i = 0; i < tok->n_args; ++i) {
  2088. smartlist_add(ns->known_flags, tor_strdup(tok->args[i]));
  2089. if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) {
  2090. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  2091. inorder = 0;
  2092. }
  2093. }
  2094. if (!inorder) {
  2095. log_warn(LD_DIR, "known-flags not in order");
  2096. goto err;
  2097. }
  2098. tok = find_opt_by_keyword(tokens, K_PARAMS);
  2099. if (tok) {
  2100. inorder = 1;
  2101. ns->net_params = smartlist_create();
  2102. for (i = 0; i < tok->n_args; ++i) {
  2103. int ok=0;
  2104. char *eq = strchr(tok->args[i], '=');
  2105. if (!eq) {
  2106. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  2107. goto err;
  2108. }
  2109. tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
  2110. if (!ok) {
  2111. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  2112. goto err;
  2113. }
  2114. if (i > 0 && strcmp(tok->args[i-1], tok->args[i]) >= 0) {
  2115. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  2116. inorder = 0;
  2117. }
  2118. smartlist_add(ns->net_params, tor_strdup(tok->args[i]));
  2119. }
  2120. if (!inorder) {
  2121. log_warn(LD_DIR, "params not in order");
  2122. goto err;
  2123. }
  2124. }
  2125. ns->voters = smartlist_create();
  2126. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  2127. tok = _tok;
  2128. if (tok->tp == K_DIR_SOURCE) {
  2129. tor_assert(tok->n_args >= 6);
  2130. if (voter)
  2131. smartlist_add(ns->voters, voter);
  2132. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  2133. if (ns->type != NS_TYPE_CONSENSUS)
  2134. memcpy(voter->vote_digest, ns_digest, DIGEST_LEN);
  2135. voter->nickname = tor_strdup(tok->args[0]);
  2136. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  2137. base16_decode(voter->identity_digest, sizeof(voter->identity_digest),
  2138. tok->args[1], HEX_DIGEST_LEN) < 0) {
  2139. log_warn(LD_DIR, "Error decoding identity digest %s in "
  2140. "network-status vote.", escaped(tok->args[1]));
  2141. goto err;
  2142. }
  2143. if (ns->type != NS_TYPE_CONSENSUS &&
  2144. tor_memneq(ns->cert->cache_info.identity_digest,
  2145. voter->identity_digest, DIGEST_LEN)) {
  2146. log_warn(LD_DIR,"Mismatch between identities in certificate and vote");
  2147. goto err;
  2148. }
  2149. voter->address = tor_strdup(tok->args[2]);
  2150. if (!tor_inet_aton(tok->args[3], &in)) {
  2151. log_warn(LD_DIR, "Error decoding IP address %s in network-status.",
  2152. escaped(tok->args[3]));
  2153. goto err;
  2154. }
  2155. voter->addr = ntohl(in.s_addr);
  2156. voter->dir_port = (uint16_t)
  2157. tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);
  2158. if (!ok)
  2159. goto err;
  2160. voter->or_port = (uint16_t)
  2161. tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);
  2162. if (!ok)
  2163. goto err;
  2164. } else if (tok->tp == K_CONTACT) {
  2165. if (!voter || voter->contact) {
  2166. log_warn(LD_DIR, "contact element is out of place.");
  2167. goto err;
  2168. }
  2169. voter->contact = tor_strdup(tok->args[0]);
  2170. } else if (tok->tp == K_VOTE_DIGEST) {
  2171. tor_assert(ns->type == NS_TYPE_CONSENSUS);
  2172. tor_assert(tok->n_args >= 1);
  2173. if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {
  2174. log_warn(LD_DIR, "vote-digest element is out of place.");
  2175. goto err;
  2176. }
  2177. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  2178. base16_decode(voter->vote_digest, sizeof(voter->vote_digest),
  2179. tok->args[0], HEX_DIGEST_LEN) < 0) {
  2180. log_warn(LD_DIR, "Error decoding vote digest %s in "
  2181. "network-status consensus.", escaped(tok->args[0]));
  2182. goto err;
  2183. }
  2184. }
  2185. } SMARTLIST_FOREACH_END(_tok);
  2186. if (voter) {
  2187. smartlist_add(ns->voters, voter);
  2188. voter = NULL;
  2189. }
  2190. if (smartlist_len(ns->voters) == 0) {
  2191. log_warn(LD_DIR, "Missing dir-source elements in a vote networkstatus.");
  2192. goto err;
  2193. } else if (ns->type != NS_TYPE_CONSENSUS && smartlist_len(ns->voters) != 1) {
  2194. log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus.");
  2195. goto err;
  2196. }
  2197. if (ns->type != NS_TYPE_CONSENSUS &&
  2198. (tok = find_opt_by_keyword(tokens, K_LEGACY_DIR_KEY))) {
  2199. int bad = 1;
  2200. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  2201. networkstatus_voter_info_t *voter = smartlist_get(ns->voters, 0);
  2202. if (base16_decode(voter->legacy_id_digest, DIGEST_LEN,
  2203. tok->args[0], HEX_DIGEST_LEN)<0)
  2204. bad = 1;
  2205. else
  2206. bad = 0;
  2207. }
  2208. if (bad) {
  2209. log_warn(LD_DIR, "Invalid legacy key digest %s on vote.",
  2210. escaped(tok->args[0]));
  2211. }
  2212. }
  2213. /* Parse routerstatus lines. */
  2214. rs_tokens = smartlist_create();
  2215. rs_area = memarea_new();
  2216. s = end_of_header;
  2217. ns->routerstatus_list = smartlist_create();
  2218. while (!strcmpstart(s, "r ")) {
  2219. if (ns->type != NS_TYPE_CONSENSUS) {
  2220. vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  2221. if (routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, ns,
  2222. rs, 0))
  2223. smartlist_add(ns->routerstatus_list, rs);
  2224. else {
  2225. tor_free(rs->version);
  2226. tor_free(rs);
  2227. }
  2228. } else {
  2229. routerstatus_t *rs;
  2230. if ((rs = routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens,
  2231. NULL, NULL,
  2232. ns->consensus_method)))
  2233. smartlist_add(ns->routerstatus_list, rs);
  2234. }
  2235. }
  2236. for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {
  2237. routerstatus_t *rs1, *rs2;
  2238. if (ns->type != NS_TYPE_CONSENSUS) {
  2239. vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);
  2240. vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);
  2241. rs1 = &a->status; rs2 = &b->status;
  2242. } else {
  2243. rs1 = smartlist_get(ns->routerstatus_list, i-1);
  2244. rs2 = smartlist_get(ns->routerstatus_list, i);
  2245. }
  2246. if (fast_memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN)
  2247. >= 0) {
  2248. log_warn(LD_DIR, "Vote networkstatus entries not sorted by identity "
  2249. "digest");
  2250. goto err;
  2251. }
  2252. }
  2253. /* Parse footer; check signature. */
  2254. footer_tokens = smartlist_create();
  2255. if ((end_of_footer = strstr(s, "\nnetwork-status-version ")))
  2256. ++end_of_footer;
  2257. else
  2258. end_of_footer = s + strlen(s);
  2259. if (tokenize_string(area,s, end_of_footer, footer_tokens,
  2260. networkstatus_vote_footer_token_table, 0)) {
  2261. log_warn(LD_DIR, "Error tokenizing network-status vote footer.");
  2262. goto err;
  2263. }
  2264. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, _tok,
  2265. {
  2266. char declared_identity[DIGEST_LEN];
  2267. networkstatus_voter_info_t *v;
  2268. tok = _tok;
  2269. if (tok->tp != K_DIRECTORY_SIGNATURE)
  2270. continue;
  2271. tor_assert(tok->n_args >= 2);
  2272. if (!tok->object_type ||
  2273. strcmp(tok->object_type, "SIGNATURE") ||
  2274. tok->object_size < 128 || tok->object_size > 512) {
  2275. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  2276. goto err;
  2277. }
  2278. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  2279. base16_decode(declared_identity, sizeof(declared_identity),
  2280. tok->args[0], HEX_DIGEST_LEN) < 0) {
  2281. log_warn(LD_DIR, "Error decoding declared identity %s in "
  2282. "network-status vote.", escaped(tok->args[0]));
  2283. goto err;
  2284. }
  2285. if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {
  2286. log_warn(LD_DIR, "ID on signature on network-status vote does not match "
  2287. "any declared directory source.");
  2288. goto err;
  2289. }
  2290. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  2291. base16_decode(v->signing_key_digest, sizeof(v->signing_key_digest),
  2292. tok->args[1], HEX_DIGEST_LEN) < 0) {
  2293. log_warn(LD_DIR, "Error decoding declared digest %s in "
  2294. "network-status vote.", escaped(tok->args[1]));
  2295. goto err;
  2296. }
  2297. if (ns->type != NS_TYPE_CONSENSUS) {
  2298. if (tor_memneq(declared_identity, ns->cert->cache_info.identity_digest,
  2299. DIGEST_LEN)) {
  2300. log_warn(LD_DIR, "Digest mismatch between declared and actual on "
  2301. "network-status vote.");
  2302. goto err;
  2303. }
  2304. }
  2305. if (ns->type != NS_TYPE_CONSENSUS) {
  2306. if (check_signature_token(ns_digest, tok, ns->cert->signing_key, 0,
  2307. "network-status vote"))
  2308. goto err;
  2309. v->good_signature = 1;
  2310. } else {
  2311. if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING)
  2312. goto err;
  2313. /* We already parsed a vote from this voter. Use the first one. */
  2314. if (v->signature) {
  2315. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "We received a networkstatus "
  2316. "that contains two votes from the same voter. Ignoring "
  2317. "the second vote.");
  2318. continue;
  2319. }
  2320. v->signature = tor_memdup(tok->object_body, tok->object_size);
  2321. v->signature_len = (int) tok->object_size;
  2322. }
  2323. ++n_signatures;
  2324. });
  2325. if (! n_signatures) {
  2326. log_warn(LD_DIR, "No signatures on networkstatus vote.");
  2327. goto err;
  2328. }
  2329. if (eos_out)
  2330. *eos_out = end_of_footer;
  2331. goto done;
  2332. err:
  2333. if (ns)
  2334. networkstatus_vote_free(ns);
  2335. ns = NULL;
  2336. done:
  2337. if (tokens) {
  2338. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  2339. smartlist_free(tokens);
  2340. }
  2341. if (voter) {
  2342. tor_free(voter->nickname);
  2343. tor_free(voter->address);
  2344. tor_free(voter->contact);
  2345. tor_free(voter->signature);
  2346. tor_free(voter);
  2347. }
  2348. if (rs_tokens) {
  2349. SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_free(t));
  2350. smartlist_free(rs_tokens);
  2351. }
  2352. if (footer_tokens) {
  2353. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_free(t));
  2354. smartlist_free(footer_tokens);
  2355. }
  2356. if (area) {
  2357. DUMP_AREA(area, "v3 networkstatus");
  2358. memarea_drop_all(area);
  2359. }
  2360. if (rs_area)
  2361. memarea_drop_all(rs_area);
  2362. return ns;
  2363. }
  2364. /** Parse a detached v3 networkstatus signature document between <b>s</b> and
  2365. * <b>eos</b> and return the result. Return -1 on failure. */
  2366. ns_detached_signatures_t *
  2367. networkstatus_parse_detached_signatures(const char *s, const char *eos)
  2368. {
  2369. /* XXXX there is too much duplicate shared between this function and
  2370. * networkstatus_parse_vote_from_string(). */
  2371. directory_token_t *tok;
  2372. memarea_t *area = NULL;
  2373. smartlist_t *tokens = smartlist_create();
  2374. ns_detached_signatures_t *sigs =
  2375. tor_malloc_zero(sizeof(ns_detached_signatures_t));
  2376. if (!eos)
  2377. eos = s + strlen(s);
  2378. area = memarea_new();
  2379. if (tokenize_string(area,s, eos, tokens,
  2380. networkstatus_detached_signature_token_table, 0)) {
  2381. log_warn(LD_DIR, "Error tokenizing detached networkstatus signatures");
  2382. goto err;
  2383. }
  2384. tok = find_by_keyword(tokens, K_CONSENSUS_DIGEST);
  2385. if (strlen(tok->args[0]) != HEX_DIGEST_LEN) {
  2386. log_warn(LD_DIR, "Wrong length on consensus-digest in detached "
  2387. "networkstatus signatures");
  2388. goto err;
  2389. }
  2390. if (base16_decode(sigs->networkstatus_digest, DIGEST_LEN,
  2391. tok->args[0], strlen(tok->args[0])) < 0) {
  2392. log_warn(LD_DIR, "Bad encoding on on consensus-digest in detached "
  2393. "networkstatus signatures");
  2394. goto err;
  2395. }
  2396. tok = find_by_keyword(tokens, K_VALID_AFTER);
  2397. if (parse_iso_time(tok->args[0], &sigs->valid_after)) {
  2398. log_warn(LD_DIR, "Bad valid-after in detached networkstatus signatures");
  2399. goto err;
  2400. }
  2401. tok = find_by_keyword(tokens, K_FRESH_UNTIL);
  2402. if (parse_iso_time(tok->args[0], &sigs->fresh_until)) {
  2403. log_warn(LD_DIR, "Bad fresh-until in detached networkstatus signatures");
  2404. goto err;
  2405. }
  2406. tok = find_by_keyword(tokens, K_VALID_UNTIL);
  2407. if (parse_iso_time(tok->args[0], &sigs->valid_until)) {
  2408. log_warn(LD_DIR, "Bad valid-until in detached networkstatus signatures");
  2409. goto err;
  2410. }
  2411. sigs->signatures = smartlist_create();
  2412. SMARTLIST_FOREACH(tokens, directory_token_t *, _tok,
  2413. {
  2414. char id_digest[DIGEST_LEN];
  2415. char sk_digest[DIGEST_LEN];
  2416. networkstatus_voter_info_t *voter;
  2417. tok = _tok;
  2418. if (tok->tp != K_DIRECTORY_SIGNATURE)
  2419. continue;
  2420. tor_assert(tok->n_args >= 2);
  2421. if (!tok->object_type ||
  2422. strcmp(tok->object_type, "SIGNATURE") ||
  2423. tok->object_size < 128 || tok->object_size > 512) {
  2424. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  2425. goto err;
  2426. }
  2427. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  2428. base16_decode(id_digest, sizeof(id_digest),
  2429. tok->args[0], HEX_DIGEST_LEN) < 0) {
  2430. log_warn(LD_DIR, "Error decoding declared identity %s in "
  2431. "network-status vote.", escaped(tok->args[0]));
  2432. goto err;
  2433. }
  2434. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  2435. base16_decode(sk_digest, sizeof(sk_digest),
  2436. tok->args[1], HEX_DIGEST_LEN) < 0) {
  2437. log_warn(LD_DIR, "Error decoding declared digest %s in "
  2438. "network-status vote.", escaped(tok->args[1]));
  2439. goto err;
  2440. }
  2441. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  2442. memcpy(voter->identity_digest, id_digest, DIGEST_LEN);
  2443. memcpy(voter->signing_key_digest, sk_digest, DIGEST_LEN);
  2444. if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING)
  2445. goto err;
  2446. voter->signature = tor_memdup(tok->object_body, tok->object_size);
  2447. voter->signature_len = (int) tok->object_size;
  2448. smartlist_add(sigs->signatures, voter);
  2449. });
  2450. goto done;
  2451. err:
  2452. ns_detached_signatures_free(sigs);
  2453. sigs = NULL;
  2454. done:
  2455. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  2456. smartlist_free(tokens);
  2457. if (area) {
  2458. DUMP_AREA(area, "detached signatures");
  2459. memarea_drop_all(area);
  2460. }
  2461. return sigs;
  2462. }
  2463. /** Parse the addr policy in the string <b>s</b> and return it. If
  2464. * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
  2465. * ADDR_POLICY_REJECT) for items that specify no action.
  2466. */
  2467. addr_policy_t *
  2468. router_parse_addr_policy_item_from_string(const char *s, int assume_action)
  2469. {
  2470. directory_token_t *tok = NULL;
  2471. const char *cp, *eos;
  2472. /* Longest possible policy is "accept ffff:ffff:..255/ffff:...255:0-65535".
  2473. * But note that there can be an arbitrary amount of space between the
  2474. * accept and the address:mask/port element. */
  2475. char line[TOR_ADDR_BUF_LEN*2 + 32];
  2476. addr_policy_t *r;
  2477. memarea_t *area = NULL;
  2478. s = eat_whitespace(s);
  2479. if ((*s == '*' || TOR_ISDIGIT(*s)) && assume_action >= 0) {
  2480. if (tor_snprintf(line, sizeof(line), "%s %s",
  2481. assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", s)<0) {
  2482. log_warn(LD_DIR, "Policy %s is too long.", escaped(s));
  2483. return NULL;
  2484. }
  2485. cp = line;
  2486. tor_strlower(line);
  2487. } else { /* assume an already well-formed address policy line */
  2488. cp = s;
  2489. }
  2490. eos = cp + strlen(cp);
  2491. area = memarea_new();
  2492. tok = get_next_token(area, &cp, eos, routerdesc_token_table);
  2493. if (tok->tp == _ERR) {
  2494. log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
  2495. goto err;
  2496. }
  2497. if (tok->tp != K_ACCEPT && tok->tp != K_ACCEPT6 &&
  2498. tok->tp != K_REJECT && tok->tp != K_REJECT6) {
  2499. log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
  2500. goto err;
  2501. }
  2502. r = router_parse_addr_policy(tok);
  2503. goto done;
  2504. err:
  2505. r = NULL;
  2506. done:
  2507. token_free(tok);
  2508. if (area) {
  2509. DUMP_AREA(area, "policy item");
  2510. memarea_drop_all(area);
  2511. }
  2512. return r;
  2513. }
  2514. /** Add an exit policy stored in the token <b>tok</b> to the router info in
  2515. * <b>router</b>. Return 0 on success, -1 on failure. */
  2516. static int
  2517. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
  2518. {
  2519. addr_policy_t *newe;
  2520. newe = router_parse_addr_policy(tok);
  2521. if (!newe)
  2522. return -1;
  2523. if (! router->exit_policy)
  2524. router->exit_policy = smartlist_create();
  2525. if (((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  2526. tor_addr_family(&newe->addr) == AF_INET)
  2527. ||
  2528. ((tok->tp == K_ACCEPT || tok->tp == K_REJECT) &&
  2529. tor_addr_family(&newe->addr) == AF_INET6)) {
  2530. log_warn(LD_DIR, "Mismatch between field type and address type in exit "
  2531. "policy");
  2532. addr_policy_free(newe);
  2533. return -1;
  2534. }
  2535. smartlist_add(router->exit_policy, newe);
  2536. return 0;
  2537. }
  2538. /** Given a K_ACCEPT or K_REJECT token and a router, create and return
  2539. * a new exit_policy_t corresponding to the token. */
  2540. static addr_policy_t *
  2541. router_parse_addr_policy(directory_token_t *tok)
  2542. {
  2543. addr_policy_t newe;
  2544. char *arg;
  2545. tor_assert(tok->tp == K_REJECT || tok->tp == K_REJECT6 ||
  2546. tok->tp == K_ACCEPT || tok->tp == K_ACCEPT6);
  2547. if (tok->n_args != 1)
  2548. return NULL;
  2549. arg = tok->args[0];
  2550. if (!strcmpstart(arg,"private"))
  2551. return router_parse_addr_policy_private(tok);
  2552. memset(&newe, 0, sizeof(newe));
  2553. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  2554. newe.policy_type = ADDR_POLICY_REJECT;
  2555. else
  2556. newe.policy_type = ADDR_POLICY_ACCEPT;
  2557. if (tor_addr_parse_mask_ports(arg, &newe.addr, &newe.maskbits,
  2558. &newe.prt_min, &newe.prt_max) < 0) {
  2559. log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
  2560. return NULL;
  2561. }
  2562. return addr_policy_get_canonical_entry(&newe);
  2563. }
  2564. /** Parse an exit policy line of the format "accept/reject private:...".
  2565. * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
  2566. * router descriptors until earlier versions are obsolete.
  2567. */
  2568. static addr_policy_t *
  2569. router_parse_addr_policy_private(directory_token_t *tok)
  2570. {
  2571. const char *arg;
  2572. uint16_t port_min, port_max;
  2573. addr_policy_t result;
  2574. arg = tok->args[0];
  2575. if (strcmpstart(arg, "private"))
  2576. return NULL;
  2577. arg += strlen("private");
  2578. arg = (char*) eat_whitespace(arg);
  2579. if (!arg || *arg != ':')
  2580. return NULL;
  2581. if (parse_port_range(arg+1, &port_min, &port_max)<0)
  2582. return NULL;
  2583. memset(&result, 0, sizeof(result));
  2584. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  2585. result.policy_type = ADDR_POLICY_REJECT;
  2586. else
  2587. result.policy_type = ADDR_POLICY_ACCEPT;
  2588. result.is_private = 1;
  2589. result.prt_min = port_min;
  2590. result.prt_max = port_max;
  2591. return addr_policy_get_canonical_entry(&result);
  2592. }
  2593. /** Log and exit if <b>t</b> is malformed */
  2594. void
  2595. assert_addr_policy_ok(smartlist_t *lst)
  2596. {
  2597. if (!lst) return;
  2598. SMARTLIST_FOREACH(lst, addr_policy_t *, t, {
  2599. tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
  2600. t->policy_type == ADDR_POLICY_ACCEPT);
  2601. tor_assert(t->prt_min <= t->prt_max);
  2602. });
  2603. }
  2604. /*
  2605. * Low-level tokenizer for router descriptors and directories.
  2606. */
  2607. /** Free all resources allocated for <b>tok</b> */
  2608. static void
  2609. token_free(directory_token_t *tok)
  2610. {
  2611. tor_assert(tok);
  2612. if (tok->key)
  2613. crypto_free_pk_env(tok->key);
  2614. }
  2615. #define ALLOC_ZERO(sz) memarea_alloc_zero(area,sz)
  2616. #define ALLOC(sz) memarea_alloc(area,sz)
  2617. #define STRDUP(str) memarea_strdup(area,str)
  2618. #define STRNDUP(str,n) memarea_strndup(area,(str),(n))
  2619. #define RET_ERR(msg) \
  2620. STMT_BEGIN \
  2621. if (tok) token_free(tok); \
  2622. tok = ALLOC_ZERO(sizeof(directory_token_t)); \
  2623. tok->tp = _ERR; \
  2624. tok->error = STRDUP(msg); \
  2625. goto done_tokenizing; \
  2626. STMT_END
  2627. /** Helper: make sure that the token <b>tok</b> with keyword <b>kwd</b> obeys
  2628. * the object syntax of <b>o_syn</b>. Allocate all storage in <b>area</b>.
  2629. * Return <b>tok</b> on success, or a new _ERR token if the token didn't
  2630. * conform to the syntax we wanted.
  2631. **/
  2632. static INLINE directory_token_t *
  2633. token_check_object(memarea_t *area, const char *kwd,
  2634. directory_token_t *tok, obj_syntax o_syn)
  2635. {
  2636. char ebuf[128];
  2637. switch (o_syn) {
  2638. case NO_OBJ:
  2639. /* No object is allowed for this token. */
  2640. if (tok->object_body) {
  2641. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected object for %s", kwd);
  2642. RET_ERR(ebuf);
  2643. }
  2644. if (tok->key) {
  2645. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected public key for %s", kwd);
  2646. RET_ERR(ebuf);
  2647. }
  2648. break;
  2649. case NEED_OBJ:
  2650. /* There must be a (non-key) object. */
  2651. if (!tok->object_body) {
  2652. tor_snprintf(ebuf, sizeof(ebuf), "Missing object for %s", kwd);
  2653. RET_ERR(ebuf);
  2654. }
  2655. break;
  2656. case NEED_KEY_1024: /* There must be a 1024-bit public key. */
  2657. case NEED_SKEY_1024: /* There must be a 1024-bit private key. */
  2658. if (tok->key && crypto_pk_keysize(tok->key) != PK_BYTES) {
  2659. tor_snprintf(ebuf, sizeof(ebuf), "Wrong size on key for %s: %d bits",
  2660. kwd, (int)crypto_pk_keysize(tok->key));
  2661. RET_ERR(ebuf);
  2662. }
  2663. /* fall through */
  2664. case NEED_KEY: /* There must be some kind of key. */
  2665. if (!tok->key) {
  2666. tor_snprintf(ebuf, sizeof(ebuf), "Missing public key for %s", kwd);
  2667. RET_ERR(ebuf);
  2668. }
  2669. if (o_syn != NEED_SKEY_1024) {
  2670. if (crypto_pk_key_is_private(tok->key)) {
  2671. tor_snprintf(ebuf, sizeof(ebuf),
  2672. "Private key given for %s, which wants a public key", kwd);
  2673. RET_ERR(ebuf);
  2674. }
  2675. } else { /* o_syn == NEED_SKEY_1024 */
  2676. if (!crypto_pk_key_is_private(tok->key)) {
  2677. tor_snprintf(ebuf, sizeof(ebuf),
  2678. "Public key given for %s, which wants a private key", kwd);
  2679. RET_ERR(ebuf);
  2680. }
  2681. }
  2682. break;
  2683. case OBJ_OK:
  2684. /* Anything goes with this token. */
  2685. break;
  2686. }
  2687. done_tokenizing:
  2688. return tok;
  2689. }
  2690. /** Helper: parse space-separated arguments from the string <b>s</b> ending at
  2691. * <b>eol</b>, and store them in the args field of <b>tok</b>. Store the
  2692. * number of parsed elements into the n_args field of <b>tok</b>. Allocate
  2693. * all storage in <b>area</b>. Return the number of arguments parsed, or
  2694. * return -1 if there was an insanely high number of arguments. */
  2695. static INLINE int
  2696. get_token_arguments(memarea_t *area, directory_token_t *tok,
  2697. const char *s, const char *eol)
  2698. {
  2699. /** Largest number of arguments we'll accept to any token, ever. */
  2700. #define MAX_ARGS 512
  2701. char *mem = memarea_strndup(area, s, eol-s);
  2702. char *cp = mem;
  2703. int j = 0;
  2704. char *args[MAX_ARGS];
  2705. while (*cp) {
  2706. if (j == MAX_ARGS)
  2707. return -1;
  2708. args[j++] = cp;
  2709. cp = (char*)find_whitespace(cp);
  2710. if (!cp || !*cp)
  2711. break; /* End of the line. */
  2712. *cp++ = '\0';
  2713. cp = (char*)eat_whitespace(cp);
  2714. }
  2715. tok->n_args = j;
  2716. tok->args = memarea_memdup(area, args, j*sizeof(char*));
  2717. return j;
  2718. #undef MAX_ARGS
  2719. }
  2720. /** Helper function: read the next token from *s, advance *s to the end of the
  2721. * token, and return the parsed token. Parse *<b>s</b> according to the list
  2722. * of tokens in <b>table</b>.
  2723. */
  2724. static directory_token_t *
  2725. get_next_token(memarea_t *area,
  2726. const char **s, const char *eos, token_rule_t *table)
  2727. {
  2728. /** Reject any object at least this big; it is probably an overflow, an
  2729. * attack, a bug, or some other nonsense. */
  2730. #define MAX_UNPARSED_OBJECT_SIZE (128*1024)
  2731. /** Reject any line at least this big; it is probably an overflow, an
  2732. * attack, a bug, or some other nonsense. */
  2733. #define MAX_LINE_LENGTH (128*1024)
  2734. const char *next, *eol, *obstart;
  2735. size_t obname_len;
  2736. int i;
  2737. directory_token_t *tok;
  2738. obj_syntax o_syn = NO_OBJ;
  2739. char ebuf[128];
  2740. const char *kwd = "";
  2741. tor_assert(area);
  2742. tok = ALLOC_ZERO(sizeof(directory_token_t));
  2743. tok->tp = _ERR;
  2744. /* Set *s to first token, eol to end-of-line, next to after first token */
  2745. *s = eat_whitespace_eos(*s, eos); /* eat multi-line whitespace */
  2746. tor_assert(eos >= *s);
  2747. eol = memchr(*s, '\n', eos-*s);
  2748. if (!eol)
  2749. eol = eos;
  2750. if (eol - *s > MAX_LINE_LENGTH) {
  2751. RET_ERR("Line far too long");
  2752. }
  2753. next = find_whitespace_eos(*s, eol);
  2754. if (!strcmp_len(*s, "opt", next-*s)) {
  2755. /* Skip past an "opt" at the start of the line. */
  2756. *s = eat_whitespace_eos_no_nl(next, eol);
  2757. next = find_whitespace_eos(*s, eol);
  2758. } else if (*s == eos) { /* If no "opt", and end-of-line, line is invalid */
  2759. RET_ERR("Unexpected EOF");
  2760. }
  2761. /* Search the table for the appropriate entry. (I tried a binary search
  2762. * instead, but it wasn't any faster.) */
  2763. for (i = 0; table[i].t ; ++i) {
  2764. if (!strcmp_len(*s, table[i].t, next-*s)) {
  2765. /* We've found the keyword. */
  2766. kwd = table[i].t;
  2767. tok->tp = table[i].v;
  2768. o_syn = table[i].os;
  2769. *s = eat_whitespace_eos_no_nl(next, eol);
  2770. /* We go ahead whether there are arguments or not, so that tok->args is
  2771. * always set if we want arguments. */
  2772. if (table[i].concat_args) {
  2773. /* The keyword takes the line as a single argument */
  2774. tok->args = ALLOC(sizeof(char*));
  2775. tok->args[0] = STRNDUP(*s,eol-*s); /* Grab everything on line */
  2776. tok->n_args = 1;
  2777. } else {
  2778. /* This keyword takes multiple arguments. */
  2779. if (get_token_arguments(area, tok, *s, eol)<0) {
  2780. tor_snprintf(ebuf, sizeof(ebuf),"Far too many arguments to %s", kwd);
  2781. RET_ERR(ebuf);
  2782. }
  2783. *s = eol;
  2784. }
  2785. if (tok->n_args < table[i].min_args) {
  2786. tor_snprintf(ebuf, sizeof(ebuf), "Too few arguments to %s", kwd);
  2787. RET_ERR(ebuf);
  2788. } else if (tok->n_args > table[i].max_args) {
  2789. tor_snprintf(ebuf, sizeof(ebuf), "Too many arguments to %s", kwd);
  2790. RET_ERR(ebuf);
  2791. }
  2792. break;
  2793. }
  2794. }
  2795. if (tok->tp == _ERR) {
  2796. /* No keyword matched; call it an "K_opt" or "A_unrecognized" */
  2797. if (**s == '@')
  2798. tok->tp = _A_UNKNOWN;
  2799. else
  2800. tok->tp = K_OPT;
  2801. tok->args = ALLOC(sizeof(char*));
  2802. tok->args[0] = STRNDUP(*s, eol-*s);
  2803. tok->n_args = 1;
  2804. o_syn = OBJ_OK;
  2805. }
  2806. /* Check whether there's an object present */
  2807. *s = eat_whitespace_eos(eol, eos); /* Scan from end of first line */
  2808. tor_assert(eos >= *s);
  2809. eol = memchr(*s, '\n', eos-*s);
  2810. if (!eol || eol-*s<11 || strcmpstart(*s, "-----BEGIN ")) /* No object. */
  2811. goto check_object;
  2812. obstart = *s; /* Set obstart to start of object spec */
  2813. if (*s+16 >= eol || memchr(*s+11,'\0',eol-*s-16) || /* no short lines, */
  2814. strcmp_len(eol-5, "-----", 5) || /* nuls or invalid endings */
  2815. (eol-*s) > MAX_UNPARSED_OBJECT_SIZE) { /* name too long */
  2816. RET_ERR("Malformed object: bad begin line");
  2817. }
  2818. tok->object_type = STRNDUP(*s+11, eol-*s-16);
  2819. obname_len = eol-*s-16; /* store objname length here to avoid a strlen() */
  2820. *s = eol+1; /* Set *s to possible start of object data (could be eos) */
  2821. /* Go to the end of the object */
  2822. next = tor_memstr(*s, eos-*s, "-----END ");
  2823. if (!next) {
  2824. RET_ERR("Malformed object: missing object end line");
  2825. }
  2826. tor_assert(eos >= next);
  2827. eol = memchr(next, '\n', eos-next);
  2828. if (!eol) /* end-of-line marker, or eos if there's no '\n' */
  2829. eol = eos;
  2830. /* Validate the ending tag, which should be 9 + NAME + 5 + eol */
  2831. if ((size_t)(eol-next) != 9+obname_len+5 ||
  2832. strcmp_len(next+9, tok->object_type, obname_len) ||
  2833. strcmp_len(eol-5, "-----", 5)) {
  2834. snprintf(ebuf, sizeof(ebuf), "Malformed object: mismatched end tag %s",
  2835. tok->object_type);
  2836. ebuf[sizeof(ebuf)-1] = '\0';
  2837. RET_ERR(ebuf);
  2838. }
  2839. if (next - *s > MAX_UNPARSED_OBJECT_SIZE)
  2840. RET_ERR("Couldn't parse object: missing footer or object much too big.");
  2841. if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) { /* If it's a public key */
  2842. tok->key = crypto_new_pk_env();
  2843. if (crypto_pk_read_public_key_from_string(tok->key, obstart, eol-obstart))
  2844. RET_ERR("Couldn't parse public key.");
  2845. } else if (!strcmp(tok->object_type, "RSA PRIVATE KEY")) { /* private key */
  2846. tok->key = crypto_new_pk_env();
  2847. if (crypto_pk_read_private_key_from_string(tok->key, obstart, eol-obstart))
  2848. RET_ERR("Couldn't parse private key.");
  2849. } else { /* If it's something else, try to base64-decode it */
  2850. int r;
  2851. tok->object_body = ALLOC(next-*s); /* really, this is too much RAM. */
  2852. r = base64_decode(tok->object_body, next-*s, *s, next-*s);
  2853. if (r<0)
  2854. RET_ERR("Malformed object: bad base64-encoded data");
  2855. tok->object_size = r;
  2856. }
  2857. *s = eol;
  2858. check_object:
  2859. tok = token_check_object(area, kwd, tok, o_syn);
  2860. done_tokenizing:
  2861. return tok;
  2862. #undef RET_ERR
  2863. #undef ALLOC
  2864. #undef ALLOC_ZERO
  2865. #undef STRDUP
  2866. #undef STRNDUP
  2867. }
  2868. /** Read all tokens from a string between <b>start</b> and <b>end</b>, and add
  2869. * them to <b>out</b>. Parse according to the token rules in <b>table</b>.
  2870. * Caller must free tokens in <b>out</b>. If <b>end</b> is NULL, use the
  2871. * entire string.
  2872. */
  2873. static int
  2874. tokenize_string(memarea_t *area,
  2875. const char *start, const char *end, smartlist_t *out,
  2876. token_rule_t *table, int flags)
  2877. {
  2878. const char **s;
  2879. directory_token_t *tok = NULL;
  2880. int counts[_NIL];
  2881. int i;
  2882. int first_nonannotation;
  2883. int prev_len = smartlist_len(out);
  2884. tor_assert(area);
  2885. s = &start;
  2886. if (!end)
  2887. end = start+strlen(start);
  2888. for (i = 0; i < _NIL; ++i)
  2889. counts[i] = 0;
  2890. SMARTLIST_FOREACH(out, const directory_token_t *, t, ++counts[t->tp]);
  2891. while (*s < end && (!tok || tok->tp != _EOF)) {
  2892. tok = get_next_token(area, s, end, table);
  2893. if (tok->tp == _ERR) {
  2894. log_warn(LD_DIR, "parse error: %s", tok->error);
  2895. token_free(tok);
  2896. return -1;
  2897. }
  2898. ++counts[tok->tp];
  2899. smartlist_add(out, tok);
  2900. *s = eat_whitespace_eos(*s, end);
  2901. }
  2902. if (flags & TS_NOCHECK)
  2903. return 0;
  2904. if ((flags & TS_ANNOTATIONS_OK)) {
  2905. first_nonannotation = -1;
  2906. for (i = 0; i < smartlist_len(out); ++i) {
  2907. tok = smartlist_get(out, i);
  2908. if (tok->tp < MIN_ANNOTATION || tok->tp > MAX_ANNOTATION) {
  2909. first_nonannotation = i;
  2910. break;
  2911. }
  2912. }
  2913. if (first_nonannotation < 0) {
  2914. log_warn(LD_DIR, "parse error: item contains only annotations");
  2915. return -1;
  2916. }
  2917. for (i=first_nonannotation; i < smartlist_len(out); ++i) {
  2918. tok = smartlist_get(out, i);
  2919. if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
  2920. log_warn(LD_DIR, "parse error: Annotations mixed with keywords");
  2921. return -1;
  2922. }
  2923. }
  2924. if ((flags & TS_NO_NEW_ANNOTATIONS)) {
  2925. if (first_nonannotation != prev_len) {
  2926. log_warn(LD_DIR, "parse error: Unexpected annotations.");
  2927. return -1;
  2928. }
  2929. }
  2930. } else {
  2931. for (i=0; i < smartlist_len(out); ++i) {
  2932. tok = smartlist_get(out, i);
  2933. if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
  2934. log_warn(LD_DIR, "parse error: no annotations allowed.");
  2935. return -1;
  2936. }
  2937. }
  2938. first_nonannotation = 0;
  2939. }
  2940. for (i = 0; table[i].t; ++i) {
  2941. if (counts[table[i].v] < table[i].min_cnt) {
  2942. log_warn(LD_DIR, "Parse error: missing %s element.", table[i].t);
  2943. return -1;
  2944. }
  2945. if (counts[table[i].v] > table[i].max_cnt) {
  2946. log_warn(LD_DIR, "Parse error: too many %s elements.", table[i].t);
  2947. return -1;
  2948. }
  2949. if (table[i].pos & AT_START) {
  2950. if (smartlist_len(out) < 1 ||
  2951. (tok = smartlist_get(out, first_nonannotation))->tp != table[i].v) {
  2952. log_warn(LD_DIR, "Parse error: first item is not %s.", table[i].t);
  2953. return -1;
  2954. }
  2955. }
  2956. if (table[i].pos & AT_END) {
  2957. if (smartlist_len(out) < 1 ||
  2958. (tok = smartlist_get(out, smartlist_len(out)-1))->tp != table[i].v) {
  2959. log_warn(LD_DIR, "Parse error: last item is not %s.", table[i].t);
  2960. return -1;
  2961. }
  2962. }
  2963. }
  2964. return 0;
  2965. }
  2966. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
  2967. * NULL if no such keyword is found.
  2968. */
  2969. static directory_token_t *
  2970. find_opt_by_keyword(smartlist_t *s, directory_keyword keyword)
  2971. {
  2972. SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
  2973. return NULL;
  2974. }
  2975. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; fail
  2976. * with an assert if no such keyword is found.
  2977. */
  2978. static directory_token_t *
  2979. _find_by_keyword(smartlist_t *s, directory_keyword keyword,
  2980. const char *keyword_as_string)
  2981. {
  2982. directory_token_t *tok = find_opt_by_keyword(s, keyword);
  2983. if (PREDICT_UNLIKELY(!tok)) {
  2984. log_err(LD_BUG, "Missing %s [%d] in directory object that should have "
  2985. "been validated. Internal error.", keyword_as_string, (int)keyword);
  2986. tor_assert(tok);
  2987. }
  2988. return tok;
  2989. }
  2990. /** Return a newly allocated smartlist of all accept or reject tokens in
  2991. * <b>s</b>.
  2992. */
  2993. static smartlist_t *
  2994. find_all_exitpolicy(smartlist_t *s)
  2995. {
  2996. smartlist_t *out = smartlist_create();
  2997. SMARTLIST_FOREACH(s, directory_token_t *, t,
  2998. if (t->tp == K_ACCEPT || t->tp == K_ACCEPT6 ||
  2999. t->tp == K_REJECT || t->tp == K_REJECT6)
  3000. smartlist_add(out,t));
  3001. return out;
  3002. }
  3003. /** Compute the SHA-1 digest of the substring of <b>s</b> taken from the first
  3004. * occurrence of <b>start_str</b> through the first instance of c after the
  3005. * first subsequent occurrence of <b>end_str</b>; store the 20-byte result in
  3006. * <b>digest</b>; return 0 on success.
  3007. *
  3008. * If no such substring exists, return -1.
  3009. */
  3010. static int
  3011. router_get_hash_impl(const char *s, size_t s_len, char *digest,
  3012. const char *start_str,
  3013. const char *end_str, char end_c)
  3014. {
  3015. const char *start, *end;
  3016. start = tor_memstr(s, s_len, start_str);
  3017. if (!start) {
  3018. log_warn(LD_DIR,"couldn't find start of hashed material \"%s\"",start_str);
  3019. return -1;
  3020. }
  3021. if (start != s && *(start-1) != '\n') {
  3022. log_warn(LD_DIR,
  3023. "first occurrence of \"%s\" is not at the start of a line",
  3024. start_str);
  3025. return -1;
  3026. }
  3027. end = tor_memstr(start+strlen(start_str),
  3028. s_len - (start-s) - strlen(start_str), end_str);
  3029. if (!end) {
  3030. log_warn(LD_DIR,"couldn't find end of hashed material \"%s\"",end_str);
  3031. return -1;
  3032. }
  3033. end = memchr(end+strlen(end_str), end_c, s_len - (end-s) - strlen(end_str));
  3034. if (!end) {
  3035. log_warn(LD_DIR,"couldn't find EOL");
  3036. return -1;
  3037. }
  3038. ++end;
  3039. if (crypto_digest(digest, start, end-start)) {
  3040. log_warn(LD_BUG,"couldn't compute digest");
  3041. return -1;
  3042. }
  3043. return 0;
  3044. }
  3045. /** Parse the Tor version of the platform string <b>platform</b>,
  3046. * and compare it to the version in <b>cutoff</b>. Return 1 if
  3047. * the router is at least as new as the cutoff, else return 0.
  3048. */
  3049. int
  3050. tor_version_as_new_as(const char *platform, const char *cutoff)
  3051. {
  3052. tor_version_t cutoff_version, router_version;
  3053. char *s, *s2, *start;
  3054. char tmp[128];
  3055. tor_assert(platform);
  3056. if (tor_version_parse(cutoff, &cutoff_version)<0) {
  3057. log_warn(LD_BUG,"cutoff version '%s' unparseable.",cutoff);
  3058. return 0;
  3059. }
  3060. if (strcmpstart(platform,"Tor ")) /* nonstandard Tor; be safe and say yes */
  3061. return 1;
  3062. start = (char *)eat_whitespace(platform+3);
  3063. if (!*start) return 0;
  3064. s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
  3065. s2 = (char*)eat_whitespace(s);
  3066. if (!strcmpstart(s2, "(r"))
  3067. s = (char*)find_whitespace(s2);
  3068. if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
  3069. return 0;
  3070. strlcpy(tmp, start, s-start+1);
  3071. if (tor_version_parse(tmp, &router_version)<0) {
  3072. log_info(LD_DIR,"Router version '%s' unparseable.",tmp);
  3073. return 1; /* be safe and say yes */
  3074. }
  3075. /* Here's why we don't need to do any special handling for svn revisions:
  3076. * - If neither has an svn revision, we're fine.
  3077. * - If the router doesn't have an svn revision, we can't assume that it
  3078. * is "at least" any svn revision, so we need to return 0.
  3079. * - If the target version doesn't have an svn revision, any svn revision
  3080. * (or none at all) is good enough, so return 1.
  3081. * - If both target and router have an svn revision, we compare them.
  3082. */
  3083. return tor_version_compare(&router_version, &cutoff_version) >= 0;
  3084. }
  3085. /** Parse a tor version from <b>s</b>, and store the result in <b>out</b>.
  3086. * Return 0 on success, -1 on failure. */
  3087. int
  3088. tor_version_parse(const char *s, tor_version_t *out)
  3089. {
  3090. char *eos=NULL;
  3091. const char *cp=NULL;
  3092. /* Format is:
  3093. * "Tor " ? NUM dot NUM dot NUM [ ( pre | rc | dot ) NUM [ - tag ] ]
  3094. */
  3095. tor_assert(s);
  3096. tor_assert(out);
  3097. memset(out, 0, sizeof(tor_version_t));
  3098. if (!strcasecmpstart(s, "Tor "))
  3099. s += 4;
  3100. /* Get major. */
  3101. out->major = (int)strtol(s,&eos,10);
  3102. if (!eos || eos==s || *eos != '.') return -1;
  3103. cp = eos+1;
  3104. /* Get minor */
  3105. out->minor = (int) strtol(cp,&eos,10);
  3106. if (!eos || eos==cp || *eos != '.') return -1;
  3107. cp = eos+1;
  3108. /* Get micro */
  3109. out->micro = (int) strtol(cp,&eos,10);
  3110. if (!eos || eos==cp) return -1;
  3111. if (!*eos) {
  3112. out->status = VER_RELEASE;
  3113. out->patchlevel = 0;
  3114. return 0;
  3115. }
  3116. cp = eos;
  3117. /* Get status */
  3118. if (*cp == '.') {
  3119. out->status = VER_RELEASE;
  3120. ++cp;
  3121. } else if (0==strncmp(cp, "pre", 3)) {
  3122. out->status = VER_PRE;
  3123. cp += 3;
  3124. } else if (0==strncmp(cp, "rc", 2)) {
  3125. out->status = VER_RC;
  3126. cp += 2;
  3127. } else {
  3128. return -1;
  3129. }
  3130. /* Get patchlevel */
  3131. out->patchlevel = (int) strtol(cp,&eos,10);
  3132. if (!eos || eos==cp) return -1;
  3133. cp = eos;
  3134. /* Get status tag. */
  3135. if (*cp == '-' || *cp == '.')
  3136. ++cp;
  3137. eos = (char*) find_whitespace(cp);
  3138. if (eos-cp >= (int)sizeof(out->status_tag))
  3139. strlcpy(out->status_tag, cp, sizeof(out->status_tag));
  3140. else {
  3141. memcpy(out->status_tag, cp, eos-cp);
  3142. out->status_tag[eos-cp] = 0;
  3143. }
  3144. cp = eat_whitespace(eos);
  3145. if (!strcmpstart(cp, "(r")) {
  3146. cp += 2;
  3147. out->svn_revision = (int) strtol(cp,&eos,10);
  3148. }
  3149. return 0;
  3150. }
  3151. /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
  3152. * b. */
  3153. int
  3154. tor_version_compare(tor_version_t *a, tor_version_t *b)
  3155. {
  3156. int i;
  3157. tor_assert(a);
  3158. tor_assert(b);
  3159. if ((i = a->major - b->major))
  3160. return i;
  3161. else if ((i = a->minor - b->minor))
  3162. return i;
  3163. else if ((i = a->micro - b->micro))
  3164. return i;
  3165. else if ((i = a->status - b->status))
  3166. return i;
  3167. else if ((i = a->patchlevel - b->patchlevel))
  3168. return i;
  3169. else if ((i = strcmp(a->status_tag, b->status_tag)))
  3170. return i;
  3171. else
  3172. return a->svn_revision - b->svn_revision;
  3173. }
  3174. /** Return true iff versions <b>a</b> and <b>b</b> belong to the same series.
  3175. */
  3176. static int
  3177. tor_version_same_series(tor_version_t *a, tor_version_t *b)
  3178. {
  3179. tor_assert(a);
  3180. tor_assert(b);
  3181. return ((a->major == b->major) &&
  3182. (a->minor == b->minor) &&
  3183. (a->micro == b->micro));
  3184. }
  3185. /** Helper: Given pointers to two strings describing tor versions, return -1
  3186. * if _a precedes _b, 1 if _b precedes _a, and 0 if they are equivalent.
  3187. * Used to sort a list of versions. */
  3188. static int
  3189. _compare_tor_version_str_ptr(const void **_a, const void **_b)
  3190. {
  3191. const char *a = *_a, *b = *_b;
  3192. int ca, cb;
  3193. tor_version_t va, vb;
  3194. ca = tor_version_parse(a, &va);
  3195. cb = tor_version_parse(b, &vb);
  3196. /* If they both parse, compare them. */
  3197. if (!ca && !cb)
  3198. return tor_version_compare(&va,&vb);
  3199. /* If one parses, it comes first. */
  3200. if (!ca && cb)
  3201. return -1;
  3202. if (ca && !cb)
  3203. return 1;
  3204. /* If neither parses, compare strings. Also, the directory server admin
  3205. ** needs to be smacked upside the head. But Tor is tolerant and gentle. */
  3206. return strcmp(a,b);
  3207. }
  3208. /** Sort a list of string-representations of versions in ascending order. */
  3209. void
  3210. sort_version_list(smartlist_t *versions, int remove_duplicates)
  3211. {
  3212. smartlist_sort(versions, _compare_tor_version_str_ptr);
  3213. if (remove_duplicates)
  3214. smartlist_uniq(versions, _compare_tor_version_str_ptr, _tor_free);
  3215. }
  3216. /** Parse and validate the ASCII-encoded v2 descriptor in <b>desc</b>,
  3217. * write the parsed descriptor to the newly allocated *<b>parsed_out</b>, the
  3218. * binary descriptor ID of length DIGEST_LEN to <b>desc_id_out</b>, the
  3219. * encrypted introduction points to the newly allocated
  3220. * *<b>intro_points_encrypted_out</b>, their encrypted size to
  3221. * *<b>intro_points_encrypted_size_out</b>, the size of the encoded descriptor
  3222. * to *<b>encoded_size_out</b>, and a pointer to the possibly next
  3223. * descriptor to *<b>next_out</b>; return 0 for success (including validation)
  3224. * and -1 for failure.
  3225. */
  3226. int
  3227. rend_parse_v2_service_descriptor(rend_service_descriptor_t **parsed_out,
  3228. char *desc_id_out,
  3229. char **intro_points_encrypted_out,
  3230. size_t *intro_points_encrypted_size_out,
  3231. size_t *encoded_size_out,
  3232. const char **next_out, const char *desc)
  3233. {
  3234. rend_service_descriptor_t *result =
  3235. tor_malloc_zero(sizeof(rend_service_descriptor_t));
  3236. char desc_hash[DIGEST_LEN];
  3237. const char *eos;
  3238. smartlist_t *tokens = smartlist_create();
  3239. directory_token_t *tok;
  3240. char secret_id_part[DIGEST_LEN];
  3241. int i, version, num_ok=1;
  3242. smartlist_t *versions;
  3243. char public_key_hash[DIGEST_LEN];
  3244. char test_desc_id[DIGEST_LEN];
  3245. memarea_t *area = NULL;
  3246. tor_assert(desc);
  3247. /* Check if desc starts correctly. */
  3248. if (strncmp(desc, "rendezvous-service-descriptor ",
  3249. strlen("rendezvous-service-descriptor "))) {
  3250. log_info(LD_REND, "Descriptor does not start correctly.");
  3251. goto err;
  3252. }
  3253. /* Compute descriptor hash for later validation. */
  3254. if (router_get_hash_impl(desc, strlen(desc), desc_hash,
  3255. "rendezvous-service-descriptor ",
  3256. "\nsignature", '\n') < 0) {
  3257. log_warn(LD_REND, "Couldn't compute descriptor hash.");
  3258. goto err;
  3259. }
  3260. /* Determine end of string. */
  3261. eos = strstr(desc, "\nrendezvous-service-descriptor ");
  3262. if (!eos)
  3263. eos = desc + strlen(desc);
  3264. else
  3265. eos = eos + 1;
  3266. /* Check length. */
  3267. if (strlen(desc) > REND_DESC_MAX_SIZE) {
  3268. /* XXX023 If we are parsing this descriptor as a server, this
  3269. * should be a protocol warning. */
  3270. log_warn(LD_REND, "Descriptor length is %i which exceeds "
  3271. "maximum rendezvous descriptor size of %i bytes.",
  3272. (int)strlen(desc), REND_DESC_MAX_SIZE);
  3273. goto err;
  3274. }
  3275. /* Tokenize descriptor. */
  3276. area = memarea_new();
  3277. if (tokenize_string(area, desc, eos, tokens, desc_token_table, 0)) {
  3278. log_warn(LD_REND, "Error tokenizing descriptor.");
  3279. goto err;
  3280. }
  3281. /* Set next to next descriptor, if available. */
  3282. *next_out = eos;
  3283. /* Set length of encoded descriptor. */
  3284. *encoded_size_out = eos - desc;
  3285. /* Check min allowed length of token list. */
  3286. if (smartlist_len(tokens) < 7) {
  3287. log_warn(LD_REND, "Impossibly short descriptor.");
  3288. goto err;
  3289. }
  3290. /* Parse base32-encoded descriptor ID. */
  3291. tok = find_by_keyword(tokens, R_RENDEZVOUS_SERVICE_DESCRIPTOR);
  3292. tor_assert(tok == smartlist_get(tokens, 0));
  3293. tor_assert(tok->n_args == 1);
  3294. if (strlen(tok->args[0]) != REND_DESC_ID_V2_LEN_BASE32 ||
  3295. strspn(tok->args[0], BASE32_CHARS) != REND_DESC_ID_V2_LEN_BASE32) {
  3296. log_warn(LD_REND, "Invalid descriptor ID: '%s'", tok->args[0]);
  3297. goto err;
  3298. }
  3299. if (base32_decode(desc_id_out, DIGEST_LEN,
  3300. tok->args[0], REND_DESC_ID_V2_LEN_BASE32) < 0) {
  3301. log_warn(LD_REND, "Descriptor ID contains illegal characters: %s",
  3302. tok->args[0]);
  3303. goto err;
  3304. }
  3305. /* Parse descriptor version. */
  3306. tok = find_by_keyword(tokens, R_VERSION);
  3307. tor_assert(tok->n_args == 1);
  3308. result->version =
  3309. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &num_ok, NULL);
  3310. if (result->version != 2 || !num_ok) {
  3311. /* If it's <2, it shouldn't be under this format. If the number
  3312. * is greater than 2, we bumped it because we broke backward
  3313. * compatibility. See how version numbers in our other formats
  3314. * work. */
  3315. log_warn(LD_REND, "Unrecognized descriptor version: %s",
  3316. escaped(tok->args[0]));
  3317. goto err;
  3318. }
  3319. /* Parse public key. */
  3320. tok = find_by_keyword(tokens, R_PERMANENT_KEY);
  3321. result->pk = tok->key;
  3322. tok->key = NULL; /* Prevent free */
  3323. /* Parse secret ID part. */
  3324. tok = find_by_keyword(tokens, R_SECRET_ID_PART);
  3325. tor_assert(tok->n_args == 1);
  3326. if (strlen(tok->args[0]) != REND_SECRET_ID_PART_LEN_BASE32 ||
  3327. strspn(tok->args[0], BASE32_CHARS) != REND_SECRET_ID_PART_LEN_BASE32) {
  3328. log_warn(LD_REND, "Invalid secret ID part: '%s'", tok->args[0]);
  3329. goto err;
  3330. }
  3331. if (base32_decode(secret_id_part, DIGEST_LEN, tok->args[0], 32) < 0) {
  3332. log_warn(LD_REND, "Secret ID part contains illegal characters: %s",
  3333. tok->args[0]);
  3334. goto err;
  3335. }
  3336. /* Parse publication time -- up-to-date check is done when storing the
  3337. * descriptor. */
  3338. tok = find_by_keyword(tokens, R_PUBLICATION_TIME);
  3339. tor_assert(tok->n_args == 1);
  3340. if (parse_iso_time(tok->args[0], &result->timestamp) < 0) {
  3341. log_warn(LD_REND, "Invalid publication time: '%s'", tok->args[0]);
  3342. goto err;
  3343. }
  3344. /* Parse protocol versions. */
  3345. tok = find_by_keyword(tokens, R_PROTOCOL_VERSIONS);
  3346. tor_assert(tok->n_args == 1);
  3347. versions = smartlist_create();
  3348. smartlist_split_string(versions, tok->args[0], ",",
  3349. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3350. for (i = 0; i < smartlist_len(versions); i++) {
  3351. version = (int) tor_parse_long(smartlist_get(versions, i),
  3352. 10, 0, INT_MAX, &num_ok, NULL);
  3353. if (!num_ok) /* It's a string; let's ignore it. */
  3354. continue;
  3355. result->protocols |= 1 << version;
  3356. }
  3357. SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
  3358. smartlist_free(versions);
  3359. /* Parse encrypted introduction points. Don't verify. */
  3360. tok = find_opt_by_keyword(tokens, R_INTRODUCTION_POINTS);
  3361. if (tok) {
  3362. if (strcmp(tok->object_type, "MESSAGE")) {
  3363. log_warn(LD_DIR, "Bad object type: introduction points should be of "
  3364. "type MESSAGE");
  3365. goto err;
  3366. }
  3367. *intro_points_encrypted_out = tor_memdup(tok->object_body,
  3368. tok->object_size);
  3369. *intro_points_encrypted_size_out = tok->object_size;
  3370. } else {
  3371. *intro_points_encrypted_out = NULL;
  3372. *intro_points_encrypted_size_out = 0;
  3373. }
  3374. /* Parse and verify signature. */
  3375. tok = find_by_keyword(tokens, R_SIGNATURE);
  3376. note_crypto_pk_op(VERIFY_RTR);
  3377. if (check_signature_token(desc_hash, tok, result->pk, 0,
  3378. "v2 rendezvous service descriptor") < 0)
  3379. goto err;
  3380. /* Verify that descriptor ID belongs to public key and secret ID part. */
  3381. crypto_pk_get_digest(result->pk, public_key_hash);
  3382. rend_get_descriptor_id_bytes(test_desc_id, public_key_hash,
  3383. secret_id_part);
  3384. if (tor_memneq(desc_id_out, test_desc_id, DIGEST_LEN)) {
  3385. log_warn(LD_REND, "Parsed descriptor ID does not match "
  3386. "computed descriptor ID.");
  3387. goto err;
  3388. }
  3389. goto done;
  3390. err:
  3391. if (result)
  3392. rend_service_descriptor_free(result);
  3393. result = NULL;
  3394. done:
  3395. if (tokens) {
  3396. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  3397. smartlist_free(tokens);
  3398. }
  3399. if (area)
  3400. memarea_drop_all(area);
  3401. *parsed_out = result;
  3402. if (result)
  3403. return 0;
  3404. return -1;
  3405. }
  3406. /** Decrypt the encrypted introduction points in <b>ipos_encrypted</b> of
  3407. * length <b>ipos_encrypted_size</b> using <b>descriptor_cookie</b> and
  3408. * write the result to a newly allocated string that is pointed to by
  3409. * <b>ipos_decrypted</b> and its length to <b>ipos_decrypted_size</b>.
  3410. * Return 0 if decryption was successful and -1 otherwise. */
  3411. int
  3412. rend_decrypt_introduction_points(char **ipos_decrypted,
  3413. size_t *ipos_decrypted_size,
  3414. const char *descriptor_cookie,
  3415. const char *ipos_encrypted,
  3416. size_t ipos_encrypted_size)
  3417. {
  3418. tor_assert(ipos_encrypted);
  3419. tor_assert(descriptor_cookie);
  3420. if (ipos_encrypted_size < 2) {
  3421. log_warn(LD_REND, "Size of encrypted introduction points is too "
  3422. "small.");
  3423. return -1;
  3424. }
  3425. if (ipos_encrypted[0] == (int)REND_BASIC_AUTH) {
  3426. char iv[CIPHER_IV_LEN], client_id[REND_BASIC_AUTH_CLIENT_ID_LEN],
  3427. session_key[CIPHER_KEY_LEN], *dec;
  3428. int declen, client_blocks;
  3429. size_t pos = 0, len, client_entries_len;
  3430. crypto_digest_env_t *digest;
  3431. crypto_cipher_env_t *cipher;
  3432. client_blocks = (int) ipos_encrypted[1];
  3433. client_entries_len = client_blocks * REND_BASIC_AUTH_CLIENT_MULTIPLE *
  3434. REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
  3435. if (ipos_encrypted_size < 2 + client_entries_len + CIPHER_IV_LEN + 1) {
  3436. log_warn(LD_REND, "Size of encrypted introduction points is too "
  3437. "small.");
  3438. return -1;
  3439. }
  3440. memcpy(iv, ipos_encrypted + 2 + client_entries_len, CIPHER_IV_LEN);
  3441. digest = crypto_new_digest_env();
  3442. crypto_digest_add_bytes(digest, descriptor_cookie, REND_DESC_COOKIE_LEN);
  3443. crypto_digest_add_bytes(digest, iv, CIPHER_IV_LEN);
  3444. crypto_digest_get_digest(digest, client_id,
  3445. REND_BASIC_AUTH_CLIENT_ID_LEN);
  3446. crypto_free_digest_env(digest);
  3447. for (pos = 2; pos < 2 + client_entries_len;
  3448. pos += REND_BASIC_AUTH_CLIENT_ENTRY_LEN) {
  3449. if (tor_memeq(ipos_encrypted + pos, client_id,
  3450. REND_BASIC_AUTH_CLIENT_ID_LEN)) {
  3451. /* Attempt to decrypt introduction points. */
  3452. cipher = crypto_create_init_cipher(descriptor_cookie, 0);
  3453. if (crypto_cipher_decrypt(cipher, session_key, ipos_encrypted
  3454. + pos + REND_BASIC_AUTH_CLIENT_ID_LEN,
  3455. CIPHER_KEY_LEN) < 0) {
  3456. log_warn(LD_REND, "Could not decrypt session key for client.");
  3457. crypto_free_cipher_env(cipher);
  3458. return -1;
  3459. }
  3460. crypto_free_cipher_env(cipher);
  3461. cipher = crypto_create_init_cipher(session_key, 0);
  3462. len = ipos_encrypted_size - 2 - client_entries_len - CIPHER_IV_LEN;
  3463. dec = tor_malloc(len);
  3464. declen = crypto_cipher_decrypt_with_iv(cipher, dec, len,
  3465. ipos_encrypted + 2 + client_entries_len,
  3466. ipos_encrypted_size - 2 - client_entries_len);
  3467. crypto_free_cipher_env(cipher);
  3468. if (declen < 0) {
  3469. log_warn(LD_REND, "Could not decrypt introduction point string.");
  3470. tor_free(dec);
  3471. return -1;
  3472. }
  3473. if (fast_memcmpstart(dec, declen, "introduction-point ")) {
  3474. log_warn(LD_REND, "Decrypted introduction points don't "
  3475. "look like we could parse them.");
  3476. tor_free(dec);
  3477. continue;
  3478. }
  3479. *ipos_decrypted = dec;
  3480. *ipos_decrypted_size = declen;
  3481. return 0;
  3482. }
  3483. }
  3484. log_warn(LD_REND, "Could not decrypt introduction points. Please "
  3485. "check your authorization for this service!");
  3486. return -1;
  3487. } else if (ipos_encrypted[0] == (int)REND_STEALTH_AUTH) {
  3488. crypto_cipher_env_t *cipher;
  3489. char *dec;
  3490. int declen;
  3491. dec = tor_malloc_zero(ipos_encrypted_size - CIPHER_IV_LEN - 1);
  3492. cipher = crypto_create_init_cipher(descriptor_cookie, 0);
  3493. declen = crypto_cipher_decrypt_with_iv(cipher, dec,
  3494. ipos_encrypted_size -
  3495. CIPHER_IV_LEN - 1,
  3496. ipos_encrypted + 1,
  3497. ipos_encrypted_size - 1);
  3498. crypto_free_cipher_env(cipher);
  3499. if (declen < 0) {
  3500. log_warn(LD_REND, "Decrypting introduction points failed!");
  3501. tor_free(dec);
  3502. return -1;
  3503. }
  3504. *ipos_decrypted = dec;
  3505. *ipos_decrypted_size = declen;
  3506. return 0;
  3507. } else {
  3508. log_warn(LD_REND, "Unknown authorization type number: %d",
  3509. ipos_encrypted[0]);
  3510. return -1;
  3511. }
  3512. }
  3513. /** Parse the encoded introduction points in <b>intro_points_encoded</b> of
  3514. * length <b>intro_points_encoded_size</b> and write the result to the
  3515. * descriptor in <b>parsed</b>; return the number of successfully parsed
  3516. * introduction points or -1 in case of a failure. */
  3517. int
  3518. rend_parse_introduction_points(rend_service_descriptor_t *parsed,
  3519. const char *intro_points_encoded,
  3520. size_t intro_points_encoded_size)
  3521. {
  3522. const char *current_ipo, *end_of_intro_points;
  3523. smartlist_t *tokens;
  3524. directory_token_t *tok;
  3525. rend_intro_point_t *intro;
  3526. extend_info_t *info;
  3527. int result, num_ok=1;
  3528. memarea_t *area = NULL;
  3529. tor_assert(parsed);
  3530. /** Function may only be invoked once. */
  3531. tor_assert(!parsed->intro_nodes);
  3532. tor_assert(intro_points_encoded);
  3533. tor_assert(intro_points_encoded_size > 0);
  3534. /* Consider one intro point after the other. */
  3535. current_ipo = intro_points_encoded;
  3536. end_of_intro_points = intro_points_encoded + intro_points_encoded_size;
  3537. tokens = smartlist_create();
  3538. parsed->intro_nodes = smartlist_create();
  3539. area = memarea_new();
  3540. while (!fast_memcmpstart(current_ipo, end_of_intro_points-current_ipo,
  3541. "introduction-point ")) {
  3542. /* Determine end of string. */
  3543. const char *eos = tor_memstr(current_ipo, end_of_intro_points-current_ipo,
  3544. "\nintroduction-point ");
  3545. if (!eos)
  3546. eos = end_of_intro_points;
  3547. else
  3548. eos = eos+1;
  3549. tor_assert(eos <= intro_points_encoded+intro_points_encoded_size);
  3550. /* Free tokens and clear token list. */
  3551. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  3552. smartlist_clear(tokens);
  3553. memarea_clear(area);
  3554. /* Tokenize string. */
  3555. if (tokenize_string(area, current_ipo, eos, tokens, ipo_token_table, 0)) {
  3556. log_warn(LD_REND, "Error tokenizing introduction point");
  3557. goto err;
  3558. }
  3559. /* Advance to next introduction point, if available. */
  3560. current_ipo = eos;
  3561. /* Check minimum allowed length of introduction point. */
  3562. if (smartlist_len(tokens) < 5) {
  3563. log_warn(LD_REND, "Impossibly short introduction point.");
  3564. goto err;
  3565. }
  3566. /* Allocate new intro point and extend info. */
  3567. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  3568. info = intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  3569. /* Parse identifier. */
  3570. tok = find_by_keyword(tokens, R_IPO_IDENTIFIER);
  3571. if (base32_decode(info->identity_digest, DIGEST_LEN,
  3572. tok->args[0], REND_INTRO_POINT_ID_LEN_BASE32) < 0) {
  3573. log_warn(LD_REND, "Identity digest contains illegal characters: %s",
  3574. tok->args[0]);
  3575. rend_intro_point_free(intro);
  3576. goto err;
  3577. }
  3578. /* Write identifier to nickname. */
  3579. info->nickname[0] = '$';
  3580. base16_encode(info->nickname + 1, sizeof(info->nickname) - 1,
  3581. info->identity_digest, DIGEST_LEN);
  3582. /* Parse IP address. */
  3583. tok = find_by_keyword(tokens, R_IPO_IP_ADDRESS);
  3584. if (tor_addr_from_str(&info->addr, tok->args[0])<0) {
  3585. log_warn(LD_REND, "Could not parse introduction point address.");
  3586. rend_intro_point_free(intro);
  3587. goto err;
  3588. }
  3589. if (tor_addr_family(&info->addr) != AF_INET) {
  3590. log_warn(LD_REND, "Introduction point address was not ipv4.");
  3591. rend_intro_point_free(intro);
  3592. goto err;
  3593. }
  3594. /* Parse onion port. */
  3595. tok = find_by_keyword(tokens, R_IPO_ONION_PORT);
  3596. info->port = (uint16_t) tor_parse_long(tok->args[0],10,1,65535,
  3597. &num_ok,NULL);
  3598. if (!info->port || !num_ok) {
  3599. log_warn(LD_REND, "Introduction point onion port %s is invalid",
  3600. escaped(tok->args[0]));
  3601. rend_intro_point_free(intro);
  3602. goto err;
  3603. }
  3604. /* Parse onion key. */
  3605. tok = find_by_keyword(tokens, R_IPO_ONION_KEY);
  3606. info->onion_key = tok->key;
  3607. tok->key = NULL; /* Prevent free */
  3608. /* Parse service key. */
  3609. tok = find_by_keyword(tokens, R_IPO_SERVICE_KEY);
  3610. intro->intro_key = tok->key;
  3611. tok->key = NULL; /* Prevent free */
  3612. /* Add extend info to list of introduction points. */
  3613. smartlist_add(parsed->intro_nodes, intro);
  3614. }
  3615. result = smartlist_len(parsed->intro_nodes);
  3616. goto done;
  3617. err:
  3618. result = -1;
  3619. done:
  3620. /* Free tokens and clear token list. */
  3621. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  3622. smartlist_free(tokens);
  3623. if (area)
  3624. memarea_drop_all(area);
  3625. return result;
  3626. }
  3627. /** Parse the content of a client_key file in <b>ckstr</b> and add
  3628. * rend_authorized_client_t's for each parsed client to
  3629. * <b>parsed_clients</b>. Return the number of parsed clients as result
  3630. * or -1 for failure. */
  3631. int
  3632. rend_parse_client_keys(strmap_t *parsed_clients, const char *ckstr)
  3633. {
  3634. int result = -1;
  3635. smartlist_t *tokens;
  3636. directory_token_t *tok;
  3637. const char *current_entry = NULL;
  3638. memarea_t *area = NULL;
  3639. if (!ckstr || strlen(ckstr) == 0)
  3640. return -1;
  3641. tokens = smartlist_create();
  3642. /* Begin parsing with first entry, skipping comments or whitespace at the
  3643. * beginning. */
  3644. area = memarea_new();
  3645. current_entry = eat_whitespace(ckstr);
  3646. while (!strcmpstart(current_entry, "client-name ")) {
  3647. rend_authorized_client_t *parsed_entry;
  3648. size_t len;
  3649. char descriptor_cookie_base64[REND_DESC_COOKIE_LEN_BASE64+2+1];
  3650. char descriptor_cookie_tmp[REND_DESC_COOKIE_LEN+2];
  3651. /* Determine end of string. */
  3652. const char *eos = strstr(current_entry, "\nclient-name ");
  3653. if (!eos)
  3654. eos = current_entry + strlen(current_entry);
  3655. else
  3656. eos = eos + 1;
  3657. /* Free tokens and clear token list. */
  3658. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  3659. smartlist_clear(tokens);
  3660. memarea_clear(area);
  3661. /* Tokenize string. */
  3662. if (tokenize_string(area, current_entry, eos, tokens,
  3663. client_keys_token_table, 0)) {
  3664. log_warn(LD_REND, "Error tokenizing client keys file.");
  3665. goto err;
  3666. }
  3667. /* Advance to next entry, if available. */
  3668. current_entry = eos;
  3669. /* Check minimum allowed length of token list. */
  3670. if (smartlist_len(tokens) < 2) {
  3671. log_warn(LD_REND, "Impossibly short client key entry.");
  3672. goto err;
  3673. }
  3674. /* Parse client name. */
  3675. tok = find_by_keyword(tokens, C_CLIENT_NAME);
  3676. tor_assert(tok == smartlist_get(tokens, 0));
  3677. tor_assert(tok->n_args == 1);
  3678. len = strlen(tok->args[0]);
  3679. if (len < 1 || len > 19 ||
  3680. strspn(tok->args[0], REND_LEGAL_CLIENTNAME_CHARACTERS) != len) {
  3681. log_warn(LD_CONFIG, "Illegal client name: %s. (Length must be "
  3682. "between 1 and 19, and valid characters are "
  3683. "[A-Za-z0-9+-_].)", tok->args[0]);
  3684. goto err;
  3685. }
  3686. /* Check if client name is duplicate. */
  3687. if (strmap_get(parsed_clients, tok->args[0])) {
  3688. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains a "
  3689. "duplicate client name: '%s'. Ignoring.", tok->args[0]);
  3690. goto err;
  3691. }
  3692. parsed_entry = tor_malloc_zero(sizeof(rend_authorized_client_t));
  3693. parsed_entry->client_name = tor_strdup(tok->args[0]);
  3694. strmap_set(parsed_clients, parsed_entry->client_name, parsed_entry);
  3695. /* Parse client key. */
  3696. tok = find_opt_by_keyword(tokens, C_CLIENT_KEY);
  3697. if (tok) {
  3698. parsed_entry->client_key = tok->key;
  3699. tok->key = NULL; /* Prevent free */
  3700. }
  3701. /* Parse descriptor cookie. */
  3702. tok = find_by_keyword(tokens, C_DESCRIPTOR_COOKIE);
  3703. tor_assert(tok->n_args == 1);
  3704. if (strlen(tok->args[0]) != REND_DESC_COOKIE_LEN_BASE64 + 2) {
  3705. log_warn(LD_REND, "Descriptor cookie has illegal length: %s",
  3706. escaped(tok->args[0]));
  3707. goto err;
  3708. }
  3709. /* The size of descriptor_cookie_tmp needs to be REND_DESC_COOKIE_LEN+2,
  3710. * because a base64 encoding of length 24 does not fit into 16 bytes in all
  3711. * cases. */
  3712. if ((base64_decode(descriptor_cookie_tmp, REND_DESC_COOKIE_LEN+2,
  3713. tok->args[0], REND_DESC_COOKIE_LEN_BASE64+2+1)
  3714. != REND_DESC_COOKIE_LEN)) {
  3715. log_warn(LD_REND, "Descriptor cookie contains illegal characters: "
  3716. "%s", descriptor_cookie_base64);
  3717. goto err;
  3718. }
  3719. memcpy(parsed_entry->descriptor_cookie, descriptor_cookie_tmp,
  3720. REND_DESC_COOKIE_LEN);
  3721. }
  3722. result = strmap_size(parsed_clients);
  3723. goto done;
  3724. err:
  3725. result = -1;
  3726. done:
  3727. /* Free tokens and clear token list. */
  3728. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  3729. smartlist_free(tokens);
  3730. if (area)
  3731. memarea_drop_all(area);
  3732. return result;
  3733. }