routerparse.c 181 KB

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