routerparse.c 179 KB

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