routerparse.c 165 KB

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