routerparse.c 184 KB

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