routerparse.c 133 KB

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