123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156 |
- /* Copyright (c) 2001 Matej Pfajfar.
- * Copyright (c) 2001-2004, Roger Dingledine.
- * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
- * Copyright (c) 2007-2018, The Tor Project, Inc. */
- /* See LICENSE for licensing information */
- /**
- * \file routerparse.c
- * \brief Code to parse and validate router descriptors, consenus directories,
- * and similar objects.
- *
- * The objects parsed by this module use a common text-based metaformat,
- * documented in dir-spec.txt in torspec.git. This module is itself divided
- * into two major kinds of function: code to handle the metaformat, and code
- * to convert from particular instances of the metaformat into the
- * objects that Tor uses.
- *
- * The generic parsing code works by calling a table-based tokenizer on the
- * input string. Each token corresponds to a single line with a token, plus
- * optional arguments on that line, plus an optional base-64 encoded object
- * after that line. Each token has a definition in a table of token_rule_t
- * entries that describes how many arguments it can take, whether it takes an
- * object, how many times it may appear, whether it must appear first, and so
- * on.
- *
- * The tokenizer function tokenize_string() converts its string input into a
- * smartlist full of instances of directory_token_t, according to a provided
- * table of token_rule_t.
- *
- * The generic parts of this module additionally include functions for
- * finding the start and end of signed information inside a signed object, and
- * computing the digest that will be signed.
- *
- * There are also functions for saving objects to disk that have caused
- * parsing to fail.
- *
- * The specific parts of this module describe conversions between
- * particular lists of directory_token_t and particular objects. The
- * kinds of objects that can be parsed here are:
- * <ul>
- * <li>router descriptors (managed from routerlist.c)
- * <li>extra-info documents (managed from routerlist.c)
- * <li>microdescriptors (managed from microdesc.c)
- * <li>vote and consensus networkstatus documents, and the routerstatus_t
- * objects that they comprise (managed from networkstatus.c)
- * <li>detached-signature objects used by authorities for gathering
- * signatures on the networkstatus consensus (managed from dirvote.c)
- * <li>authority key certificates (managed from routerlist.c)
- * <li>hidden service descriptors (managed from rendcommon.c and rendcache.c)
- * </ul>
- **/
- #define ROUTERPARSE_PRIVATE
- #include "core/or/or.h"
- #include "app/config/config.h"
- #include "core/or/circuitstats.h"
- #include "core/or/policies.h"
- #include "core/or/protover.h"
- #include "feature/client/entrynodes.h"
- #include "feature/dirauth/shared_random.h"
- #include "feature/dircommon/voting_schedule.h"
- #include "feature/dirparse/parsecommon.h"
- #include "feature/dirparse/routerparse.h"
- #include "feature/hs_common/shared_random_client.h"
- #include "feature/nodelist/authcert.h"
- #include "feature/nodelist/describe.h"
- #include "feature/nodelist/microdesc.h"
- #include "feature/nodelist/networkstatus.h"
- #include "feature/nodelist/nickname.h"
- #include "feature/nodelist/routerinfo.h"
- #include "feature/nodelist/routerlist.h"
- #include "feature/nodelist/torcert.h"
- #include "feature/relay/router.h"
- #include "feature/relay/routerkeys.h"
- #include "feature/rend/rendcommon.h"
- #include "feature/stats/rephist.h"
- #include "lib/crypt_ops/crypto_format.h"
- #include "lib/crypt_ops/crypto_util.h"
- #include "lib/memarea/memarea.h"
- #include "lib/sandbox/sandbox.h"
- #include "feature/dirparse/authcert_parse.h"
- #include "feature/dirparse/sigcommon.h"
- #include "feature/dirparse/unparseable.h"
- #include "feature/dirauth/dirvote.h"
- #include "core/or/addr_policy_st.h"
- #include "feature/nodelist/authority_cert_st.h"
- #include "feature/nodelist/document_signature_st.h"
- #include "core/or/extend_info_st.h"
- #include "feature/nodelist/extrainfo_st.h"
- #include "feature/nodelist/microdesc_st.h"
- #include "feature/nodelist/networkstatus_st.h"
- #include "feature/nodelist/networkstatus_voter_info_st.h"
- #include "feature/dirauth/ns_detached_signatures_st.h"
- #include "feature/rend/rend_authorized_client_st.h"
- #include "feature/rend/rend_intro_point_st.h"
- #include "feature/rend/rend_service_descriptor_st.h"
- #include "feature/nodelist/routerinfo_st.h"
- #include "feature/nodelist/routerlist_st.h"
- #include "core/or/tor_version_st.h"
- #include "feature/dirauth/vote_microdesc_hash_st.h"
- #include "feature/nodelist/vote_routerstatus_st.h"
- #include "lib/container/bloomfilt.h"
- #undef log
- #include <math.h>
- /****************************************************************************/
- /** List of tokens recognized in router descriptors */
- static token_rule_t routerdesc_token_table[] = {
- T0N("reject", K_REJECT, ARGS, NO_OBJ ),
- T0N("accept", K_ACCEPT, ARGS, NO_OBJ ),
- T0N("reject6", K_REJECT6, ARGS, NO_OBJ ),
- T0N("accept6", K_ACCEPT6, ARGS, NO_OBJ ),
- T1_START( "router", K_ROUTER, GE(5), NO_OBJ ),
- T01("ipv6-policy", K_IPV6_POLICY, CONCAT_ARGS, NO_OBJ),
- T1( "signing-key", K_SIGNING_KEY, NO_ARGS, NEED_KEY_1024 ),
- T1( "onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY_1024 ),
- T01("ntor-onion-key", K_ONION_KEY_NTOR, GE(1), NO_OBJ ),
- T1_END( "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ ),
- T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
- T01("uptime", K_UPTIME, GE(1), NO_OBJ ),
- T01("fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
- T01("hibernating", K_HIBERNATING, GE(1), NO_OBJ ),
- T01("platform", K_PLATFORM, CONCAT_ARGS, NO_OBJ ),
- T01("proto", K_PROTO, CONCAT_ARGS, NO_OBJ ),
- T01("contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
- T01("read-history", K_READ_HISTORY, ARGS, NO_OBJ ),
- T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
- T01("extra-info-digest", K_EXTRA_INFO_DIGEST, GE(1), NO_OBJ ),
- T01("hidden-service-dir", K_HIDDEN_SERVICE_DIR, NO_ARGS, NO_OBJ ),
- T01("identity-ed25519", K_IDENTITY_ED25519, NO_ARGS, NEED_OBJ ),
- T01("master-key-ed25519", K_MASTER_KEY_ED25519, GE(1), NO_OBJ ),
- T01("router-sig-ed25519", K_ROUTER_SIG_ED25519, GE(1), NO_OBJ ),
- T01("onion-key-crosscert", K_ONION_KEY_CROSSCERT, NO_ARGS, NEED_OBJ ),
- T01("ntor-onion-key-crosscert", K_NTOR_ONION_KEY_CROSSCERT,
- EQ(1), NEED_OBJ ),
- T01("allow-single-hop-exits",K_ALLOW_SINGLE_HOP_EXITS, NO_ARGS, NO_OBJ ),
- T01("family", K_FAMILY, ARGS, NO_OBJ ),
- T01("caches-extra-info", K_CACHES_EXTRA_INFO, NO_ARGS, NO_OBJ ),
- T0N("or-address", K_OR_ADDRESS, GE(1), NO_OBJ ),
- T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
- T1( "bandwidth", K_BANDWIDTH, GE(3), NO_OBJ ),
- A01("@purpose", A_PURPOSE, GE(1), NO_OBJ ),
- T01("tunnelled-dir-server",K_DIR_TUNNELLED, NO_ARGS, NO_OBJ ),
- END_OF_TABLE
- };
- /** List of tokens recognized in extra-info documents. */
- static token_rule_t extrainfo_token_table[] = {
- T1_END( "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ ),
- T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
- T01("identity-ed25519", K_IDENTITY_ED25519, NO_ARGS, NEED_OBJ ),
- T01("router-sig-ed25519", K_ROUTER_SIG_ED25519, GE(1), NO_OBJ ),
- T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
- T01("read-history", K_READ_HISTORY, ARGS, NO_OBJ ),
- T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
- T01("dirreq-stats-end", K_DIRREQ_END, ARGS, NO_OBJ ),
- T01("dirreq-v2-ips", K_DIRREQ_V2_IPS, ARGS, NO_OBJ ),
- T01("dirreq-v3-ips", K_DIRREQ_V3_IPS, ARGS, NO_OBJ ),
- T01("dirreq-v2-reqs", K_DIRREQ_V2_REQS, ARGS, NO_OBJ ),
- T01("dirreq-v3-reqs", K_DIRREQ_V3_REQS, ARGS, NO_OBJ ),
- T01("dirreq-v2-share", K_DIRREQ_V2_SHARE, ARGS, NO_OBJ ),
- T01("dirreq-v3-share", K_DIRREQ_V3_SHARE, ARGS, NO_OBJ ),
- T01("dirreq-v2-resp", K_DIRREQ_V2_RESP, ARGS, NO_OBJ ),
- T01("dirreq-v3-resp", K_DIRREQ_V3_RESP, ARGS, NO_OBJ ),
- T01("dirreq-v2-direct-dl", K_DIRREQ_V2_DIR, ARGS, NO_OBJ ),
- T01("dirreq-v3-direct-dl", K_DIRREQ_V3_DIR, ARGS, NO_OBJ ),
- T01("dirreq-v2-tunneled-dl", K_DIRREQ_V2_TUN, ARGS, NO_OBJ ),
- T01("dirreq-v3-tunneled-dl", K_DIRREQ_V3_TUN, ARGS, NO_OBJ ),
- T01("entry-stats-end", K_ENTRY_END, ARGS, NO_OBJ ),
- T01("entry-ips", K_ENTRY_IPS, ARGS, NO_OBJ ),
- T01("cell-stats-end", K_CELL_END, ARGS, NO_OBJ ),
- T01("cell-processed-cells", K_CELL_PROCESSED, ARGS, NO_OBJ ),
- T01("cell-queued-cells", K_CELL_QUEUED, ARGS, NO_OBJ ),
- T01("cell-time-in-queue", K_CELL_TIME, ARGS, NO_OBJ ),
- T01("cell-circuits-per-decile", K_CELL_CIRCS, ARGS, NO_OBJ ),
- T01("exit-stats-end", K_EXIT_END, ARGS, NO_OBJ ),
- T01("exit-kibibytes-written", K_EXIT_WRITTEN, ARGS, NO_OBJ ),
- T01("exit-kibibytes-read", K_EXIT_READ, ARGS, NO_OBJ ),
- T01("exit-streams-opened", K_EXIT_OPENED, ARGS, NO_OBJ ),
- T1_START( "extra-info", K_EXTRA_INFO, GE(2), NO_OBJ ),
- END_OF_TABLE
- };
- /** List of tokens recognized in the body part of v3 networkstatus
- * documents. */
- static token_rule_t rtrstatus_token_table[] = {
- T01("p", K_P, CONCAT_ARGS, NO_OBJ ),
- T1( "r", K_R, GE(7), NO_OBJ ),
- T0N("a", K_A, GE(1), NO_OBJ ),
- T1( "s", K_S, ARGS, NO_OBJ ),
- T01("v", K_V, CONCAT_ARGS, NO_OBJ ),
- T01("w", K_W, ARGS, NO_OBJ ),
- T0N("m", K_M, CONCAT_ARGS, NO_OBJ ),
- T0N("id", K_ID, GE(2), NO_OBJ ),
- T01("pr", K_PROTO, CONCAT_ARGS, NO_OBJ ),
- T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
- END_OF_TABLE
- };
- /** List of tokens recognized in V3 networkstatus votes. */
- static token_rule_t networkstatus_token_table[] = {
- T1_START("network-status-version", K_NETWORK_STATUS_VERSION,
- GE(1), NO_OBJ ),
- T1("vote-status", K_VOTE_STATUS, GE(1), NO_OBJ ),
- T1("published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
- T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
- T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
- T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
- T1("voting-delay", K_VOTING_DELAY, GE(2), NO_OBJ ),
- T1("known-flags", K_KNOWN_FLAGS, ARGS, NO_OBJ ),
- T01("params", K_PARAMS, ARGS, NO_OBJ ),
- T( "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
- T01("signing-ed25519", K_SIGNING_CERT_ED, NO_ARGS , NEED_OBJ ),
- T01("shared-rand-participate",K_SR_FLAG, NO_ARGS, NO_OBJ ),
- T0N("shared-rand-commit", K_COMMIT, GE(3), NO_OBJ ),
- T01("shared-rand-previous-value", K_PREVIOUS_SRV,EQ(2), NO_OBJ ),
- T01("shared-rand-current-value", K_CURRENT_SRV, EQ(2), NO_OBJ ),
- T0N("package", K_PACKAGE, CONCAT_ARGS, NO_OBJ ),
- T01("recommended-client-protocols", K_RECOMMENDED_CLIENT_PROTOCOLS,
- CONCAT_ARGS, NO_OBJ ),
- T01("recommended-relay-protocols", K_RECOMMENDED_RELAY_PROTOCOLS,
- CONCAT_ARGS, NO_OBJ ),
- T01("required-client-protocols", K_REQUIRED_CLIENT_PROTOCOLS,
- CONCAT_ARGS, NO_OBJ ),
- T01("required-relay-protocols", K_REQUIRED_RELAY_PROTOCOLS,
- CONCAT_ARGS, NO_OBJ ),
- #include "feature/dirparse/authcert_members.i"
- T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
- T1( "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
- T1( "dir-source", K_DIR_SOURCE, GE(6), NO_OBJ ),
- T01("legacy-dir-key", K_LEGACY_DIR_KEY, GE(1), NO_OBJ ),
- T1( "known-flags", K_KNOWN_FLAGS, CONCAT_ARGS, NO_OBJ ),
- T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
- T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
- T1( "consensus-methods", K_CONSENSUS_METHODS, GE(1), NO_OBJ ),
- END_OF_TABLE
- };
- /** List of tokens recognized in V3 networkstatus consensuses. */
- static token_rule_t networkstatus_consensus_token_table[] = {
- T1_START("network-status-version", K_NETWORK_STATUS_VERSION,
- GE(1), NO_OBJ ),
- T1("vote-status", K_VOTE_STATUS, GE(1), NO_OBJ ),
- T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
- T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
- T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
- T1("voting-delay", K_VOTING_DELAY, GE(2), NO_OBJ ),
- T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
- T1N("dir-source", K_DIR_SOURCE, GE(6), NO_OBJ ),
- T1N("contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
- T1N("vote-digest", K_VOTE_DIGEST, GE(1), NO_OBJ ),
- T1( "known-flags", K_KNOWN_FLAGS, CONCAT_ARGS, NO_OBJ ),
- T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
- T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
- T01("consensus-method", K_CONSENSUS_METHOD, EQ(1), NO_OBJ),
- T01("params", K_PARAMS, ARGS, NO_OBJ ),
- T01("shared-rand-previous-value", K_PREVIOUS_SRV, EQ(2), NO_OBJ ),
- T01("shared-rand-current-value", K_CURRENT_SRV, EQ(2), NO_OBJ ),
- T01("recommended-client-protocols", K_RECOMMENDED_CLIENT_PROTOCOLS,
- CONCAT_ARGS, NO_OBJ ),
- T01("recommended-relay-protocols", K_RECOMMENDED_RELAY_PROTOCOLS,
- CONCAT_ARGS, NO_OBJ ),
- T01("required-client-protocols", K_REQUIRED_CLIENT_PROTOCOLS,
- CONCAT_ARGS, NO_OBJ ),
- T01("required-relay-protocols", K_REQUIRED_RELAY_PROTOCOLS,
- CONCAT_ARGS, NO_OBJ ),
- END_OF_TABLE
- };
- /** List of tokens recognized in the footer of v1 directory footers. */
- static token_rule_t networkstatus_vote_footer_token_table[] = {
- T01("directory-footer", K_DIRECTORY_FOOTER, NO_ARGS, NO_OBJ ),
- T01("bandwidth-weights", K_BW_WEIGHTS, ARGS, NO_OBJ ),
- T( "directory-signature", K_DIRECTORY_SIGNATURE, GE(2), NEED_OBJ ),
- END_OF_TABLE
- };
- #undef T
- /* static function prototypes */
- static int router_add_exit_policy(routerinfo_t *router,directory_token_t *tok);
- static addr_policy_t *router_parse_addr_policy(directory_token_t *tok,
- unsigned fmt_flags);
- static addr_policy_t *router_parse_addr_policy_private(directory_token_t *tok);
- static smartlist_t *find_all_exitpolicy(smartlist_t *s);
- /** Set <b>digest</b> to the SHA-1 digest of the hash of the first router in
- * <b>s</b>. Return 0 on success, -1 on failure.
- */
- int
- router_get_router_hash(const char *s, size_t s_len, char *digest)
- {
- return router_get_hash_impl(s, s_len, digest,
- "router ","\nrouter-signature", '\n',
- DIGEST_SHA1);
- }
- /** Try to find the start and end of the signed portion of a networkstatus
- * document in <b>s</b>. On success, set <b>start_out</b> to the first
- * character of the document, and <b>end_out</b> to a position one after the
- * final character of the signed document, and return 0. On failure, return
- * -1. */
- int
- router_get_networkstatus_v3_signed_boundaries(const char *s,
- const char **start_out,
- const char **end_out)
- {
- return router_get_hash_impl_helper(s, strlen(s),
- "network-status-version",
- "\ndirectory-signature",
- ' ', LOG_INFO,
- start_out, end_out);
- }
- /** Set <b>digest_out</b> to the SHA3-256 digest of the signed portion of the
- * networkstatus vote in <b>s</b> -- or of the entirety of <b>s</b> if no
- * signed portion can be identified. Return 0 on success, -1 on failure. */
- int
- router_get_networkstatus_v3_sha3_as_signed(uint8_t *digest_out,
- const char *s)
- {
- const char *start, *end;
- if (router_get_networkstatus_v3_signed_boundaries(s, &start, &end) < 0) {
- start = s;
- end = s + strlen(s);
- }
- tor_assert(start);
- tor_assert(end);
- return crypto_digest256((char*)digest_out, start, end-start,
- DIGEST_SHA3_256);
- }
- /** Set <b>digests</b> to all the digests of the consensus document in
- * <b>s</b> */
- int
- router_get_networkstatus_v3_hashes(const char *s, common_digests_t *digests)
- {
- return router_get_hashes_impl(s,strlen(s),digests,
- "network-status-version",
- "\ndirectory-signature",
- ' ');
- }
- /** Set <b>digest</b> to the SHA-1 digest of the hash of the <b>s_len</b>-byte
- * extrainfo string at <b>s</b>. Return 0 on success, -1 on failure. */
- int
- router_get_extrainfo_hash(const char *s, size_t s_len, char *digest)
- {
- return router_get_hash_impl(s, s_len, digest, "extra-info",
- "\nrouter-signature",'\n', DIGEST_SHA1);
- }
- /** Helper: move *<b>s_ptr</b> ahead to the next router, the next extra-info,
- * or to the first of the annotations proceeding the next router or
- * extra-info---whichever comes first. Set <b>is_extrainfo_out</b> to true if
- * we found an extrainfo, or false if found a router. Do not scan beyond
- * <b>eos</b>. Return -1 if we found nothing; 0 if we found something. */
- static int
- find_start_of_next_router_or_extrainfo(const char **s_ptr,
- const char *eos,
- int *is_extrainfo_out)
- {
- const char *annotations = NULL;
- const char *s = *s_ptr;
- s = eat_whitespace_eos(s, eos);
- while (s < eos-32) { /* 32 gives enough room for a the first keyword. */
- /* We're at the start of a line. */
- tor_assert(*s != '\n');
- if (*s == '@' && !annotations) {
- annotations = s;
- } else if (*s == 'r' && !strcmpstart(s, "router ")) {
- *s_ptr = annotations ? annotations : s;
- *is_extrainfo_out = 0;
- return 0;
- } else if (*s == 'e' && !strcmpstart(s, "extra-info ")) {
- *s_ptr = annotations ? annotations : s;
- *is_extrainfo_out = 1;
- return 0;
- }
- if (!(s = memchr(s+1, '\n', eos-(s+1))))
- break;
- s = eat_whitespace_eos(s, eos);
- }
- return -1;
- }
- /** Given a string *<b>s</b> containing a concatenated sequence of router
- * descriptors (or extra-info documents if <b>want_extrainfo</b> is set),
- * parses them and stores the result in <b>dest</b>. All routers are marked
- * running and valid. Advances *s to a point immediately following the last
- * router entry. Ignore any trailing router entries that are not complete.
- *
- * If <b>saved_location</b> isn't SAVED_IN_CACHE, make a local copy of each
- * descriptor in the signed_descriptor_body field of each routerinfo_t. If it
- * isn't SAVED_NOWHERE, remember the offset of each descriptor.
- *
- * Returns 0 on success and -1 on failure. Adds a digest to
- * <b>invalid_digests_out</b> for every entry that was unparseable or
- * invalid. (This may cause duplicate entries.)
- */
- int
- router_parse_list_from_string(const char **s, const char *eos,
- smartlist_t *dest,
- saved_location_t saved_location,
- int want_extrainfo,
- int allow_annotations,
- const char *prepend_annotations,
- smartlist_t *invalid_digests_out)
- {
- routerinfo_t *router;
- extrainfo_t *extrainfo;
- signed_descriptor_t *signed_desc = NULL;
- void *elt;
- const char *end, *start;
- int have_extrainfo;
- tor_assert(s);
- tor_assert(*s);
- tor_assert(dest);
- start = *s;
- if (!eos)
- eos = *s + strlen(*s);
- tor_assert(eos >= *s);
- while (1) {
- char raw_digest[DIGEST_LEN];
- int have_raw_digest = 0;
- int dl_again = 0;
- if (find_start_of_next_router_or_extrainfo(s, eos, &have_extrainfo) < 0)
- break;
- end = tor_memstr(*s, eos-*s, "\nrouter-signature");
- if (end)
- end = tor_memstr(end, eos-end, "\n-----END SIGNATURE-----\n");
- if (end)
- end += strlen("\n-----END SIGNATURE-----\n");
- if (!end)
- break;
- elt = NULL;
- if (have_extrainfo && want_extrainfo) {
- routerlist_t *rl = router_get_routerlist();
- have_raw_digest = router_get_extrainfo_hash(*s, end-*s, raw_digest) == 0;
- extrainfo = extrainfo_parse_entry_from_string(*s, end,
- saved_location != SAVED_IN_CACHE,
- rl->identity_map, &dl_again);
- if (extrainfo) {
- signed_desc = &extrainfo->cache_info;
- elt = extrainfo;
- }
- } else if (!have_extrainfo && !want_extrainfo) {
- have_raw_digest = router_get_router_hash(*s, end-*s, raw_digest) == 0;
- router = router_parse_entry_from_string(*s, end,
- saved_location != SAVED_IN_CACHE,
- allow_annotations,
- prepend_annotations, &dl_again);
- if (router) {
- log_debug(LD_DIR, "Read router '%s', purpose '%s'",
- router_describe(router),
- router_purpose_to_string(router->purpose));
- signed_desc = &router->cache_info;
- elt = router;
- }
- }
- if (! elt && ! dl_again && have_raw_digest && invalid_digests_out) {
- smartlist_add(invalid_digests_out, tor_memdup(raw_digest, DIGEST_LEN));
- }
- if (!elt) {
- *s = end;
- continue;
- }
- if (saved_location != SAVED_NOWHERE) {
- tor_assert(signed_desc);
- signed_desc->saved_location = saved_location;
- signed_desc->saved_offset = *s - start;
- }
- *s = end;
- smartlist_add(dest, elt);
- }
- return 0;
- }
- /** Try to find an IPv6 OR port in <b>list</b> of directory_token_t's
- * with at least one argument (use GE(1) in setup). If found, store
- * address and port number to <b>addr_out</b> and
- * <b>port_out</b>. Return number of OR ports found. */
- int
- find_single_ipv6_orport(const smartlist_t *list,
- tor_addr_t *addr_out,
- uint16_t *port_out)
- {
- int ret = 0;
- tor_assert(list != NULL);
- tor_assert(addr_out != NULL);
- tor_assert(port_out != NULL);
- SMARTLIST_FOREACH_BEGIN(list, directory_token_t *, t) {
- tor_addr_t a;
- maskbits_t bits;
- uint16_t port_min, port_max;
- tor_assert(t->n_args >= 1);
- /* XXXX Prop186 the full spec allows much more than this. */
- if (tor_addr_parse_mask_ports(t->args[0], 0,
- &a, &bits, &port_min,
- &port_max) == AF_INET6 &&
- bits == 128 &&
- port_min == port_max) {
- /* Okay, this is one we can understand. Use it and ignore
- any potential more addresses in list. */
- tor_addr_copy(addr_out, &a);
- *port_out = port_min;
- ret = 1;
- break;
- }
- } SMARTLIST_FOREACH_END(t);
- return ret;
- }
- /** Helper function: reads a single router entry from *<b>s</b> ...
- * *<b>end</b>. Mallocs a new router and returns it if all goes well, else
- * returns NULL. If <b>cache_copy</b> is true, duplicate the contents of
- * s through end into the signed_descriptor_body of the resulting
- * routerinfo_t.
- *
- * If <b>end</b> is NULL, <b>s</b> must be properly NUL-terminated.
- *
- * If <b>allow_annotations</b>, it's okay to encounter annotations in <b>s</b>
- * before the router; if it's false, reject the router if it's annotated. If
- * <b>prepend_annotations</b> is set, it should contain some annotations:
- * append them to the front of the router before parsing it, and keep them
- * around when caching the router.
- *
- * Only one of allow_annotations and prepend_annotations may be set.
- *
- * If <b>can_dl_again_out</b> is provided, set *<b>can_dl_again_out</b> to 1
- * if it's okay to try to download a descriptor with this same digest again,
- * and 0 if it isn't. (It might not be okay to download it again if part of
- * the part covered by the digest is invalid.)
- */
- routerinfo_t *
- router_parse_entry_from_string(const char *s, const char *end,
- int cache_copy, int allow_annotations,
- const char *prepend_annotations,
- int *can_dl_again_out)
- {
- routerinfo_t *router = NULL;
- char digest[128];
- smartlist_t *tokens = NULL, *exit_policy_tokens = NULL;
- directory_token_t *tok;
- struct in_addr in;
- const char *start_of_annotations, *cp, *s_dup = s;
- size_t prepend_len = prepend_annotations ? strlen(prepend_annotations) : 0;
- int ok = 1;
- memarea_t *area = NULL;
- tor_cert_t *ntor_cc_cert = NULL;
- /* Do not set this to '1' until we have parsed everything that we intend to
- * parse that's covered by the hash. */
- int can_dl_again = 0;
- crypto_pk_t *rsa_pubkey = NULL;
- tor_assert(!allow_annotations || !prepend_annotations);
- if (!end) {
- end = s + strlen(s);
- }
- /* point 'end' to a point immediately after the final newline. */
- while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
- --end;
- area = memarea_new();
- tokens = smartlist_new();
- if (prepend_annotations) {
- if (tokenize_string(area,prepend_annotations,NULL,tokens,
- routerdesc_token_table,TS_NOCHECK)) {
- log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
- goto err;
- }
- }
- start_of_annotations = s;
- cp = tor_memstr(s, end-s, "\nrouter ");
- if (!cp) {
- if (end-s < 7 || strcmpstart(s, "router ")) {
- log_warn(LD_DIR, "No router keyword found.");
- goto err;
- }
- } else {
- s = cp+1;
- }
- if (start_of_annotations != s) { /* We have annotations */
- if (allow_annotations) {
- if (tokenize_string(area,start_of_annotations,s,tokens,
- routerdesc_token_table,TS_NOCHECK)) {
- log_warn(LD_DIR, "Error tokenizing router descriptor (annotations).");
- goto err;
- }
- } else {
- log_warn(LD_DIR, "Found unexpected annotations on router descriptor not "
- "loaded from disk. Dropping it.");
- goto err;
- }
- }
- if (router_get_router_hash(s, end - s, digest) < 0) {
- log_warn(LD_DIR, "Couldn't compute router hash.");
- goto err;
- }
- {
- int flags = 0;
- if (allow_annotations)
- flags |= TS_ANNOTATIONS_OK;
- if (prepend_annotations)
- flags |= TS_ANNOTATIONS_OK|TS_NO_NEW_ANNOTATIONS;
- if (tokenize_string(area,s,end,tokens,routerdesc_token_table, flags)) {
- log_warn(LD_DIR, "Error tokenizing router descriptor.");
- goto err;
- }
- }
- if (smartlist_len(tokens) < 2) {
- log_warn(LD_DIR, "Impossibly short router descriptor.");
- goto err;
- }
- tok = find_by_keyword(tokens, K_ROUTER);
- const int router_token_pos = smartlist_pos(tokens, tok);
- tor_assert(tok->n_args >= 5);
- router = tor_malloc_zero(sizeof(routerinfo_t));
- router->cert_expiration_time = TIME_MAX;
- router->cache_info.routerlist_index = -1;
- router->cache_info.annotations_len = s-start_of_annotations + prepend_len;
- router->cache_info.signed_descriptor_len = end-s;
- if (cache_copy) {
- size_t len = router->cache_info.signed_descriptor_len +
- router->cache_info.annotations_len;
- char *signed_body =
- router->cache_info.signed_descriptor_body = tor_malloc(len+1);
- if (prepend_annotations) {
- memcpy(signed_body, prepend_annotations, prepend_len);
- signed_body += prepend_len;
- }
- /* This assertion will always succeed.
- * len == signed_desc_len + annotations_len
- * == end-s + s-start_of_annotations + prepend_len
- * == end-start_of_annotations + prepend_len
- * We already wrote prepend_len bytes into the buffer; now we're
- * writing end-start_of_annotations -NM. */
- tor_assert(signed_body+(end-start_of_annotations) ==
- router->cache_info.signed_descriptor_body+len);
- memcpy(signed_body, start_of_annotations, end-start_of_annotations);
- router->cache_info.signed_descriptor_body[len] = '\0';
- tor_assert(strlen(router->cache_info.signed_descriptor_body) == len);
- }
- memcpy(router->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
- router->nickname = tor_strdup(tok->args[0]);
- if (!is_legal_nickname(router->nickname)) {
- log_warn(LD_DIR,"Router nickname is invalid");
- goto err;
- }
- if (!tor_inet_aton(tok->args[1], &in)) {
- log_warn(LD_DIR,"Router address is not an IP address.");
- goto err;
- }
- router->addr = ntohl(in.s_addr);
- router->or_port =
- (uint16_t) tor_parse_long(tok->args[2],10,0,65535,&ok,NULL);
- if (!ok) {
- log_warn(LD_DIR,"Invalid OR port %s", escaped(tok->args[2]));
- goto err;
- }
- router->dir_port =
- (uint16_t) tor_parse_long(tok->args[4],10,0,65535,&ok,NULL);
- if (!ok) {
- log_warn(LD_DIR,"Invalid dir port %s", escaped(tok->args[4]));
- goto err;
- }
- tok = find_by_keyword(tokens, K_BANDWIDTH);
- tor_assert(tok->n_args >= 3);
- router->bandwidthrate = (int)
- tor_parse_long(tok->args[0],10,1,INT_MAX,&ok,NULL);
- if (!ok) {
- log_warn(LD_DIR, "bandwidthrate %s unreadable or 0. Failing.",
- escaped(tok->args[0]));
- goto err;
- }
- router->bandwidthburst =
- (int) tor_parse_long(tok->args[1],10,0,INT_MAX,&ok,NULL);
- if (!ok) {
- log_warn(LD_DIR, "Invalid bandwidthburst %s", escaped(tok->args[1]));
- goto err;
- }
- router->bandwidthcapacity = (int)
- tor_parse_long(tok->args[2],10,0,INT_MAX,&ok,NULL);
- if (!ok) {
- log_warn(LD_DIR, "Invalid bandwidthcapacity %s", escaped(tok->args[1]));
- goto err;
- }
- if ((tok = find_opt_by_keyword(tokens, A_PURPOSE))) {
- tor_assert(tok->n_args);
- router->purpose = router_purpose_from_string(tok->args[0]);
- } else {
- router->purpose = ROUTER_PURPOSE_GENERAL;
- }
- router->cache_info.send_unencrypted =
- (router->purpose == ROUTER_PURPOSE_GENERAL) ? 1 : 0;
- if ((tok = find_opt_by_keyword(tokens, K_UPTIME))) {
- tor_assert(tok->n_args >= 1);
- router->uptime = tor_parse_long(tok->args[0],10,0,LONG_MAX,&ok,NULL);
- if (!ok) {
- log_warn(LD_DIR, "Invalid uptime %s", escaped(tok->args[0]));
- goto err;
- }
- }
- if ((tok = find_opt_by_keyword(tokens, K_HIBERNATING))) {
- tor_assert(tok->n_args >= 1);
- router->is_hibernating
- = (tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL) != 0);
- }
- tok = find_by_keyword(tokens, K_PUBLISHED);
- tor_assert(tok->n_args == 1);
- if (parse_iso_time(tok->args[0], &router->cache_info.published_on) < 0)
- goto err;
- tok = find_by_keyword(tokens, K_ONION_KEY);
- if (!crypto_pk_public_exponent_ok(tok->key)) {
- log_warn(LD_DIR,
- "Relay's onion key had invalid exponent.");
- goto err;
- }
- router_set_rsa_onion_pkey(tok->key, &router->onion_pkey,
- &router->onion_pkey_len);
- crypto_pk_free(tok->key);
- if ((tok = find_opt_by_keyword(tokens, K_ONION_KEY_NTOR))) {
- curve25519_public_key_t k;
- tor_assert(tok->n_args >= 1);
- if (curve25519_public_from_base64(&k, tok->args[0]) < 0) {
- log_warn(LD_DIR, "Bogus ntor-onion-key in routerinfo");
- goto err;
- }
- router->onion_curve25519_pkey =
- tor_memdup(&k, sizeof(curve25519_public_key_t));
- }
- tok = find_by_keyword(tokens, K_SIGNING_KEY);
- router->identity_pkey = tok->key;
- tok->key = NULL; /* Prevent free */
- if (crypto_pk_get_digest(router->identity_pkey,
- router->cache_info.identity_digest)) {
- log_warn(LD_DIR, "Couldn't calculate key digest"); goto err;
- }
- {
- directory_token_t *ed_sig_tok, *ed_cert_tok, *cc_tap_tok, *cc_ntor_tok,
- *master_key_tok;
- ed_sig_tok = find_opt_by_keyword(tokens, K_ROUTER_SIG_ED25519);
- ed_cert_tok = find_opt_by_keyword(tokens, K_IDENTITY_ED25519);
- master_key_tok = find_opt_by_keyword(tokens, K_MASTER_KEY_ED25519);
- cc_tap_tok = find_opt_by_keyword(tokens, K_ONION_KEY_CROSSCERT);
- cc_ntor_tok = find_opt_by_keyword(tokens, K_NTOR_ONION_KEY_CROSSCERT);
- int n_ed_toks = !!ed_sig_tok + !!ed_cert_tok +
- !!cc_tap_tok + !!cc_ntor_tok;
- if ((n_ed_toks != 0 && n_ed_toks != 4) ||
- (n_ed_toks == 4 && !router->onion_curve25519_pkey)) {
- log_warn(LD_DIR, "Router descriptor with only partial ed25519/"
- "cross-certification support");
- goto err;
- }
- if (master_key_tok && !ed_sig_tok) {
- log_warn(LD_DIR, "Router descriptor has ed25519 master key but no "
- "certificate");
- goto err;
- }
- if (ed_sig_tok) {
- tor_assert(ed_cert_tok && cc_tap_tok && cc_ntor_tok);
- const int ed_cert_token_pos = smartlist_pos(tokens, ed_cert_tok);
- if (ed_cert_token_pos == -1 || router_token_pos == -1 ||
- (ed_cert_token_pos != router_token_pos + 1 &&
- ed_cert_token_pos != router_token_pos - 1)) {
- log_warn(LD_DIR, "Ed25519 certificate in wrong position");
- goto err;
- }
- if (ed_sig_tok != smartlist_get(tokens, smartlist_len(tokens)-2)) {
- log_warn(LD_DIR, "Ed25519 signature in wrong position");
- goto err;
- }
- if (strcmp(ed_cert_tok->object_type, "ED25519 CERT")) {
- log_warn(LD_DIR, "Wrong object type on identity-ed25519 in decriptor");
- goto err;
- }
- if (strcmp(cc_ntor_tok->object_type, "ED25519 CERT")) {
- log_warn(LD_DIR, "Wrong object type on ntor-onion-key-crosscert "
- "in decriptor");
- goto err;
- }
- if (strcmp(cc_tap_tok->object_type, "CROSSCERT")) {
- log_warn(LD_DIR, "Wrong object type on onion-key-crosscert "
- "in decriptor");
- goto err;
- }
- if (strcmp(cc_ntor_tok->args[0], "0") &&
- strcmp(cc_ntor_tok->args[0], "1")) {
- log_warn(LD_DIR, "Bad sign bit on ntor-onion-key-crosscert");
- goto err;
- }
- int ntor_cc_sign_bit = !strcmp(cc_ntor_tok->args[0], "1");
- uint8_t d256[DIGEST256_LEN];
- const char *signed_start, *signed_end;
- tor_cert_t *cert = tor_cert_parse(
- (const uint8_t*)ed_cert_tok->object_body,
- ed_cert_tok->object_size);
- if (! cert) {
- log_warn(LD_DIR, "Couldn't parse ed25519 cert");
- goto err;
- }
- /* makes sure it gets freed. */
- router->cache_info.signing_key_cert = cert;
- if (cert->cert_type != CERT_TYPE_ID_SIGNING ||
- ! cert->signing_key_included) {
- log_warn(LD_DIR, "Invalid form for ed25519 cert");
- goto err;
- }
- if (master_key_tok) {
- /* This token is optional, but if it's present, it must match
- * the signature in the signing cert, or supplant it. */
- tor_assert(master_key_tok->n_args >= 1);
- ed25519_public_key_t pkey;
- if (ed25519_public_from_base64(&pkey, master_key_tok->args[0])<0) {
- log_warn(LD_DIR, "Can't parse ed25519 master key");
- goto err;
- }
- if (fast_memneq(&cert->signing_key.pubkey,
- pkey.pubkey, ED25519_PUBKEY_LEN)) {
- log_warn(LD_DIR, "Ed25519 master key does not match "
- "key in certificate");
- goto err;
- }
- }
- ntor_cc_cert = tor_cert_parse((const uint8_t*)cc_ntor_tok->object_body,
- cc_ntor_tok->object_size);
- if (!ntor_cc_cert) {
- log_warn(LD_DIR, "Couldn't parse ntor-onion-key-crosscert cert");
- goto err;
- }
- if (ntor_cc_cert->cert_type != CERT_TYPE_ONION_ID ||
- ! ed25519_pubkey_eq(&ntor_cc_cert->signed_key, &cert->signing_key)) {
- log_warn(LD_DIR, "Invalid contents for ntor-onion-key-crosscert cert");
- goto err;
- }
- ed25519_public_key_t ntor_cc_pk;
- if (ed25519_public_key_from_curve25519_public_key(&ntor_cc_pk,
- router->onion_curve25519_pkey,
- ntor_cc_sign_bit)<0) {
- log_warn(LD_DIR, "Error converting onion key to ed25519");
- goto err;
- }
- if (router_get_hash_impl_helper(s, end-s, "router ",
- "\nrouter-sig-ed25519",
- ' ', LOG_WARN,
- &signed_start, &signed_end) < 0) {
- log_warn(LD_DIR, "Can't find ed25519-signed portion of descriptor");
- goto err;
- }
- crypto_digest_t *d = crypto_digest256_new(DIGEST_SHA256);
- crypto_digest_add_bytes(d, ED_DESC_SIGNATURE_PREFIX,
- strlen(ED_DESC_SIGNATURE_PREFIX));
- crypto_digest_add_bytes(d, signed_start, signed_end-signed_start);
- crypto_digest_get_digest(d, (char*)d256, sizeof(d256));
- crypto_digest_free(d);
- ed25519_checkable_t check[3];
- int check_ok[3];
- time_t expires = TIME_MAX;
- if (tor_cert_get_checkable_sig(&check[0], cert, NULL, &expires) < 0) {
- log_err(LD_BUG, "Couldn't create 'checkable' for cert.");
- goto err;
- }
- if (tor_cert_get_checkable_sig(&check[1],
- ntor_cc_cert, &ntor_cc_pk, &expires) < 0) {
- log_err(LD_BUG, "Couldn't create 'checkable' for ntor_cc_cert.");
- goto err;
- }
- if (ed25519_signature_from_base64(&check[2].signature,
- ed_sig_tok->args[0])<0) {
- log_warn(LD_DIR, "Couldn't decode ed25519 signature");
- goto err;
- }
- check[2].pubkey = &cert->signed_key;
- check[2].msg = d256;
- check[2].len = DIGEST256_LEN;
- if (ed25519_checksig_batch(check_ok, check, 3) < 0) {
- log_warn(LD_DIR, "Incorrect ed25519 signature(s)");
- goto err;
- }
- rsa_pubkey = router_get_rsa_onion_pkey(router->onion_pkey,
- router->onion_pkey_len);
- if (check_tap_onion_key_crosscert(
- (const uint8_t*)cc_tap_tok->object_body,
- (int)cc_tap_tok->object_size,
- rsa_pubkey,
- &cert->signing_key,
- (const uint8_t*)router->cache_info.identity_digest)<0) {
- log_warn(LD_DIR, "Incorrect TAP cross-verification");
- goto err;
- }
- /* We check this before adding it to the routerlist. */
- router->cert_expiration_time = expires;
- }
- }
- if ((tok = find_opt_by_keyword(tokens, K_FINGERPRINT))) {
- /* If there's a fingerprint line, it must match the identity digest. */
- char d[DIGEST_LEN];
- tor_assert(tok->n_args == 1);
- tor_strstrip(tok->args[0], " ");
- if (base16_decode(d, DIGEST_LEN,
- tok->args[0], strlen(tok->args[0])) != DIGEST_LEN) {
- log_warn(LD_DIR, "Couldn't decode router fingerprint %s",
- escaped(tok->args[0]));
- goto err;
- }
- if (tor_memneq(d,router->cache_info.identity_digest, DIGEST_LEN)) {
- log_warn(LD_DIR, "Fingerprint '%s' does not match identity digest.",
- tok->args[0]);
- goto err;
- }
- }
- {
- const char *version = NULL, *protocols = NULL;
- if ((tok = find_opt_by_keyword(tokens, K_PLATFORM))) {
- router->platform = tor_strdup(tok->args[0]);
- version = tok->args[0];
- }
- if ((tok = find_opt_by_keyword(tokens, K_PROTO))) {
- router->protocol_list = tor_strdup(tok->args[0]);
- protocols = tok->args[0];
- }
- summarize_protover_flags(&router->pv, protocols, version);
- }
- if ((tok = find_opt_by_keyword(tokens, K_CONTACT))) {
- router->contact_info = tor_strdup(tok->args[0]);
- }
- if (find_opt_by_keyword(tokens, K_REJECT6) ||
- find_opt_by_keyword(tokens, K_ACCEPT6)) {
- log_warn(LD_DIR, "Rejecting router with reject6/accept6 line: they crash "
- "older Tors.");
- goto err;
- }
- {
- smartlist_t *or_addresses = find_all_by_keyword(tokens, K_OR_ADDRESS);
- if (or_addresses) {
- find_single_ipv6_orport(or_addresses, &router->ipv6_addr,
- &router->ipv6_orport);
- smartlist_free(or_addresses);
- }
- }
- exit_policy_tokens = find_all_exitpolicy(tokens);
- if (!smartlist_len(exit_policy_tokens)) {
- log_warn(LD_DIR, "No exit policy tokens in descriptor.");
- goto err;
- }
- SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
- if (router_add_exit_policy(router,t)<0) {
- log_warn(LD_DIR,"Error in exit policy");
- goto err;
- });
- policy_expand_private(&router->exit_policy);
- if ((tok = find_opt_by_keyword(tokens, K_IPV6_POLICY)) && tok->n_args) {
- router->ipv6_exit_policy = parse_short_policy(tok->args[0]);
- if (! router->ipv6_exit_policy) {
- log_warn(LD_DIR , "Error in ipv6-policy %s", escaped(tok->args[0]));
- goto err;
- }
- }
- if (policy_is_reject_star(router->exit_policy, AF_INET, 1) &&
- (!router->ipv6_exit_policy ||
- short_policy_is_reject_star(router->ipv6_exit_policy)))
- router->policy_is_reject_star = 1;
- if ((tok = find_opt_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
- int i;
- router->declared_family = smartlist_new();
- for (i=0;i<tok->n_args;++i) {
- if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
- log_warn(LD_DIR, "Illegal nickname %s in family line",
- escaped(tok->args[i]));
- goto err;
- }
- smartlist_add_strdup(router->declared_family, tok->args[i]);
- }
- }
- if (find_opt_by_keyword(tokens, K_CACHES_EXTRA_INFO))
- router->caches_extra_info = 1;
- if (find_opt_by_keyword(tokens, K_ALLOW_SINGLE_HOP_EXITS))
- router->allow_single_hop_exits = 1;
- if ((tok = find_opt_by_keyword(tokens, K_EXTRA_INFO_DIGEST))) {
- tor_assert(tok->n_args >= 1);
- if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
- if (base16_decode(router->cache_info.extra_info_digest, DIGEST_LEN,
- tok->args[0], HEX_DIGEST_LEN) != DIGEST_LEN) {
- log_warn(LD_DIR,"Invalid extra info digest");
- }
- } else {
- log_warn(LD_DIR, "Invalid extra info digest %s", escaped(tok->args[0]));
- }
- if (tok->n_args >= 2) {
- if (digest256_from_base64(router->cache_info.extra_info_digest256,
- tok->args[1]) < 0) {
- log_warn(LD_DIR, "Invalid extra info digest256 %s",
- escaped(tok->args[1]));
- }
- }
- }
- if (find_opt_by_keyword(tokens, K_HIDDEN_SERVICE_DIR)) {
- router->wants_to_be_hs_dir = 1;
- }
- /* This router accepts tunnelled directory requests via begindir if it has
- * an open dirport or it included "tunnelled-dir-server". */
- if (find_opt_by_keyword(tokens, K_DIR_TUNNELLED) || router->dir_port > 0) {
- router->supports_tunnelled_dir_requests = 1;
- }
- tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
- if (!router->or_port) {
- log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
- goto err;
- }
- /* We've checked everything that's covered by the hash. */
- can_dl_again = 1;
- if (check_signature_token(digest, DIGEST_LEN, tok, router->identity_pkey, 0,
- "router descriptor") < 0)
- goto err;
- if (!router->platform) {
- router->platform = tor_strdup("<unknown>");
- }
- goto done;
- err:
- dump_desc(s_dup, "router descriptor");
- routerinfo_free(router);
- router = NULL;
- done:
- crypto_pk_free(rsa_pubkey);
- tor_cert_free(ntor_cc_cert);
- if (tokens) {
- SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
- smartlist_free(tokens);
- }
- smartlist_free(exit_policy_tokens);
- if (area) {
- DUMP_AREA(area, "routerinfo");
- memarea_drop_all(area);
- }
- if (can_dl_again_out)
- *can_dl_again_out = can_dl_again;
- return router;
- }
- /** Parse a single extrainfo entry from the string <b>s</b>, ending at
- * <b>end</b>. (If <b>end</b> is NULL, parse up to the end of <b>s</b>.) If
- * <b>cache_copy</b> is true, make a copy of the extra-info document in the
- * cache_info fields of the result. If <b>routermap</b> is provided, use it
- * as a map from router identity to routerinfo_t when looking up signing keys.
- *
- * If <b>can_dl_again_out</b> is provided, set *<b>can_dl_again_out</b> to 1
- * if it's okay to try to download an extrainfo with this same digest again,
- * and 0 if it isn't. (It might not be okay to download it again if part of
- * the part covered by the digest is invalid.)
- */
- extrainfo_t *
- extrainfo_parse_entry_from_string(const char *s, const char *end,
- int cache_copy, struct digest_ri_map_t *routermap,
- int *can_dl_again_out)
- {
- extrainfo_t *extrainfo = NULL;
- char digest[128];
- smartlist_t *tokens = NULL;
- directory_token_t *tok;
- crypto_pk_t *key = NULL;
- routerinfo_t *router = NULL;
- memarea_t *area = NULL;
- const char *s_dup = s;
- /* Do not set this to '1' until we have parsed everything that we intend to
- * parse that's covered by the hash. */
- int can_dl_again = 0;
- if (BUG(s == NULL))
- return NULL;
- if (!end) {
- end = s + strlen(s);
- }
- /* point 'end' to a point immediately after the final newline. */
- while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
- --end;
- if (router_get_extrainfo_hash(s, end-s, digest) < 0) {
- log_warn(LD_DIR, "Couldn't compute router hash.");
- goto err;
- }
- tokens = smartlist_new();
- area = memarea_new();
- if (tokenize_string(area,s,end,tokens,extrainfo_token_table,0)) {
- log_warn(LD_DIR, "Error tokenizing extra-info document.");
- goto err;
- }
- if (smartlist_len(tokens) < 2) {
- log_warn(LD_DIR, "Impossibly short extra-info document.");
- goto err;
- }
- /* XXXX Accept this in position 1 too, and ed identity in position 0. */
- tok = smartlist_get(tokens,0);
- if (tok->tp != K_EXTRA_INFO) {
- log_warn(LD_DIR,"Entry does not start with \"extra-info\"");
- goto err;
- }
- extrainfo = tor_malloc_zero(sizeof(extrainfo_t));
- extrainfo->cache_info.is_extrainfo = 1;
- if (cache_copy)
- extrainfo->cache_info.signed_descriptor_body = tor_memdup_nulterm(s,end-s);
- extrainfo->cache_info.signed_descriptor_len = end-s;
- memcpy(extrainfo->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
- crypto_digest256((char*)extrainfo->digest256, s, end-s, DIGEST_SHA256);
- tor_assert(tok->n_args >= 2);
- if (!is_legal_nickname(tok->args[0])) {
- log_warn(LD_DIR,"Bad nickname %s on \"extra-info\"",escaped(tok->args[0]));
- goto err;
- }
- strlcpy(extrainfo->nickname, tok->args[0], sizeof(extrainfo->nickname));
- if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
- base16_decode(extrainfo->cache_info.identity_digest, DIGEST_LEN,
- tok->args[1], HEX_DIGEST_LEN) != DIGEST_LEN) {
- log_warn(LD_DIR,"Invalid fingerprint %s on \"extra-info\"",
- escaped(tok->args[1]));
- goto err;
- }
- tok = find_by_keyword(tokens, K_PUBLISHED);
- if (parse_iso_time(tok->args[0], &extrainfo->cache_info.published_on)) {
- log_warn(LD_DIR,"Invalid published time %s on \"extra-info\"",
- escaped(tok->args[0]));
- goto err;
- }
- {
- directory_token_t *ed_sig_tok, *ed_cert_tok;
- ed_sig_tok = find_opt_by_keyword(tokens, K_ROUTER_SIG_ED25519);
- ed_cert_tok = find_opt_by_keyword(tokens, K_IDENTITY_ED25519);
- int n_ed_toks = !!ed_sig_tok + !!ed_cert_tok;
- if (n_ed_toks != 0 && n_ed_toks != 2) {
- log_warn(LD_DIR, "Router descriptor with only partial ed25519/"
- "cross-certification support");
- goto err;
- }
- if (ed_sig_tok) {
- tor_assert(ed_cert_tok);
- const int ed_cert_token_pos = smartlist_pos(tokens, ed_cert_tok);
- if (ed_cert_token_pos != 1) {
- /* Accept this in position 0 XXXX */
- log_warn(LD_DIR, "Ed25519 certificate in wrong position");
- goto err;
- }
- if (ed_sig_tok != smartlist_get(tokens, smartlist_len(tokens)-2)) {
- log_warn(LD_DIR, "Ed25519 signature in wrong position");
- goto err;
- }
- if (strcmp(ed_cert_tok->object_type, "ED25519 CERT")) {
- log_warn(LD_DIR, "Wrong object type on identity-ed25519 in decriptor");
- goto err;
- }
- uint8_t d256[DIGEST256_LEN];
- const char *signed_start, *signed_end;
- tor_cert_t *cert = tor_cert_parse(
- (const uint8_t*)ed_cert_tok->object_body,
- ed_cert_tok->object_size);
- if (! cert) {
- log_warn(LD_DIR, "Couldn't parse ed25519 cert");
- goto err;
- }
- /* makes sure it gets freed. */
- extrainfo->cache_info.signing_key_cert = cert;
- if (cert->cert_type != CERT_TYPE_ID_SIGNING ||
- ! cert->signing_key_included) {
- log_warn(LD_DIR, "Invalid form for ed25519 cert");
- goto err;
- }
- if (router_get_hash_impl_helper(s, end-s, "extra-info ",
- "\nrouter-sig-ed25519",
- ' ', LOG_WARN,
- &signed_start, &signed_end) < 0) {
- log_warn(LD_DIR, "Can't find ed25519-signed portion of extrainfo");
- goto err;
- }
- crypto_digest_t *d = crypto_digest256_new(DIGEST_SHA256);
- crypto_digest_add_bytes(d, ED_DESC_SIGNATURE_PREFIX,
- strlen(ED_DESC_SIGNATURE_PREFIX));
- crypto_digest_add_bytes(d, signed_start, signed_end-signed_start);
- crypto_digest_get_digest(d, (char*)d256, sizeof(d256));
- crypto_digest_free(d);
- ed25519_checkable_t check[2];
- int check_ok[2];
- if (tor_cert_get_checkable_sig(&check[0], cert, NULL, NULL) < 0) {
- log_err(LD_BUG, "Couldn't create 'checkable' for cert.");
- goto err;
- }
- if (ed25519_signature_from_base64(&check[1].signature,
- ed_sig_tok->args[0])<0) {
- log_warn(LD_DIR, "Couldn't decode ed25519 signature");
- goto err;
- }
- check[1].pubkey = &cert->signed_key;
- check[1].msg = d256;
- check[1].len = DIGEST256_LEN;
- if (ed25519_checksig_batch(check_ok, check, 2) < 0) {
- log_warn(LD_DIR, "Incorrect ed25519 signature(s)");
- goto err;
- }
- /* We don't check the certificate expiration time: checking that it
- * matches the cert in the router descriptor is adequate. */
- }
- }
- /* We've checked everything that's covered by the hash. */
- can_dl_again = 1;
- if (routermap &&
- (router = digestmap_get((digestmap_t*)routermap,
- extrainfo->cache_info.identity_digest))) {
- key = router->identity_pkey;
- }
- tok = find_by_keyword(tokens, K_ROUTER_SIGNATURE);
- if (strcmp(tok->object_type, "SIGNATURE") ||
- tok->object_size < 128 || tok->object_size > 512) {
- log_warn(LD_DIR, "Bad object type or length on extra-info signature");
- goto err;
- }
- if (key) {
- if (check_signature_token(digest, DIGEST_LEN, tok, key, 0,
- "extra-info") < 0)
- goto err;
- if (router)
- extrainfo->cache_info.send_unencrypted =
- router->cache_info.send_unencrypted;
- } else {
- extrainfo->pending_sig = tor_memdup(tok->object_body,
- tok->object_size);
- extrainfo->pending_sig_len = tok->object_size;
- }
- goto done;
- err:
- dump_desc(s_dup, "extra-info descriptor");
- extrainfo_free(extrainfo);
- extrainfo = NULL;
- done:
- if (tokens) {
- SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
- smartlist_free(tokens);
- }
- if (area) {
- DUMP_AREA(area, "extrainfo");
- memarea_drop_all(area);
- }
- if (can_dl_again_out)
- *can_dl_again_out = can_dl_again;
- return extrainfo;
- }
- /** Helper: given a string <b>s</b>, return the start of the next router-status
- * object (starting with "r " at the start of a line). If none is found,
- * return the start of the directory footer, or the next directory signature.
- * If none is found, return the end of the string. */
- static inline const char *
- find_start_of_next_routerstatus(const char *s)
- {
- const char *eos, *footer, *sig;
- if ((eos = strstr(s, "\nr ")))
- ++eos;
- else
- eos = s + strlen(s);
- footer = tor_memstr(s, eos-s, "\ndirectory-footer");
- sig = tor_memstr(s, eos-s, "\ndirectory-signature");
- if (footer && sig)
- return MIN(footer, sig) + 1;
- else if (footer)
- return footer+1;
- else if (sig)
- return sig+1;
- else
- return eos;
- }
- /** Parse the GuardFraction string from a consensus or vote.
- *
- * If <b>vote</b> or <b>vote_rs</b> are set the document getting
- * parsed is a vote routerstatus. Otherwise it's a consensus. This is
- * the same semantic as in routerstatus_parse_entry_from_string(). */
- STATIC int
- routerstatus_parse_guardfraction(const char *guardfraction_str,
- networkstatus_t *vote,
- vote_routerstatus_t *vote_rs,
- routerstatus_t *rs)
- {
- int ok;
- const char *end_of_header = NULL;
- int is_consensus = !vote_rs;
- uint32_t guardfraction;
- tor_assert(bool_eq(vote, vote_rs));
- /* If this info comes from a consensus, but we should't apply
- guardfraction, just exit. */
- if (is_consensus && !should_apply_guardfraction(NULL)) {
- return 0;
- }
- end_of_header = strchr(guardfraction_str, '=');
- if (!end_of_header) {
- return -1;
- }
- guardfraction = (uint32_t)tor_parse_ulong(end_of_header+1,
- 10, 0, 100, &ok, NULL);
- if (!ok) {
- log_warn(LD_DIR, "Invalid GuardFraction %s", escaped(guardfraction_str));
- return -1;
- }
- log_debug(LD_GENERAL, "[*] Parsed %s guardfraction '%s' for '%s'.",
- is_consensus ? "consensus" : "vote",
- guardfraction_str, rs->nickname);
- if (!is_consensus) { /* We are parsing a vote */
- vote_rs->status.guardfraction_percentage = guardfraction;
- vote_rs->status.has_guardfraction = 1;
- } else {
- /* We are parsing a consensus. Only apply guardfraction to guards. */
- if (rs->is_possible_guard) {
- rs->guardfraction_percentage = guardfraction;
- rs->has_guardfraction = 1;
- } else {
- log_warn(LD_BUG, "Got GuardFraction for non-guard %s. "
- "This is not supposed to happen. Not applying. ", rs->nickname);
- }
- }
- return 0;
- }
- /** Summarize the protocols listed in <b>protocols</b> into <b>out</b>,
- * falling back or correcting them based on <b>version</b> as appropriate.
- */
- STATIC void
- summarize_protover_flags(protover_summary_flags_t *out,
- const char *protocols,
- const char *version)
- {
- tor_assert(out);
- memset(out, 0, sizeof(*out));
- if (protocols) {
- out->protocols_known = 1;
- out->supports_extend2_cells =
- protocol_list_supports_protocol(protocols, PRT_RELAY, 2);
- out->supports_ed25519_link_handshake_compat =
- protocol_list_supports_protocol(protocols, PRT_LINKAUTH, 3);
- out->supports_ed25519_link_handshake_any =
- protocol_list_supports_protocol_or_later(protocols, PRT_LINKAUTH, 3);
- out->supports_ed25519_hs_intro =
- protocol_list_supports_protocol(protocols, PRT_HSINTRO, 4);
- out->supports_v3_hsdir =
- protocol_list_supports_protocol(protocols, PRT_HSDIR,
- PROTOVER_HSDIR_V3);
- out->supports_v3_rendezvous_point =
- protocol_list_supports_protocol(protocols, PRT_HSREND,
- PROTOVER_HS_RENDEZVOUS_POINT_V3);
- }
- if (version && !strcmpstart(version, "Tor ")) {
- if (!out->protocols_known) {
- /* The version is a "Tor" version, and where there is no
- * list of protocol versions that we should be looking at instead. */
- out->supports_extend2_cells =
- tor_version_as_new_as(version, "0.2.4.8-alpha");
- out->protocols_known = 1;
- } else {
- /* Bug #22447 forces us to filter on this version. */
- if (!tor_version_as_new_as(version, "0.3.0.8")) {
- out->supports_v3_hsdir = 0;
- }
- }
- }
- }
- /** Given a string at *<b>s</b>, containing a routerstatus object, and an
- * empty smartlist at <b>tokens</b>, parse and return the first router status
- * object in the string, and advance *<b>s</b> to just after the end of the
- * router status. Return NULL and advance *<b>s</b> on error.
- *
- * If <b>vote</b> and <b>vote_rs</b> are provided, don't allocate a fresh
- * routerstatus but use <b>vote_rs</b> instead.
- *
- * If <b>consensus_method</b> is nonzero, this routerstatus is part of a
- * consensus, and we should parse it according to the method used to
- * make that consensus.
- *
- * Parse according to the syntax used by the consensus flavor <b>flav</b>.
- **/
- STATIC routerstatus_t *
- routerstatus_parse_entry_from_string(memarea_t *area,
- const char **s, smartlist_t *tokens,
- networkstatus_t *vote,
- vote_routerstatus_t *vote_rs,
- int consensus_method,
- consensus_flavor_t flav)
- {
- const char *eos, *s_dup = *s;
- routerstatus_t *rs = NULL;
- directory_token_t *tok;
- char timebuf[ISO_TIME_LEN+1];
- struct in_addr in;
- int offset = 0;
- tor_assert(tokens);
- tor_assert(bool_eq(vote, vote_rs));
- if (!consensus_method)
- flav = FLAV_NS;
- tor_assert(flav == FLAV_NS || flav == FLAV_MICRODESC);
- eos = find_start_of_next_routerstatus(*s);
- if (tokenize_string(area,*s, eos, tokens, rtrstatus_token_table,0)) {
- log_warn(LD_DIR, "Error tokenizing router status");
- goto err;
- }
- if (smartlist_len(tokens) < 1) {
- log_warn(LD_DIR, "Impossibly short router status");
- goto err;
- }
- tok = find_by_keyword(tokens, K_R);
- tor_assert(tok->n_args >= 7); /* guaranteed by GE(7) in K_R setup */
- if (flav == FLAV_NS) {
- if (tok->n_args < 8) {
- log_warn(LD_DIR, "Too few arguments to r");
- goto err;
- }
- } else if (flav == FLAV_MICRODESC) {
- offset = -1; /* There is no descriptor digest in an md consensus r line */
- }
- if (vote_rs) {
- rs = &vote_rs->status;
- } else {
- rs = tor_malloc_zero(sizeof(routerstatus_t));
- }
- if (!is_legal_nickname(tok->args[0])) {
- log_warn(LD_DIR,
- "Invalid nickname %s in router status; skipping.",
- escaped(tok->args[0]));
- goto err;
- }
- strlcpy(rs->nickname, tok->args[0], sizeof(rs->nickname));
- if (digest_from_base64(rs->identity_digest, tok->args[1])) {
- log_warn(LD_DIR, "Error decoding identity digest %s",
- escaped(tok->args[1]));
- goto err;
- }
- if (flav == FLAV_NS) {
- if (digest_from_base64(rs->descriptor_digest, tok->args[2])) {
- log_warn(LD_DIR, "Error decoding descriptor digest %s",
- escaped(tok->args[2]));
- goto err;
- }
- }
- if (tor_snprintf(timebuf, sizeof(timebuf), "%s %s",
- tok->args[3+offset], tok->args[4+offset]) < 0 ||
- parse_iso_time(timebuf, &rs->published_on)<0) {
- log_warn(LD_DIR, "Error parsing time '%s %s' [%d %d]",
- tok->args[3+offset], tok->args[4+offset],
- offset, (int)flav);
- goto err;
- }
- if (tor_inet_aton(tok->args[5+offset], &in) == 0) {
- log_warn(LD_DIR, "Error parsing router address in network-status %s",
- escaped(tok->args[5+offset]));
- goto err;
- }
- rs->addr = ntohl(in.s_addr);
- rs->or_port = (uint16_t) tor_parse_long(tok->args[6+offset],
- 10,0,65535,NULL,NULL);
- rs->dir_port = (uint16_t) tor_parse_long(tok->args[7+offset],
- 10,0,65535,NULL,NULL);
- {
- smartlist_t *a_lines = find_all_by_keyword(tokens, K_A);
- if (a_lines) {
- find_single_ipv6_orport(a_lines, &rs->ipv6_addr, &rs->ipv6_orport);
- smartlist_free(a_lines);
- }
- }
- tok = find_opt_by_keyword(tokens, K_S);
- if (tok && vote) {
- int i;
- vote_rs->flags = 0;
- for (i=0; i < tok->n_args; ++i) {
- int p = smartlist_string_pos(vote->known_flags, tok->args[i]);
- if (p >= 0) {
- vote_rs->flags |= (UINT64_C(1)<<p);
- } else {
- log_warn(LD_DIR, "Flags line had a flag %s not listed in known_flags.",
- escaped(tok->args[i]));
- goto err;
- }
- }
- } else if (tok) {
- /* This is a consensus, not a vote. */
- int i;
- for (i=0; i < tok->n_args; ++i) {
- if (!strcmp(tok->args[i], "Exit"))
- rs->is_exit = 1;
- else if (!strcmp(tok->args[i], "Stable"))
- rs->is_stable = 1;
- else if (!strcmp(tok->args[i], "Fast"))
- rs->is_fast = 1;
- else if (!strcmp(tok->args[i], "Running"))
- rs->is_flagged_running = 1;
- else if (!strcmp(tok->args[i], "Named"))
- rs->is_named = 1;
- else if (!strcmp(tok->args[i], "Valid"))
- rs->is_valid = 1;
- else if (!strcmp(tok->args[i], "Guard"))
- rs->is_possible_guard = 1;
- else if (!strcmp(tok->args[i], "BadExit"))
- rs->is_bad_exit = 1;
- else if (!strcmp(tok->args[i], "Authority"))
- rs->is_authority = 1;
- else if (!strcmp(tok->args[i], "Unnamed") &&
- consensus_method >= 2) {
- /* Unnamed is computed right by consensus method 2 and later. */
- rs->is_unnamed = 1;
- } else if (!strcmp(tok->args[i], "HSDir")) {
- rs->is_hs_dir = 1;
- } else if (!strcmp(tok->args[i], "V2Dir")) {
- rs->is_v2_dir = 1;
- }
- }
- /* These are implied true by having been included in a consensus made
- * with a given method */
- rs->is_flagged_running = 1; /* Starting with consensus method 4. */
- rs->is_valid = 1; /* Starting with consensus method 24. */
- }
- {
- const char *protocols = NULL, *version = NULL;
- if ((tok = find_opt_by_keyword(tokens, K_PROTO))) {
- tor_assert(tok->n_args == 1);
- protocols = tok->args[0];
- }
- if ((tok = find_opt_by_keyword(tokens, K_V))) {
- tor_assert(tok->n_args == 1);
- version = tok->args[0];
- if (vote_rs) {
- vote_rs->version = tor_strdup(tok->args[0]);
- }
- }
- summarize_protover_flags(&rs->pv, protocols, version);
- }
- /* handle weighting/bandwidth info */
- if ((tok = find_opt_by_keyword(tokens, K_W))) {
- int i;
- for (i=0; i < tok->n_args; ++i) {
- if (!strcmpstart(tok->args[i], "Bandwidth=")) {
- int ok;
- rs->bandwidth_kb =
- (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
- 10, 0, UINT32_MAX,
- &ok, NULL);
- if (!ok) {
- log_warn(LD_DIR, "Invalid Bandwidth %s", escaped(tok->args[i]));
- goto err;
- }
- rs->has_bandwidth = 1;
- } else if (!strcmpstart(tok->args[i], "Measured=") && vote_rs) {
- int ok;
- vote_rs->measured_bw_kb =
- (uint32_t)tor_parse_ulong(strchr(tok->args[i], '=')+1,
- 10, 0, UINT32_MAX, &ok, NULL);
- if (!ok) {
- log_warn(LD_DIR, "Invalid Measured Bandwidth %s",
- escaped(tok->args[i]));
- goto err;
- }
- vote_rs->has_measured_bw = 1;
- vote->has_measured_bws = 1;
- } else if (!strcmpstart(tok->args[i], "Unmeasured=1")) {
- rs->bw_is_unmeasured = 1;
- } else if (!strcmpstart(tok->args[i], "GuardFraction=")) {
- if (routerstatus_parse_guardfraction(tok->args[i],
- vote, vote_rs, rs) < 0) {
- goto err;
- }
- }
- }
- }
- /* parse exit policy summaries */
- if ((tok = find_opt_by_keyword(tokens, K_P))) {
- tor_assert(tok->n_args == 1);
- if (strcmpstart(tok->args[0], "accept ") &&
- strcmpstart(tok->args[0], "reject ")) {
- log_warn(LD_DIR, "Unknown exit policy summary type %s.",
- escaped(tok->args[0]));
- goto err;
- }
- /* XXX weasel: parse this into ports and represent them somehow smart,
- * maybe not here but somewhere on if we need it for the client.
- * we should still parse it here to check it's valid tho.
- */
- rs->exitsummary = tor_strdup(tok->args[0]);
- rs->has_exitsummary = 1;
- }
- if (vote_rs) {
- SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, t) {
- if (t->tp == K_M && t->n_args) {
- vote_microdesc_hash_t *line =
- tor_malloc(sizeof(vote_microdesc_hash_t));
- line->next = vote_rs->microdesc;
- line->microdesc_hash_line = tor_strdup(t->args[0]);
- vote_rs->microdesc = line;
- }
- if (t->tp == K_ID) {
- tor_assert(t->n_args >= 2);
- if (!strcmp(t->args[0], "ed25519")) {
- vote_rs->has_ed25519_listing = 1;
- if (strcmp(t->args[1], "none") &&
- digest256_from_base64((char*)vote_rs->ed25519_id,
- t->args[1])<0) {
- log_warn(LD_DIR, "Bogus ed25519 key in networkstatus vote");
- goto err;
- }
- }
- }
- if (t->tp == K_PROTO) {
- tor_assert(t->n_args == 1);
- vote_rs->protocols = tor_strdup(t->args[0]);
- }
- } SMARTLIST_FOREACH_END(t);
- } else if (flav == FLAV_MICRODESC) {
- tok = find_opt_by_keyword(tokens, K_M);
- if (tok) {
- tor_assert(tok->n_args);
- if (digest256_from_base64(rs->descriptor_digest, tok->args[0])) {
- log_warn(LD_DIR, "Error decoding microdescriptor digest %s",
- escaped(tok->args[0]));
- goto err;
- }
- } else {
- log_info(LD_BUG, "Found an entry in networkstatus with no "
- "microdescriptor digest. (Router %s ($%s) at %s:%d.)",
- rs->nickname, hex_str(rs->identity_digest, DIGEST_LEN),
- fmt_addr32(rs->addr), rs->or_port);
- }
- }
- if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME))
- rs->is_named = 0;
- goto done;
- err:
- dump_desc(s_dup, "routerstatus entry");
- if (rs && !vote_rs)
- routerstatus_free(rs);
- rs = NULL;
- done:
- SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
- smartlist_clear(tokens);
- if (area) {
- DUMP_AREA(area, "routerstatus entry");
- memarea_clear(area);
- }
- *s = eos;
- return rs;
- }
- int
- compare_vote_routerstatus_entries(const void **_a, const void **_b)
- {
- const vote_routerstatus_t *a = *_a, *b = *_b;
- return fast_memcmp(a->status.identity_digest, b->status.identity_digest,
- DIGEST_LEN);
- }
- /** Verify the bandwidth weights of a network status document */
- int
- networkstatus_verify_bw_weights(networkstatus_t *ns, int consensus_method)
- {
- int64_t G=0, M=0, E=0, D=0, T=0;
- double Wgg, Wgm, Wgd, Wmg, Wmm, Wme, Wmd, Weg, Wem, Wee, Wed;
- double Gtotal=0, Mtotal=0, Etotal=0;
- const char *casename = NULL;
- int valid = 1;
- (void) consensus_method;
- const int64_t weight_scale = networkstatus_get_weight_scale_param(ns);
- tor_assert(weight_scale >= 1);
- Wgg = networkstatus_get_bw_weight(ns, "Wgg", -1);
- Wgm = networkstatus_get_bw_weight(ns, "Wgm", -1);
- Wgd = networkstatus_get_bw_weight(ns, "Wgd", -1);
- Wmg = networkstatus_get_bw_weight(ns, "Wmg", -1);
- Wmm = networkstatus_get_bw_weight(ns, "Wmm", -1);
- Wme = networkstatus_get_bw_weight(ns, "Wme", -1);
- Wmd = networkstatus_get_bw_weight(ns, "Wmd", -1);
- Weg = networkstatus_get_bw_weight(ns, "Weg", -1);
- Wem = networkstatus_get_bw_weight(ns, "Wem", -1);
- Wee = networkstatus_get_bw_weight(ns, "Wee", -1);
- Wed = networkstatus_get_bw_weight(ns, "Wed", -1);
- if (Wgg<0 || Wgm<0 || Wgd<0 || Wmg<0 || Wmm<0 || Wme<0 || Wmd<0 || Weg<0
- || Wem<0 || Wee<0 || Wed<0) {
- log_warn(LD_BUG, "No bandwidth weights produced in consensus!");
- return 0;
- }
- // First, sanity check basic summing properties that hold for all cases
- // We use > 1 as the check for these because they are computed as integers.
- // Sometimes there are rounding errors.
- if (fabs(Wmm - weight_scale) > 1) {
- log_warn(LD_BUG, "Wmm=%f != %"PRId64,
- Wmm, (weight_scale));
- valid = 0;
- }
- if (fabs(Wem - Wee) > 1) {
- log_warn(LD_BUG, "Wem=%f != Wee=%f", Wem, Wee);
- valid = 0;
- }
- if (fabs(Wgm - Wgg) > 1) {
- log_warn(LD_BUG, "Wgm=%f != Wgg=%f", Wgm, Wgg);
- valid = 0;
- }
- if (fabs(Weg - Wed) > 1) {
- log_warn(LD_BUG, "Wed=%f != Weg=%f", Wed, Weg);
- valid = 0;
- }
- if (fabs(Wgg + Wmg - weight_scale) > 0.001*weight_scale) {
- log_warn(LD_BUG, "Wgg=%f != %"PRId64" - Wmg=%f", Wgg,
- (weight_scale), Wmg);
- valid = 0;
- }
- if (fabs(Wee + Wme - weight_scale) > 0.001*weight_scale) {
- log_warn(LD_BUG, "Wee=%f != %"PRId64" - Wme=%f", Wee,
- (weight_scale), Wme);
- valid = 0;
- }
- if (fabs(Wgd + Wmd + Wed - weight_scale) > 0.001*weight_scale) {
- log_warn(LD_BUG, "Wgd=%f + Wmd=%f + Wed=%f != %"PRId64,
- Wgd, Wmd, Wed, (weight_scale));
- valid = 0;
- }
- Wgg /= weight_scale;
- Wgm /= weight_scale; (void) Wgm; // unused from here on.
- Wgd /= weight_scale;
- Wmg /= weight_scale;
- Wmm /= weight_scale;
- Wme /= weight_scale;
- Wmd /= weight_scale;
- Weg /= weight_scale; (void) Weg; // unused from here on.
- Wem /= weight_scale; (void) Wem; // unused from here on.
- Wee /= weight_scale;
- Wed /= weight_scale;
- // Then, gather G, M, E, D, T to determine case
- SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) {
- int is_exit = 0;
- /* Bug #2203: Don't count bad exits as exits for balancing */
- is_exit = rs->is_exit && !rs->is_bad_exit;
- if (rs->has_bandwidth) {
- T += rs->bandwidth_kb;
- if (is_exit && rs->is_possible_guard) {
- D += rs->bandwidth_kb;
- Gtotal += Wgd*rs->bandwidth_kb;
- Mtotal += Wmd*rs->bandwidth_kb;
- Etotal += Wed*rs->bandwidth_kb;
- } else if (is_exit) {
- E += rs->bandwidth_kb;
- Mtotal += Wme*rs->bandwidth_kb;
- Etotal += Wee*rs->bandwidth_kb;
- } else if (rs->is_possible_guard) {
- G += rs->bandwidth_kb;
- Gtotal += Wgg*rs->bandwidth_kb;
- Mtotal += Wmg*rs->bandwidth_kb;
- } else {
- M += rs->bandwidth_kb;
- Mtotal += Wmm*rs->bandwidth_kb;
- }
- } else {
- log_warn(LD_BUG, "Missing consensus bandwidth for router %s",
- routerstatus_describe(rs));
- }
- } SMARTLIST_FOREACH_END(rs);
- // Finally, check equality conditions depending upon case 1, 2 or 3
- // Full equality cases: 1, 3b
- // Partial equality cases: 2b (E=G), 3a (M=E)
- // Fully unknown: 2a
- if (3*E >= T && 3*G >= T) {
- // Case 1: Neither are scarce
- casename = "Case 1";
- if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
- log_warn(LD_DIR,
- "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
- "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
- " T=%"PRId64". "
- "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
- casename, Etotal, Mtotal,
- (G), (M), (E),
- (D), (T),
- Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
- valid = 0;
- }
- if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
- log_warn(LD_DIR,
- "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
- "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
- " T=%"PRId64". "
- "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
- casename, Etotal, Gtotal,
- (G), (M), (E),
- (D), (T),
- Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
- valid = 0;
- }
- if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
- log_warn(LD_DIR,
- "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
- "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
- " T=%"PRId64". "
- "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
- casename, Mtotal, Gtotal,
- (G), (M), (E),
- (D), (T),
- Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
- valid = 0;
- }
- } else if (3*E < T && 3*G < T) {
- int64_t R = MIN(E, G);
- int64_t S = MAX(E, G);
- /*
- * Case 2: Both Guards and Exits are scarce
- * Balance D between E and G, depending upon
- * D capacity and scarcity. Devote no extra
- * bandwidth to middle nodes.
- */
- if (R+D < S) { // Subcase a
- double Rtotal, Stotal;
- if (E < G) {
- Rtotal = Etotal;
- Stotal = Gtotal;
- } else {
- Rtotal = Gtotal;
- Stotal = Etotal;
- }
- casename = "Case 2a";
- // Rtotal < Stotal
- if (Rtotal > Stotal) {
- log_warn(LD_DIR,
- "Bw Weight Failure for %s: Rtotal %f > Stotal %f. "
- "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
- " T=%"PRId64". "
- "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
- casename, Rtotal, Stotal,
- (G), (M), (E),
- (D), (T),
- Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
- valid = 0;
- }
- // Rtotal < T/3
- if (3*Rtotal > T) {
- log_warn(LD_DIR,
- "Bw Weight Failure for %s: 3*Rtotal %f > T "
- "%"PRId64". G=%"PRId64" M=%"PRId64" E=%"PRId64
- " D=%"PRId64" T=%"PRId64". "
- "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
- casename, Rtotal*3, (T),
- (G), (M), (E),
- (D), (T),
- Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
- valid = 0;
- }
- // Stotal < T/3
- if (3*Stotal > T) {
- log_warn(LD_DIR,
- "Bw Weight Failure for %s: 3*Stotal %f > T "
- "%"PRId64". G=%"PRId64" M=%"PRId64" E=%"PRId64
- " D=%"PRId64" T=%"PRId64". "
- "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
- casename, Stotal*3, (T),
- (G), (M), (E),
- (D), (T),
- Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
- valid = 0;
- }
- // Mtotal > T/3
- if (3*Mtotal < T) {
- log_warn(LD_DIR,
- "Bw Weight Failure for %s: 3*Mtotal %f < T "
- "%"PRId64". "
- "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
- " T=%"PRId64". "
- "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
- casename, Mtotal*3, (T),
- (G), (M), (E),
- (D), (T),
- Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
- valid = 0;
- }
- } else { // Subcase b: R+D > S
- casename = "Case 2b";
- /* Check the rare-M redirect case. */
- if (D != 0 && 3*M < T) {
- casename = "Case 2b (balanced)";
- if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
- log_warn(LD_DIR,
- "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
- "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
- " T=%"PRId64". "
- "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
- casename, Etotal, Mtotal,
- (G), (M), (E),
- (D), (T),
- Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
- valid = 0;
- }
- if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
- log_warn(LD_DIR,
- "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
- "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
- " T=%"PRId64". "
- "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
- casename, Etotal, Gtotal,
- (G), (M), (E),
- (D), (T),
- Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
- valid = 0;
- }
- if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
- log_warn(LD_DIR,
- "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
- "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
- " T=%"PRId64". "
- "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
- casename, Mtotal, Gtotal,
- (G), (M), (E),
- (D), (T),
- Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
- valid = 0;
- }
- } else {
- if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
- log_warn(LD_DIR,
- "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
- "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
- " T=%"PRId64". "
- "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
- casename, Etotal, Gtotal,
- (G), (M), (E),
- (D), (T),
- Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
- valid = 0;
- }
- }
- }
- } else { // if (E < T/3 || G < T/3) {
- int64_t S = MIN(E, G);
- int64_t NS = MAX(E, G);
- if (3*(S+D) < T) { // Subcase a:
- double Stotal;
- double NStotal;
- if (G < E) {
- casename = "Case 3a (G scarce)";
- Stotal = Gtotal;
- NStotal = Etotal;
- } else { // if (G >= E) {
- casename = "Case 3a (E scarce)";
- NStotal = Gtotal;
- Stotal = Etotal;
- }
- // Stotal < T/3
- if (3*Stotal > T) {
- log_warn(LD_DIR,
- "Bw Weight Failure for %s: 3*Stotal %f > T "
- "%"PRId64". G=%"PRId64" M=%"PRId64" E=%"PRId64
- " D=%"PRId64" T=%"PRId64". "
- "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
- casename, Stotal*3, (T),
- (G), (M), (E),
- (D), (T),
- Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
- valid = 0;
- }
- if (NS >= M) {
- if (fabs(NStotal-Mtotal) > 0.01*MAX(NStotal,Mtotal)) {
- log_warn(LD_DIR,
- "Bw Weight Failure for %s: NStotal %f != Mtotal %f. "
- "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
- " T=%"PRId64". "
- "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
- casename, NStotal, Mtotal,
- (G), (M), (E),
- (D), (T),
- Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
- valid = 0;
- }
- } else {
- // if NS < M, NStotal > T/3 because only one of G or E is scarce
- if (3*NStotal < T) {
- log_warn(LD_DIR,
- "Bw Weight Failure for %s: 3*NStotal %f < T "
- "%"PRId64". G=%"PRId64" M=%"PRId64
- " E=%"PRId64" D=%"PRId64" T=%"PRId64". "
- "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
- casename, NStotal*3, (T),
- (G), (M), (E),
- (D), (T),
- Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
- valid = 0;
- }
- }
- } else { // Subcase b: S+D >= T/3
- casename = "Case 3b";
- if (fabs(Etotal-Mtotal) > 0.01*MAX(Etotal,Mtotal)) {
- log_warn(LD_DIR,
- "Bw Weight Failure for %s: Etotal %f != Mtotal %f. "
- "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
- " T=%"PRId64". "
- "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
- casename, Etotal, Mtotal,
- (G), (M), (E),
- (D), (T),
- Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
- valid = 0;
- }
- if (fabs(Etotal-Gtotal) > 0.01*MAX(Etotal,Gtotal)) {
- log_warn(LD_DIR,
- "Bw Weight Failure for %s: Etotal %f != Gtotal %f. "
- "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
- " T=%"PRId64". "
- "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
- casename, Etotal, Gtotal,
- (G), (M), (E),
- (D), (T),
- Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
- valid = 0;
- }
- if (fabs(Gtotal-Mtotal) > 0.01*MAX(Gtotal,Mtotal)) {
- log_warn(LD_DIR,
- "Bw Weight Failure for %s: Mtotal %f != Gtotal %f. "
- "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
- " T=%"PRId64". "
- "Wgg=%f Wgd=%f Wmg=%f Wme=%f Wmd=%f Wee=%f Wed=%f",
- casename, Mtotal, Gtotal,
- (G), (M), (E),
- (D), (T),
- Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed);
- valid = 0;
- }
- }
- }
- if (valid)
- log_notice(LD_DIR, "Bandwidth-weight %s is verified and valid.",
- casename);
- return valid;
- }
- /** Check if a shared random value of type <b>srv_type</b> is in
- * <b>tokens</b>. If there is, parse it and set it to <b>srv_out</b>. Return
- * -1 on failure, 0 on success. The resulting srv is allocated on the heap and
- * it's the responsibility of the caller to free it. */
- static int
- extract_one_srv(smartlist_t *tokens, directory_keyword srv_type,
- sr_srv_t **srv_out)
- {
- int ret = -1;
- directory_token_t *tok;
- sr_srv_t *srv = NULL;
- smartlist_t *chunks;
- tor_assert(tokens);
- chunks = smartlist_new();
- tok = find_opt_by_keyword(tokens, srv_type);
- if (!tok) {
- /* That's fine, no SRV is allowed. */
- ret = 0;
- goto end;
- }
- for (int i = 0; i < tok->n_args; i++) {
- smartlist_add(chunks, tok->args[i]);
- }
- srv = sr_parse_srv(chunks);
- if (srv == NULL) {
- log_warn(LD_DIR, "SR: Unparseable SRV %s", escaped(tok->object_body));
- goto end;
- }
- /* All is good. */
- *srv_out = srv;
- ret = 0;
- end:
- smartlist_free(chunks);
- return ret;
- }
- /** Extract any shared random values found in <b>tokens</b> and place them in
- * the networkstatus <b>ns</b>. */
- static void
- extract_shared_random_srvs(networkstatus_t *ns, smartlist_t *tokens)
- {
- const char *voter_identity;
- networkstatus_voter_info_t *voter;
- tor_assert(ns);
- tor_assert(tokens);
- /* Can be only one of them else code flow. */
- tor_assert(ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_CONSENSUS);
- if (ns->type == NS_TYPE_VOTE) {
- voter = smartlist_get(ns->voters, 0);
- tor_assert(voter);
- voter_identity = hex_str(voter->identity_digest,
- sizeof(voter->identity_digest));
- } else {
- /* Consensus has multiple voters so no specific voter. */
- voter_identity = "consensus";
- }
- /* We extract both, and on error everything is stopped because it means
- * the vote is malformed for the shared random value(s). */
- if (extract_one_srv(tokens, K_PREVIOUS_SRV, &ns->sr_info.previous_srv) < 0) {
- log_warn(LD_DIR, "SR: Unable to parse previous SRV from %s",
- voter_identity);
- /* Maybe we have a chance with the current SRV so let's try it anyway. */
- }
- if (extract_one_srv(tokens, K_CURRENT_SRV, &ns->sr_info.current_srv) < 0) {
- log_warn(LD_DIR, "SR: Unable to parse current SRV from %s",
- voter_identity);
- }
- }
- /** Parse a v3 networkstatus vote, opinion, or consensus (depending on
- * ns_type), from <b>s</b>, and return the result. Return NULL on failure. */
- networkstatus_t *
- networkstatus_parse_vote_from_string(const char *s, const char **eos_out,
- networkstatus_type_t ns_type)
- {
- smartlist_t *tokens = smartlist_new();
- smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;
- networkstatus_voter_info_t *voter = NULL;
- networkstatus_t *ns = NULL;
- common_digests_t ns_digests;
- uint8_t sha3_as_signed[DIGEST256_LEN];
- const char *cert, *end_of_header, *end_of_footer, *s_dup = s;
- directory_token_t *tok;
- struct in_addr in;
- int i, inorder, n_signatures = 0;
- memarea_t *area = NULL, *rs_area = NULL;
- consensus_flavor_t flav = FLAV_NS;
- char *last_kwd=NULL;
- tor_assert(s);
- if (eos_out)
- *eos_out = NULL;
- if (router_get_networkstatus_v3_hashes(s, &ns_digests) ||
- router_get_networkstatus_v3_sha3_as_signed(sha3_as_signed, s)<0) {
- log_warn(LD_DIR, "Unable to compute digest of network-status");
- goto err;
- }
- area = memarea_new();
- end_of_header = find_start_of_next_routerstatus(s);
- if (tokenize_string(area, s, end_of_header, tokens,
- (ns_type == NS_TYPE_CONSENSUS) ?
- networkstatus_consensus_token_table :
- networkstatus_token_table, 0)) {
- log_warn(LD_DIR, "Error tokenizing network-status header");
- goto err;
- }
- ns = tor_malloc_zero(sizeof(networkstatus_t));
- memcpy(&ns->digests, &ns_digests, sizeof(ns_digests));
- memcpy(&ns->digest_sha3_as_signed, sha3_as_signed, sizeof(sha3_as_signed));
- tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
- tor_assert(tok);
- if (tok->n_args > 1) {
- int flavor = networkstatus_parse_flavor_name(tok->args[1]);
- if (flavor < 0) {
- log_warn(LD_DIR, "Can't parse document with unknown flavor %s",
- escaped(tok->args[1]));
- goto err;
- }
- ns->flavor = flav = flavor;
- }
- if (flav != FLAV_NS && ns_type != NS_TYPE_CONSENSUS) {
- log_warn(LD_DIR, "Flavor found on non-consensus networkstatus.");
- goto err;
- }
- if (ns_type != NS_TYPE_CONSENSUS) {
- const char *end_of_cert = NULL;
- if (!(cert = strstr(s, "\ndir-key-certificate-version")))
- goto err;
- ++cert;
- ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);
- if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)
- goto err;
- }
- tok = find_by_keyword(tokens, K_VOTE_STATUS);
- tor_assert(tok->n_args);
- if (!strcmp(tok->args[0], "vote")) {
- ns->type = NS_TYPE_VOTE;
- } else if (!strcmp(tok->args[0], "consensus")) {
- ns->type = NS_TYPE_CONSENSUS;
- } else if (!strcmp(tok->args[0], "opinion")) {
- ns->type = NS_TYPE_OPINION;
- } else {
- log_warn(LD_DIR, "Unrecognized vote status %s in network-status",
- escaped(tok->args[0]));
- goto err;
- }
- if (ns_type != ns->type) {
- log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus.");
- goto err;
- }
- if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
- tok = find_by_keyword(tokens, K_PUBLISHED);
- if (parse_iso_time(tok->args[0], &ns->published))
- goto err;
- ns->supported_methods = smartlist_new();
- tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHODS);
- if (tok) {
- for (i=0; i < tok->n_args; ++i)
- smartlist_add_strdup(ns->supported_methods, tok->args[i]);
- } else {
- smartlist_add_strdup(ns->supported_methods, "1");
- }
- } else {
- tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHOD);
- if (tok) {
- int num_ok;
- ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX,
- &num_ok, NULL);
- if (!num_ok)
- goto err;
- } else {
- ns->consensus_method = 1;
- }
- }
- if ((tok = find_opt_by_keyword(tokens, K_RECOMMENDED_CLIENT_PROTOCOLS)))
- ns->recommended_client_protocols = tor_strdup(tok->args[0]);
- if ((tok = find_opt_by_keyword(tokens, K_RECOMMENDED_RELAY_PROTOCOLS)))
- ns->recommended_relay_protocols = tor_strdup(tok->args[0]);
- if ((tok = find_opt_by_keyword(tokens, K_REQUIRED_CLIENT_PROTOCOLS)))
- ns->required_client_protocols = tor_strdup(tok->args[0]);
- if ((tok = find_opt_by_keyword(tokens, K_REQUIRED_RELAY_PROTOCOLS)))
- ns->required_relay_protocols = tor_strdup(tok->args[0]);
- tok = find_by_keyword(tokens, K_VALID_AFTER);
- if (parse_iso_time(tok->args[0], &ns->valid_after))
- goto err;
- tok = find_by_keyword(tokens, K_FRESH_UNTIL);
- if (parse_iso_time(tok->args[0], &ns->fresh_until))
- goto err;
- tok = find_by_keyword(tokens, K_VALID_UNTIL);
- if (parse_iso_time(tok->args[0], &ns->valid_until))
- goto err;
- tok = find_by_keyword(tokens, K_VOTING_DELAY);
- tor_assert(tok->n_args >= 2);
- {
- int ok;
- ns->vote_seconds =
- (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);
- if (!ok)
- goto err;
- ns->dist_seconds =
- (int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL);
- if (!ok)
- goto err;
- }
- if (ns->valid_after +
- (get_options()->TestingTorNetwork ?
- MIN_VOTE_INTERVAL_TESTING : MIN_VOTE_INTERVAL) > ns->fresh_until) {
- log_warn(LD_DIR, "Vote/consensus freshness interval is too short");
- goto err;
- }
- if (ns->valid_after +
- (get_options()->TestingTorNetwork ?
- MIN_VOTE_INTERVAL_TESTING : MIN_VOTE_INTERVAL)*2 > ns->valid_until) {
- log_warn(LD_DIR, "Vote/consensus liveness interval is too short");
- goto err;
- }
- if (ns->vote_seconds < MIN_VOTE_SECONDS) {
- log_warn(LD_DIR, "Vote seconds is too short");
- goto err;
- }
- if (ns->dist_seconds < MIN_DIST_SECONDS) {
- log_warn(LD_DIR, "Dist seconds is too short");
- goto err;
- }
- if ((tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
- ns->client_versions = tor_strdup(tok->args[0]);
- }
- if ((tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS))) {
- ns->server_versions = tor_strdup(tok->args[0]);
- }
- {
- smartlist_t *package_lst = find_all_by_keyword(tokens, K_PACKAGE);
- ns->package_lines = smartlist_new();
- if (package_lst) {
- SMARTLIST_FOREACH(package_lst, directory_token_t *, t,
- smartlist_add_strdup(ns->package_lines, t->args[0]));
- }
- smartlist_free(package_lst);
- }
- tok = find_by_keyword(tokens, K_KNOWN_FLAGS);
- ns->known_flags = smartlist_new();
- inorder = 1;
- for (i = 0; i < tok->n_args; ++i) {
- smartlist_add_strdup(ns->known_flags, tok->args[i]);
- if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) {
- log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
- inorder = 0;
- }
- }
- if (!inorder) {
- log_warn(LD_DIR, "known-flags not in order");
- goto err;
- }
- if (ns->type != NS_TYPE_CONSENSUS &&
- smartlist_len(ns->known_flags) > MAX_KNOWN_FLAGS_IN_VOTE) {
- /* If we allowed more than 64 flags in votes, then parsing them would make
- * us invoke undefined behavior whenever we used 1<<flagnum to do a
- * bit-shift. This is only for votes and opinions: consensus users don't
- * care about flags they don't recognize, and so don't build a bitfield
- * for them. */
- log_warn(LD_DIR, "Too many known-flags in consensus vote or opinion");
- goto err;
- }
- tok = find_opt_by_keyword(tokens, K_PARAMS);
- if (tok) {
- int any_dups = 0;
- inorder = 1;
- ns->net_params = smartlist_new();
- for (i = 0; i < tok->n_args; ++i) {
- int ok=0;
- char *eq = strchr(tok->args[i], '=');
- size_t eq_pos;
- if (!eq) {
- log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
- goto err;
- }
- eq_pos = eq-tok->args[i];
- tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
- if (!ok) {
- log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
- goto err;
- }
- if (i > 0 && strcmp(tok->args[i-1], tok->args[i]) >= 0) {
- log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
- inorder = 0;
- }
- if (last_kwd && eq_pos == strlen(last_kwd) &&
- fast_memeq(last_kwd, tok->args[i], eq_pos)) {
- log_warn(LD_DIR, "Duplicate value for %s parameter",
- escaped(tok->args[i]));
- any_dups = 1;
- }
- tor_free(last_kwd);
- last_kwd = tor_strndup(tok->args[i], eq_pos);
- smartlist_add_strdup(ns->net_params, tok->args[i]);
- }
- if (!inorder) {
- log_warn(LD_DIR, "params not in order");
- goto err;
- }
- if (any_dups) {
- log_warn(LD_DIR, "Duplicate in parameters");
- goto err;
- }
- }
- ns->voters = smartlist_new();
- SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
- tok = _tok;
- if (tok->tp == K_DIR_SOURCE) {
- tor_assert(tok->n_args >= 6);
- if (voter)
- smartlist_add(ns->voters, voter);
- voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
- voter->sigs = smartlist_new();
- if (ns->type != NS_TYPE_CONSENSUS)
- memcpy(voter->vote_digest, ns_digests.d[DIGEST_SHA1], DIGEST_LEN);
- voter->nickname = tor_strdup(tok->args[0]);
- if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
- base16_decode(voter->identity_digest, sizeof(voter->identity_digest),
- tok->args[1], HEX_DIGEST_LEN)
- != sizeof(voter->identity_digest)) {
- log_warn(LD_DIR, "Error decoding identity digest %s in "
- "network-status document.", escaped(tok->args[1]));
- goto err;
- }
- if (ns->type != NS_TYPE_CONSENSUS &&
- tor_memneq(ns->cert->cache_info.identity_digest,
- voter->identity_digest, DIGEST_LEN)) {
- log_warn(LD_DIR,"Mismatch between identities in certificate and vote");
- goto err;
- }
- if (ns->type != NS_TYPE_CONSENSUS) {
- if (authority_cert_is_blacklisted(ns->cert)) {
- log_warn(LD_DIR, "Rejecting vote signature made with blacklisted "
- "signing key %s",
- hex_str(ns->cert->signing_key_digest, DIGEST_LEN));
- goto err;
- }
- }
- voter->address = tor_strdup(tok->args[2]);
- if (!tor_inet_aton(tok->args[3], &in)) {
- log_warn(LD_DIR, "Error decoding IP address %s in network-status.",
- escaped(tok->args[3]));
- goto err;
- }
- voter->addr = ntohl(in.s_addr);
- int ok;
- voter->dir_port = (uint16_t)
- tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);
- if (!ok)
- goto err;
- voter->or_port = (uint16_t)
- tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);
- if (!ok)
- goto err;
- } else if (tok->tp == K_CONTACT) {
- if (!voter || voter->contact) {
- log_warn(LD_DIR, "contact element is out of place.");
- goto err;
- }
- voter->contact = tor_strdup(tok->args[0]);
- } else if (tok->tp == K_VOTE_DIGEST) {
- tor_assert(ns->type == NS_TYPE_CONSENSUS);
- tor_assert(tok->n_args >= 1);
- if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {
- log_warn(LD_DIR, "vote-digest element is out of place.");
- goto err;
- }
- if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
- base16_decode(voter->vote_digest, sizeof(voter->vote_digest),
- tok->args[0], HEX_DIGEST_LEN)
- != sizeof(voter->vote_digest)) {
- log_warn(LD_DIR, "Error decoding vote digest %s in "
- "network-status consensus.", escaped(tok->args[0]));
- goto err;
- }
- }
- } SMARTLIST_FOREACH_END(_tok);
- if (voter) {
- smartlist_add(ns->voters, voter);
- voter = NULL;
- }
- if (smartlist_len(ns->voters) == 0) {
- log_warn(LD_DIR, "Missing dir-source elements in a networkstatus.");
- goto err;
- } else if (ns->type != NS_TYPE_CONSENSUS && smartlist_len(ns->voters) != 1) {
- log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus.");
- goto err;
- }
- if (ns->type != NS_TYPE_CONSENSUS &&
- (tok = find_opt_by_keyword(tokens, K_LEGACY_DIR_KEY))) {
- int bad = 1;
- if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
- networkstatus_voter_info_t *voter_0 = smartlist_get(ns->voters, 0);
- if (base16_decode(voter_0->legacy_id_digest, DIGEST_LEN,
- tok->args[0], HEX_DIGEST_LEN) != DIGEST_LEN)
- bad = 1;
- else
- bad = 0;
- }
- if (bad) {
- log_warn(LD_DIR, "Invalid legacy key digest %s on vote.",
- escaped(tok->args[0]));
- }
- }
- /* If this is a vote document, check if information about the shared
- randomness protocol is included, and extract it. */
- if (ns->type == NS_TYPE_VOTE) {
- dirvote_parse_sr_commits(ns, tokens);
- }
- /* For both a vote and consensus, extract the shared random values. */
- if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_CONSENSUS) {
- extract_shared_random_srvs(ns, tokens);
- }
- /* Parse routerstatus lines. */
- rs_tokens = smartlist_new();
- rs_area = memarea_new();
- s = end_of_header;
- ns->routerstatus_list = smartlist_new();
- while (!strcmpstart(s, "r ")) {
- if (ns->type != NS_TYPE_CONSENSUS) {
- vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));
- if (routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, ns,
- rs, 0, 0)) {
- smartlist_add(ns->routerstatus_list, rs);
- } else {
- vote_routerstatus_free(rs);
- }
- } else {
- routerstatus_t *rs;
- if ((rs = routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens,
- NULL, NULL,
- ns->consensus_method,
- flav))) {
- /* Use exponential-backoff scheduling when downloading microdescs */
- smartlist_add(ns->routerstatus_list, rs);
- }
- }
- }
- for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {
- routerstatus_t *rs1, *rs2;
- if (ns->type != NS_TYPE_CONSENSUS) {
- vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);
- vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);
- rs1 = &a->status; rs2 = &b->status;
- } else {
- rs1 = smartlist_get(ns->routerstatus_list, i-1);
- rs2 = smartlist_get(ns->routerstatus_list, i);
- }
- if (fast_memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN)
- >= 0) {
- log_warn(LD_DIR, "Networkstatus entries not sorted by identity digest");
- goto err;
- }
- }
- if (ns_type != NS_TYPE_CONSENSUS) {
- digest256map_t *ed_id_map = digest256map_new();
- SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, vote_routerstatus_t *,
- vrs) {
- if (! vrs->has_ed25519_listing ||
- tor_mem_is_zero((const char *)vrs->ed25519_id, DIGEST256_LEN))
- continue;
- if (digest256map_get(ed_id_map, vrs->ed25519_id) != NULL) {
- log_warn(LD_DIR, "Vote networkstatus ed25519 identities were not "
- "unique");
- digest256map_free(ed_id_map, NULL);
- goto err;
- }
- digest256map_set(ed_id_map, vrs->ed25519_id, (void*)1);
- } SMARTLIST_FOREACH_END(vrs);
- digest256map_free(ed_id_map, NULL);
- }
- /* Parse footer; check signature. */
- footer_tokens = smartlist_new();
- if ((end_of_footer = strstr(s, "\nnetwork-status-version ")))
- ++end_of_footer;
- else
- end_of_footer = s + strlen(s);
- if (tokenize_string(area,s, end_of_footer, footer_tokens,
- networkstatus_vote_footer_token_table, 0)) {
- log_warn(LD_DIR, "Error tokenizing network-status vote footer.");
- goto err;
- }
- {
- int found_sig = 0;
- SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
- tok = _tok;
- if (tok->tp == K_DIRECTORY_SIGNATURE)
- found_sig = 1;
- else if (found_sig) {
- log_warn(LD_DIR, "Extraneous token after first directory-signature");
- goto err;
- }
- } SMARTLIST_FOREACH_END(_tok);
- }
- if ((tok = find_opt_by_keyword(footer_tokens, K_DIRECTORY_FOOTER))) {
- if (tok != smartlist_get(footer_tokens, 0)) {
- log_warn(LD_DIR, "Misplaced directory-footer token");
- goto err;
- }
- }
- tok = find_opt_by_keyword(footer_tokens, K_BW_WEIGHTS);
- if (tok) {
- ns->weight_params = smartlist_new();
- for (i = 0; i < tok->n_args; ++i) {
- int ok=0;
- char *eq = strchr(tok->args[i], '=');
- if (!eq) {
- log_warn(LD_DIR, "Bad element '%s' in weight params",
- escaped(tok->args[i]));
- goto err;
- }
- tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
- if (!ok) {
- log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
- goto err;
- }
- smartlist_add_strdup(ns->weight_params, tok->args[i]);
- }
- }
- SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
- char declared_identity[DIGEST_LEN];
- networkstatus_voter_info_t *v;
- document_signature_t *sig;
- const char *id_hexdigest = NULL;
- const char *sk_hexdigest = NULL;
- digest_algorithm_t alg = DIGEST_SHA1;
- tok = _tok;
- if (tok->tp != K_DIRECTORY_SIGNATURE)
- continue;
- tor_assert(tok->n_args >= 2);
- if (tok->n_args == 2) {
- id_hexdigest = tok->args[0];
- sk_hexdigest = tok->args[1];
- } else {
- const char *algname = tok->args[0];
- int a;
- id_hexdigest = tok->args[1];
- sk_hexdigest = tok->args[2];
- a = crypto_digest_algorithm_parse_name(algname);
- if (a<0) {
- log_warn(LD_DIR, "Unknown digest algorithm %s; skipping",
- escaped(algname));
- continue;
- }
- alg = a;
- }
- if (!tok->object_type ||
- strcmp(tok->object_type, "SIGNATURE") ||
- tok->object_size < 128 || tok->object_size > 512) {
- log_warn(LD_DIR, "Bad object type or length on directory-signature");
- goto err;
- }
- if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
- base16_decode(declared_identity, sizeof(declared_identity),
- id_hexdigest, HEX_DIGEST_LEN)
- != sizeof(declared_identity)) {
- log_warn(LD_DIR, "Error decoding declared identity %s in "
- "network-status document.", escaped(id_hexdigest));
- goto err;
- }
- if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {
- log_warn(LD_DIR, "ID on signature on network-status document does "
- "not match any declared directory source.");
- goto err;
- }
- sig = tor_malloc_zero(sizeof(document_signature_t));
- memcpy(sig->identity_digest, v->identity_digest, DIGEST_LEN);
- sig->alg = alg;
- if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
- base16_decode(sig->signing_key_digest, sizeof(sig->signing_key_digest),
- sk_hexdigest, HEX_DIGEST_LEN)
- != sizeof(sig->signing_key_digest)) {
- log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
- "network-status document.", escaped(sk_hexdigest));
- tor_free(sig);
- goto err;
- }
- if (ns->type != NS_TYPE_CONSENSUS) {
- if (tor_memneq(declared_identity, ns->cert->cache_info.identity_digest,
- DIGEST_LEN)) {
- log_warn(LD_DIR, "Digest mismatch between declared and actual on "
- "network-status vote.");
- tor_free(sig);
- goto err;
- }
- }
- if (networkstatus_get_voter_sig_by_alg(v, sig->alg)) {
- /* We already parsed a vote with this algorithm from this voter. Use the
- first one. */
- log_fn(LOG_PROTOCOL_WARN, LD_DIR, "We received a networkstatus "
- "that contains two signatures from the same voter with the same "
- "algorithm. Ignoring the second signature.");
- tor_free(sig);
- continue;
- }
- if (ns->type != NS_TYPE_CONSENSUS) {
- if (check_signature_token(ns_digests.d[DIGEST_SHA1], DIGEST_LEN,
- tok, ns->cert->signing_key, 0,
- "network-status document")) {
- tor_free(sig);
- goto err;
- }
- sig->good_signature = 1;
- } else {
- if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
- tor_free(sig);
- goto err;
- }
- sig->signature = tor_memdup(tok->object_body, tok->object_size);
- sig->signature_len = (int) tok->object_size;
- }
- smartlist_add(v->sigs, sig);
- ++n_signatures;
- } SMARTLIST_FOREACH_END(_tok);
- if (! n_signatures) {
- log_warn(LD_DIR, "No signatures on networkstatus document.");
- goto err;
- } else if (ns->type == NS_TYPE_VOTE && n_signatures != 1) {
- log_warn(LD_DIR, "Received more than one signature on a "
- "network-status vote.");
- goto err;
- }
- if (eos_out)
- *eos_out = end_of_footer;
- goto done;
- err:
- dump_desc(s_dup, "v3 networkstatus");
- networkstatus_vote_free(ns);
- ns = NULL;
- done:
- if (tokens) {
- SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
- smartlist_free(tokens);
- }
- if (voter) {
- if (voter->sigs) {
- SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
- document_signature_free(sig));
- smartlist_free(voter->sigs);
- }
- tor_free(voter->nickname);
- tor_free(voter->address);
- tor_free(voter->contact);
- tor_free(voter);
- }
- if (rs_tokens) {
- SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_clear(t));
- smartlist_free(rs_tokens);
- }
- if (footer_tokens) {
- SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_clear(t));
- smartlist_free(footer_tokens);
- }
- if (area) {
- DUMP_AREA(area, "v3 networkstatus");
- memarea_drop_all(area);
- }
- if (rs_area)
- memarea_drop_all(rs_area);
- tor_free(last_kwd);
- return ns;
- }
- /** Parse the addr policy in the string <b>s</b> and return it. If
- * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
- * ADDR_POLICY_REJECT) for items that specify no action.
- *
- * Returns NULL on policy errors.
- *
- * Set *<b>malformed_list</b> to true if the entire policy list should be
- * discarded. Otherwise, set it to false, and only this item should be ignored
- * on error - the rest of the policy list can continue to be processed and
- * used.
- *
- * The addr_policy_t returned by this function can have its address set to
- * AF_UNSPEC for '*'. Use policy_expand_unspec() to turn this into a pair
- * of AF_INET and AF_INET6 items.
- */
- MOCK_IMPL(addr_policy_t *,
- router_parse_addr_policy_item_from_string,(const char *s, int assume_action,
- int *malformed_list))
- {
- directory_token_t *tok = NULL;
- const char *cp, *eos;
- /* Longest possible policy is
- * "accept6 [ffff:ffff:..255]/128:10000-65535",
- * which contains a max-length IPv6 address, plus 26 characters.
- * But note that there can be an arbitrary amount of space between the
- * accept and the address:mask/port element.
- * We don't need to multiply TOR_ADDR_BUF_LEN by 2, as there is only one
- * IPv6 address. But making the buffer shorter might cause valid long lines,
- * which parsed in previous versions, to fail to parse in new versions.
- * (These lines would have to have excessive amounts of whitespace.) */
- char line[TOR_ADDR_BUF_LEN*2 + 32];
- addr_policy_t *r;
- memarea_t *area = NULL;
- tor_assert(malformed_list);
- *malformed_list = 0;
- s = eat_whitespace(s);
- /* We can only do assume_action on []-quoted IPv6, as "a" (accept)
- * and ":" (port separator) are ambiguous */
- if ((*s == '*' || *s == '[' || TOR_ISDIGIT(*s)) && assume_action >= 0) {
- if (tor_snprintf(line, sizeof(line), "%s %s",
- assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", s)<0) {
- log_warn(LD_DIR, "Policy %s is too long.", escaped(s));
- return NULL;
- }
- cp = line;
- tor_strlower(line);
- } else { /* assume an already well-formed address policy line */
- cp = s;
- }
- eos = cp + strlen(cp);
- area = memarea_new();
- tok = get_next_token(area, &cp, eos, routerdesc_token_table);
- if (tok->tp == ERR_) {
- log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
- goto err;
- }
- if (tok->tp != K_ACCEPT && tok->tp != K_ACCEPT6 &&
- tok->tp != K_REJECT && tok->tp != K_REJECT6) {
- log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
- goto err;
- }
- /* Use the extended interpretation of accept/reject *,
- * expanding it into an IPv4 wildcard and an IPv6 wildcard.
- * Also permit *4 and *6 for IPv4 and IPv6 only wildcards. */
- r = router_parse_addr_policy(tok, TAPMP_EXTENDED_STAR);
- if (!r) {
- goto err;
- }
- /* Ensure that accept6/reject6 fields are followed by IPv6 addresses.
- * AF_UNSPEC addresses are only permitted on the accept/reject field type.
- * Unlike descriptors, torrcs exit policy accept/reject can be followed by
- * either an IPv4 or IPv6 address. */
- if ((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
- tor_addr_family(&r->addr) != AF_INET6) {
- /* This is a non-fatal error, just ignore this one entry. */
- *malformed_list = 0;
- log_warn(LD_DIR, "IPv4 address '%s' with accept6/reject6 field type in "
- "exit policy. Ignoring, but continuing to parse rules. (Use "
- "accept/reject with IPv4 addresses.)",
- tok->n_args == 1 ? tok->args[0] : "");
- addr_policy_free(r);
- r = NULL;
- goto done;
- }
- goto done;
- err:
- *malformed_list = 1;
- r = NULL;
- done:
- token_clear(tok);
- if (area) {
- DUMP_AREA(area, "policy item");
- memarea_drop_all(area);
- }
- return r;
- }
- /** Add an exit policy stored in the token <b>tok</b> to the router info in
- * <b>router</b>. Return 0 on success, -1 on failure. */
- static int
- router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
- {
- addr_policy_t *newe;
- /* Use the standard interpretation of accept/reject *, an IPv4 wildcard. */
- newe = router_parse_addr_policy(tok, 0);
- if (!newe)
- return -1;
- if (! router->exit_policy)
- router->exit_policy = smartlist_new();
- /* Ensure that in descriptors, accept/reject fields are followed by
- * IPv4 addresses, and accept6/reject6 fields are followed by
- * IPv6 addresses. Unlike torrcs, descriptor exit policies do not permit
- * accept/reject followed by IPv6. */
- if (((tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) &&
- tor_addr_family(&newe->addr) == AF_INET)
- ||
- ((tok->tp == K_ACCEPT || tok->tp == K_REJECT) &&
- tor_addr_family(&newe->addr) == AF_INET6)) {
- /* There's nothing the user can do about other relays' descriptors,
- * so we don't provide usage advice here. */
- log_warn(LD_DIR, "Mismatch between field type and address type in exit "
- "policy '%s'. Discarding entire router descriptor.",
- tok->n_args == 1 ? tok->args[0] : "");
- addr_policy_free(newe);
- return -1;
- }
- smartlist_add(router->exit_policy, newe);
- return 0;
- }
- /** Given a K_ACCEPT[6] or K_REJECT[6] token and a router, create and return
- * a new exit_policy_t corresponding to the token. If TAPMP_EXTENDED_STAR
- * is set in fmt_flags, K_ACCEPT6 and K_REJECT6 tokens followed by *
- * expand to IPv6-only policies, otherwise they expand to IPv4 and IPv6
- * policies */
- static addr_policy_t *
- router_parse_addr_policy(directory_token_t *tok, unsigned fmt_flags)
- {
- addr_policy_t newe;
- char *arg;
- tor_assert(tok->tp == K_REJECT || tok->tp == K_REJECT6 ||
- tok->tp == K_ACCEPT || tok->tp == K_ACCEPT6);
- if (tok->n_args != 1)
- return NULL;
- arg = tok->args[0];
- if (!strcmpstart(arg,"private"))
- return router_parse_addr_policy_private(tok);
- memset(&newe, 0, sizeof(newe));
- if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
- newe.policy_type = ADDR_POLICY_REJECT;
- else
- newe.policy_type = ADDR_POLICY_ACCEPT;
- /* accept6/reject6 * produces an IPv6 wildcard address only.
- * (accept/reject * produces rules for IPv4 and IPv6 wildcard addresses.) */
- if ((fmt_flags & TAPMP_EXTENDED_STAR)
- && (tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6)) {
- fmt_flags |= TAPMP_STAR_IPV6_ONLY;
- }
- if (tor_addr_parse_mask_ports(arg, fmt_flags, &newe.addr, &newe.maskbits,
- &newe.prt_min, &newe.prt_max) < 0) {
- log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
- return NULL;
- }
- return addr_policy_get_canonical_entry(&newe);
- }
- /** Parse an exit policy line of the format "accept[6]/reject[6] private:...".
- * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
- * router descriptors until earlier versions are obsolete.
- *
- * accept/reject and accept6/reject6 private all produce rules for both
- * IPv4 and IPv6 addresses.
- */
- static addr_policy_t *
- router_parse_addr_policy_private(directory_token_t *tok)
- {
- const char *arg;
- uint16_t port_min, port_max;
- addr_policy_t result;
- arg = tok->args[0];
- if (strcmpstart(arg, "private"))
- return NULL;
- arg += strlen("private");
- arg = (char*) eat_whitespace(arg);
- if (!arg || *arg != ':')
- return NULL;
- if (parse_port_range(arg+1, &port_min, &port_max)<0)
- return NULL;
- memset(&result, 0, sizeof(result));
- if (tok->tp == K_REJECT || tok->tp == K_REJECT6)
- result.policy_type = ADDR_POLICY_REJECT;
- else
- result.policy_type = ADDR_POLICY_ACCEPT;
- result.is_private = 1;
- result.prt_min = port_min;
- result.prt_max = port_max;
- if (tok->tp == K_ACCEPT6 || tok->tp == K_REJECT6) {
- log_warn(LD_GENERAL,
- "'%s' expands into rules which apply to all private IPv4 and "
- "IPv6 addresses. (Use accept/reject private:* for IPv4 and "
- "IPv6.)", tok->n_args == 1 ? tok->args[0] : "");
- }
- return addr_policy_get_canonical_entry(&result);
- }
- /** Return a newly allocated smartlist of all accept or reject tokens in
- * <b>s</b>.
- */
- static smartlist_t *
- find_all_exitpolicy(smartlist_t *s)
- {
- smartlist_t *out = smartlist_new();
- SMARTLIST_FOREACH(s, directory_token_t *, t,
- if (t->tp == K_ACCEPT || t->tp == K_ACCEPT6 ||
- t->tp == K_REJECT || t->tp == K_REJECT6)
- smartlist_add(out,t));
- return out;
- }
- /** Called on startup; right now we just handle scanning the unparseable
- * descriptor dumps, but hang anything else we might need to do in the
- * future here as well.
- */
- void
- routerparse_init(void)
- {
- /*
- * Check both if the sandbox is active and whether it's configured; no
- * point in loading all that if we won't be able to use it after the
- * sandbox becomes active.
- */
- if (!(sandbox_is_active() || get_options()->Sandbox)) {
- dump_desc_init();
- }
- }
- /** Clean up all data structures used by routerparse.c at exit */
- void
- routerparse_free_all(void)
- {
- dump_desc_fifo_cleanup();
- }
|