routerparse.c 132 KB

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