routerparse.c 178 KB

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