routerparse.c 177 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297
  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 ((tok = find_opt_by_keyword(tokens, K_IPV6_POLICY)) && tok->n_args) {
  1417. router->ipv6_exit_policy = parse_short_policy(tok->args[0]);
  1418. if (! router->ipv6_exit_policy) {
  1419. log_warn(LD_DIR , "Error in ipv6-policy %s", escaped(tok->args[0]));
  1420. goto err;
  1421. }
  1422. }
  1423. if (policy_is_reject_star(router->exit_policy, AF_INET) &&
  1424. (!router->ipv6_exit_policy ||
  1425. short_policy_is_reject_star(router->ipv6_exit_policy)))
  1426. router->policy_is_reject_star = 1;
  1427. if ((tok = find_opt_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
  1428. int i;
  1429. router->declared_family = smartlist_new();
  1430. for (i=0;i<tok->n_args;++i) {
  1431. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  1432. log_warn(LD_DIR, "Illegal nickname %s in family line",
  1433. escaped(tok->args[i]));
  1434. goto err;
  1435. }
  1436. smartlist_add(router->declared_family, tor_strdup(tok->args[i]));
  1437. }
  1438. }
  1439. if (find_opt_by_keyword(tokens, K_CACHES_EXTRA_INFO))
  1440. router->caches_extra_info = 1;
  1441. if (find_opt_by_keyword(tokens, K_ALLOW_SINGLE_HOP_EXITS))
  1442. router->allow_single_hop_exits = 1;
  1443. if ((tok = find_opt_by_keyword(tokens, K_EXTRA_INFO_DIGEST))) {
  1444. tor_assert(tok->n_args >= 1);
  1445. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  1446. base16_decode(router->cache_info.extra_info_digest,
  1447. DIGEST_LEN, tok->args[0], HEX_DIGEST_LEN);
  1448. } else {
  1449. log_warn(LD_DIR, "Invalid extra info digest %s", escaped(tok->args[0]));
  1450. }
  1451. }
  1452. if (find_opt_by_keyword(tokens, K_HIDDEN_SERVICE_DIR)) {
  1453. router->wants_to_be_hs_dir = 1;
  1454. }
  1455. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1456. note_crypto_pk_op(VERIFY_RTR);
  1457. #ifdef COUNT_DISTINCT_DIGESTS
  1458. if (!verified_digests)
  1459. verified_digests = digestmap_new();
  1460. digestmap_set(verified_digests, signed_digest, (void*)(uintptr_t)1);
  1461. #endif
  1462. if (check_signature_token(digest, DIGEST_LEN, tok, router->identity_pkey, 0,
  1463. "router descriptor") < 0)
  1464. goto err;
  1465. if (!router->or_port) {
  1466. log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
  1467. goto err;
  1468. }
  1469. if (!router->platform) {
  1470. router->platform = tor_strdup("<unknown>");
  1471. }
  1472. goto done;
  1473. err:
  1474. dump_desc(s_dup, "router descriptor");
  1475. routerinfo_free(router);
  1476. router = NULL;
  1477. done:
  1478. if (tokens) {
  1479. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1480. smartlist_free(tokens);
  1481. }
  1482. smartlist_free(exit_policy_tokens);
  1483. if (area) {
  1484. DUMP_AREA(area, "routerinfo");
  1485. memarea_drop_all(area);
  1486. }
  1487. return router;
  1488. }
  1489. /** Parse a single extrainfo entry from the string <b>s</b>, ending at
  1490. * <b>end</b>. (If <b>end</b> is NULL, parse up to the end of <b>s</b>.) If
  1491. * <b>cache_copy</b> is true, make a copy of the extra-info document in the
  1492. * cache_info fields of the result. If <b>routermap</b> is provided, use it
  1493. * as a map from router identity to routerinfo_t when looking up signing keys.
  1494. */
  1495. extrainfo_t *
  1496. extrainfo_parse_entry_from_string(const char *s, const char *end,
  1497. int cache_copy, struct digest_ri_map_t *routermap)
  1498. {
  1499. extrainfo_t *extrainfo = NULL;
  1500. char digest[128];
  1501. smartlist_t *tokens = NULL;
  1502. directory_token_t *tok;
  1503. crypto_pk_t *key = NULL;
  1504. routerinfo_t *router = NULL;
  1505. memarea_t *area = NULL;
  1506. const char *s_dup = s;
  1507. if (!end) {
  1508. end = s + strlen(s);
  1509. }
  1510. /* point 'end' to a point immediately after the final newline. */
  1511. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  1512. --end;
  1513. if (router_get_extrainfo_hash(s, end-s, digest) < 0) {
  1514. log_warn(LD_DIR, "Couldn't compute router hash.");
  1515. goto err;
  1516. }
  1517. tokens = smartlist_new();
  1518. area = memarea_new();
  1519. if (tokenize_string(area,s,end,tokens,extrainfo_token_table,0)) {
  1520. log_warn(LD_DIR, "Error tokenizing extra-info document.");
  1521. goto err;
  1522. }
  1523. if (smartlist_len(tokens) < 2) {
  1524. log_warn(LD_DIR, "Impossibly short extra-info document.");
  1525. goto err;
  1526. }
  1527. tok = smartlist_get(tokens,0);
  1528. if (tok->tp != K_EXTRA_INFO) {
  1529. log_warn(LD_DIR,"Entry does not start with \"extra-info\"");
  1530. goto err;
  1531. }
  1532. extrainfo = tor_malloc_zero(sizeof(extrainfo_t));
  1533. extrainfo->cache_info.is_extrainfo = 1;
  1534. if (cache_copy)
  1535. extrainfo->cache_info.signed_descriptor_body = tor_strndup(s, end-s);
  1536. extrainfo->cache_info.signed_descriptor_len = end-s;
  1537. memcpy(extrainfo->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1538. tor_assert(tok->n_args >= 2);
  1539. if (!is_legal_nickname(tok->args[0])) {
  1540. log_warn(LD_DIR,"Bad nickname %s on \"extra-info\"",escaped(tok->args[0]));
  1541. goto err;
  1542. }
  1543. strlcpy(extrainfo->nickname, tok->args[0], sizeof(extrainfo->nickname));
  1544. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  1545. base16_decode(extrainfo->cache_info.identity_digest, DIGEST_LEN,
  1546. tok->args[1], HEX_DIGEST_LEN)) {
  1547. log_warn(LD_DIR,"Invalid fingerprint %s on \"extra-info\"",
  1548. escaped(tok->args[1]));
  1549. goto err;
  1550. }
  1551. tok = find_by_keyword(tokens, K_PUBLISHED);
  1552. if (parse_iso_time(tok->args[0], &extrainfo->cache_info.published_on)) {
  1553. log_warn(LD_DIR,"Invalid published time %s on \"extra-info\"",
  1554. escaped(tok->args[0]));
  1555. goto err;
  1556. }
  1557. if (routermap &&
  1558. (router = digestmap_get((digestmap_t*)routermap,
  1559. extrainfo->cache_info.identity_digest))) {
  1560. key = router->identity_pkey;
  1561. }
  1562. tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1563. if (strcmp(tok->object_type, "SIGNATURE") ||
  1564. tok->object_size < 128 || tok->object_size > 512) {
  1565. log_warn(LD_DIR, "Bad object type or length on extra-info signature");
  1566. goto err;
  1567. }
  1568. if (key) {
  1569. note_crypto_pk_op(VERIFY_RTR);
  1570. if (check_signature_token(digest, DIGEST_LEN, tok, key, 0,
  1571. "extra-info") < 0)
  1572. goto err;
  1573. if (router)
  1574. extrainfo->cache_info.send_unencrypted =
  1575. router->cache_info.send_unencrypted;
  1576. } else {
  1577. extrainfo->pending_sig = tor_memdup(tok->object_body,
  1578. tok->object_size);
  1579. extrainfo->pending_sig_len = tok->object_size;
  1580. }
  1581. goto done;
  1582. err:
  1583. dump_desc(s_dup, "extra-info descriptor");
  1584. extrainfo_free(extrainfo);
  1585. extrainfo = NULL;
  1586. done:
  1587. if (tokens) {
  1588. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1589. smartlist_free(tokens);
  1590. }
  1591. if (area) {
  1592. DUMP_AREA(area, "extrainfo");
  1593. memarea_drop_all(area);
  1594. }
  1595. return extrainfo;
  1596. }
  1597. /** Parse a key certificate from <b>s</b>; point <b>end-of-string</b> to
  1598. * the first character after the certificate. */
  1599. authority_cert_t *
  1600. authority_cert_parse_from_string(const char *s, const char **end_of_string)
  1601. {
  1602. /** Reject any certificate at least this big; it is probably an overflow, an
  1603. * attack, a bug, or some other nonsense. */
  1604. #define MAX_CERT_SIZE (128*1024)
  1605. authority_cert_t *cert = NULL, *old_cert;
  1606. smartlist_t *tokens = NULL;
  1607. char digest[DIGEST_LEN];
  1608. directory_token_t *tok;
  1609. char fp_declared[DIGEST_LEN];
  1610. char *eos;
  1611. size_t len;
  1612. int found;
  1613. memarea_t *area = NULL;
  1614. const char *s_dup = s;
  1615. s = eat_whitespace(s);
  1616. eos = strstr(s, "\ndir-key-certification");
  1617. if (! eos) {
  1618. log_warn(LD_DIR, "No signature found on key certificate");
  1619. return NULL;
  1620. }
  1621. eos = strstr(eos, "\n-----END SIGNATURE-----\n");
  1622. if (! eos) {
  1623. log_warn(LD_DIR, "No end-of-signature found on key certificate");
  1624. return NULL;
  1625. }
  1626. eos = strchr(eos+2, '\n');
  1627. tor_assert(eos);
  1628. ++eos;
  1629. len = eos - s;
  1630. if (len > MAX_CERT_SIZE) {
  1631. log_warn(LD_DIR, "Certificate is far too big (at %lu bytes long); "
  1632. "rejecting", (unsigned long)len);
  1633. return NULL;
  1634. }
  1635. tokens = smartlist_new();
  1636. area = memarea_new();
  1637. if (tokenize_string(area,s, eos, tokens, dir_key_certificate_table, 0) < 0) {
  1638. log_warn(LD_DIR, "Error tokenizing key certificate");
  1639. goto err;
  1640. }
  1641. if (router_get_hash_impl(s, strlen(s), digest, "dir-key-certificate-version",
  1642. "\ndir-key-certification", '\n', DIGEST_SHA1) < 0)
  1643. goto err;
  1644. tok = smartlist_get(tokens, 0);
  1645. if (tok->tp != K_DIR_KEY_CERTIFICATE_VERSION || strcmp(tok->args[0], "3")) {
  1646. log_warn(LD_DIR,
  1647. "Key certificate does not begin with a recognized version (3).");
  1648. goto err;
  1649. }
  1650. cert = tor_malloc_zero(sizeof(authority_cert_t));
  1651. memcpy(cert->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1652. tok = find_by_keyword(tokens, K_DIR_SIGNING_KEY);
  1653. tor_assert(tok->key);
  1654. cert->signing_key = tok->key;
  1655. tok->key = NULL;
  1656. if (crypto_pk_get_digest(cert->signing_key, cert->signing_key_digest))
  1657. goto err;
  1658. tok = find_by_keyword(tokens, K_DIR_IDENTITY_KEY);
  1659. tor_assert(tok->key);
  1660. cert->identity_key = tok->key;
  1661. tok->key = NULL;
  1662. tok = find_by_keyword(tokens, K_FINGERPRINT);
  1663. tor_assert(tok->n_args);
  1664. if (base16_decode(fp_declared, DIGEST_LEN, tok->args[0],
  1665. strlen(tok->args[0]))) {
  1666. log_warn(LD_DIR, "Couldn't decode key certificate fingerprint %s",
  1667. escaped(tok->args[0]));
  1668. goto err;
  1669. }
  1670. if (crypto_pk_get_digest(cert->identity_key,
  1671. cert->cache_info.identity_digest))
  1672. goto err;
  1673. if (tor_memneq(cert->cache_info.identity_digest, fp_declared, DIGEST_LEN)) {
  1674. log_warn(LD_DIR, "Digest of certificate key didn't match declared "
  1675. "fingerprint");
  1676. goto err;
  1677. }
  1678. tok = find_opt_by_keyword(tokens, K_DIR_ADDRESS);
  1679. if (tok) {
  1680. struct in_addr in;
  1681. char *address = NULL;
  1682. tor_assert(tok->n_args);
  1683. /* XXX024 use some tor_addr parse function below instead. -RD */
  1684. if (tor_addr_port_split(LOG_WARN, tok->args[0], &address,
  1685. &cert->dir_port) < 0 ||
  1686. tor_inet_aton(address, &in) == 0) {
  1687. log_warn(LD_DIR, "Couldn't parse dir-address in certificate");
  1688. tor_free(address);
  1689. goto err;
  1690. }
  1691. cert->addr = ntohl(in.s_addr);
  1692. tor_free(address);
  1693. }
  1694. tok = find_by_keyword(tokens, K_DIR_KEY_PUBLISHED);
  1695. if (parse_iso_time(tok->args[0], &cert->cache_info.published_on) < 0) {
  1696. goto err;
  1697. }
  1698. tok = find_by_keyword(tokens, K_DIR_KEY_EXPIRES);
  1699. if (parse_iso_time(tok->args[0], &cert->expires) < 0) {
  1700. goto err;
  1701. }
  1702. tok = smartlist_get(tokens, smartlist_len(tokens)-1);
  1703. if (tok->tp != K_DIR_KEY_CERTIFICATION) {
  1704. log_warn(LD_DIR, "Certificate didn't end with dir-key-certification.");
  1705. goto err;
  1706. }
  1707. /* If we already have this cert, don't bother checking the signature. */
  1708. old_cert = authority_cert_get_by_digests(
  1709. cert->cache_info.identity_digest,
  1710. cert->signing_key_digest);
  1711. found = 0;
  1712. if (old_cert) {
  1713. /* XXXX We could just compare signed_descriptor_digest, but that wouldn't
  1714. * buy us much. */
  1715. if (old_cert->cache_info.signed_descriptor_len == len &&
  1716. old_cert->cache_info.signed_descriptor_body &&
  1717. tor_memeq(s, old_cert->cache_info.signed_descriptor_body, len)) {
  1718. log_debug(LD_DIR, "We already checked the signature on this "
  1719. "certificate; no need to do so again.");
  1720. found = 1;
  1721. cert->is_cross_certified = old_cert->is_cross_certified;
  1722. }
  1723. }
  1724. if (!found) {
  1725. if (check_signature_token(digest, DIGEST_LEN, tok, cert->identity_key, 0,
  1726. "key certificate")) {
  1727. goto err;
  1728. }
  1729. if ((tok = find_opt_by_keyword(tokens, K_DIR_KEY_CROSSCERT))) {
  1730. /* XXXX Once all authorities generate cross-certified certificates,
  1731. * make this field mandatory. */
  1732. if (check_signature_token(cert->cache_info.identity_digest,
  1733. DIGEST_LEN,
  1734. tok,
  1735. cert->signing_key,
  1736. CST_NO_CHECK_OBJTYPE,
  1737. "key cross-certification")) {
  1738. goto err;
  1739. }
  1740. cert->is_cross_certified = 1;
  1741. }
  1742. }
  1743. cert->cache_info.signed_descriptor_len = len;
  1744. cert->cache_info.signed_descriptor_body = tor_malloc(len+1);
  1745. memcpy(cert->cache_info.signed_descriptor_body, s, len);
  1746. cert->cache_info.signed_descriptor_body[len] = 0;
  1747. cert->cache_info.saved_location = SAVED_NOWHERE;
  1748. if (end_of_string) {
  1749. *end_of_string = eat_whitespace(eos);
  1750. }
  1751. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1752. smartlist_free(tokens);
  1753. if (area) {
  1754. DUMP_AREA(area, "authority cert");
  1755. memarea_drop_all(area);
  1756. }
  1757. return cert;
  1758. err:
  1759. dump_desc(s_dup, "authority cert");
  1760. authority_cert_free(cert);
  1761. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1762. smartlist_free(tokens);
  1763. if (area) {
  1764. DUMP_AREA(area, "authority cert");
  1765. memarea_drop_all(area);
  1766. }
  1767. return NULL;
  1768. }
  1769. /** Helper: given a string <b>s</b>, return the start of the next router-status
  1770. * object (starting with "r " at the start of a line). If none is found,
  1771. * return the start of the directory footer, or the next directory signature.
  1772. * If none is found, return the end of the string. */
  1773. static INLINE const char *
  1774. find_start_of_next_routerstatus(const char *s)
  1775. {
  1776. const char *eos, *footer, *sig;
  1777. if ((eos = strstr(s, "\nr ")))
  1778. ++eos;
  1779. else
  1780. eos = s + strlen(s);
  1781. footer = tor_memstr(s, eos-s, "\ndirectory-footer");
  1782. sig = tor_memstr(s, eos-s, "\ndirectory-signature");
  1783. if (footer && sig)
  1784. return MIN(footer, sig) + 1;
  1785. else if (footer)
  1786. return footer+1;
  1787. else if (sig)
  1788. return sig+1;
  1789. else
  1790. return eos;
  1791. }
  1792. /** Given a string at *<b>s</b>, containing a routerstatus object, and an
  1793. * empty smartlist at <b>tokens</b>, parse and return the first router status
  1794. * object in the string, and advance *<b>s</b> to just after the end of the
  1795. * router status. Return NULL and advance *<b>s</b> on error.
  1796. *
  1797. * If <b>vote</b> and <b>vote_rs</b> are provided, don't allocate a fresh
  1798. * routerstatus but use <b>vote_rs</b> instead.
  1799. *
  1800. * If <b>consensus_method</b> is nonzero, this routerstatus is part of a
  1801. * consensus, and we should parse it according to the method used to
  1802. * make that consensus.
  1803. *
  1804. * Parse according to the syntax used by the consensus flavor <b>flav</b>.
  1805. **/
  1806. static routerstatus_t *
  1807. routerstatus_parse_entry_from_string(memarea_t *area,
  1808. const char **s, smartlist_t *tokens,
  1809. networkstatus_t *vote,
  1810. vote_routerstatus_t *vote_rs,
  1811. int consensus_method,
  1812. consensus_flavor_t flav)
  1813. {
  1814. const char *eos, *s_dup = *s;
  1815. routerstatus_t *rs = NULL;
  1816. directory_token_t *tok;
  1817. char timebuf[ISO_TIME_LEN+1];
  1818. struct in_addr in;
  1819. int offset = 0;
  1820. tor_assert(tokens);
  1821. tor_assert(bool_eq(vote, vote_rs));
  1822. if (!consensus_method)
  1823. flav = FLAV_NS;
  1824. tor_assert(flav == FLAV_NS || flav == FLAV_MICRODESC);
  1825. eos = find_start_of_next_routerstatus(*s);
  1826. if (tokenize_string(area,*s, eos, tokens, rtrstatus_token_table,0)) {
  1827. log_warn(LD_DIR, "Error tokenizing router status");
  1828. goto err;
  1829. }
  1830. if (smartlist_len(tokens) < 1) {
  1831. log_warn(LD_DIR, "Impossibly short router status");
  1832. goto err;
  1833. }
  1834. tok = find_by_keyword(tokens, K_R);
  1835. tor_assert(tok->n_args >= 7); /* guaranteed by GE(7) in K_R setup */
  1836. if (flav == FLAV_NS) {
  1837. if (tok->n_args < 8) {
  1838. log_warn(LD_DIR, "Too few arguments to r");
  1839. goto err;
  1840. }
  1841. } else if (flav == FLAV_MICRODESC) {
  1842. offset = -1; /* There is no identity digest */
  1843. }
  1844. if (vote_rs) {
  1845. rs = &vote_rs->status;
  1846. } else {
  1847. rs = tor_malloc_zero(sizeof(routerstatus_t));
  1848. }
  1849. if (!is_legal_nickname(tok->args[0])) {
  1850. log_warn(LD_DIR,
  1851. "Invalid nickname %s in router status; skipping.",
  1852. escaped(tok->args[0]));
  1853. goto err;
  1854. }
  1855. strlcpy(rs->nickname, tok->args[0], sizeof(rs->nickname));
  1856. if (digest_from_base64(rs->identity_digest, tok->args[1])) {
  1857. log_warn(LD_DIR, "Error decoding identity digest %s",
  1858. escaped(tok->args[1]));
  1859. goto err;
  1860. }
  1861. if (flav == FLAV_NS) {
  1862. if (digest_from_base64(rs->descriptor_digest, tok->args[2])) {
  1863. log_warn(LD_DIR, "Error decoding descriptor digest %s",
  1864. escaped(tok->args[2]));
  1865. goto err;
  1866. }
  1867. }
  1868. if (tor_snprintf(timebuf, sizeof(timebuf), "%s %s",
  1869. tok->args[3+offset], tok->args[4+offset]) < 0 ||
  1870. parse_iso_time(timebuf, &rs->published_on)<0) {
  1871. log_warn(LD_DIR, "Error parsing time '%s %s' [%d %d]",
  1872. tok->args[3+offset], tok->args[4+offset],
  1873. offset, (int)flav);
  1874. goto err;
  1875. }
  1876. if (tor_inet_aton(tok->args[5+offset], &in) == 0) {
  1877. log_warn(LD_DIR, "Error parsing router address in network-status %s",
  1878. escaped(tok->args[5+offset]));
  1879. goto err;
  1880. }
  1881. rs->addr = ntohl(in.s_addr);
  1882. rs->or_port = (uint16_t) tor_parse_long(tok->args[6+offset],
  1883. 10,0,65535,NULL,NULL);
  1884. rs->dir_port = (uint16_t) tor_parse_long(tok->args[7+offset],
  1885. 10,0,65535,NULL,NULL);
  1886. {
  1887. smartlist_t *a_lines = find_all_by_keyword(tokens, K_A);
  1888. if (a_lines) {
  1889. find_single_ipv6_orport(a_lines, &rs->ipv6_addr, &rs->ipv6_orport);
  1890. smartlist_free(a_lines);
  1891. }
  1892. }
  1893. tok = find_opt_by_keyword(tokens, K_S);
  1894. if (tok && vote) {
  1895. int i;
  1896. vote_rs->flags = 0;
  1897. for (i=0; i < tok->n_args; ++i) {
  1898. int p = smartlist_string_pos(vote->known_flags, tok->args[i]);
  1899. if (p >= 0) {
  1900. vote_rs->flags |= (U64_LITERAL(1)<<p);
  1901. } else {
  1902. log_warn(LD_DIR, "Flags line had a flag %s not listed in known_flags.",
  1903. escaped(tok->args[i]));
  1904. goto err;
  1905. }
  1906. }
  1907. } else if (tok) {
  1908. int i;
  1909. for (i=0; i < tok->n_args; ++i) {
  1910. if (!strcmp(tok->args[i], "Exit"))
  1911. rs->is_exit = 1;
  1912. else if (!strcmp(tok->args[i], "Stable"))
  1913. rs->is_stable = 1;
  1914. else if (!strcmp(tok->args[i], "Fast"))
  1915. rs->is_fast = 1;
  1916. else if (!strcmp(tok->args[i], "Running"))
  1917. rs->is_flagged_running = 1;
  1918. else if (!strcmp(tok->args[i], "Named"))
  1919. rs->is_named = 1;
  1920. else if (!strcmp(tok->args[i], "Valid"))
  1921. rs->is_valid = 1;
  1922. else if (!strcmp(tok->args[i], "V2Dir"))
  1923. rs->is_v2_dir = 1;
  1924. else if (!strcmp(tok->args[i], "Guard"))
  1925. rs->is_possible_guard = 1;
  1926. else if (!strcmp(tok->args[i], "BadExit"))
  1927. rs->is_bad_exit = 1;
  1928. else if (!strcmp(tok->args[i], "BadDirectory"))
  1929. rs->is_bad_directory = 1;
  1930. else if (!strcmp(tok->args[i], "Authority"))
  1931. rs->is_authority = 1;
  1932. else if (!strcmp(tok->args[i], "Unnamed") &&
  1933. consensus_method >= 2) {
  1934. /* Unnamed is computed right by consensus method 2 and later. */
  1935. rs->is_unnamed = 1;
  1936. } else if (!strcmp(tok->args[i], "HSDir")) {
  1937. rs->is_hs_dir = 1;
  1938. }
  1939. }
  1940. }
  1941. if ((tok = find_opt_by_keyword(tokens, K_V))) {
  1942. tor_assert(tok->n_args == 1);
  1943. rs->version_known = 1;
  1944. if (strcmpstart(tok->args[0], "Tor ")) {
  1945. rs->version_supports_microdesc_cache = 1;
  1946. rs->version_supports_optimistic_data = 1;
  1947. } else {
  1948. rs->version_supports_microdesc_cache =
  1949. tor_version_supports_microdescriptors(tok->args[0]);
  1950. rs->version_supports_optimistic_data =
  1951. tor_version_as_new_as(tok->args[0], "0.2.3.1-alpha");
  1952. }
  1953. if (vote_rs) {
  1954. vote_rs->version = tor_strdup(tok->args[0]);
  1955. }
  1956. }
  1957. /* handle weighting/bandwidth info */
  1958. if ((tok = find_opt_by_keyword(tokens, K_W))) {
  1959. int i;
  1960. for (i=0; i < tok->n_args; ++i) {
  1961. if (!strcmpstart(tok->args[i], "Bandwidth=")) {
  1962. int ok;
  1963. rs->bandwidth = (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
  1964. 10, 0, UINT32_MAX,
  1965. &ok, NULL);
  1966. if (!ok) {
  1967. log_warn(LD_DIR, "Invalid Bandwidth %s", escaped(tok->args[i]));
  1968. goto err;
  1969. }
  1970. rs->has_bandwidth = 1;
  1971. } else if (!strcmpstart(tok->args[i], "Measured=")) {
  1972. int ok;
  1973. rs->measured_bw =
  1974. (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
  1975. 10, 0, UINT32_MAX, &ok, NULL);
  1976. if (!ok) {
  1977. log_warn(LD_DIR, "Invalid Measured Bandwidth %s",
  1978. escaped(tok->args[i]));
  1979. goto err;
  1980. }
  1981. rs->has_measured_bw = 1;
  1982. }
  1983. }
  1984. }
  1985. /* parse exit policy summaries */
  1986. if ((tok = find_opt_by_keyword(tokens, K_P))) {
  1987. tor_assert(tok->n_args == 1);
  1988. if (strcmpstart(tok->args[0], "accept ") &&
  1989. strcmpstart(tok->args[0], "reject ")) {
  1990. log_warn(LD_DIR, "Unknown exit policy summary type %s.",
  1991. escaped(tok->args[0]));
  1992. goto err;
  1993. }
  1994. /* XXX weasel: parse this into ports and represent them somehow smart,
  1995. * maybe not here but somewhere on if we need it for the client.
  1996. * we should still parse it here to check it's valid tho.
  1997. */
  1998. rs->exitsummary = tor_strdup(tok->args[0]);
  1999. rs->has_exitsummary = 1;
  2000. }
  2001. if (vote_rs) {
  2002. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, t) {
  2003. if (t->tp == K_M && t->n_args) {
  2004. vote_microdesc_hash_t *line =
  2005. tor_malloc(sizeof(vote_microdesc_hash_t));
  2006. line->next = vote_rs->microdesc;
  2007. line->microdesc_hash_line = tor_strdup(t->args[0]);
  2008. vote_rs->microdesc = line;
  2009. }
  2010. } SMARTLIST_FOREACH_END(t);
  2011. } else if (flav == FLAV_MICRODESC) {
  2012. tok = find_opt_by_keyword(tokens, K_M);
  2013. if (tok) {
  2014. tor_assert(tok->n_args);
  2015. if (digest256_from_base64(rs->descriptor_digest, tok->args[0])) {
  2016. log_warn(LD_DIR, "Error decoding microdescriptor digest %s",
  2017. escaped(tok->args[0]));
  2018. goto err;
  2019. }
  2020. } else {
  2021. log_info(LD_BUG, "Found an entry in networkstatus with no "
  2022. "microdescriptor digest. (Router %s=%s at %s:%d.)",
  2023. rs->nickname, hex_str(rs->identity_digest, DIGEST_LEN),
  2024. fmt_addr32(rs->addr), rs->or_port);
  2025. }
  2026. }
  2027. if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME))
  2028. rs->is_named = 0;
  2029. goto done;
  2030. err:
  2031. dump_desc(s_dup, "routerstatus entry");
  2032. if (rs && !vote_rs)
  2033. routerstatus_free(rs);
  2034. rs = NULL;
  2035. done:
  2036. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2037. smartlist_clear(tokens);
  2038. if (area) {
  2039. DUMP_AREA(area, "routerstatus entry");
  2040. memarea_clear(area);
  2041. }
  2042. *s = eos;
  2043. return rs;
  2044. }
  2045. /** Helper to sort a smartlist of pointers to routerstatus_t */
  2046. int
  2047. compare_routerstatus_entries(const void **_a, const void **_b)
  2048. {
  2049. const routerstatus_t *a = *_a, *b = *_b;
  2050. return fast_memcmp(a->identity_digest, b->identity_digest, DIGEST_LEN);
  2051. }
  2052. /** Helper: used in call to _smartlist_uniq to clear out duplicate entries. */
  2053. static void
  2054. free_duplicate_routerstatus_entry_(void *e)
  2055. {
  2056. log_warn(LD_DIR,
  2057. "Network-status has two entries for the same router. "
  2058. "Dropping one.");
  2059. routerstatus_free(e);
  2060. }
  2061. /** Given a v2 network-status object in <b>s</b>, try to
  2062. * parse it and return the result. Return NULL on failure. Check the
  2063. * signature of the network status, but do not (yet) check the signing key for
  2064. * authority.
  2065. */
  2066. networkstatus_v2_t *
  2067. networkstatus_v2_parse_from_string(const char *s)
  2068. {
  2069. const char *eos, *s_dup = s;
  2070. smartlist_t *tokens = smartlist_new();
  2071. smartlist_t *footer_tokens = smartlist_new();
  2072. networkstatus_v2_t *ns = NULL;
  2073. char ns_digest[DIGEST_LEN];
  2074. char tmp_digest[DIGEST_LEN];
  2075. struct in_addr in;
  2076. directory_token_t *tok;
  2077. int i;
  2078. memarea_t *area = NULL;
  2079. if (router_get_networkstatus_v2_hash(s, ns_digest)) {
  2080. log_warn(LD_DIR, "Unable to compute digest of network-status");
  2081. goto err;
  2082. }
  2083. area = memarea_new();
  2084. eos = find_start_of_next_routerstatus(s);
  2085. if (tokenize_string(area, s, eos, tokens, netstatus_token_table,0)) {
  2086. log_warn(LD_DIR, "Error tokenizing network-status header.");
  2087. goto err;
  2088. }
  2089. ns = tor_malloc_zero(sizeof(networkstatus_v2_t));
  2090. memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN);
  2091. tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
  2092. tor_assert(tok->n_args >= 1);
  2093. if (strcmp(tok->args[0], "2")) {
  2094. log_warn(LD_BUG, "Got a non-v2 networkstatus. Version was "
  2095. "%s", escaped(tok->args[0]));
  2096. goto err;
  2097. }
  2098. tok = find_by_keyword(tokens, K_DIR_SOURCE);
  2099. tor_assert(tok->n_args >= 3);
  2100. ns->source_address = tor_strdup(tok->args[0]);
  2101. if (tor_inet_aton(tok->args[1], &in) == 0) {
  2102. log_warn(LD_DIR, "Error parsing network-status source address %s",
  2103. escaped(tok->args[1]));
  2104. goto err;
  2105. }
  2106. ns->source_addr = ntohl(in.s_addr);
  2107. ns->source_dirport =
  2108. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
  2109. if (ns->source_dirport == 0) {
  2110. log_warn(LD_DIR, "Directory source without dirport; skipping.");
  2111. goto err;
  2112. }
  2113. tok = find_by_keyword(tokens, K_FINGERPRINT);
  2114. tor_assert(tok->n_args);
  2115. if (base16_decode(ns->identity_digest, DIGEST_LEN, tok->args[0],
  2116. strlen(tok->args[0]))) {
  2117. log_warn(LD_DIR, "Couldn't decode networkstatus fingerprint %s",
  2118. escaped(tok->args[0]));
  2119. goto err;
  2120. }
  2121. if ((tok = find_opt_by_keyword(tokens, K_CONTACT))) {
  2122. tor_assert(tok->n_args);
  2123. ns->contact = tor_strdup(tok->args[0]);
  2124. }
  2125. tok = find_by_keyword(tokens, K_DIR_SIGNING_KEY);
  2126. tor_assert(tok->key);
  2127. ns->signing_key = tok->key;
  2128. tok->key = NULL;
  2129. if (crypto_pk_get_digest(ns->signing_key, tmp_digest)<0) {
  2130. log_warn(LD_DIR, "Couldn't compute signing key digest");
  2131. goto err;
  2132. }
  2133. if (tor_memneq(tmp_digest, ns->identity_digest, DIGEST_LEN)) {
  2134. log_warn(LD_DIR,
  2135. "network-status fingerprint did not match dir-signing-key");
  2136. goto err;
  2137. }
  2138. if ((tok = find_opt_by_keyword(tokens, K_DIR_OPTIONS))) {
  2139. for (i=0; i < tok->n_args; ++i) {
  2140. if (!strcmp(tok->args[i], "Names"))
  2141. ns->binds_names = 1;
  2142. if (!strcmp(tok->args[i], "Versions"))
  2143. ns->recommends_versions = 1;
  2144. if (!strcmp(tok->args[i], "BadExits"))
  2145. ns->lists_bad_exits = 1;
  2146. if (!strcmp(tok->args[i], "BadDirectories"))
  2147. ns->lists_bad_directories = 1;
  2148. }
  2149. }
  2150. if (ns->recommends_versions) {
  2151. if (!(tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  2152. log_warn(LD_DIR, "Missing client-versions on versioning directory");
  2153. goto err;
  2154. }
  2155. ns->client_versions = tor_strdup(tok->args[0]);
  2156. if (!(tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS)) ||
  2157. tok->n_args<1) {
  2158. log_warn(LD_DIR, "Missing server-versions on versioning directory");
  2159. goto err;
  2160. }
  2161. ns->server_versions = tor_strdup(tok->args[0]);
  2162. }
  2163. tok = find_by_keyword(tokens, K_PUBLISHED);
  2164. tor_assert(tok->n_args == 1);
  2165. if (parse_iso_time(tok->args[0], &ns->published_on) < 0) {
  2166. goto err;
  2167. }
  2168. ns->entries = smartlist_new();
  2169. s = eos;
  2170. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2171. smartlist_clear(tokens);
  2172. memarea_clear(area);
  2173. while (!strcmpstart(s, "r ")) {
  2174. routerstatus_t *rs;
  2175. if ((rs = routerstatus_parse_entry_from_string(area, &s, tokens,
  2176. NULL, NULL, 0, 0)))
  2177. smartlist_add(ns->entries, rs);
  2178. }
  2179. smartlist_sort(ns->entries, compare_routerstatus_entries);
  2180. smartlist_uniq(ns->entries, compare_routerstatus_entries,
  2181. free_duplicate_routerstatus_entry_);
  2182. if (tokenize_string(area,s, NULL, footer_tokens, dir_footer_token_table,0)) {
  2183. log_warn(LD_DIR, "Error tokenizing network-status footer.");
  2184. goto err;
  2185. }
  2186. if (smartlist_len(footer_tokens) < 1) {
  2187. log_warn(LD_DIR, "Too few items in network-status footer.");
  2188. goto err;
  2189. }
  2190. tok = smartlist_get(footer_tokens, smartlist_len(footer_tokens)-1);
  2191. if (tok->tp != K_DIRECTORY_SIGNATURE) {
  2192. log_warn(LD_DIR,
  2193. "Expected network-status footer to end with a signature.");
  2194. goto err;
  2195. }
  2196. note_crypto_pk_op(VERIFY_DIR);
  2197. if (check_signature_token(ns_digest, DIGEST_LEN, tok, ns->signing_key, 0,
  2198. "network-status") < 0)
  2199. goto err;
  2200. goto done;
  2201. err:
  2202. dump_desc(s_dup, "v2 networkstatus");
  2203. networkstatus_v2_free(ns);
  2204. ns = NULL;
  2205. done:
  2206. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2207. smartlist_free(tokens);
  2208. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_clear(t));
  2209. smartlist_free(footer_tokens);
  2210. if (area) {
  2211. DUMP_AREA(area, "v2 networkstatus");
  2212. memarea_drop_all(area);
  2213. }
  2214. return ns;
  2215. }
  2216. /** Verify the bandwidth weights of a network status document */
  2217. int
  2218. networkstatus_verify_bw_weights(networkstatus_t *ns)
  2219. {
  2220. int64_t weight_scale;
  2221. int64_t G=0, M=0, E=0, D=0, T=0;
  2222. double Wgg, Wgm, Wgd, Wmg, Wmm, Wme, Wmd, Weg, Wem, Wee, Wed;
  2223. double Gtotal=0, Mtotal=0, Etotal=0;
  2224. const char *casename = NULL;
  2225. int valid = 1;
  2226. weight_scale = circuit_build_times_get_bw_scale(ns);
  2227. Wgg = networkstatus_get_bw_weight(ns, "Wgg", -1);
  2228. Wgm = networkstatus_get_bw_weight(ns, "Wgm", -1);
  2229. Wgd = networkstatus_get_bw_weight(ns, "Wgd", -1);
  2230. Wmg = networkstatus_get_bw_weight(ns, "Wmg", -1);
  2231. Wmm = networkstatus_get_bw_weight(ns, "Wmm", -1);
  2232. Wme = networkstatus_get_bw_weight(ns, "Wme", -1);
  2233. Wmd = networkstatus_get_bw_weight(ns, "Wmd", -1);
  2234. Weg = networkstatus_get_bw_weight(ns, "Weg", -1);
  2235. Wem = networkstatus_get_bw_weight(ns, "Wem", -1);
  2236. Wee = networkstatus_get_bw_weight(ns, "Wee", -1);
  2237. Wed = networkstatus_get_bw_weight(ns, "Wed", -1);
  2238. if (Wgg<0 || Wgm<0 || Wgd<0 || Wmg<0 || Wmm<0 || Wme<0 || Wmd<0 || Weg<0
  2239. || Wem<0 || Wee<0 || Wed<0) {
  2240. log_warn(LD_BUG, "No bandwidth weights produced in consensus!");
  2241. return 0;
  2242. }
  2243. // First, sanity check basic summing properties that hold for all cases
  2244. // We use > 1 as the check for these because they are computed as integers.
  2245. // Sometimes there are rounding errors.
  2246. if (fabs(Wmm - weight_scale) > 1) {
  2247. log_warn(LD_BUG, "Wmm=%f != "I64_FORMAT,
  2248. Wmm, I64_PRINTF_ARG(weight_scale));
  2249. valid = 0;
  2250. }
  2251. if (fabs(Wem - Wee) > 1) {
  2252. log_warn(LD_BUG, "Wem=%f != Wee=%f", Wem, Wee);
  2253. valid = 0;
  2254. }
  2255. if (fabs(Wgm - Wgg) > 1) {
  2256. log_warn(LD_BUG, "Wgm=%f != Wgg=%f", Wgm, Wgg);
  2257. valid = 0;
  2258. }
  2259. if (fabs(Weg - Wed) > 1) {
  2260. log_warn(LD_BUG, "Wed=%f != Weg=%f", Wed, Weg);
  2261. valid = 0;
  2262. }
  2263. if (fabs(Wgg + Wmg - weight_scale) > 0.001*weight_scale) {
  2264. log_warn(LD_BUG, "Wgg=%f != "I64_FORMAT" - Wmg=%f", Wgg,
  2265. I64_PRINTF_ARG(weight_scale), Wmg);
  2266. valid = 0;
  2267. }
  2268. if (fabs(Wee + Wme - weight_scale) > 0.001*weight_scale) {
  2269. log_warn(LD_BUG, "Wee=%f != "I64_FORMAT" - Wme=%f", Wee,
  2270. I64_PRINTF_ARG(weight_scale), Wme);
  2271. valid = 0;
  2272. }
  2273. if (fabs(Wgd + Wmd + Wed - weight_scale) > 0.001*weight_scale) {
  2274. log_warn(LD_BUG, "Wgd=%f + Wmd=%f + Wed=%f != "I64_FORMAT,
  2275. Wgd, Wmd, Wed, I64_PRINTF_ARG(weight_scale));
  2276. valid = 0;
  2277. }
  2278. Wgg /= weight_scale;
  2279. Wgm /= weight_scale;
  2280. Wgd /= weight_scale;
  2281. Wmg /= weight_scale;
  2282. Wmm /= weight_scale;
  2283. Wme /= weight_scale;
  2284. Wmd /= weight_scale;
  2285. Weg /= weight_scale;
  2286. Wem /= weight_scale;
  2287. Wee /= weight_scale;
  2288. Wed /= weight_scale;
  2289. // Then, gather G, M, E, D, T to determine case
  2290. SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) {
  2291. if (rs->has_bandwidth) {
  2292. T += rs->bandwidth;
  2293. if (rs->is_exit && rs->is_possible_guard) {
  2294. D += rs->bandwidth;
  2295. Gtotal += Wgd*rs->bandwidth;
  2296. Mtotal += Wmd*rs->bandwidth;
  2297. Etotal += Wed*rs->bandwidth;
  2298. } else if (rs->is_exit) {
  2299. E += rs->bandwidth;
  2300. Mtotal += Wme*rs->bandwidth;
  2301. Etotal += Wee*rs->bandwidth;
  2302. } else if (rs->is_possible_guard) {
  2303. G += rs->bandwidth;
  2304. Gtotal += Wgg*rs->bandwidth;
  2305. Mtotal += Wmg*rs->bandwidth;
  2306. } else {
  2307. M += rs->bandwidth;
  2308. Mtotal += Wmm*rs->bandwidth;
  2309. }
  2310. } else {
  2311. log_warn(LD_BUG, "Missing consensus bandwidth for router %s",
  2312. routerstatus_describe(rs));
  2313. }
  2314. } SMARTLIST_FOREACH_END(rs);
  2315. // Finally, check equality conditions depending upon case 1, 2 or 3
  2316. // Full equality cases: 1, 3b
  2317. // Partial equality cases: 2b (E=G), 3a (M=E)
  2318. // Fully unknown: 2a
  2319. if (3*E >= T && 3*G >= T) {
  2320. // Case 1: Neither are scarce
  2321. casename = "Case 1";
  2322. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  2323. log_warn(LD_DIR,
  2324. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  2325. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2326. " T="I64_FORMAT". "
  2327. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2328. casename, Etotal, Mtotal,
  2329. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2330. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2331. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2332. valid = 0;
  2333. }
  2334. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2335. log_warn(LD_DIR,
  2336. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2337. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2338. " T="I64_FORMAT". "
  2339. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2340. casename, Etotal, Gtotal,
  2341. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2342. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2343. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2344. valid = 0;
  2345. }
  2346. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  2347. log_warn(LD_DIR,
  2348. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  2349. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2350. " T="I64_FORMAT". "
  2351. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2352. casename, Mtotal, Gtotal,
  2353. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2354. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2355. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2356. valid = 0;
  2357. }
  2358. } else if (3*E < T && 3*G < T) {
  2359. int64_t R = MIN(E, G);
  2360. int64_t S = MAX(E, G);
  2361. /*
  2362. * Case 2: Both Guards and Exits are scarce
  2363. * Balance D between E and G, depending upon
  2364. * D capacity and scarcity. Devote no extra
  2365. * bandwidth to middle nodes.
  2366. */
  2367. if (R+D < S) { // Subcase a
  2368. double Rtotal, Stotal;
  2369. if (E < G) {
  2370. Rtotal = Etotal;
  2371. Stotal = Gtotal;
  2372. } else {
  2373. Rtotal = Gtotal;
  2374. Stotal = Etotal;
  2375. }
  2376. casename = "Case 2a";
  2377. // Rtotal < Stotal
  2378. if (Rtotal > Stotal) {
  2379. log_warn(LD_DIR,
  2380. "Bw Weight Failure for %s: Rtotal %f > Stotal %f. "
  2381. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2382. " T="I64_FORMAT". "
  2383. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2384. casename, Rtotal, Stotal,
  2385. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2386. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2387. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2388. valid = 0;
  2389. }
  2390. // Rtotal < T/3
  2391. if (3*Rtotal > T) {
  2392. log_warn(LD_DIR,
  2393. "Bw Weight Failure for %s: 3*Rtotal %f > T "
  2394. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
  2395. " D="I64_FORMAT" T="I64_FORMAT". "
  2396. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2397. casename, Rtotal*3, I64_PRINTF_ARG(T),
  2398. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2399. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2400. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2401. valid = 0;
  2402. }
  2403. // Stotal < T/3
  2404. if (3*Stotal > T) {
  2405. log_warn(LD_DIR,
  2406. "Bw Weight Failure for %s: 3*Stotal %f > T "
  2407. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
  2408. " D="I64_FORMAT" T="I64_FORMAT". "
  2409. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2410. casename, Stotal*3, I64_PRINTF_ARG(T),
  2411. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2412. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2413. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2414. valid = 0;
  2415. }
  2416. // Mtotal > T/3
  2417. if (3*Mtotal < T) {
  2418. log_warn(LD_DIR,
  2419. "Bw Weight Failure for %s: 3*Mtotal %f < T "
  2420. I64_FORMAT". "
  2421. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2422. " T="I64_FORMAT". "
  2423. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2424. casename, Mtotal*3, I64_PRINTF_ARG(T),
  2425. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2426. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2427. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2428. valid = 0;
  2429. }
  2430. } else { // Subcase b: R+D > S
  2431. casename = "Case 2b";
  2432. /* Check the rare-M redirect case. */
  2433. if (D != 0 && 3*M < T) {
  2434. casename = "Case 2b (balanced)";
  2435. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  2436. log_warn(LD_DIR,
  2437. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  2438. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2439. " T="I64_FORMAT". "
  2440. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2441. casename, Etotal, Mtotal,
  2442. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2443. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2444. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2445. valid = 0;
  2446. }
  2447. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2448. log_warn(LD_DIR,
  2449. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2450. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2451. " T="I64_FORMAT". "
  2452. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2453. casename, Etotal, Gtotal,
  2454. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2455. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2456. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2457. valid = 0;
  2458. }
  2459. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  2460. log_warn(LD_DIR,
  2461. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  2462. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2463. " T="I64_FORMAT". "
  2464. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2465. casename, Mtotal, Gtotal,
  2466. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2467. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2468. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2469. valid = 0;
  2470. }
  2471. } else {
  2472. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2473. log_warn(LD_DIR,
  2474. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2475. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2476. " T="I64_FORMAT". "
  2477. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2478. casename, Etotal, Gtotal,
  2479. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2480. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2481. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2482. valid = 0;
  2483. }
  2484. }
  2485. }
  2486. } else { // if (E < T/3 || G < T/3) {
  2487. int64_t S = MIN(E, G);
  2488. int64_t NS = MAX(E, G);
  2489. if (3*(S+D) < T) { // Subcase a:
  2490. double Stotal;
  2491. double NStotal;
  2492. if (G < E) {
  2493. casename = "Case 3a (G scarce)";
  2494. Stotal = Gtotal;
  2495. NStotal = Etotal;
  2496. } else { // if (G >= E) {
  2497. casename = "Case 3a (E scarce)";
  2498. NStotal = Gtotal;
  2499. Stotal = Etotal;
  2500. }
  2501. // Stotal < T/3
  2502. if (3*Stotal > T) {
  2503. log_warn(LD_DIR,
  2504. "Bw Weight Failure for %s: 3*Stotal %f > T "
  2505. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
  2506. " D="I64_FORMAT" T="I64_FORMAT". "
  2507. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2508. casename, Stotal*3, I64_PRINTF_ARG(T),
  2509. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2510. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2511. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2512. valid = 0;
  2513. }
  2514. if (NS >= M) {
  2515. if (fabs(NStotal-Mtotal) > 0.01*MAX(NStotal,Mtotal)) {
  2516. log_warn(LD_DIR,
  2517. "Bw Weight Failure for %s: NStotal %f != Mtotal %f. "
  2518. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2519. " T="I64_FORMAT". "
  2520. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2521. casename, NStotal, Mtotal,
  2522. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2523. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2524. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2525. valid = 0;
  2526. }
  2527. } else {
  2528. // if NS < M, NStotal > T/3 because only one of G or E is scarce
  2529. if (3*NStotal < T) {
  2530. log_warn(LD_DIR,
  2531. "Bw Weight Failure for %s: 3*NStotal %f < T "
  2532. I64_FORMAT". G="I64_FORMAT" M="I64_FORMAT
  2533. " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT". "
  2534. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2535. casename, NStotal*3, I64_PRINTF_ARG(T),
  2536. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2537. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2538. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2539. valid = 0;
  2540. }
  2541. }
  2542. } else { // Subcase b: S+D >= T/3
  2543. casename = "Case 3b";
  2544. if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
  2545. log_warn(LD_DIR,
  2546. "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
  2547. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2548. " T="I64_FORMAT". "
  2549. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2550. casename, Etotal, Mtotal,
  2551. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2552. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2553. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2554. valid = 0;
  2555. }
  2556. if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
  2557. log_warn(LD_DIR,
  2558. "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
  2559. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2560. " T="I64_FORMAT". "
  2561. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2562. casename, Etotal, Gtotal,
  2563. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2564. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2565. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2566. valid = 0;
  2567. }
  2568. if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
  2569. log_warn(LD_DIR,
  2570. "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
  2571. "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
  2572. " T="I64_FORMAT". "
  2573. "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
  2574. casename, Mtotal, Gtotal,
  2575. I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
  2576. I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
  2577. Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
  2578. valid = 0;
  2579. }
  2580. }
  2581. }
  2582. if (valid)
  2583. log_notice(LD_DIR, "Bandwidth-weight %s is verified and valid.",
  2584. casename);
  2585. return valid;
  2586. }
  2587. /** Parse a v3 networkstatus vote, opinion, or consensus (depending on
  2588. * ns_type), from <b>s</b>, and return the result. Return NULL on failure. */
  2589. networkstatus_t *
  2590. networkstatus_parse_vote_from_string(const char *s, const char **eos_out,
  2591. networkstatus_type_t ns_type)
  2592. {
  2593. smartlist_t *tokens = smartlist_new();
  2594. smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;
  2595. networkstatus_voter_info_t *voter = NULL;
  2596. networkstatus_t *ns = NULL;
  2597. digests_t ns_digests;
  2598. const char *cert, *end_of_header, *end_of_footer, *s_dup = s;
  2599. directory_token_t *tok;
  2600. int ok;
  2601. struct in_addr in;
  2602. int i, inorder, n_signatures = 0;
  2603. memarea_t *area = NULL, *rs_area = NULL;
  2604. consensus_flavor_t flav = FLAV_NS;
  2605. char *last_kwd=NULL;
  2606. tor_assert(s);
  2607. if (eos_out)
  2608. *eos_out = NULL;
  2609. if (router_get_networkstatus_v3_hashes(s, &ns_digests)) {
  2610. log_warn(LD_DIR, "Unable to compute digest of network-status");
  2611. goto err;
  2612. }
  2613. area = memarea_new();
  2614. end_of_header = find_start_of_next_routerstatus(s);
  2615. if (tokenize_string(area, s, end_of_header, tokens,
  2616. (ns_type == NS_TYPE_CONSENSUS) ?
  2617. networkstatus_consensus_token_table :
  2618. networkstatus_token_table, 0)) {
  2619. log_warn(LD_DIR, "Error tokenizing network-status vote header");
  2620. goto err;
  2621. }
  2622. ns = tor_malloc_zero(sizeof(networkstatus_t));
  2623. memcpy(&ns->digests, &ns_digests, sizeof(ns_digests));
  2624. tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
  2625. tor_assert(tok);
  2626. if (tok->n_args > 1) {
  2627. int flavor = networkstatus_parse_flavor_name(tok->args[1]);
  2628. if (flavor < 0) {
  2629. log_warn(LD_DIR, "Can't parse document with unknown flavor %s",
  2630. escaped(tok->args[1]));
  2631. goto err;
  2632. }
  2633. ns->flavor = flav = flavor;
  2634. }
  2635. if (flav != FLAV_NS && ns_type != NS_TYPE_CONSENSUS) {
  2636. log_warn(LD_DIR, "Flavor found on non-consensus networkstatus.");
  2637. goto err;
  2638. }
  2639. if (ns_type != NS_TYPE_CONSENSUS) {
  2640. const char *end_of_cert = NULL;
  2641. if (!(cert = strstr(s, "\ndir-key-certificate-version")))
  2642. goto err;
  2643. ++cert;
  2644. ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);
  2645. if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)
  2646. goto err;
  2647. }
  2648. tok = find_by_keyword(tokens, K_VOTE_STATUS);
  2649. tor_assert(tok->n_args);
  2650. if (!strcmp(tok->args[0], "vote")) {
  2651. ns->type = NS_TYPE_VOTE;
  2652. } else if (!strcmp(tok->args[0], "consensus")) {
  2653. ns->type = NS_TYPE_CONSENSUS;
  2654. } else if (!strcmp(tok->args[0], "opinion")) {
  2655. ns->type = NS_TYPE_OPINION;
  2656. } else {
  2657. log_warn(LD_DIR, "Unrecognized vote status %s in network-status",
  2658. escaped(tok->args[0]));
  2659. goto err;
  2660. }
  2661. if (ns_type != ns->type) {
  2662. log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus.");
  2663. goto err;
  2664. }
  2665. if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
  2666. tok = find_by_keyword(tokens, K_PUBLISHED);
  2667. if (parse_iso_time(tok->args[0], &ns->published))
  2668. goto err;
  2669. ns->supported_methods = smartlist_new();
  2670. tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHODS);
  2671. if (tok) {
  2672. for (i=0; i < tok->n_args; ++i)
  2673. smartlist_add(ns->supported_methods, tor_strdup(tok->args[i]));
  2674. } else {
  2675. smartlist_add(ns->supported_methods, tor_strdup("1"));
  2676. }
  2677. } else {
  2678. tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHOD);
  2679. if (tok) {
  2680. ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX,
  2681. &ok, NULL);
  2682. if (!ok)
  2683. goto err;
  2684. } else {
  2685. ns->consensus_method = 1;
  2686. }
  2687. }
  2688. tok = find_by_keyword(tokens, K_VALID_AFTER);
  2689. if (parse_iso_time(tok->args[0], &ns->valid_after))
  2690. goto err;
  2691. tok = find_by_keyword(tokens, K_FRESH_UNTIL);
  2692. if (parse_iso_time(tok->args[0], &ns->fresh_until))
  2693. goto err;
  2694. tok = find_by_keyword(tokens, K_VALID_UNTIL);
  2695. if (parse_iso_time(tok->args[0], &ns->valid_until))
  2696. goto err;
  2697. tok = find_by_keyword(tokens, K_VOTING_DELAY);
  2698. tor_assert(tok->n_args >= 2);
  2699. ns->vote_seconds =
  2700. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);
  2701. if (!ok)
  2702. goto err;
  2703. ns->dist_seconds =
  2704. (int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL);
  2705. if (!ok)
  2706. goto err;
  2707. if (ns->valid_after + MIN_VOTE_INTERVAL > ns->fresh_until) {
  2708. log_warn(LD_DIR, "Vote/consensus freshness interval is too short");
  2709. goto err;
  2710. }
  2711. if (ns->valid_after + MIN_VOTE_INTERVAL*2 > ns->valid_until) {
  2712. log_warn(LD_DIR, "Vote/consensus liveness interval is too short");
  2713. goto err;
  2714. }
  2715. if (ns->vote_seconds < MIN_VOTE_SECONDS) {
  2716. log_warn(LD_DIR, "Vote seconds is too short");
  2717. goto err;
  2718. }
  2719. if (ns->dist_seconds < MIN_DIST_SECONDS) {
  2720. log_warn(LD_DIR, "Dist seconds is too short");
  2721. goto err;
  2722. }
  2723. if ((tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  2724. ns->client_versions = tor_strdup(tok->args[0]);
  2725. }
  2726. if ((tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS))) {
  2727. ns->server_versions = tor_strdup(tok->args[0]);
  2728. }
  2729. tok = find_by_keyword(tokens, K_KNOWN_FLAGS);
  2730. ns->known_flags = smartlist_new();
  2731. inorder = 1;
  2732. for (i = 0; i < tok->n_args; ++i) {
  2733. smartlist_add(ns->known_flags, tor_strdup(tok->args[i]));
  2734. if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) {
  2735. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  2736. inorder = 0;
  2737. }
  2738. }
  2739. if (!inorder) {
  2740. log_warn(LD_DIR, "known-flags not in order");
  2741. goto err;
  2742. }
  2743. if (ns->type != NS_TYPE_CONSENSUS &&
  2744. smartlist_len(ns->known_flags) > MAX_KNOWN_FLAGS_IN_VOTE) {
  2745. /* If we allowed more than 64 flags in votes, then parsing them would make
  2746. * us invoke undefined behavior whenever we used 1<<flagnum to do a
  2747. * bit-shift. This is only for votes and opinions: consensus users don't
  2748. * care about flags they don't recognize, and so don't build a bitfield
  2749. * for them. */
  2750. log_warn(LD_DIR, "Too many known-flags in consensus vote or opinion");
  2751. goto err;
  2752. }
  2753. tok = find_opt_by_keyword(tokens, K_PARAMS);
  2754. if (tok) {
  2755. int any_dups = 0;
  2756. inorder = 1;
  2757. ns->net_params = smartlist_new();
  2758. for (i = 0; i < tok->n_args; ++i) {
  2759. int ok=0;
  2760. char *eq = strchr(tok->args[i], '=');
  2761. size_t eq_pos;
  2762. if (!eq) {
  2763. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  2764. goto err;
  2765. }
  2766. eq_pos = eq-tok->args[i];
  2767. tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
  2768. if (!ok) {
  2769. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  2770. goto err;
  2771. }
  2772. if (i > 0 && strcmp(tok->args[i-1], tok->args[i]) >= 0) {
  2773. log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
  2774. inorder = 0;
  2775. }
  2776. if (last_kwd && eq_pos == strlen(last_kwd) &&
  2777. fast_memeq(last_kwd, tok->args[i], eq_pos)) {
  2778. log_warn(LD_DIR, "Duplicate value for %s parameter",
  2779. escaped(tok->args[i]));
  2780. any_dups = 1;
  2781. }
  2782. tor_free(last_kwd);
  2783. last_kwd = tor_strndup(tok->args[i], eq_pos);
  2784. smartlist_add(ns->net_params, tor_strdup(tok->args[i]));
  2785. }
  2786. if (!inorder) {
  2787. log_warn(LD_DIR, "params not in order");
  2788. goto err;
  2789. }
  2790. if (any_dups) {
  2791. log_warn(LD_DIR, "Duplicate in parameters");
  2792. goto err;
  2793. }
  2794. }
  2795. ns->voters = smartlist_new();
  2796. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  2797. tok = _tok;
  2798. if (tok->tp == K_DIR_SOURCE) {
  2799. tor_assert(tok->n_args >= 6);
  2800. if (voter)
  2801. smartlist_add(ns->voters, voter);
  2802. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  2803. voter->sigs = smartlist_new();
  2804. if (ns->type != NS_TYPE_CONSENSUS)
  2805. memcpy(voter->vote_digest, ns_digests.d[DIGEST_SHA1], DIGEST_LEN);
  2806. voter->nickname = tor_strdup(tok->args[0]);
  2807. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  2808. base16_decode(voter->identity_digest, sizeof(voter->identity_digest),
  2809. tok->args[1], HEX_DIGEST_LEN) < 0) {
  2810. log_warn(LD_DIR, "Error decoding identity digest %s in "
  2811. "network-status vote.", escaped(tok->args[1]));
  2812. goto err;
  2813. }
  2814. if (ns->type != NS_TYPE_CONSENSUS &&
  2815. tor_memneq(ns->cert->cache_info.identity_digest,
  2816. voter->identity_digest, DIGEST_LEN)) {
  2817. log_warn(LD_DIR,"Mismatch between identities in certificate and vote");
  2818. goto err;
  2819. }
  2820. voter->address = tor_strdup(tok->args[2]);
  2821. if (!tor_inet_aton(tok->args[3], &in)) {
  2822. log_warn(LD_DIR, "Error decoding IP address %s in network-status.",
  2823. escaped(tok->args[3]));
  2824. goto err;
  2825. }
  2826. voter->addr = ntohl(in.s_addr);
  2827. voter->dir_port = (uint16_t)
  2828. tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);
  2829. if (!ok)
  2830. goto err;
  2831. voter->or_port = (uint16_t)
  2832. tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);
  2833. if (!ok)
  2834. goto err;
  2835. } else if (tok->tp == K_CONTACT) {
  2836. if (!voter || voter->contact) {
  2837. log_warn(LD_DIR, "contact element is out of place.");
  2838. goto err;
  2839. }
  2840. voter->contact = tor_strdup(tok->args[0]);
  2841. } else if (tok->tp == K_VOTE_DIGEST) {
  2842. tor_assert(ns->type == NS_TYPE_CONSENSUS);
  2843. tor_assert(tok->n_args >= 1);
  2844. if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {
  2845. log_warn(LD_DIR, "vote-digest element is out of place.");
  2846. goto err;
  2847. }
  2848. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  2849. base16_decode(voter->vote_digest, sizeof(voter->vote_digest),
  2850. tok->args[0], HEX_DIGEST_LEN) < 0) {
  2851. log_warn(LD_DIR, "Error decoding vote digest %s in "
  2852. "network-status consensus.", escaped(tok->args[0]));
  2853. goto err;
  2854. }
  2855. }
  2856. } SMARTLIST_FOREACH_END(_tok);
  2857. if (voter) {
  2858. smartlist_add(ns->voters, voter);
  2859. voter = NULL;
  2860. }
  2861. if (smartlist_len(ns->voters) == 0) {
  2862. log_warn(LD_DIR, "Missing dir-source elements in a vote networkstatus.");
  2863. goto err;
  2864. } else if (ns->type != NS_TYPE_CONSENSUS && smartlist_len(ns->voters) != 1) {
  2865. log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus.");
  2866. goto err;
  2867. }
  2868. if (ns->type != NS_TYPE_CONSENSUS &&
  2869. (tok = find_opt_by_keyword(tokens, K_LEGACY_DIR_KEY))) {
  2870. int bad = 1;
  2871. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  2872. networkstatus_voter_info_t *voter = smartlist_get(ns->voters, 0);
  2873. if (base16_decode(voter->legacy_id_digest, DIGEST_LEN,
  2874. tok->args[0], HEX_DIGEST_LEN)<0)
  2875. bad = 1;
  2876. else
  2877. bad = 0;
  2878. }
  2879. if (bad) {
  2880. log_warn(LD_DIR, "Invalid legacy key digest %s on vote.",
  2881. escaped(tok->args[0]));
  2882. }
  2883. }
  2884. /* Parse routerstatus lines. */
  2885. rs_tokens = smartlist_new();
  2886. rs_area = memarea_new();
  2887. s = end_of_header;
  2888. ns->routerstatus_list = smartlist_new();
  2889. while (!strcmpstart(s, "r ")) {
  2890. if (ns->type != NS_TYPE_CONSENSUS) {
  2891. vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  2892. if (routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, ns,
  2893. rs, 0, 0))
  2894. smartlist_add(ns->routerstatus_list, rs);
  2895. else {
  2896. tor_free(rs->version);
  2897. tor_free(rs);
  2898. }
  2899. } else {
  2900. routerstatus_t *rs;
  2901. if ((rs = routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens,
  2902. NULL, NULL,
  2903. ns->consensus_method,
  2904. flav)))
  2905. smartlist_add(ns->routerstatus_list, rs);
  2906. }
  2907. }
  2908. for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {
  2909. routerstatus_t *rs1, *rs2;
  2910. if (ns->type != NS_TYPE_CONSENSUS) {
  2911. vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);
  2912. vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);
  2913. rs1 = &a->status; rs2 = &b->status;
  2914. } else {
  2915. rs1 = smartlist_get(ns->routerstatus_list, i-1);
  2916. rs2 = smartlist_get(ns->routerstatus_list, i);
  2917. }
  2918. if (fast_memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN)
  2919. >= 0) {
  2920. log_warn(LD_DIR, "Vote networkstatus entries not sorted by identity "
  2921. "digest");
  2922. goto err;
  2923. }
  2924. }
  2925. /* Parse footer; check signature. */
  2926. footer_tokens = smartlist_new();
  2927. if ((end_of_footer = strstr(s, "\nnetwork-status-version ")))
  2928. ++end_of_footer;
  2929. else
  2930. end_of_footer = s + strlen(s);
  2931. if (tokenize_string(area,s, end_of_footer, footer_tokens,
  2932. networkstatus_vote_footer_token_table, 0)) {
  2933. log_warn(LD_DIR, "Error tokenizing network-status vote footer.");
  2934. goto err;
  2935. }
  2936. {
  2937. int found_sig = 0;
  2938. SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
  2939. tok = _tok;
  2940. if (tok->tp == K_DIRECTORY_SIGNATURE)
  2941. found_sig = 1;
  2942. else if (found_sig) {
  2943. log_warn(LD_DIR, "Extraneous token after first directory-signature");
  2944. goto err;
  2945. }
  2946. } SMARTLIST_FOREACH_END(_tok);
  2947. }
  2948. if ((tok = find_opt_by_keyword(footer_tokens, K_DIRECTORY_FOOTER))) {
  2949. if (tok != smartlist_get(footer_tokens, 0)) {
  2950. log_warn(LD_DIR, "Misplaced directory-footer token");
  2951. goto err;
  2952. }
  2953. }
  2954. tok = find_opt_by_keyword(footer_tokens, K_BW_WEIGHTS);
  2955. if (tok) {
  2956. ns->weight_params = smartlist_new();
  2957. for (i = 0; i < tok->n_args; ++i) {
  2958. int ok=0;
  2959. char *eq = strchr(tok->args[i], '=');
  2960. if (!eq) {
  2961. log_warn(LD_DIR, "Bad element '%s' in weight params",
  2962. escaped(tok->args[i]));
  2963. goto err;
  2964. }
  2965. tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
  2966. if (!ok) {
  2967. log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
  2968. goto err;
  2969. }
  2970. smartlist_add(ns->weight_params, tor_strdup(tok->args[i]));
  2971. }
  2972. }
  2973. SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
  2974. char declared_identity[DIGEST_LEN];
  2975. networkstatus_voter_info_t *v;
  2976. document_signature_t *sig;
  2977. const char *id_hexdigest = NULL;
  2978. const char *sk_hexdigest = NULL;
  2979. digest_algorithm_t alg = DIGEST_SHA1;
  2980. tok = _tok;
  2981. if (tok->tp != K_DIRECTORY_SIGNATURE)
  2982. continue;
  2983. tor_assert(tok->n_args >= 2);
  2984. if (tok->n_args == 2) {
  2985. id_hexdigest = tok->args[0];
  2986. sk_hexdigest = tok->args[1];
  2987. } else {
  2988. const char *algname = tok->args[0];
  2989. int a;
  2990. id_hexdigest = tok->args[1];
  2991. sk_hexdigest = tok->args[2];
  2992. a = crypto_digest_algorithm_parse_name(algname);
  2993. if (a<0) {
  2994. log_warn(LD_DIR, "Unknown digest algorithm %s; skipping",
  2995. escaped(algname));
  2996. continue;
  2997. }
  2998. alg = a;
  2999. }
  3000. if (!tok->object_type ||
  3001. strcmp(tok->object_type, "SIGNATURE") ||
  3002. tok->object_size < 128 || tok->object_size > 512) {
  3003. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  3004. goto err;
  3005. }
  3006. if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
  3007. base16_decode(declared_identity, sizeof(declared_identity),
  3008. id_hexdigest, HEX_DIGEST_LEN) < 0) {
  3009. log_warn(LD_DIR, "Error decoding declared identity %s in "
  3010. "network-status vote.", escaped(id_hexdigest));
  3011. goto err;
  3012. }
  3013. if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {
  3014. log_warn(LD_DIR, "ID on signature on network-status vote does not match "
  3015. "any declared directory source.");
  3016. goto err;
  3017. }
  3018. sig = tor_malloc_zero(sizeof(document_signature_t));
  3019. memcpy(sig->identity_digest, v->identity_digest, DIGEST_LEN);
  3020. sig->alg = alg;
  3021. if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
  3022. base16_decode(sig->signing_key_digest, sizeof(sig->signing_key_digest),
  3023. sk_hexdigest, HEX_DIGEST_LEN) < 0) {
  3024. log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
  3025. "network-status vote.", escaped(sk_hexdigest));
  3026. tor_free(sig);
  3027. goto err;
  3028. }
  3029. if (ns->type != NS_TYPE_CONSENSUS) {
  3030. if (tor_memneq(declared_identity, ns->cert->cache_info.identity_digest,
  3031. DIGEST_LEN)) {
  3032. log_warn(LD_DIR, "Digest mismatch between declared and actual on "
  3033. "network-status vote.");
  3034. tor_free(sig);
  3035. goto err;
  3036. }
  3037. }
  3038. if (voter_get_sig_by_algorithm(v, sig->alg)) {
  3039. /* We already parsed a vote with this algorithm from this voter. Use the
  3040. first one. */
  3041. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "We received a networkstatus "
  3042. "that contains two votes from the same voter with the same "
  3043. "algorithm. Ignoring the second vote.");
  3044. tor_free(sig);
  3045. continue;
  3046. }
  3047. if (ns->type != NS_TYPE_CONSENSUS) {
  3048. if (check_signature_token(ns_digests.d[DIGEST_SHA1], DIGEST_LEN,
  3049. tok, ns->cert->signing_key, 0,
  3050. "network-status vote")) {
  3051. tor_free(sig);
  3052. goto err;
  3053. }
  3054. sig->good_signature = 1;
  3055. } else {
  3056. if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
  3057. tor_free(sig);
  3058. goto err;
  3059. }
  3060. sig->signature = tor_memdup(tok->object_body, tok->object_size);
  3061. sig->signature_len = (int) tok->object_size;
  3062. }
  3063. smartlist_add(v->sigs, sig);
  3064. ++n_signatures;
  3065. } SMARTLIST_FOREACH_END(_tok);
  3066. if (! n_signatures) {
  3067. log_warn(LD_DIR, "No signatures on networkstatus vote.");
  3068. goto err;
  3069. } else if (ns->type == NS_TYPE_VOTE && n_signatures != 1) {
  3070. log_warn(LD_DIR, "Received more than one signature on a "
  3071. "network-status vote.");
  3072. goto err;
  3073. }
  3074. if (eos_out)
  3075. *eos_out = end_of_footer;
  3076. goto done;
  3077. err:
  3078. dump_desc(s_dup, "v3 networkstatus");
  3079. networkstatus_vote_free(ns);
  3080. ns = NULL;
  3081. done:
  3082. if (tokens) {
  3083. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  3084. smartlist_free(tokens);
  3085. }
  3086. if (voter) {
  3087. if (voter->sigs) {
  3088. SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
  3089. document_signature_free(sig));
  3090. smartlist_free(voter->sigs);
  3091. }
  3092. tor_free(voter->nickname);
  3093. tor_free(voter->address);
  3094. tor_free(voter->contact);
  3095. tor_free(voter);
  3096. }
  3097. if (rs_tokens) {
  3098. SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_clear(t));
  3099. smartlist_free(rs_tokens);
  3100. }
  3101. if (footer_tokens) {
  3102. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_clear(t));
  3103. smartlist_free(footer_tokens);
  3104. }
  3105. if (area) {
  3106. DUMP_AREA(area, "v3 networkstatus");
  3107. memarea_drop_all(area);
  3108. }
  3109. if (rs_area)
  3110. memarea_drop_all(rs_area);
  3111. tor_free(last_kwd);
  3112. return ns;
  3113. }
  3114. /** Return the digests_t that holds the digests of the
  3115. * <b>flavor_name</b>-flavored networkstatus according to the detached
  3116. * signatures document <b>sigs</b>, allocating a new digests_t as neeeded. */
  3117. static digests_t *
  3118. detached_get_digests(ns_detached_signatures_t *sigs, const char *flavor_name)
  3119. {
  3120. digests_t *d = strmap_get(sigs->digests, flavor_name);
  3121. if (!d) {
  3122. d = tor_malloc_zero(sizeof(digests_t));
  3123. strmap_set(sigs->digests, flavor_name, d);
  3124. }
  3125. return d;
  3126. }
  3127. /** Return the list of signatures of the <b>flavor_name</b>-flavored
  3128. * networkstatus according to the detached signatures document <b>sigs</b>,
  3129. * allocating a new digests_t as neeeded. */
  3130. static smartlist_t *
  3131. detached_get_signatures(ns_detached_signatures_t *sigs,
  3132. const char *flavor_name)
  3133. {
  3134. smartlist_t *sl = strmap_get(sigs->signatures, flavor_name);
  3135. if (!sl) {
  3136. sl = smartlist_new();
  3137. strmap_set(sigs->signatures, flavor_name, sl);
  3138. }
  3139. return sl;
  3140. }
  3141. /** Parse a detached v3 networkstatus signature document between <b>s</b> and
  3142. * <b>eos</b> and return the result. Return -1 on failure. */
  3143. ns_detached_signatures_t *
  3144. networkstatus_parse_detached_signatures(const char *s, const char *eos)
  3145. {
  3146. /* XXXX there is too much duplicate shared between this function and
  3147. * networkstatus_parse_vote_from_string(). */
  3148. directory_token_t *tok;
  3149. memarea_t *area = NULL;
  3150. digests_t *digests;
  3151. smartlist_t *tokens = smartlist_new();
  3152. ns_detached_signatures_t *sigs =
  3153. tor_malloc_zero(sizeof(ns_detached_signatures_t));
  3154. sigs->digests = strmap_new();
  3155. sigs->signatures = strmap_new();
  3156. if (!eos)
  3157. eos = s + strlen(s);
  3158. area = memarea_new();
  3159. if (tokenize_string(area,s, eos, tokens,
  3160. networkstatus_detached_signature_token_table, 0)) {
  3161. log_warn(LD_DIR, "Error tokenizing detached networkstatus signatures");
  3162. goto err;
  3163. }
  3164. /* Grab all the digest-like tokens. */
  3165. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  3166. const char *algname;
  3167. digest_algorithm_t alg;
  3168. const char *flavor;
  3169. const char *hexdigest;
  3170. size_t expected_length;
  3171. tok = _tok;
  3172. if (tok->tp == K_CONSENSUS_DIGEST) {
  3173. algname = "sha1";
  3174. alg = DIGEST_SHA1;
  3175. flavor = "ns";
  3176. hexdigest = tok->args[0];
  3177. } else if (tok->tp == K_ADDITIONAL_DIGEST) {
  3178. int a = crypto_digest_algorithm_parse_name(tok->args[1]);
  3179. if (a<0) {
  3180. log_warn(LD_DIR, "Unrecognized algorithm name %s", tok->args[0]);
  3181. continue;
  3182. }
  3183. alg = (digest_algorithm_t) a;
  3184. flavor = tok->args[0];
  3185. algname = tok->args[1];
  3186. hexdigest = tok->args[2];
  3187. } else {
  3188. continue;
  3189. }
  3190. expected_length =
  3191. (alg == DIGEST_SHA1) ? HEX_DIGEST_LEN : HEX_DIGEST256_LEN;
  3192. if (strlen(hexdigest) != expected_length) {
  3193. log_warn(LD_DIR, "Wrong length on consensus-digest in detached "
  3194. "networkstatus signatures");
  3195. goto err;
  3196. }
  3197. digests = detached_get_digests(sigs, flavor);
  3198. tor_assert(digests);
  3199. if (!tor_mem_is_zero(digests->d[alg], DIGEST256_LEN)) {
  3200. log_warn(LD_DIR, "Multiple digests for %s with %s on detached "
  3201. "signatures document", flavor, algname);
  3202. continue;
  3203. }
  3204. if (base16_decode(digests->d[alg], DIGEST256_LEN,
  3205. hexdigest, strlen(hexdigest)) < 0) {
  3206. log_warn(LD_DIR, "Bad encoding on consensus-digest in detached "
  3207. "networkstatus signatures");
  3208. goto err;
  3209. }
  3210. } SMARTLIST_FOREACH_END(_tok);
  3211. tok = find_by_keyword(tokens, K_VALID_AFTER);
  3212. if (parse_iso_time(tok->args[0], &sigs->valid_after)) {
  3213. log_warn(LD_DIR, "Bad valid-after in detached networkstatus signatures");
  3214. goto err;
  3215. }
  3216. tok = find_by_keyword(tokens, K_FRESH_UNTIL);
  3217. if (parse_iso_time(tok->args[0], &sigs->fresh_until)) {
  3218. log_warn(LD_DIR, "Bad fresh-until in detached networkstatus signatures");
  3219. goto err;
  3220. }
  3221. tok = find_by_keyword(tokens, K_VALID_UNTIL);
  3222. if (parse_iso_time(tok->args[0], &sigs->valid_until)) {
  3223. log_warn(LD_DIR, "Bad valid-until in detached networkstatus signatures");
  3224. goto err;
  3225. }
  3226. SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
  3227. const char *id_hexdigest;
  3228. const char *sk_hexdigest;
  3229. const char *algname;
  3230. const char *flavor;
  3231. digest_algorithm_t alg;
  3232. char id_digest[DIGEST_LEN];
  3233. char sk_digest[DIGEST_LEN];
  3234. smartlist_t *siglist;
  3235. document_signature_t *sig;
  3236. int is_duplicate;
  3237. tok = _tok;
  3238. if (tok->tp == K_DIRECTORY_SIGNATURE) {
  3239. tor_assert(tok->n_args >= 2);
  3240. flavor = "ns";
  3241. algname = "sha1";
  3242. id_hexdigest = tok->args[0];
  3243. sk_hexdigest = tok->args[1];
  3244. } else if (tok->tp == K_ADDITIONAL_SIGNATURE) {
  3245. tor_assert(tok->n_args >= 4);
  3246. flavor = tok->args[0];
  3247. algname = tok->args[1];
  3248. id_hexdigest = tok->args[2];
  3249. sk_hexdigest = tok->args[3];
  3250. } else {
  3251. continue;
  3252. }
  3253. {
  3254. int a = crypto_digest_algorithm_parse_name(algname);
  3255. if (a<0) {
  3256. log_warn(LD_DIR, "Unrecognized algorithm name %s", algname);
  3257. continue;
  3258. }
  3259. alg = (digest_algorithm_t) a;
  3260. }
  3261. if (!tok->object_type ||
  3262. strcmp(tok->object_type, "SIGNATURE") ||
  3263. tok->object_size < 128 || tok->object_size > 512) {
  3264. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  3265. goto err;
  3266. }
  3267. if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
  3268. base16_decode(id_digest, sizeof(id_digest),
  3269. id_hexdigest, HEX_DIGEST_LEN) < 0) {
  3270. log_warn(LD_DIR, "Error decoding declared identity %s in "
  3271. "network-status vote.", escaped(id_hexdigest));
  3272. goto err;
  3273. }
  3274. if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
  3275. base16_decode(sk_digest, sizeof(sk_digest),
  3276. sk_hexdigest, HEX_DIGEST_LEN) < 0) {
  3277. log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
  3278. "network-status vote.", escaped(sk_hexdigest));
  3279. goto err;
  3280. }
  3281. siglist = detached_get_signatures(sigs, flavor);
  3282. is_duplicate = 0;
  3283. SMARTLIST_FOREACH(siglist, document_signature_t *, dsig, {
  3284. if (dsig->alg == alg &&
  3285. tor_memeq(id_digest, dsig->identity_digest, DIGEST_LEN) &&
  3286. tor_memeq(sk_digest, dsig->signing_key_digest, DIGEST_LEN)) {
  3287. is_duplicate = 1;
  3288. }
  3289. });
  3290. if (is_duplicate) {
  3291. log_warn(LD_DIR, "Two signatures with identical keys and algorithm "
  3292. "found.");
  3293. continue;
  3294. }
  3295. sig = tor_malloc_zero(sizeof(document_signature_t));
  3296. sig->alg = alg;
  3297. memcpy(sig->identity_digest, id_digest, DIGEST_LEN);
  3298. memcpy(sig->signing_key_digest, sk_digest, DIGEST_LEN);
  3299. if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
  3300. tor_free(sig);
  3301. goto err;
  3302. }
  3303. sig->signature = tor_memdup(tok->object_body, tok->object_size);
  3304. sig->signature_len = (int) tok->object_size;
  3305. smartlist_add(siglist, sig);
  3306. } SMARTLIST_FOREACH_END(_tok);
  3307. goto done;
  3308. err:
  3309. ns_detached_signatures_free(sigs);
  3310. sigs = NULL;
  3311. done:
  3312. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  3313. smartlist_free(tokens);
  3314. if (area) {
  3315. DUMP_AREA(area, "detached signatures");
  3316. memarea_drop_all(area);
  3317. }
  3318. return sigs;
  3319. }
  3320. /** Parse the addr policy in the string <b>s</b> and return it. If
  3321. * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
  3322. * ADDR_POLICY_REJECT) for items that specify no action.
  3323. *
  3324. * The addr_policy_t returned by this function can have its address set to
  3325. * AF_UNSPEC for '*'. Use policy_expand_unspec() to turn this into a pair
  3326. * of AF_INET and AF_INET6 items.
  3327. */
  3328. addr_policy_t *
  3329. router_parse_addr_policy_item_from_string(const char *s, int assume_action)
  3330. {
  3331. directory_token_t *tok = NULL;
  3332. const char *cp, *eos;
  3333. /* Longest possible policy is "accept ffff:ffff:..255/ffff:...255:0-65535".
  3334. * But note that there can be an arbitrary amount of space between the
  3335. * accept and the address:mask/port element. */
  3336. char line[TOR_ADDR_BUF_LEN*2 + 32];
  3337. addr_policy_t *r;
  3338. memarea_t *area = NULL;
  3339. s = eat_whitespace(s);
  3340. if ((*s == '*' || TOR_ISDIGIT(*s)) && assume_action >= 0) {
  3341. if (tor_snprintf(line, sizeof(line), "%s %s",
  3342. assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", s)<0) {
  3343. log_warn(LD_DIR, "Policy %s is too long.", escaped(s));
  3344. return NULL;
  3345. }
  3346. cp = line;
  3347. tor_strlower(line);
  3348. } else { /* assume an already well-formed address policy line */
  3349. cp = s;
  3350. }
  3351. eos = cp + strlen(cp);
  3352. area = memarea_new();
  3353. tok = get_next_token(area, &cp, eos, routerdesc_token_table);
  3354. if (tok->tp == ERR_) {
  3355. log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
  3356. goto err;
  3357. }
  3358. if (tok->tp != K_ACCEPT && tok->tp != K_ACCEPT6 &&
  3359. tok->tp != K_REJECT && tok->tp != K_REJECT6) {
  3360. log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
  3361. goto err;
  3362. }
  3363. r = router_parse_addr_policy(tok, TAPMP_EXTENDED_STAR);
  3364. goto done;
  3365. err:
  3366. r = NULL;
  3367. done:
  3368. token_clear(tok);
  3369. if (area) {
  3370. DUMP_AREA(area, "policy item");
  3371. memarea_drop_all(area);
  3372. }
  3373. return r;
  3374. }
  3375. /** Add an exit policy stored in the token <b>tok</b> to the router info in
  3376. * <b>router</b>. Return 0 on success, -1 on failure. */
  3377. static int
  3378. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
  3379. {
  3380. addr_policy_t *newe;
  3381. newe = router_parse_addr_policy(tok, 0);
  3382. if (!newe)
  3383. return -1;
  3384. if (! router->exit_policy)
  3385. router->exit_policy = smartlist_new();
  3386. if (((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
  3387. tor_addr_family(&newe->addr) == AF_INET)
  3388. ||
  3389. ((tok->tp == K_ACCEPT || tok->tp == K_REJECT) &&
  3390. tor_addr_family(&newe->addr) == AF_INET6)) {
  3391. log_warn(LD_DIR, "Mismatch between field type and address type in exit "
  3392. "policy");
  3393. addr_policy_free(newe);
  3394. return -1;
  3395. }
  3396. smartlist_add(router->exit_policy, newe);
  3397. return 0;
  3398. }
  3399. /** Given a K_ACCEPT or K_REJECT token and a router, create and return
  3400. * a new exit_policy_t corresponding to the token. */
  3401. static addr_policy_t *
  3402. router_parse_addr_policy(directory_token_t *tok, unsigned fmt_flags)
  3403. {
  3404. addr_policy_t newe;
  3405. char *arg;
  3406. tor_assert(tok->tp == K_REJECT || tok->tp == K_REJECT6 ||
  3407. tok->tp == K_ACCEPT || tok->tp == K_ACCEPT6);
  3408. if (tok->n_args != 1)
  3409. return NULL;
  3410. arg = tok->args[0];
  3411. if (!strcmpstart(arg,"private"))
  3412. return router_parse_addr_policy_private(tok);
  3413. memset(&newe, 0, sizeof(newe));
  3414. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  3415. newe.policy_type = ADDR_POLICY_REJECT;
  3416. else
  3417. newe.policy_type = ADDR_POLICY_ACCEPT;
  3418. if (tor_addr_parse_mask_ports(arg, fmt_flags, &newe.addr, &newe.maskbits,
  3419. &newe.prt_min, &newe.prt_max) < 0) {
  3420. log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
  3421. return NULL;
  3422. }
  3423. return addr_policy_get_canonical_entry(&newe);
  3424. }
  3425. /** Parse an exit policy line of the format "accept/reject private:...".
  3426. * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
  3427. * router descriptors until earlier versions are obsolete.
  3428. */
  3429. static addr_policy_t *
  3430. router_parse_addr_policy_private(directory_token_t *tok)
  3431. {
  3432. const char *arg;
  3433. uint16_t port_min, port_max;
  3434. addr_policy_t result;
  3435. arg = tok->args[0];
  3436. if (strcmpstart(arg, "private"))
  3437. return NULL;
  3438. arg += strlen("private");
  3439. arg = (char*) eat_whitespace(arg);
  3440. if (!arg || *arg != ':')
  3441. return NULL;
  3442. if (parse_port_range(arg+1, &port_min, &port_max)<0)
  3443. return NULL;
  3444. memset(&result, 0, sizeof(result));
  3445. if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
  3446. result.policy_type = ADDR_POLICY_REJECT;
  3447. else
  3448. result.policy_type = ADDR_POLICY_ACCEPT;
  3449. result.is_private = 1;
  3450. result.prt_min = port_min;
  3451. result.prt_max = port_max;
  3452. return addr_policy_get_canonical_entry(&result);
  3453. }
  3454. /** Log and exit if <b>t</b> is malformed */
  3455. void
  3456. assert_addr_policy_ok(smartlist_t *lst)
  3457. {
  3458. if (!lst) return;
  3459. SMARTLIST_FOREACH(lst, addr_policy_t *, t, {
  3460. tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
  3461. t->policy_type == ADDR_POLICY_ACCEPT);
  3462. tor_assert(t->prt_min <= t->prt_max);
  3463. });
  3464. }
  3465. /*
  3466. * Low-level tokenizer for router descriptors and directories.
  3467. */
  3468. /** Free all resources allocated for <b>tok</b> */
  3469. static void
  3470. token_clear(directory_token_t *tok)
  3471. {
  3472. if (tok->key)
  3473. crypto_pk_free(tok->key);
  3474. }
  3475. #define ALLOC_ZERO(sz) memarea_alloc_zero(area,sz)
  3476. #define ALLOC(sz) memarea_alloc(area,sz)
  3477. #define STRDUP(str) memarea_strdup(area,str)
  3478. #define STRNDUP(str,n) memarea_strndup(area,(str),(n))
  3479. #define RET_ERR(msg) \
  3480. STMT_BEGIN \
  3481. if (tok) token_clear(tok); \
  3482. tok = ALLOC_ZERO(sizeof(directory_token_t)); \
  3483. tok->tp = ERR_; \
  3484. tok->error = STRDUP(msg); \
  3485. goto done_tokenizing; \
  3486. STMT_END
  3487. /** Helper: make sure that the token <b>tok</b> with keyword <b>kwd</b> obeys
  3488. * the object syntax of <b>o_syn</b>. Allocate all storage in <b>area</b>.
  3489. * Return <b>tok</b> on success, or a new ERR_ token if the token didn't
  3490. * conform to the syntax we wanted.
  3491. **/
  3492. static INLINE directory_token_t *
  3493. token_check_object(memarea_t *area, const char *kwd,
  3494. directory_token_t *tok, obj_syntax o_syn)
  3495. {
  3496. char ebuf[128];
  3497. switch (o_syn) {
  3498. case NO_OBJ:
  3499. /* No object is allowed for this token. */
  3500. if (tok->object_body) {
  3501. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected object for %s", kwd);
  3502. RET_ERR(ebuf);
  3503. }
  3504. if (tok->key) {
  3505. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected public key for %s", kwd);
  3506. RET_ERR(ebuf);
  3507. }
  3508. break;
  3509. case NEED_OBJ:
  3510. /* There must be a (non-key) object. */
  3511. if (!tok->object_body) {
  3512. tor_snprintf(ebuf, sizeof(ebuf), "Missing object for %s", kwd);
  3513. RET_ERR(ebuf);
  3514. }
  3515. break;
  3516. case NEED_KEY_1024: /* There must be a 1024-bit public key. */
  3517. case NEED_SKEY_1024: /* There must be a 1024-bit private key. */
  3518. if (tok->key && crypto_pk_num_bits(tok->key) != PK_BYTES*8) {
  3519. tor_snprintf(ebuf, sizeof(ebuf), "Wrong size on key for %s: %d bits",
  3520. kwd, crypto_pk_num_bits(tok->key));
  3521. RET_ERR(ebuf);
  3522. }
  3523. /* fall through */
  3524. case NEED_KEY: /* There must be some kind of key. */
  3525. if (!tok->key) {
  3526. tor_snprintf(ebuf, sizeof(ebuf), "Missing public key for %s", kwd);
  3527. RET_ERR(ebuf);
  3528. }
  3529. if (o_syn != NEED_SKEY_1024) {
  3530. if (crypto_pk_key_is_private(tok->key)) {
  3531. tor_snprintf(ebuf, sizeof(ebuf),
  3532. "Private key given for %s, which wants a public key", kwd);
  3533. RET_ERR(ebuf);
  3534. }
  3535. } else { /* o_syn == NEED_SKEY_1024 */
  3536. if (!crypto_pk_key_is_private(tok->key)) {
  3537. tor_snprintf(ebuf, sizeof(ebuf),
  3538. "Public key given for %s, which wants a private key", kwd);
  3539. RET_ERR(ebuf);
  3540. }
  3541. }
  3542. break;
  3543. case OBJ_OK:
  3544. /* Anything goes with this token. */
  3545. break;
  3546. }
  3547. done_tokenizing:
  3548. return tok;
  3549. }
  3550. /** Helper: parse space-separated arguments from the string <b>s</b> ending at
  3551. * <b>eol</b>, and store them in the args field of <b>tok</b>. Store the
  3552. * number of parsed elements into the n_args field of <b>tok</b>. Allocate
  3553. * all storage in <b>area</b>. Return the number of arguments parsed, or
  3554. * return -1 if there was an insanely high number of arguments. */
  3555. static INLINE int
  3556. get_token_arguments(memarea_t *area, directory_token_t *tok,
  3557. const char *s, const char *eol)
  3558. {
  3559. /** Largest number of arguments we'll accept to any token, ever. */
  3560. #define MAX_ARGS 512
  3561. char *mem = memarea_strndup(area, s, eol-s);
  3562. char *cp = mem;
  3563. int j = 0;
  3564. char *args[MAX_ARGS];
  3565. while (*cp) {
  3566. if (j == MAX_ARGS)
  3567. return -1;
  3568. args[j++] = cp;
  3569. cp = (char*)find_whitespace(cp);
  3570. if (!cp || !*cp)
  3571. break; /* End of the line. */
  3572. *cp++ = '\0';
  3573. cp = (char*)eat_whitespace(cp);
  3574. }
  3575. tok->n_args = j;
  3576. tok->args = memarea_memdup(area, args, j*sizeof(char*));
  3577. return j;
  3578. #undef MAX_ARGS
  3579. }
  3580. /** Helper function: read the next token from *s, advance *s to the end of the
  3581. * token, and return the parsed token. Parse *<b>s</b> according to the list
  3582. * of tokens in <b>table</b>.
  3583. */
  3584. static directory_token_t *
  3585. get_next_token(memarea_t *area,
  3586. const char **s, const char *eos, token_rule_t *table)
  3587. {
  3588. /** Reject any object at least this big; it is probably an overflow, an
  3589. * attack, a bug, or some other nonsense. */
  3590. #define MAX_UNPARSED_OBJECT_SIZE (128*1024)
  3591. /** Reject any line at least this big; it is probably an overflow, an
  3592. * attack, a bug, or some other nonsense. */
  3593. #define MAX_LINE_LENGTH (128*1024)
  3594. const char *next, *eol, *obstart;
  3595. size_t obname_len;
  3596. int i;
  3597. directory_token_t *tok;
  3598. obj_syntax o_syn = NO_OBJ;
  3599. char ebuf[128];
  3600. const char *kwd = "";
  3601. tor_assert(area);
  3602. tok = ALLOC_ZERO(sizeof(directory_token_t));
  3603. tok->tp = ERR_;
  3604. /* Set *s to first token, eol to end-of-line, next to after first token */
  3605. *s = eat_whitespace_eos(*s, eos); /* eat multi-line whitespace */
  3606. tor_assert(eos >= *s);
  3607. eol = memchr(*s, '\n', eos-*s);
  3608. if (!eol)
  3609. eol = eos;
  3610. if (eol - *s > MAX_LINE_LENGTH) {
  3611. RET_ERR("Line far too long");
  3612. }
  3613. next = find_whitespace_eos(*s, eol);
  3614. if (!strcmp_len(*s, "opt", next-*s)) {
  3615. /* Skip past an "opt" at the start of the line. */
  3616. *s = eat_whitespace_eos_no_nl(next, eol);
  3617. next = find_whitespace_eos(*s, eol);
  3618. } else if (*s == eos) { /* If no "opt", and end-of-line, line is invalid */
  3619. RET_ERR("Unexpected EOF");
  3620. }
  3621. /* Search the table for the appropriate entry. (I tried a binary search
  3622. * instead, but it wasn't any faster.) */
  3623. for (i = 0; table[i].t ; ++i) {
  3624. if (!strcmp_len(*s, table[i].t, next-*s)) {
  3625. /* We've found the keyword. */
  3626. kwd = table[i].t;
  3627. tok->tp = table[i].v;
  3628. o_syn = table[i].os;
  3629. *s = eat_whitespace_eos_no_nl(next, eol);
  3630. /* We go ahead whether there are arguments or not, so that tok->args is
  3631. * always set if we want arguments. */
  3632. if (table[i].concat_args) {
  3633. /* The keyword takes the line as a single argument */
  3634. tok->args = ALLOC(sizeof(char*));
  3635. tok->args[0] = STRNDUP(*s,eol-*s); /* Grab everything on line */
  3636. tok->n_args = 1;
  3637. } else {
  3638. /* This keyword takes multiple arguments. */
  3639. if (get_token_arguments(area, tok, *s, eol)<0) {
  3640. tor_snprintf(ebuf, sizeof(ebuf),"Far too many arguments to %s", kwd);
  3641. RET_ERR(ebuf);
  3642. }
  3643. *s = eol;
  3644. }
  3645. if (tok->n_args < table[i].min_args) {
  3646. tor_snprintf(ebuf, sizeof(ebuf), "Too few arguments to %s", kwd);
  3647. RET_ERR(ebuf);
  3648. } else if (tok->n_args > table[i].max_args) {
  3649. tor_snprintf(ebuf, sizeof(ebuf), "Too many arguments to %s", kwd);
  3650. RET_ERR(ebuf);
  3651. }
  3652. break;
  3653. }
  3654. }
  3655. if (tok->tp == ERR_) {
  3656. /* No keyword matched; call it an "K_opt" or "A_unrecognized" */
  3657. if (**s == '@')
  3658. tok->tp = A_UNKNOWN_;
  3659. else
  3660. tok->tp = K_OPT;
  3661. tok->args = ALLOC(sizeof(char*));
  3662. tok->args[0] = STRNDUP(*s, eol-*s);
  3663. tok->n_args = 1;
  3664. o_syn = OBJ_OK;
  3665. }
  3666. /* Check whether there's an object present */
  3667. *s = eat_whitespace_eos(eol, eos); /* Scan from end of first line */
  3668. tor_assert(eos >= *s);
  3669. eol = memchr(*s, '\n', eos-*s);
  3670. if (!eol || eol-*s<11 || strcmpstart(*s, "-----BEGIN ")) /* No object. */
  3671. goto check_object;
  3672. obstart = *s; /* Set obstart to start of object spec */
  3673. if (*s+16 >= eol || memchr(*s+11,'\0',eol-*s-16) || /* no short lines, */
  3674. strcmp_len(eol-5, "-----", 5) || /* nuls or invalid endings */
  3675. (eol-*s) > MAX_UNPARSED_OBJECT_SIZE) { /* name too long */
  3676. RET_ERR("Malformed object: bad begin line");
  3677. }
  3678. tok->object_type = STRNDUP(*s+11, eol-*s-16);
  3679. obname_len = eol-*s-16; /* store objname length here to avoid a strlen() */
  3680. *s = eol+1; /* Set *s to possible start of object data (could be eos) */
  3681. /* Go to the end of the object */
  3682. next = tor_memstr(*s, eos-*s, "-----END ");
  3683. if (!next) {
  3684. RET_ERR("Malformed object: missing object end line");
  3685. }
  3686. tor_assert(eos >= next);
  3687. eol = memchr(next, '\n', eos-next);
  3688. if (!eol) /* end-of-line marker, or eos if there's no '\n' */
  3689. eol = eos;
  3690. /* Validate the ending tag, which should be 9 + NAME + 5 + eol */
  3691. if ((size_t)(eol-next) != 9+obname_len+5 ||
  3692. strcmp_len(next+9, tok->object_type, obname_len) ||
  3693. strcmp_len(eol-5, "-----", 5)) {
  3694. snprintf(ebuf, sizeof(ebuf), "Malformed object: mismatched end tag %s",
  3695. tok->object_type);
  3696. ebuf[sizeof(ebuf)-1] = '\0';
  3697. RET_ERR(ebuf);
  3698. }
  3699. if (next - *s > MAX_UNPARSED_OBJECT_SIZE)
  3700. RET_ERR("Couldn't parse object: missing footer or object much too big.");
  3701. if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) { /* If it's a public key */
  3702. tok->key = crypto_pk_new();
  3703. if (crypto_pk_read_public_key_from_string(tok->key, obstart, eol-obstart))
  3704. RET_ERR("Couldn't parse public key.");
  3705. } else if (!strcmp(tok->object_type, "RSA PRIVATE KEY")) { /* private key */
  3706. tok->key = crypto_pk_new();
  3707. if (crypto_pk_read_private_key_from_string(tok->key, obstart, eol-obstart))
  3708. RET_ERR("Couldn't parse private key.");
  3709. } else { /* If it's something else, try to base64-decode it */
  3710. int r;
  3711. tok->object_body = ALLOC(next-*s); /* really, this is too much RAM. */
  3712. r = base64_decode(tok->object_body, next-*s, *s, next-*s);
  3713. if (r<0)
  3714. RET_ERR("Malformed object: bad base64-encoded data");
  3715. tok->object_size = r;
  3716. }
  3717. *s = eol;
  3718. check_object:
  3719. tok = token_check_object(area, kwd, tok, o_syn);
  3720. done_tokenizing:
  3721. return tok;
  3722. #undef RET_ERR
  3723. #undef ALLOC
  3724. #undef ALLOC_ZERO
  3725. #undef STRDUP
  3726. #undef STRNDUP
  3727. }
  3728. /** Read all tokens from a string between <b>start</b> and <b>end</b>, and add
  3729. * them to <b>out</b>. Parse according to the token rules in <b>table</b>.
  3730. * Caller must free tokens in <b>out</b>. If <b>end</b> is NULL, use the
  3731. * entire string.
  3732. */
  3733. static int
  3734. tokenize_string(memarea_t *area,
  3735. const char *start, const char *end, smartlist_t *out,
  3736. token_rule_t *table, int flags)
  3737. {
  3738. const char **s;
  3739. directory_token_t *tok = NULL;
  3740. int counts[NIL_];
  3741. int i;
  3742. int first_nonannotation;
  3743. int prev_len = smartlist_len(out);
  3744. tor_assert(area);
  3745. s = &start;
  3746. if (!end)
  3747. end = start+strlen(start);
  3748. for (i = 0; i < NIL_; ++i)
  3749. counts[i] = 0;
  3750. SMARTLIST_FOREACH(out, const directory_token_t *, t, ++counts[t->tp]);
  3751. while (*s < end && (!tok || tok->tp != EOF_)) {
  3752. tok = get_next_token(area, s, end, table);
  3753. if (tok->tp == ERR_) {
  3754. log_warn(LD_DIR, "parse error: %s", tok->error);
  3755. token_clear(tok);
  3756. return -1;
  3757. }
  3758. ++counts[tok->tp];
  3759. smartlist_add(out, tok);
  3760. *s = eat_whitespace_eos(*s, end);
  3761. }
  3762. if (flags & TS_NOCHECK)
  3763. return 0;
  3764. if ((flags & TS_ANNOTATIONS_OK)) {
  3765. first_nonannotation = -1;
  3766. for (i = 0; i < smartlist_len(out); ++i) {
  3767. tok = smartlist_get(out, i);
  3768. if (tok->tp < MIN_ANNOTATION || tok->tp > MAX_ANNOTATION) {
  3769. first_nonannotation = i;
  3770. break;
  3771. }
  3772. }
  3773. if (first_nonannotation < 0) {
  3774. log_warn(LD_DIR, "parse error: item contains only annotations");
  3775. return -1;
  3776. }
  3777. for (i=first_nonannotation; i < smartlist_len(out); ++i) {
  3778. tok = smartlist_get(out, i);
  3779. if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
  3780. log_warn(LD_DIR, "parse error: Annotations mixed with keywords");
  3781. return -1;
  3782. }
  3783. }
  3784. if ((flags & TS_NO_NEW_ANNOTATIONS)) {
  3785. if (first_nonannotation != prev_len) {
  3786. log_warn(LD_DIR, "parse error: Unexpected annotations.");
  3787. return -1;
  3788. }
  3789. }
  3790. } else {
  3791. for (i=0; i < smartlist_len(out); ++i) {
  3792. tok = smartlist_get(out, i);
  3793. if (tok->tp >= MIN_ANNOTATION && tok->tp <= MAX_ANNOTATION) {
  3794. log_warn(LD_DIR, "parse error: no annotations allowed.");
  3795. return -1;
  3796. }
  3797. }
  3798. first_nonannotation = 0;
  3799. }
  3800. for (i = 0; table[i].t; ++i) {
  3801. if (counts[table[i].v] < table[i].min_cnt) {
  3802. log_warn(LD_DIR, "Parse error: missing %s element.", table[i].t);
  3803. return -1;
  3804. }
  3805. if (counts[table[i].v] > table[i].max_cnt) {
  3806. log_warn(LD_DIR, "Parse error: too many %s elements.", table[i].t);
  3807. return -1;
  3808. }
  3809. if (table[i].pos & AT_START) {
  3810. if (smartlist_len(out) < 1 ||
  3811. (tok = smartlist_get(out, first_nonannotation))->tp != table[i].v) {
  3812. log_warn(LD_DIR, "Parse error: first item is not %s.", table[i].t);
  3813. return -1;
  3814. }
  3815. }
  3816. if (table[i].pos & AT_END) {
  3817. if (smartlist_len(out) < 1 ||
  3818. (tok = smartlist_get(out, smartlist_len(out)-1))->tp != table[i].v) {
  3819. log_warn(LD_DIR, "Parse error: last item is not %s.", table[i].t);
  3820. return -1;
  3821. }
  3822. }
  3823. }
  3824. return 0;
  3825. }
  3826. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
  3827. * NULL if no such keyword is found.
  3828. */
  3829. static directory_token_t *
  3830. find_opt_by_keyword(smartlist_t *s, directory_keyword keyword)
  3831. {
  3832. SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
  3833. return NULL;
  3834. }
  3835. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; fail
  3836. * with an assert if no such keyword is found.
  3837. */
  3838. static directory_token_t *
  3839. find_by_keyword_(smartlist_t *s, directory_keyword keyword,
  3840. const char *keyword_as_string)
  3841. {
  3842. directory_token_t *tok = find_opt_by_keyword(s, keyword);
  3843. if (PREDICT_UNLIKELY(!tok)) {
  3844. log_err(LD_BUG, "Missing %s [%d] in directory object that should have "
  3845. "been validated. Internal error.", keyword_as_string, (int)keyword);
  3846. tor_assert(tok);
  3847. }
  3848. return tok;
  3849. }
  3850. /** If there are any directory_token_t entries in <b>s</b> whose keyword is
  3851. * <b>k</b>, return a newly allocated smartlist_t containing all such entries,
  3852. * in the same order in which they occur in <b>s</b>. Otherwise return
  3853. * NULL. */
  3854. static smartlist_t *
  3855. find_all_by_keyword(smartlist_t *s, directory_keyword k)
  3856. {
  3857. smartlist_t *out = NULL;
  3858. SMARTLIST_FOREACH(s, directory_token_t *, t,
  3859. if (t->tp == k) {
  3860. if (!out)
  3861. out = smartlist_new();
  3862. smartlist_add(out, t);
  3863. });
  3864. return out;
  3865. }
  3866. /** Return a newly allocated smartlist of all accept or reject tokens in
  3867. * <b>s</b>.
  3868. */
  3869. static smartlist_t *
  3870. find_all_exitpolicy(smartlist_t *s)
  3871. {
  3872. smartlist_t *out = smartlist_new();
  3873. SMARTLIST_FOREACH(s, directory_token_t *, t,
  3874. if (t->tp == K_ACCEPT || t->tp == K_ACCEPT6 ||
  3875. t->tp == K_REJECT || t->tp == K_REJECT6)
  3876. smartlist_add(out,t));
  3877. return out;
  3878. }
  3879. /** Helper function for <b>router_get_hash_impl</b>: given <b>s</b>,
  3880. * <b>s_len</b>, <b>start_str</b>, <b>end_str</b>, and <b>end_c</b> with the
  3881. * same semantics as in that function, set *<b>start_out</b> (inclusive) and
  3882. * *<b>end_out</b> (exclusive) to the boundaries of the string to be hashed.
  3883. *
  3884. * Return 0 on success and -1 on failure.
  3885. */
  3886. static int
  3887. router_get_hash_impl_helper(const char *s, size_t s_len,
  3888. const char *start_str,
  3889. const char *end_str, char end_c,
  3890. const char **start_out, const char **end_out)
  3891. {
  3892. const char *start, *end;
  3893. start = tor_memstr(s, s_len, start_str);
  3894. if (!start) {
  3895. log_warn(LD_DIR,"couldn't find start of hashed material \"%s\"",start_str);
  3896. return -1;
  3897. }
  3898. if (start != s && *(start-1) != '\n') {
  3899. log_warn(LD_DIR,
  3900. "first occurrence of \"%s\" is not at the start of a line",
  3901. start_str);
  3902. return -1;
  3903. }
  3904. end = tor_memstr(start+strlen(start_str),
  3905. s_len - (start-s) - strlen(start_str), end_str);
  3906. if (!end) {
  3907. log_warn(LD_DIR,"couldn't find end of hashed material \"%s\"",end_str);
  3908. return -1;
  3909. }
  3910. end = memchr(end+strlen(end_str), end_c, s_len - (end-s) - strlen(end_str));
  3911. if (!end) {
  3912. log_warn(LD_DIR,"couldn't find EOL");
  3913. return -1;
  3914. }
  3915. ++end;
  3916. *start_out = start;
  3917. *end_out = end;
  3918. return 0;
  3919. }
  3920. /** Compute the digest of the substring of <b>s</b> taken from the first
  3921. * occurrence of <b>start_str</b> through the first instance of c after the
  3922. * first subsequent occurrence of <b>end_str</b>; store the 20-byte result in
  3923. * <b>digest</b>; return 0 on success.
  3924. *
  3925. * If no such substring exists, return -1.
  3926. */
  3927. static int
  3928. router_get_hash_impl(const char *s, size_t s_len, char *digest,
  3929. const char *start_str,
  3930. const char *end_str, char end_c,
  3931. digest_algorithm_t alg)
  3932. {
  3933. const char *start=NULL, *end=NULL;
  3934. if (router_get_hash_impl_helper(s,s_len,start_str,end_str,end_c,
  3935. &start,&end)<0)
  3936. return -1;
  3937. if (alg == DIGEST_SHA1) {
  3938. if (crypto_digest(digest, start, end-start)) {
  3939. log_warn(LD_BUG,"couldn't compute digest");
  3940. return -1;
  3941. }
  3942. } else {
  3943. if (crypto_digest256(digest, start, end-start, alg)) {
  3944. log_warn(LD_BUG,"couldn't compute digest");
  3945. return -1;
  3946. }
  3947. }
  3948. return 0;
  3949. }
  3950. /** As router_get_hash_impl, but compute all hashes. */
  3951. static int
  3952. router_get_hashes_impl(const char *s, size_t s_len, digests_t *digests,
  3953. const char *start_str,
  3954. const char *end_str, char end_c)
  3955. {
  3956. const char *start=NULL, *end=NULL;
  3957. if (router_get_hash_impl_helper(s,s_len,start_str,end_str,end_c,
  3958. &start,&end)<0)
  3959. return -1;
  3960. if (crypto_digest_all(digests, start, end-start)) {
  3961. log_warn(LD_BUG,"couldn't compute digests");
  3962. return -1;
  3963. }
  3964. return 0;
  3965. }
  3966. /** Assuming that s starts with a microdesc, return the start of the
  3967. * *NEXT* one. Return NULL on "not found." */
  3968. static const char *
  3969. find_start_of_next_microdesc(const char *s, const char *eos)
  3970. {
  3971. int started_with_annotations;
  3972. s = eat_whitespace_eos(s, eos);
  3973. if (!s)
  3974. return NULL;
  3975. #define CHECK_LENGTH() STMT_BEGIN \
  3976. if (s+32 > eos) \
  3977. return NULL; \
  3978. STMT_END
  3979. #define NEXT_LINE() STMT_BEGIN \
  3980. s = memchr(s, '\n', eos-s); \
  3981. if (!s || s+1 >= eos) \
  3982. return NULL; \
  3983. s++; \
  3984. STMT_END
  3985. CHECK_LENGTH();
  3986. started_with_annotations = (*s == '@');
  3987. if (started_with_annotations) {
  3988. /* Start by advancing to the first non-annotation line. */
  3989. while (*s == '@')
  3990. NEXT_LINE();
  3991. }
  3992. CHECK_LENGTH();
  3993. /* Now we should be pointed at an onion-key line. If we are, then skip
  3994. * it. */
  3995. if (!strcmpstart(s, "onion-key"))
  3996. NEXT_LINE();
  3997. /* Okay, now we're pointed at the first line of the microdescriptor which is
  3998. not an annotation or onion-key. The next line that _is_ an annotation or
  3999. onion-key is the start of the next microdescriptor. */
  4000. while (s+32 < eos) {
  4001. if (*s == '@' || !strcmpstart(s, "onion-key"))
  4002. return s;
  4003. NEXT_LINE();
  4004. }
  4005. return NULL;
  4006. #undef CHECK_LENGTH
  4007. #undef NEXT_LINE
  4008. }
  4009. /** Parse as many microdescriptors as are found from the string starting at
  4010. * <b>s</b> and ending at <b>eos</b>. If allow_annotations is set, read any
  4011. * annotations we recognize and ignore ones we don't. If <b>copy_body</b> is
  4012. * true, then strdup the bodies of the microdescriptors. Return all newly
  4013. * parsed microdescriptors in a newly allocated smartlist_t. */
  4014. smartlist_t *
  4015. microdescs_parse_from_string(const char *s, const char *eos,
  4016. int allow_annotations, int copy_body)
  4017. {
  4018. smartlist_t *tokens;
  4019. smartlist_t *result;
  4020. microdesc_t *md = NULL;
  4021. memarea_t *area;
  4022. const char *start = s;
  4023. const char *start_of_next_microdesc;
  4024. int flags = allow_annotations ? TS_ANNOTATIONS_OK : 0;
  4025. directory_token_t *tok;
  4026. if (!eos)
  4027. eos = s + strlen(s);
  4028. s = eat_whitespace_eos(s, eos);
  4029. area = memarea_new();
  4030. result = smartlist_new();
  4031. tokens = smartlist_new();
  4032. while (s < eos) {
  4033. start_of_next_microdesc = find_start_of_next_microdesc(s, eos);
  4034. if (!start_of_next_microdesc)
  4035. start_of_next_microdesc = eos;
  4036. if (tokenize_string(area, s, start_of_next_microdesc, tokens,
  4037. microdesc_token_table, flags)) {
  4038. log_warn(LD_DIR, "Unparseable microdescriptor");
  4039. goto next;
  4040. }
  4041. md = tor_malloc_zero(sizeof(microdesc_t));
  4042. {
  4043. const char *cp = tor_memstr(s, start_of_next_microdesc-s,
  4044. "onion-key");
  4045. tor_assert(cp);
  4046. md->bodylen = start_of_next_microdesc - cp;
  4047. if (copy_body)
  4048. md->body = tor_strndup(cp, md->bodylen);
  4049. else
  4050. md->body = (char*)cp;
  4051. md->off = cp - start;
  4052. }
  4053. if ((tok = find_opt_by_keyword(tokens, A_LAST_LISTED))) {
  4054. if (parse_iso_time(tok->args[0], &md->last_listed)) {
  4055. log_warn(LD_DIR, "Bad last-listed time in microdescriptor");
  4056. goto next;
  4057. }
  4058. }
  4059. tok = find_by_keyword(tokens, K_ONION_KEY);
  4060. if (!crypto_pk_public_exponent_ok(tok->key)) {
  4061. log_warn(LD_DIR,
  4062. "Relay's onion key had invalid exponent.");
  4063. goto next;
  4064. }
  4065. md->onion_pkey = tok->key;
  4066. tok->key = NULL;
  4067. {
  4068. smartlist_t *a_lines = find_all_by_keyword(tokens, K_A);
  4069. if (a_lines) {
  4070. find_single_ipv6_orport(a_lines, &md->ipv6_addr, &md->ipv6_orport);
  4071. smartlist_free(a_lines);
  4072. }
  4073. }
  4074. if ((tok = find_opt_by_keyword(tokens, K_FAMILY))) {
  4075. int i;
  4076. md->family = smartlist_new();
  4077. for (i=0;i<tok->n_args;++i) {
  4078. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  4079. log_warn(LD_DIR, "Illegal nickname %s in family line",
  4080. escaped(tok->args[i]));
  4081. goto next;
  4082. }
  4083. smartlist_add(md->family, tor_strdup(tok->args[i]));
  4084. }
  4085. }
  4086. if ((tok = find_opt_by_keyword(tokens, K_P))) {
  4087. md->exit_policy = parse_short_policy(tok->args[0]);
  4088. }
  4089. if ((tok = find_opt_by_keyword(tokens, K_P6))) {
  4090. md->ipv6_exit_policy = parse_short_policy(tok->args[0]);
  4091. }
  4092. crypto_digest256(md->digest, md->body, md->bodylen, DIGEST_SHA256);
  4093. smartlist_add(result, md);
  4094. md = NULL;
  4095. next:
  4096. microdesc_free(md);
  4097. md = NULL;
  4098. memarea_clear(area);
  4099. smartlist_clear(tokens);
  4100. s = start_of_next_microdesc;
  4101. }
  4102. memarea_drop_all(area);
  4103. smartlist_free(tokens);
  4104. return result;
  4105. }
  4106. /** Return true iff this Tor version can answer directory questions
  4107. * about microdescriptors. */
  4108. int
  4109. tor_version_supports_microdescriptors(const char *platform)
  4110. {
  4111. return tor_version_as_new_as(platform, "0.2.3.1-alpha");
  4112. }
  4113. /** Parse the Tor version of the platform string <b>platform</b>,
  4114. * and compare it to the version in <b>cutoff</b>. Return 1 if
  4115. * the router is at least as new as the cutoff, else return 0.
  4116. */
  4117. int
  4118. tor_version_as_new_as(const char *platform, const char *cutoff)
  4119. {
  4120. tor_version_t cutoff_version, router_version;
  4121. char *s, *s2, *start;
  4122. char tmp[128];
  4123. tor_assert(platform);
  4124. if (tor_version_parse(cutoff, &cutoff_version)<0) {
  4125. log_warn(LD_BUG,"cutoff version '%s' unparseable.",cutoff);
  4126. return 0;
  4127. }
  4128. if (strcmpstart(platform,"Tor ")) /* nonstandard Tor; be safe and say yes */
  4129. return 1;
  4130. start = (char *)eat_whitespace(platform+3);
  4131. if (!*start) return 0;
  4132. s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
  4133. s2 = (char*)eat_whitespace(s);
  4134. if (!strcmpstart(s2, "(r") || !strcmpstart(s2, "(git-"))
  4135. s = (char*)find_whitespace(s2);
  4136. if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
  4137. return 0;
  4138. strlcpy(tmp, start, s-start+1);
  4139. if (tor_version_parse(tmp, &router_version)<0) {
  4140. log_info(LD_DIR,"Router version '%s' unparseable.",tmp);
  4141. return 1; /* be safe and say yes */
  4142. }
  4143. /* Here's why we don't need to do any special handling for svn revisions:
  4144. * - If neither has an svn revision, we're fine.
  4145. * - If the router doesn't have an svn revision, we can't assume that it
  4146. * is "at least" any svn revision, so we need to return 0.
  4147. * - If the target version doesn't have an svn revision, any svn revision
  4148. * (or none at all) is good enough, so return 1.
  4149. * - If both target and router have an svn revision, we compare them.
  4150. */
  4151. return tor_version_compare(&router_version, &cutoff_version) >= 0;
  4152. }
  4153. /** Parse a tor version from <b>s</b>, and store the result in <b>out</b>.
  4154. * Return 0 on success, -1 on failure. */
  4155. int
  4156. tor_version_parse(const char *s, tor_version_t *out)
  4157. {
  4158. char *eos=NULL;
  4159. const char *cp=NULL;
  4160. /* Format is:
  4161. * "Tor " ? NUM dot NUM dot NUM [ ( pre | rc | dot ) NUM [ - tag ] ]
  4162. */
  4163. tor_assert(s);
  4164. tor_assert(out);
  4165. memset(out, 0, sizeof(tor_version_t));
  4166. if (!strcasecmpstart(s, "Tor "))
  4167. s += 4;
  4168. /* Get major. */
  4169. out->major = (int)strtol(s,&eos,10);
  4170. if (!eos || eos==s || *eos != '.') return -1;
  4171. cp = eos+1;
  4172. /* Get minor */
  4173. out->minor = (int) strtol(cp,&eos,10);
  4174. if (!eos || eos==cp || *eos != '.') return -1;
  4175. cp = eos+1;
  4176. /* Get micro */
  4177. out->micro = (int) strtol(cp,&eos,10);
  4178. if (!eos || eos==cp) return -1;
  4179. if (!*eos) {
  4180. out->status = VER_RELEASE;
  4181. out->patchlevel = 0;
  4182. return 0;
  4183. }
  4184. cp = eos;
  4185. /* Get status */
  4186. if (*cp == '.') {
  4187. out->status = VER_RELEASE;
  4188. ++cp;
  4189. } else if (0==strncmp(cp, "pre", 3)) {
  4190. out->status = VER_PRE;
  4191. cp += 3;
  4192. } else if (0==strncmp(cp, "rc", 2)) {
  4193. out->status = VER_RC;
  4194. cp += 2;
  4195. } else {
  4196. return -1;
  4197. }
  4198. /* Get patchlevel */
  4199. out->patchlevel = (int) strtol(cp,&eos,10);
  4200. if (!eos || eos==cp) return -1;
  4201. cp = eos;
  4202. /* Get status tag. */
  4203. if (*cp == '-' || *cp == '.')
  4204. ++cp;
  4205. eos = (char*) find_whitespace(cp);
  4206. if (eos-cp >= (int)sizeof(out->status_tag))
  4207. strlcpy(out->status_tag, cp, sizeof(out->status_tag));
  4208. else {
  4209. memcpy(out->status_tag, cp, eos-cp);
  4210. out->status_tag[eos-cp] = 0;
  4211. }
  4212. cp = eat_whitespace(eos);
  4213. if (!strcmpstart(cp, "(r")) {
  4214. cp += 2;
  4215. out->svn_revision = (int) strtol(cp,&eos,10);
  4216. } else if (!strcmpstart(cp, "(git-")) {
  4217. char *close_paren = strchr(cp, ')');
  4218. int hexlen;
  4219. char digest[DIGEST_LEN];
  4220. if (! close_paren)
  4221. return -1;
  4222. cp += 5;
  4223. if (close_paren-cp > HEX_DIGEST_LEN)
  4224. return -1;
  4225. hexlen = (int)(close_paren-cp);
  4226. memwipe(digest, 0, sizeof(digest));
  4227. if ( hexlen == 0 || (hexlen % 2) == 1)
  4228. return -1;
  4229. if (base16_decode(digest, hexlen/2, cp, hexlen))
  4230. return -1;
  4231. memcpy(out->git_tag, digest, hexlen/2);
  4232. out->git_tag_len = hexlen/2;
  4233. }
  4234. return 0;
  4235. }
  4236. /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
  4237. * b. */
  4238. int
  4239. tor_version_compare(tor_version_t *a, tor_version_t *b)
  4240. {
  4241. int i;
  4242. tor_assert(a);
  4243. tor_assert(b);
  4244. if ((i = a->major - b->major))
  4245. return i;
  4246. else if ((i = a->minor - b->minor))
  4247. return i;
  4248. else if ((i = a->micro - b->micro))
  4249. return i;
  4250. else if ((i = a->status - b->status))
  4251. return i;
  4252. else if ((i = a->patchlevel - b->patchlevel))
  4253. return i;
  4254. else if ((i = strcmp(a->status_tag, b->status_tag)))
  4255. return i;
  4256. else if ((i = a->svn_revision - b->svn_revision))
  4257. return i;
  4258. else if ((i = a->git_tag_len - b->git_tag_len))
  4259. return i;
  4260. else if (a->git_tag_len)
  4261. return fast_memcmp(a->git_tag, b->git_tag, a->git_tag_len);
  4262. else
  4263. return 0;
  4264. }
  4265. /** Return true iff versions <b>a</b> and <b>b</b> belong to the same series.
  4266. */
  4267. int
  4268. tor_version_same_series(tor_version_t *a, tor_version_t *b)
  4269. {
  4270. tor_assert(a);
  4271. tor_assert(b);
  4272. return ((a->major == b->major) &&
  4273. (a->minor == b->minor) &&
  4274. (a->micro == b->micro));
  4275. }
  4276. /** Helper: Given pointers to two strings describing tor versions, return -1
  4277. * if _a precedes _b, 1 if _b precedes _a, and 0 if they are equivalent.
  4278. * Used to sort a list of versions. */
  4279. static int
  4280. compare_tor_version_str_ptr_(const void **_a, const void **_b)
  4281. {
  4282. const char *a = *_a, *b = *_b;
  4283. int ca, cb;
  4284. tor_version_t va, vb;
  4285. ca = tor_version_parse(a, &va);
  4286. cb = tor_version_parse(b, &vb);
  4287. /* If they both parse, compare them. */
  4288. if (!ca && !cb)
  4289. return tor_version_compare(&va,&vb);
  4290. /* If one parses, it comes first. */
  4291. if (!ca && cb)
  4292. return -1;
  4293. if (ca && !cb)
  4294. return 1;
  4295. /* If neither parses, compare strings. Also, the directory server admin
  4296. ** needs to be smacked upside the head. But Tor is tolerant and gentle. */
  4297. return strcmp(a,b);
  4298. }
  4299. /** Sort a list of string-representations of versions in ascending order. */
  4300. void
  4301. sort_version_list(smartlist_t *versions, int remove_duplicates)
  4302. {
  4303. smartlist_sort(versions, compare_tor_version_str_ptr_);
  4304. if (remove_duplicates)
  4305. smartlist_uniq(versions, compare_tor_version_str_ptr_, tor_free_);
  4306. }
  4307. /** Parse and validate the ASCII-encoded v2 descriptor in <b>desc</b>,
  4308. * write the parsed descriptor to the newly allocated *<b>parsed_out</b>, the
  4309. * binary descriptor ID of length DIGEST_LEN to <b>desc_id_out</b>, the
  4310. * encrypted introduction points to the newly allocated
  4311. * *<b>intro_points_encrypted_out</b>, their encrypted size to
  4312. * *<b>intro_points_encrypted_size_out</b>, the size of the encoded descriptor
  4313. * to *<b>encoded_size_out</b>, and a pointer to the possibly next
  4314. * descriptor to *<b>next_out</b>; return 0 for success (including validation)
  4315. * and -1 for failure.
  4316. */
  4317. int
  4318. rend_parse_v2_service_descriptor(rend_service_descriptor_t **parsed_out,
  4319. char *desc_id_out,
  4320. char **intro_points_encrypted_out,
  4321. size_t *intro_points_encrypted_size_out,
  4322. size_t *encoded_size_out,
  4323. const char **next_out, const char *desc)
  4324. {
  4325. rend_service_descriptor_t *result =
  4326. tor_malloc_zero(sizeof(rend_service_descriptor_t));
  4327. char desc_hash[DIGEST_LEN];
  4328. const char *eos;
  4329. smartlist_t *tokens = smartlist_new();
  4330. directory_token_t *tok;
  4331. char secret_id_part[DIGEST_LEN];
  4332. int i, version, num_ok=1;
  4333. smartlist_t *versions;
  4334. char public_key_hash[DIGEST_LEN];
  4335. char test_desc_id[DIGEST_LEN];
  4336. memarea_t *area = NULL;
  4337. tor_assert(desc);
  4338. /* Check if desc starts correctly. */
  4339. if (strncmp(desc, "rendezvous-service-descriptor ",
  4340. strlen("rendezvous-service-descriptor "))) {
  4341. log_info(LD_REND, "Descriptor does not start correctly.");
  4342. goto err;
  4343. }
  4344. /* Compute descriptor hash for later validation. */
  4345. if (router_get_hash_impl(desc, strlen(desc), desc_hash,
  4346. "rendezvous-service-descriptor ",
  4347. "\nsignature", '\n', DIGEST_SHA1) < 0) {
  4348. log_warn(LD_REND, "Couldn't compute descriptor hash.");
  4349. goto err;
  4350. }
  4351. /* Determine end of string. */
  4352. eos = strstr(desc, "\nrendezvous-service-descriptor ");
  4353. if (!eos)
  4354. eos = desc + strlen(desc);
  4355. else
  4356. eos = eos + 1;
  4357. /* Check length. */
  4358. if (eos-desc > REND_DESC_MAX_SIZE) {
  4359. /* XXX023 If we are parsing this descriptor as a server, this
  4360. * should be a protocol warning. */
  4361. log_warn(LD_REND, "Descriptor length is %d which exceeds "
  4362. "maximum rendezvous descriptor size of %d bytes.",
  4363. (int)(eos-desc), REND_DESC_MAX_SIZE);
  4364. goto err;
  4365. }
  4366. /* Tokenize descriptor. */
  4367. area = memarea_new();
  4368. if (tokenize_string(area, desc, eos, tokens, desc_token_table, 0)) {
  4369. log_warn(LD_REND, "Error tokenizing descriptor.");
  4370. goto err;
  4371. }
  4372. /* Set next to next descriptor, if available. */
  4373. *next_out = eos;
  4374. /* Set length of encoded descriptor. */
  4375. *encoded_size_out = eos - desc;
  4376. /* Check min allowed length of token list. */
  4377. if (smartlist_len(tokens) < 7) {
  4378. log_warn(LD_REND, "Impossibly short descriptor.");
  4379. goto err;
  4380. }
  4381. /* Parse base32-encoded descriptor ID. */
  4382. tok = find_by_keyword(tokens, R_RENDEZVOUS_SERVICE_DESCRIPTOR);
  4383. tor_assert(tok == smartlist_get(tokens, 0));
  4384. tor_assert(tok->n_args == 1);
  4385. if (strlen(tok->args[0]) != REND_DESC_ID_V2_LEN_BASE32 ||
  4386. strspn(tok->args[0], BASE32_CHARS) != REND_DESC_ID_V2_LEN_BASE32) {
  4387. log_warn(LD_REND, "Invalid descriptor ID: '%s'", tok->args[0]);
  4388. goto err;
  4389. }
  4390. if (base32_decode(desc_id_out, DIGEST_LEN,
  4391. tok->args[0], REND_DESC_ID_V2_LEN_BASE32) < 0) {
  4392. log_warn(LD_REND, "Descriptor ID contains illegal characters: %s",
  4393. tok->args[0]);
  4394. goto err;
  4395. }
  4396. /* Parse descriptor version. */
  4397. tok = find_by_keyword(tokens, R_VERSION);
  4398. tor_assert(tok->n_args == 1);
  4399. result->version =
  4400. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &num_ok, NULL);
  4401. if (result->version != 2 || !num_ok) {
  4402. /* If it's <2, it shouldn't be under this format. If the number
  4403. * is greater than 2, we bumped it because we broke backward
  4404. * compatibility. See how version numbers in our other formats
  4405. * work. */
  4406. log_warn(LD_REND, "Unrecognized descriptor version: %s",
  4407. escaped(tok->args[0]));
  4408. goto err;
  4409. }
  4410. /* Parse public key. */
  4411. tok = find_by_keyword(tokens, R_PERMANENT_KEY);
  4412. result->pk = tok->key;
  4413. tok->key = NULL; /* Prevent free */
  4414. /* Parse secret ID part. */
  4415. tok = find_by_keyword(tokens, R_SECRET_ID_PART);
  4416. tor_assert(tok->n_args == 1);
  4417. if (strlen(tok->args[0]) != REND_SECRET_ID_PART_LEN_BASE32 ||
  4418. strspn(tok->args[0], BASE32_CHARS) != REND_SECRET_ID_PART_LEN_BASE32) {
  4419. log_warn(LD_REND, "Invalid secret ID part: '%s'", tok->args[0]);
  4420. goto err;
  4421. }
  4422. if (base32_decode(secret_id_part, DIGEST_LEN, tok->args[0], 32) < 0) {
  4423. log_warn(LD_REND, "Secret ID part contains illegal characters: %s",
  4424. tok->args[0]);
  4425. goto err;
  4426. }
  4427. /* Parse publication time -- up-to-date check is done when storing the
  4428. * descriptor. */
  4429. tok = find_by_keyword(tokens, R_PUBLICATION_TIME);
  4430. tor_assert(tok->n_args == 1);
  4431. if (parse_iso_time(tok->args[0], &result->timestamp) < 0) {
  4432. log_warn(LD_REND, "Invalid publication time: '%s'", tok->args[0]);
  4433. goto err;
  4434. }
  4435. /* Parse protocol versions. */
  4436. tok = find_by_keyword(tokens, R_PROTOCOL_VERSIONS);
  4437. tor_assert(tok->n_args == 1);
  4438. versions = smartlist_new();
  4439. smartlist_split_string(versions, tok->args[0], ",",
  4440. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  4441. for (i = 0; i < smartlist_len(versions); i++) {
  4442. version = (int) tor_parse_long(smartlist_get(versions, i),
  4443. 10, 0, INT_MAX, &num_ok, NULL);
  4444. if (!num_ok) /* It's a string; let's ignore it. */
  4445. continue;
  4446. if (version >= REND_PROTOCOL_VERSION_BITMASK_WIDTH)
  4447. /* Avoid undefined left-shift behaviour. */
  4448. continue;
  4449. result->protocols |= 1 << version;
  4450. }
  4451. SMARTLIST_FOREACH(versions, char *, cp, tor_free(cp));
  4452. smartlist_free(versions);
  4453. /* Parse encrypted introduction points. Don't verify. */
  4454. tok = find_opt_by_keyword(tokens, R_INTRODUCTION_POINTS);
  4455. if (tok) {
  4456. if (strcmp(tok->object_type, "MESSAGE")) {
  4457. log_warn(LD_DIR, "Bad object type: introduction points should be of "
  4458. "type MESSAGE");
  4459. goto err;
  4460. }
  4461. *intro_points_encrypted_out = tor_memdup(tok->object_body,
  4462. tok->object_size);
  4463. *intro_points_encrypted_size_out = tok->object_size;
  4464. } else {
  4465. *intro_points_encrypted_out = NULL;
  4466. *intro_points_encrypted_size_out = 0;
  4467. }
  4468. /* Parse and verify signature. */
  4469. tok = find_by_keyword(tokens, R_SIGNATURE);
  4470. note_crypto_pk_op(VERIFY_RTR);
  4471. if (check_signature_token(desc_hash, DIGEST_LEN, tok, result->pk, 0,
  4472. "v2 rendezvous service descriptor") < 0)
  4473. goto err;
  4474. /* Verify that descriptor ID belongs to public key and secret ID part. */
  4475. crypto_pk_get_digest(result->pk, public_key_hash);
  4476. rend_get_descriptor_id_bytes(test_desc_id, public_key_hash,
  4477. secret_id_part);
  4478. if (tor_memneq(desc_id_out, test_desc_id, DIGEST_LEN)) {
  4479. log_warn(LD_REND, "Parsed descriptor ID does not match "
  4480. "computed descriptor ID.");
  4481. goto err;
  4482. }
  4483. goto done;
  4484. err:
  4485. rend_service_descriptor_free(result);
  4486. result = NULL;
  4487. done:
  4488. if (tokens) {
  4489. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4490. smartlist_free(tokens);
  4491. }
  4492. if (area)
  4493. memarea_drop_all(area);
  4494. *parsed_out = result;
  4495. if (result)
  4496. return 0;
  4497. return -1;
  4498. }
  4499. /** Decrypt the encrypted introduction points in <b>ipos_encrypted</b> of
  4500. * length <b>ipos_encrypted_size</b> using <b>descriptor_cookie</b> and
  4501. * write the result to a newly allocated string that is pointed to by
  4502. * <b>ipos_decrypted</b> and its length to <b>ipos_decrypted_size</b>.
  4503. * Return 0 if decryption was successful and -1 otherwise. */
  4504. int
  4505. rend_decrypt_introduction_points(char **ipos_decrypted,
  4506. size_t *ipos_decrypted_size,
  4507. const char *descriptor_cookie,
  4508. const char *ipos_encrypted,
  4509. size_t ipos_encrypted_size)
  4510. {
  4511. tor_assert(ipos_encrypted);
  4512. tor_assert(descriptor_cookie);
  4513. if (ipos_encrypted_size < 2) {
  4514. log_warn(LD_REND, "Size of encrypted introduction points is too "
  4515. "small.");
  4516. return -1;
  4517. }
  4518. if (ipos_encrypted[0] == (int)REND_BASIC_AUTH) {
  4519. char iv[CIPHER_IV_LEN], client_id[REND_BASIC_AUTH_CLIENT_ID_LEN],
  4520. session_key[CIPHER_KEY_LEN], *dec;
  4521. int declen, client_blocks;
  4522. size_t pos = 0, len, client_entries_len;
  4523. crypto_digest_t *digest;
  4524. crypto_cipher_t *cipher;
  4525. client_blocks = (int) ipos_encrypted[1];
  4526. client_entries_len = client_blocks * REND_BASIC_AUTH_CLIENT_MULTIPLE *
  4527. REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
  4528. if (ipos_encrypted_size < 2 + client_entries_len + CIPHER_IV_LEN + 1) {
  4529. log_warn(LD_REND, "Size of encrypted introduction points is too "
  4530. "small.");
  4531. return -1;
  4532. }
  4533. memcpy(iv, ipos_encrypted + 2 + client_entries_len, CIPHER_IV_LEN);
  4534. digest = crypto_digest_new();
  4535. crypto_digest_add_bytes(digest, descriptor_cookie, REND_DESC_COOKIE_LEN);
  4536. crypto_digest_add_bytes(digest, iv, CIPHER_IV_LEN);
  4537. crypto_digest_get_digest(digest, client_id,
  4538. REND_BASIC_AUTH_CLIENT_ID_LEN);
  4539. crypto_digest_free(digest);
  4540. for (pos = 2; pos < 2 + client_entries_len;
  4541. pos += REND_BASIC_AUTH_CLIENT_ENTRY_LEN) {
  4542. if (tor_memeq(ipos_encrypted + pos, client_id,
  4543. REND_BASIC_AUTH_CLIENT_ID_LEN)) {
  4544. /* Attempt to decrypt introduction points. */
  4545. cipher = crypto_cipher_new(descriptor_cookie);
  4546. if (crypto_cipher_decrypt(cipher, session_key, ipos_encrypted
  4547. + pos + REND_BASIC_AUTH_CLIENT_ID_LEN,
  4548. CIPHER_KEY_LEN) < 0) {
  4549. log_warn(LD_REND, "Could not decrypt session key for client.");
  4550. crypto_cipher_free(cipher);
  4551. return -1;
  4552. }
  4553. crypto_cipher_free(cipher);
  4554. len = ipos_encrypted_size - 2 - client_entries_len - CIPHER_IV_LEN;
  4555. dec = tor_malloc(len);
  4556. declen = crypto_cipher_decrypt_with_iv(session_key, dec, len,
  4557. ipos_encrypted + 2 + client_entries_len,
  4558. ipos_encrypted_size - 2 - client_entries_len);
  4559. if (declen < 0) {
  4560. log_warn(LD_REND, "Could not decrypt introduction point string.");
  4561. tor_free(dec);
  4562. return -1;
  4563. }
  4564. if (fast_memcmpstart(dec, declen, "introduction-point ")) {
  4565. log_warn(LD_REND, "Decrypted introduction points don't "
  4566. "look like we could parse them.");
  4567. tor_free(dec);
  4568. continue;
  4569. }
  4570. *ipos_decrypted = dec;
  4571. *ipos_decrypted_size = declen;
  4572. return 0;
  4573. }
  4574. }
  4575. log_warn(LD_REND, "Could not decrypt introduction points. Please "
  4576. "check your authorization for this service!");
  4577. return -1;
  4578. } else if (ipos_encrypted[0] == (int)REND_STEALTH_AUTH) {
  4579. char *dec;
  4580. int declen;
  4581. if (ipos_encrypted_size < CIPHER_IV_LEN + 2) {
  4582. log_warn(LD_REND, "Size of encrypted introduction points is too "
  4583. "small.");
  4584. return -1;
  4585. }
  4586. dec = tor_malloc_zero(ipos_encrypted_size - CIPHER_IV_LEN - 1);
  4587. declen = crypto_cipher_decrypt_with_iv(descriptor_cookie, dec,
  4588. ipos_encrypted_size -
  4589. CIPHER_IV_LEN - 1,
  4590. ipos_encrypted + 1,
  4591. ipos_encrypted_size - 1);
  4592. if (declen < 0) {
  4593. log_warn(LD_REND, "Decrypting introduction points failed!");
  4594. tor_free(dec);
  4595. return -1;
  4596. }
  4597. *ipos_decrypted = dec;
  4598. *ipos_decrypted_size = declen;
  4599. return 0;
  4600. } else {
  4601. log_warn(LD_REND, "Unknown authorization type number: %d",
  4602. ipos_encrypted[0]);
  4603. return -1;
  4604. }
  4605. }
  4606. /** Parse the encoded introduction points in <b>intro_points_encoded</b> of
  4607. * length <b>intro_points_encoded_size</b> and write the result to the
  4608. * descriptor in <b>parsed</b>; return the number of successfully parsed
  4609. * introduction points or -1 in case of a failure. */
  4610. int
  4611. rend_parse_introduction_points(rend_service_descriptor_t *parsed,
  4612. const char *intro_points_encoded,
  4613. size_t intro_points_encoded_size)
  4614. {
  4615. const char *current_ipo, *end_of_intro_points;
  4616. smartlist_t *tokens;
  4617. directory_token_t *tok;
  4618. rend_intro_point_t *intro;
  4619. extend_info_t *info;
  4620. int result, num_ok=1;
  4621. memarea_t *area = NULL;
  4622. tor_assert(parsed);
  4623. /** Function may only be invoked once. */
  4624. tor_assert(!parsed->intro_nodes);
  4625. tor_assert(intro_points_encoded);
  4626. tor_assert(intro_points_encoded_size > 0);
  4627. /* Consider one intro point after the other. */
  4628. current_ipo = intro_points_encoded;
  4629. end_of_intro_points = intro_points_encoded + intro_points_encoded_size;
  4630. tokens = smartlist_new();
  4631. parsed->intro_nodes = smartlist_new();
  4632. area = memarea_new();
  4633. while (!fast_memcmpstart(current_ipo, end_of_intro_points-current_ipo,
  4634. "introduction-point ")) {
  4635. /* Determine end of string. */
  4636. const char *eos = tor_memstr(current_ipo, end_of_intro_points-current_ipo,
  4637. "\nintroduction-point ");
  4638. if (!eos)
  4639. eos = end_of_intro_points;
  4640. else
  4641. eos = eos+1;
  4642. tor_assert(eos <= intro_points_encoded+intro_points_encoded_size);
  4643. /* Free tokens and clear token list. */
  4644. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4645. smartlist_clear(tokens);
  4646. memarea_clear(area);
  4647. /* Tokenize string. */
  4648. if (tokenize_string(area, current_ipo, eos, tokens, ipo_token_table, 0)) {
  4649. log_warn(LD_REND, "Error tokenizing introduction point");
  4650. goto err;
  4651. }
  4652. /* Advance to next introduction point, if available. */
  4653. current_ipo = eos;
  4654. /* Check minimum allowed length of introduction point. */
  4655. if (smartlist_len(tokens) < 5) {
  4656. log_warn(LD_REND, "Impossibly short introduction point.");
  4657. goto err;
  4658. }
  4659. /* Allocate new intro point and extend info. */
  4660. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  4661. info = intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  4662. /* Parse identifier. */
  4663. tok = find_by_keyword(tokens, R_IPO_IDENTIFIER);
  4664. if (base32_decode(info->identity_digest, DIGEST_LEN,
  4665. tok->args[0], REND_INTRO_POINT_ID_LEN_BASE32) < 0) {
  4666. log_warn(LD_REND, "Identity digest contains illegal characters: %s",
  4667. tok->args[0]);
  4668. rend_intro_point_free(intro);
  4669. goto err;
  4670. }
  4671. /* Write identifier to nickname. */
  4672. info->nickname[0] = '$';
  4673. base16_encode(info->nickname + 1, sizeof(info->nickname) - 1,
  4674. info->identity_digest, DIGEST_LEN);
  4675. /* Parse IP address. */
  4676. tok = find_by_keyword(tokens, R_IPO_IP_ADDRESS);
  4677. if (tor_addr_parse(&info->addr, tok->args[0])<0) {
  4678. log_warn(LD_REND, "Could not parse introduction point address.");
  4679. rend_intro_point_free(intro);
  4680. goto err;
  4681. }
  4682. if (tor_addr_family(&info->addr) != AF_INET) {
  4683. log_warn(LD_REND, "Introduction point address was not ipv4.");
  4684. rend_intro_point_free(intro);
  4685. goto err;
  4686. }
  4687. /* Parse onion port. */
  4688. tok = find_by_keyword(tokens, R_IPO_ONION_PORT);
  4689. info->port = (uint16_t) tor_parse_long(tok->args[0],10,1,65535,
  4690. &num_ok,NULL);
  4691. if (!info->port || !num_ok) {
  4692. log_warn(LD_REND, "Introduction point onion port %s is invalid",
  4693. escaped(tok->args[0]));
  4694. rend_intro_point_free(intro);
  4695. goto err;
  4696. }
  4697. /* Parse onion key. */
  4698. tok = find_by_keyword(tokens, R_IPO_ONION_KEY);
  4699. if (!crypto_pk_public_exponent_ok(tok->key)) {
  4700. log_warn(LD_REND,
  4701. "Introduction point's onion key had invalid exponent.");
  4702. rend_intro_point_free(intro);
  4703. goto err;
  4704. }
  4705. info->onion_key = tok->key;
  4706. tok->key = NULL; /* Prevent free */
  4707. /* Parse service key. */
  4708. tok = find_by_keyword(tokens, R_IPO_SERVICE_KEY);
  4709. if (!crypto_pk_public_exponent_ok(tok->key)) {
  4710. log_warn(LD_REND,
  4711. "Introduction point key had invalid exponent.");
  4712. rend_intro_point_free(intro);
  4713. goto err;
  4714. }
  4715. intro->intro_key = tok->key;
  4716. tok->key = NULL; /* Prevent free */
  4717. /* Add extend info to list of introduction points. */
  4718. smartlist_add(parsed->intro_nodes, intro);
  4719. }
  4720. result = smartlist_len(parsed->intro_nodes);
  4721. goto done;
  4722. err:
  4723. result = -1;
  4724. done:
  4725. /* Free tokens and clear token list. */
  4726. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4727. smartlist_free(tokens);
  4728. if (area)
  4729. memarea_drop_all(area);
  4730. return result;
  4731. }
  4732. /** Parse the content of a client_key file in <b>ckstr</b> and add
  4733. * rend_authorized_client_t's for each parsed client to
  4734. * <b>parsed_clients</b>. Return the number of parsed clients as result
  4735. * or -1 for failure. */
  4736. int
  4737. rend_parse_client_keys(strmap_t *parsed_clients, const char *ckstr)
  4738. {
  4739. int result = -1;
  4740. smartlist_t *tokens;
  4741. directory_token_t *tok;
  4742. const char *current_entry = NULL;
  4743. memarea_t *area = NULL;
  4744. if (!ckstr || strlen(ckstr) == 0)
  4745. return -1;
  4746. tokens = smartlist_new();
  4747. /* Begin parsing with first entry, skipping comments or whitespace at the
  4748. * beginning. */
  4749. area = memarea_new();
  4750. current_entry = eat_whitespace(ckstr);
  4751. while (!strcmpstart(current_entry, "client-name ")) {
  4752. rend_authorized_client_t *parsed_entry;
  4753. size_t len;
  4754. char descriptor_cookie_tmp[REND_DESC_COOKIE_LEN+2];
  4755. /* Determine end of string. */
  4756. const char *eos = strstr(current_entry, "\nclient-name ");
  4757. if (!eos)
  4758. eos = current_entry + strlen(current_entry);
  4759. else
  4760. eos = eos + 1;
  4761. /* Free tokens and clear token list. */
  4762. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4763. smartlist_clear(tokens);
  4764. memarea_clear(area);
  4765. /* Tokenize string. */
  4766. if (tokenize_string(area, current_entry, eos, tokens,
  4767. client_keys_token_table, 0)) {
  4768. log_warn(LD_REND, "Error tokenizing client keys file.");
  4769. goto err;
  4770. }
  4771. /* Advance to next entry, if available. */
  4772. current_entry = eos;
  4773. /* Check minimum allowed length of token list. */
  4774. if (smartlist_len(tokens) < 2) {
  4775. log_warn(LD_REND, "Impossibly short client key entry.");
  4776. goto err;
  4777. }
  4778. /* Parse client name. */
  4779. tok = find_by_keyword(tokens, C_CLIENT_NAME);
  4780. tor_assert(tok == smartlist_get(tokens, 0));
  4781. tor_assert(tok->n_args == 1);
  4782. len = strlen(tok->args[0]);
  4783. if (len < 1 || len > 19 ||
  4784. strspn(tok->args[0], REND_LEGAL_CLIENTNAME_CHARACTERS) != len) {
  4785. log_warn(LD_CONFIG, "Illegal client name: %s. (Length must be "
  4786. "between 1 and 19, and valid characters are "
  4787. "[A-Za-z0-9+-_].)", tok->args[0]);
  4788. goto err;
  4789. }
  4790. /* Check if client name is duplicate. */
  4791. if (strmap_get(parsed_clients, tok->args[0])) {
  4792. log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains a "
  4793. "duplicate client name: '%s'. Ignoring.", tok->args[0]);
  4794. goto err;
  4795. }
  4796. parsed_entry = tor_malloc_zero(sizeof(rend_authorized_client_t));
  4797. parsed_entry->client_name = tor_strdup(tok->args[0]);
  4798. strmap_set(parsed_clients, parsed_entry->client_name, parsed_entry);
  4799. /* Parse client key. */
  4800. tok = find_opt_by_keyword(tokens, C_CLIENT_KEY);
  4801. if (tok) {
  4802. parsed_entry->client_key = tok->key;
  4803. tok->key = NULL; /* Prevent free */
  4804. }
  4805. /* Parse descriptor cookie. */
  4806. tok = find_by_keyword(tokens, C_DESCRIPTOR_COOKIE);
  4807. tor_assert(tok->n_args == 1);
  4808. if (strlen(tok->args[0]) != REND_DESC_COOKIE_LEN_BASE64 + 2) {
  4809. log_warn(LD_REND, "Descriptor cookie has illegal length: %s",
  4810. escaped(tok->args[0]));
  4811. goto err;
  4812. }
  4813. /* The size of descriptor_cookie_tmp needs to be REND_DESC_COOKIE_LEN+2,
  4814. * because a base64 encoding of length 24 does not fit into 16 bytes in all
  4815. * cases. */
  4816. if (base64_decode(descriptor_cookie_tmp, sizeof(descriptor_cookie_tmp),
  4817. tok->args[0], strlen(tok->args[0]))
  4818. != REND_DESC_COOKIE_LEN) {
  4819. log_warn(LD_REND, "Descriptor cookie contains illegal characters: "
  4820. "%s", escaped(tok->args[0]));
  4821. goto err;
  4822. }
  4823. memcpy(parsed_entry->descriptor_cookie, descriptor_cookie_tmp,
  4824. REND_DESC_COOKIE_LEN);
  4825. }
  4826. result = strmap_size(parsed_clients);
  4827. goto done;
  4828. err:
  4829. result = -1;
  4830. done:
  4831. /* Free tokens and clear token list. */
  4832. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  4833. smartlist_free(tokens);
  4834. if (area)
  4835. memarea_drop_all(area);
  4836. return result;
  4837. }