routerparse.c 177 KB

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