routerparse.c 165 KB

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