routerparse.c 187 KB

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