routerparse.c 133 KB

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