123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285 |
- #include <cerrno>
- #include <chrono>
- #include <cinttypes>
- #include <condition_variable>
- #include <cstdint>
- #include <cstdio>
- #include <cstdlib>
- #include <mutex>
- #include <set>
- #include <vector>
- #include <dirent.h>
- #include <fcntl.h>
- #include <ifaddrs.h>
- #include <linux/if.h>
- #include <linux/if_tun.h>
- #include <net/if.h>
- #include <netdb.h>
- #include <netinet/in.h>
- #include <openssl/base64.h>
- #include <sys/socket.h>
- #include <sys/types.h>
- #include <android-base/file.h>
- #include <android-base/macros.h>
- #include <android-base/stringprintf.h>
- #include <android-base/strings.h>
- #include <binder/IPCThreadState.h>
- #include <bpf/BpfMap.h>
- #include <bpf/BpfUtils.h>
- #include <com/android/internal/net/BnOemNetdUnsolicitedEventListener.h>
- #include <com/android/internal/net/IOemNetd.h>
- #include <cutils/multiuser.h>
- #include <gtest/gtest.h>
- #include <logwrap/logwrap.h>
- #include <netdbpf/bpf_shared.h>
- #include <netutils/ifc.h>
- #include "Fwmark.h"
- #include "InterfaceController.h"
- #include "NetdClient.h"
- #include "NetdConstants.h"
- #include "TestUnsolService.h"
- #include "XfrmController.h"
- #include "android/net/INetd.h"
- #include "binder/IServiceManager.h"
- #include "netdutils/Stopwatch.h"
- #include "netdutils/Syscalls.h"
- #include "netid_client.h"
- #include "tun_interface.h"
- #define IP_PATH "/system/bin/ip"
- #define IP6TABLES_PATH "/system/bin/ip6tables"
- #define IPTABLES_PATH "/system/bin/iptables"
- #define TUN_DEV "/dev/tun"
- #define RAW_TABLE "raw"
- #define MANGLE_TABLE "mangle"
- #define FILTER_TABLE "filter"
- #define NAT_TABLE "nat"
- namespace binder = android::binder;
- using android::IBinder;
- using android::IServiceManager;
- using android::sp;
- using android::String16;
- using android::String8;
- using android::base::Join;
- using android::base::ReadFileToString;
- using android::base::StartsWith;
- using android::base::StringPrintf;
- using android::base::Trim;
- using android::net::INetd;
- using android::net::InterfaceConfigurationParcel;
- using android::net::InterfaceController;
- using android::net::TetherStatsParcel;
- using android::net::TunInterface;
- using android::net::UidRangeParcel;
- using android::netdutils::sSyscalls;
- using android::netdutils::Stopwatch;
- static const char* IP_RULE_V4 = "-4";
- static const char* IP_RULE_V6 = "-6";
- static const int TEST_NETID1 = 65501;
- static const int TEST_NETID2 = 65502;
- static const int TEST_UID1 = 99999;
- static const int TEST_UID2 = 99998;
- constexpr int BASE_UID = AID_USER_OFFSET * 5;
- static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
- static const std::string ESP_ALLOW_RULE("esp");
- class BinderTest : public ::testing::Test {
- public:
- BinderTest() {
- sp<IServiceManager> sm = android::defaultServiceManager();
- sp<IBinder> binder = sm->getService(String16("netd"));
- if (binder != nullptr) {
- mNetd = android::interface_cast<INetd>(binder);
- }
- }
- void SetUp() override {
- ASSERT_NE(nullptr, mNetd.get());
- }
- void TearDown() override {
- mNetd->networkDestroy(TEST_NETID1);
- mNetd->networkDestroy(TEST_NETID2);
- setNetworkForProcess(NETID_UNSET);
-
- if (mStoredDefaultNetwork >= 0) mNetd->networkSetDefault(mStoredDefaultNetwork);
- }
- bool allocateIpSecResources(bool expectOk, int32_t* spi);
-
- static void SetUpTestCase() {
- ASSERT_EQ(0, sTun.init());
- ASSERT_EQ(0, sTun2.init());
- ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
- ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
- }
- static void TearDownTestCase() {
-
- sTun.destroy();
- sTun2.destroy();
- }
- static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
- void createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId = TEST_NETID2,
- int fallthroughNetId = TEST_NETID1);
- protected:
-
-
- int mStoredDefaultNetwork = -1;
- sp<INetd> mNetd;
- static TunInterface sTun;
- static TunInterface sTun2;
- };
- TunInterface BinderTest::sTun;
- TunInterface BinderTest::sTun2;
- class TimedOperation : public Stopwatch {
- public:
- explicit TimedOperation(const std::string &name): mName(name) {}
- virtual ~TimedOperation() {
- fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
- }
- private:
- std::string mName;
- };
- TEST_F(BinderTest, IsAlive) {
- TimedOperation t("isAlive RPC");
- bool isAlive = false;
- mNetd->isAlive(&isAlive);
- ASSERT_TRUE(isAlive);
- }
- static int randomUid() {
- return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
- }
- static std::vector<std::string> runCommand(const std::string& command) {
- std::vector<std::string> lines;
- FILE *f = popen(command.c_str(), "r");
- if (f == nullptr) {
- perror("popen");
- return lines;
- }
- char *line = nullptr;
- size_t bufsize = 0;
- ssize_t linelen = 0;
- while ((linelen = getline(&line, &bufsize, f)) >= 0) {
- lines.push_back(std::string(line, linelen));
- free(line);
- line = nullptr;
- }
- pclose(f);
- return lines;
- }
- static std::vector<std::string> listIpRules(const char *ipVersion) {
- std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
- return runCommand(command);
- }
- static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
- std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
- return runCommand(command);
- }
- static int iptablesRuleLineLength(const char *binary, const char *chainName) {
- return listIptablesRule(binary, chainName).size();
- }
- static bool iptablesRuleExists(const char *binary,
- const char *chainName,
- const std::string& expectedRule) {
- std::vector<std::string> rules = listIptablesRule(binary, chainName);
- for (const auto& rule : rules) {
- if(rule.find(expectedRule) != std::string::npos) {
- return true;
- }
- }
- return false;
- }
- static bool iptablesNoSocketAllowRuleExists(const char *chainName){
- return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
- iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
- }
- static bool iptablesEspAllowRuleExists(const char *chainName){
- return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
- iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
- }
- TEST_F(BinderTest, FirewallReplaceUidChain) {
- SKIP_IF_BPF_SUPPORTED;
- std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
- const int kNumUids = 500;
- std::vector<int32_t> noUids(0);
- std::vector<int32_t> uids(kNumUids);
- for (int i = 0; i < kNumUids; i++) {
- uids[i] = randomUid();
- }
- bool ret;
- {
- TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
- mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
- }
- EXPECT_EQ(true, ret);
- EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
- EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
- EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
- EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
- {
- TimedOperation op("Clearing whitelist chain");
- mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
- }
- EXPECT_EQ(true, ret);
- EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
- EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
- {
- TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
- mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
- }
- EXPECT_EQ(true, ret);
- EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
- EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
- EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
- EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
- {
- TimedOperation op("Clearing blacklist chain");
- mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
- }
- EXPECT_EQ(true, ret);
- EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
- EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
-
- std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
- mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
- EXPECT_EQ(false, ret);
- }
- TEST_F(BinderTest, IpSecTunnelInterface) {
- const struct TestData {
- const std::string family;
- const std::string deviceName;
- const std::string localAddress;
- const std::string remoteAddress;
- int32_t iKey;
- int32_t oKey;
- int32_t ifId;
- } kTestData[] = {
- {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE},
- {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50,
- 0xFFFE},
- };
- for (size_t i = 0; i < std::size(kTestData); i++) {
- const auto& td = kTestData[i];
- binder::Status status;
-
- status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
- td.iKey, td.oKey, td.ifId);
- EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
-
- EXPECT_NE(0U, if_nametoindex(td.deviceName.c_str()));
-
- status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
- td.iKey, td.oKey, td.ifId);
- EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
-
- status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
- EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
-
- EXPECT_EQ(0U, if_nametoindex(td.deviceName.c_str()));
- }
- }
- TEST_F(BinderTest, IpSecSetEncapSocketOwner) {
- android::base::unique_fd uniqueFd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
- android::os::ParcelFileDescriptor sockFd(std::move(uniqueFd));
- int sockOptVal = UDP_ENCAP_ESPINUDP;
- setsockopt(sockFd.get(), IPPROTO_UDP, UDP_ENCAP, &sockOptVal, sizeof(sockOptVal));
- binder::Status res = mNetd->ipSecSetEncapSocketOwner(sockFd, 1001);
- EXPECT_TRUE(res.isOk());
- struct stat info;
- EXPECT_EQ(0, fstat(sockFd.get(), &info));
- EXPECT_EQ(1001, (int) info.st_uid);
- }
- #if INTPTR_MAX != INT32_MAX
- using android::net::XfrmController;
- static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
- static_cast<int>(android::net::XfrmDirection::OUT)};
- static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
- #define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
- do { if ((_expect_) != (_ret_)) return false; } while(false)
- bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
- android::netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
- SCOPED_TRACE(status);
- RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
-
- status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0, 0);
- SCOPED_TRACE(status);
- RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
-
- return expectOk == XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D,
- 0xD00D, 0xE00D, false)
- .ok();
- }
- TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
- android::binder::Status status;
-
- for (int i = 0; i < 2; i++) {
- for (int direction : XFRM_DIRECTIONS) {
- for (int addrFamily : ADDRESS_FAMILIES) {
- status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
- "127.0.0.6", 123, 0, 0, 0);
- EXPECT_TRUE(status.isOk())
- << " family: " << addrFamily << " direction: " << direction;
- }
- }
-
- for (int direction : XFRM_DIRECTIONS) {
- for (int addrFamily : ADDRESS_FAMILIES) {
- status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
- EXPECT_TRUE(status.isOk());
- }
- }
- }
- }
- TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
- binder::Status status;
-
- for (int i = 0; i < 2; i++) {
- for (int direction : XFRM_DIRECTIONS) {
- for (int addrFamily : ADDRESS_FAMILIES) {
- status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
- "2001:db8::d00d", 123, 0, 0, 0);
- EXPECT_TRUE(status.isOk())
- << " family: " << addrFamily << " direction: " << direction;
- }
- }
-
- for (int direction : XFRM_DIRECTIONS) {
- for (int addrFamily : ADDRESS_FAMILIES) {
- status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
- EXPECT_TRUE(status.isOk());
- }
- }
- }
- }
- TEST_F(BinderTest, XfrmControllerInit) {
- android::netdutils::Status status;
- status = XfrmController::Init();
- SCOPED_TRACE(status);
-
-
- if (status.code() == EOPNOTSUPP) return;
- ASSERT_TRUE(status.ok());
- int32_t spi = 0;
- ASSERT_TRUE(allocateIpSecResources(true, &spi));
- ASSERT_TRUE(allocateIpSecResources(false, &spi));
- status = XfrmController::Init();
- ASSERT_TRUE(status.ok());
- ASSERT_TRUE(allocateIpSecResources(true, &spi));
-
- status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0, 0);
- SCOPED_TRACE(status);
- ASSERT_TRUE(status.ok());
- status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0, 0);
- SCOPED_TRACE(status);
- ASSERT_TRUE(status.ok());
-
- ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok());
- }
- #endif
- static int bandwidthDataSaverEnabled(const char *binary) {
- std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
-
-
-
-
-
-
-
-
-
-
-
-
- EXPECT_GE(lines.size(), 3U);
- if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
-
- return 0;
- }
- size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
- if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
-
- return 1;
- }
- return -1;
- }
- bool enableDataSaver(sp<INetd>& netd, bool enable) {
- TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
- bool ret;
- netd->bandwidthEnableDataSaver(enable, &ret);
- return ret;
- }
- int getDataSaverState() {
- const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
- const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
- EXPECT_EQ(enabled4, enabled6);
- EXPECT_NE(-1, enabled4);
- EXPECT_NE(-1, enabled6);
- if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
- return -1;
- }
- return enabled6;
- }
- TEST_F(BinderTest, BandwidthEnableDataSaver) {
- const int wasEnabled = getDataSaverState();
- ASSERT_NE(-1, wasEnabled);
- if (wasEnabled) {
- ASSERT_TRUE(enableDataSaver(mNetd, false));
- EXPECT_EQ(0, getDataSaverState());
- }
- ASSERT_TRUE(enableDataSaver(mNetd, false));
- EXPECT_EQ(0, getDataSaverState());
- ASSERT_TRUE(enableDataSaver(mNetd, true));
- EXPECT_EQ(1, getDataSaverState());
- ASSERT_TRUE(enableDataSaver(mNetd, true));
- EXPECT_EQ(1, getDataSaverState());
- if (!wasEnabled) {
- ASSERT_TRUE(enableDataSaver(mNetd, false));
- EXPECT_EQ(0, getDataSaverState());
- }
- }
- static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
- const std::string& action, const char* ipVersion) {
-
-
- std::vector<std::string> rules = listIpRules(ipVersion);
- std::string prefix = StringPrintf("%" PRIu32 ":", priority);
- std::string suffix =
- StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
- for (const auto& line : rules) {
- if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
- return true;
- }
- }
- return false;
- }
- static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
- const std::string& action) {
- bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
- bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
- EXPECT_EQ(existsIp4, existsIp6);
- return existsIp4;
- }
- namespace {
- UidRangeParcel makeUidRangeParcel(int start, int stop) {
- UidRangeParcel res;
- res.start = start;
- res.stop = stop;
- return res;
- }
- }
- TEST_F(BinderTest, NetworkInterfaces) {
- EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
- EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
- .serviceSpecificErrorCode());
- EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
- EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, true).isOk());
- EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
- EXPECT_EQ(EBUSY,
- mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
- EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
- EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
- EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
- EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
- }
- TEST_F(BinderTest, NetworkUidRules) {
- const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
- EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, true).isOk());
- EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
- EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
- std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
- makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
- UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
- std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
- EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
- EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
- EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
- EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
- EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
- EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
- EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
- EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
- EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
- EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
- }
- TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
- constexpr uint32_t RULE_PRIORITY = 12500;
- std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
- makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
- const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
- const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
-
- ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
- EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
- EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
- for (auto const& range : uidRanges) {
- EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
- }
-
- ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
- EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
- EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
- for (auto const& range : uidRanges) {
- EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
- }
-
- binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
- ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
- EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
-
- EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
- EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
- }
- void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
- *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
- struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
- ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
- socklen_t addrlen = sizeof(server6);
- ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
- ASSERT_EQ(0, listen(*serverSocket, 10));
- *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
- struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
- ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
- ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
- ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
- *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
- ASSERT_NE(-1, *acceptedSocket);
- ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
- }
- void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
- char buf[4096];
- EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
- EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
- EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
- }
- void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
-
- int ret = write(clientSocket, "foo", sizeof("foo"));
- int err = errno;
- EXPECT_EQ(-1, ret);
- EXPECT_EQ(ECONNABORTED, err);
-
- ret = write(acceptedSocket, "foo", sizeof("foo"));
- err = errno;
- EXPECT_EQ(-1, ret);
- EXPECT_EQ(ECONNRESET, err);
- }
- TEST_F(BinderTest, SocketDestroy) {
- int clientSocket, serverSocket, acceptedSocket;
- ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
-
- constexpr int baseUid = AID_APP - 2000;
- static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
- int uid = baseUid + 500 + arc4random_uniform(1000);
- EXPECT_EQ(0, fchown(clientSocket, uid, -1));
-
- std::vector<UidRangeParcel> uidRanges = {
- makeUidRangeParcel(baseUid + 42, baseUid + 449),
- makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
- makeUidRangeParcel(baseUid + 498, uid - 1),
- makeUidRangeParcel(uid + 1, baseUid + 1520),
- };
-
- std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
-
- EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
- checkSocketpairOpen(clientSocket, acceptedSocket);
-
- uidRanges = {
- makeUidRangeParcel(baseUid + 42, baseUid + 449),
- makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
- makeUidRangeParcel(baseUid + 498, baseUid + 1520),
- };
-
- skipUids.push_back(uid);
-
- EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
- checkSocketpairOpen(clientSocket, acceptedSocket);
-
- skipUids.resize(skipUids.size() - 1);
- EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
- checkSocketpairClosed(clientSocket, acceptedSocket);
- close(clientSocket);
- close(serverSocket);
- close(acceptedSocket);
- }
- namespace {
- int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
- if (buf == nullptr) return -1;
- int prefixLength = 0;
- bool endOfContiguousBits = false;
- for (unsigned int i = 0; i < buflen; i++) {
- const uint8_t value = buf[i];
-
-
-
- const uint8_t inverse = ~value + 1;
- if ((inverse & (inverse - 1)) != 0) return -1;
- prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
-
- if (endOfContiguousBits && value != 0) return -1;
- if (value != 0xff) endOfContiguousBits = true;
- }
- return prefixLength;
- }
- template<typename T>
- int netmaskToPrefixLength(const T *p) {
- return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
- }
- static bool interfaceHasAddress(
- const std::string &ifname, const char *addrString, int prefixLength) {
- struct addrinfo *addrinfoList = nullptr;
- const struct addrinfo hints = {
- .ai_flags = AI_NUMERICHOST,
- .ai_family = AF_UNSPEC,
- .ai_socktype = SOCK_DGRAM,
- };
- if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
- addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
- return false;
- }
- ScopedAddrinfo addrinfoCleanup(addrinfoList);
- struct ifaddrs *ifaddrsList = nullptr;
- ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
- if (getifaddrs(&ifaddrsList) != 0) {
- return false;
- }
- for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
- if (std::string(addr->ifa_name) != ifname ||
- addr->ifa_addr == nullptr ||
- addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
- continue;
- }
- switch (addr->ifa_addr->sa_family) {
- case AF_INET: {
- auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
- auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
- if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
- continue;
- }
- if (prefixLength < 0) return true;
- if (addr->ifa_netmask == nullptr) return false;
- auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
- EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
- return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
- }
- case AF_INET6: {
- auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
- auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
- if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
- continue;
- }
- if (prefixLength < 0) return true;
- if (addr->ifa_netmask == nullptr) return false;
- auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
- EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
- return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
- }
- default:
-
-
- continue;
- }
- }
- return false;
- }
- }
- TEST_F(BinderTest, InterfaceAddRemoveAddress) {
- static const struct TestData {
- const char *addrString;
- const int prefixLength;
- const bool expectSuccess;
- } kTestData[] = {
- { "192.0.2.1", 24, true },
- { "192.0.2.2", 25, true },
- { "192.0.2.3", 32, true },
- { "192.0.2.4", 33, false },
- { "192.not.an.ip", 24, false },
- { "2001:db8::1", 64, true },
- { "2001:db8::2", 65, true },
- { "2001:db8::3", 128, true },
- { "2001:db8::4", 129, false },
- { "foo:bar::bad", 64, false },
- };
- for (size_t i = 0; i < std::size(kTestData); i++) {
- const auto &td = kTestData[i];
-
- binder::Status status = mNetd->interfaceAddAddress(
- sTun.name(), td.addrString, td.prefixLength);
- if (td.expectSuccess) {
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- } else {
- ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
- ASSERT_NE(0, status.serviceSpecificErrorCode());
- }
-
- if (td.expectSuccess) {
- EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
- } else {
- EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
- }
-
- status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
- if (td.expectSuccess) {
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- } else {
- ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
- ASSERT_NE(0, status.serviceSpecificErrorCode());
- }
-
- EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
- }
- }
- TEST_F(BinderTest, GetProcSysNet) {
- const char LOOPBACK[] = "lo";
- static const struct {
- const int ipversion;
- const int which;
- const char* ifname;
- const char* parameter;
- const char* expectedValue;
- const int expectedReturnCode;
- } kTestData[] = {
- {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
- {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
- {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
- {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
- {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
- {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
- {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
- };
- for (size_t i = 0; i < std::size(kTestData); i++) {
- const auto& td = kTestData[i];
- std::string value;
- const binder::Status status =
- mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
- if (td.expectedReturnCode == 0) {
- SCOPED_TRACE(String8::format("test case %zu should have passed", i));
- EXPECT_EQ(0, status.exceptionCode());
- EXPECT_EQ(0, status.serviceSpecificErrorCode());
- EXPECT_EQ(td.expectedValue, value);
- } else {
- SCOPED_TRACE(String8::format("test case %zu should have failed", i));
- EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
- EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
- }
- }
- }
- TEST_F(BinderTest, SetProcSysNet) {
- static const struct {
- const int ipversion;
- const int which;
- const char* ifname;
- const char* parameter;
- const char* value;
- const int expectedReturnCode;
- } kTestData[] = {
- {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
- {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
- {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
- {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
- {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
- {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
- {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
- };
- for (size_t i = 0; i < std::size(kTestData); i++) {
- const auto& td = kTestData[i];
- const binder::Status status =
- mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
- if (td.expectedReturnCode == 0) {
- SCOPED_TRACE(String8::format("test case %zu should have passed", i));
- EXPECT_EQ(0, status.exceptionCode());
- EXPECT_EQ(0, status.serviceSpecificErrorCode());
- } else {
- SCOPED_TRACE(String8::format("test case %zu should have failed", i));
- EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
- EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
- }
- }
- }
- TEST_F(BinderTest, GetSetProcSysNet) {
- const int ipversion = INetd::IPV6;
- const int category = INetd::NEIGH;
- const std::string& tun = sTun.name();
- const std::string parameter("ucast_solicit");
- std::string value{};
- EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
- ASSERT_FALSE(value.empty());
- const int ival = std::stoi(value);
- EXPECT_GT(ival, 0);
-
- EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
- .isOk());
- EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
- EXPECT_EQ(2 * ival, std::stoi(value));
-
- EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
- .isOk());
- EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
- EXPECT_EQ(ival, std::stoi(value));
- }
- namespace {
- void expectNoTestCounterRules() {
- for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
- std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
- std::string allRules = Join(runCommand(command), "\n");
- EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
- }
- }
- void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
- int byte, int pkt) {
- runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
- path, if1.c_str(), if2.c_str(), pkt, byte));
- }
- void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
- runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
- path, if1.c_str(), if2.c_str()));
- runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
- path, if2.c_str(), if1.c_str()));
- }
- std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
- const std::string& iface) {
- for (auto& stats : statsVec) {
- if (stats.iface == iface) {
- return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
- }
- }
- return {};
- }
- }
- TEST_F(BinderTest, TetherGetStats) {
- expectNoTestCounterRules();
-
-
-
- runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
- runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
- std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
- std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
- std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
- std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
- std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
- addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
- addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
- addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
- addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
-
-
- std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
- addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
- addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
- addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
- addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
- addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
- addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
- std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
- std::vector<TetherStatsParcel> statsVec;
- binder::Status status = mNetd->tetherGetStats(&statsVec);
- EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
- EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
- EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
- for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
- delTetherCounterValues(path, intIface1, extIface1);
- delTetherCounterValues(path, intIface2, extIface2);
- if (path == IP6TABLES_PATH) {
- delTetherCounterValues(path, intIface3, extIface2);
- }
- }
- expectNoTestCounterRules();
- }
- namespace {
- constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
- constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
- static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
- const char* chainName) {
- std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
- return runCommand(command);
- }
- bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
- const std::string& expectedInterface,
- const std::string& expectedRule, const char* table) {
- std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
- for (const auto& rule : rules) {
- if (rule.find(expectedInterface) != std::string::npos) {
- if (rule.find(expectedRule) != std::string::npos) {
- return true;
- }
- }
- }
- return false;
- }
- void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
- const std::string& classLabel) {
- std::string IdletimerRule =
- StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
- for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
- EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
- IdletimerRule, RAW_TABLE));
- EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
- ifname, IdletimerRule, MANGLE_TABLE));
- }
- }
- void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
- const std::string& classLabel) {
- std::string IdletimerRule =
- StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
- for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
- EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
- IdletimerRule, RAW_TABLE));
- EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
- ifname, IdletimerRule, MANGLE_TABLE));
- }
- }
- }
- TEST_F(BinderTest, IdletimerAddRemoveInterface) {
-
-
-
-
- binder::Status status;
- const struct TestData {
- const std::string ifname;
- int32_t timeout;
- const std::string classLabel;
- } idleTestData[] = {
- {"wlan0", 1234, "happyday"},
- {"rmnet_data0", 4567, "friday"},
- };
- for (const auto& td : idleTestData) {
- status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
- status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
- }
- }
- namespace {
- constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
- constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
- void expectStrictSetUidAccept(const int uid) {
- std::string uidRule = StringPrintf("owner UID match %u", uid);
- std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
- for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
- EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
- EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
- EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
- }
- }
- void expectStrictSetUidLog(const int uid) {
- static const char logRule[] = "st_penalty_log all";
- std::string uidRule = StringPrintf("owner UID match %u", uid);
- std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
- for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
- EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
- EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
- EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
- }
- }
- void expectStrictSetUidReject(const int uid) {
- static const char rejectRule[] = "st_penalty_reject all";
- std::string uidRule = StringPrintf("owner UID match %u", uid);
- std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
- for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
- EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
- EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
- EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
- }
- }
- }
- TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
- binder::Status status;
- int32_t uid = randomUid();
-
- status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectStrictSetUidLog(uid);
-
- status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
- expectStrictSetUidAccept(uid);
-
- status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectStrictSetUidReject(uid);
-
- status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
- expectStrictSetUidAccept(uid);
-
- int32_t wrongPolicy = -123;
- status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
- EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
- }
- namespace {
- std::vector<std::string> tryToFindProcesses(const std::string& processName, uint32_t maxTries = 1,
- uint32_t intervalMs = 50) {
-
-
-
-
-
-
- if (maxTries == 0) return {};
- std::string cmd = StringPrintf("ps -Af | grep '[0-9] %s'", processName.c_str());
- std::vector<std::string> result;
- for (uint32_t run = 1;;) {
- result = runCommand(cmd);
- if (result.size() || ++run > maxTries) {
- break;
- }
- usleep(intervalMs * 1000);
- }
- return result;
- }
- void expectProcessExists(const std::string& processName) {
- EXPECT_EQ(1U, tryToFindProcesses(processName, 5 ).size());
- }
- void expectProcessDoesNotExist(const std::string& processName) {
- EXPECT_FALSE(tryToFindProcesses(processName).size());
- }
- }
- TEST_F(BinderTest, ClatdStartStop) {
- binder::Status status;
- const std::string clatdName = StringPrintf("clatd-%s", sTun.name().c_str());
- std::string clatAddress;
- std::string nat64Prefix = "2001:db8:cafe:f00d:1:2::/96";
-
- status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
- EXPECT_FALSE(status.isOk());
- EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
-
- EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
- EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
-
- status = mNetd->clatdStart(sTun.name(), "2001:db8:cafe:f00d::/64", &clatAddress);
- EXPECT_FALSE(status.isOk());
- EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
-
- status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
- EXPECT_FALSE(status.isOk());
- EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
-
- EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
-
- status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
- EXPECT_FALSE(status.isOk());
- EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
-
- const std::string v6 = "2001:db8:1:2:f076:ae99:124e:aa99";
- EXPECT_EQ(0, sTun.addAddress(v6.c_str(), 64));
-
- status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
- EXPECT_TRUE(status.isOk());
- EXPECT_EQ(0, status.serviceSpecificErrorCode());
-
- status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
- EXPECT_FALSE(status.isOk());
- EXPECT_EQ(EBUSY, status.serviceSpecificErrorCode());
- expectProcessExists(clatdName);
-
- status = mNetd->clatdStop(sTun.name());
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectProcessDoesNotExist(clatdName);
-
- status = mNetd->clatdStop(sTun.name());
- EXPECT_FALSE(status.isOk());
- EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
- expectProcessDoesNotExist(clatdName);
-
- EXPECT_TRUE(mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
- EXPECT_EQ(0, ifc_del_address(sTun.name().c_str(), v6.c_str(), 64));
- EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
- }
- namespace {
- bool getIpfwdV4Enable() {
- static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
- std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
- EXPECT_TRUE(!result.empty());
- int v4Enable = std::stoi(result[0]);
- return v4Enable;
- }
- bool getIpfwdV6Enable() {
- static const char ipv6IpfwdCmd[] = "cat /proc/sys/net/ipv6/conf/all/forwarding";
- std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
- EXPECT_TRUE(!result.empty());
- int v6Enable = std::stoi(result[0]);
- return v6Enable;
- }
- void expectIpfwdEnable(bool enable) {
- int enableIPv4 = getIpfwdV4Enable();
- int enableIPv6 = getIpfwdV6Enable();
- EXPECT_EQ(enable, enableIPv4);
- EXPECT_EQ(enable, enableIPv6);
- }
- bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
- std::vector<std::string> rules = listIpRules(ipVersion);
- for (const auto& rule : rules) {
- if (rule.find(ipfwdRule) != std::string::npos) {
- return true;
- }
- }
- return false;
- }
- void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
- std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
- for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
- EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
- }
- }
- void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
- std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
- for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
- EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
- }
- }
- }
- TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
-
- std::vector<std::string> requesterList;
- binder::Status status = mNetd->ipfwdGetRequesterList(&requesterList);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- bool ipfwdEnabled;
- if (requesterList.size() == 0) {
-
-
- status = mNetd->ipfwdEnableForwarding("TestRequester");
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectIpfwdEnable(true);
- status = mNetd->ipfwdEnabled(&ipfwdEnabled);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- EXPECT_TRUE(ipfwdEnabled);
-
- status = mNetd->ipfwdDisableForwarding("TestRequester");
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectIpfwdEnable(false);
- status = mNetd->ipfwdEnabled(&ipfwdEnabled);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- EXPECT_FALSE(ipfwdEnabled);
- } else {
-
- for (const auto& requester : requesterList) {
- status = mNetd->ipfwdDisableForwarding(requester);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- }
-
- expectIpfwdEnable(false);
- status = mNetd->ipfwdEnabled(&ipfwdEnabled);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- EXPECT_FALSE(ipfwdEnabled);
-
- for (const auto& requester : requesterList) {
- status = mNetd->ipfwdEnableForwarding(requester);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- }
-
- expectIpfwdEnable(true);
- status = mNetd->ipfwdEnabled(&ipfwdEnabled);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- EXPECT_TRUE(ipfwdEnabled);
- }
- }
- TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
-
- EXPECT_TRUE(
- mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
- EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
- EXPECT_TRUE(
- mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
- EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
- binder::Status status =
- mNetd->ipfwdAddInterfaceForward(sTun.name(), sTun2.name());
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectIpfwdRuleExists(sTun.name().c_str(), sTun2.name().c_str());
- status = mNetd->ipfwdRemoveInterfaceForward(sTun.name(), sTun2.name());
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectIpfwdRuleNotExists(sTun.name().c_str(), sTun2.name().c_str());
- }
- namespace {
- constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
- constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
- constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
- constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
- constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
- constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
- bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
- const char* chainName, const std::string& expectedTargetA,
- const std::string& expectedTargetB) {
- std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
- int matchCount = 0;
- for (const auto& rule : rules) {
- if (rule.find(expectedTargetA) != std::string::npos) {
- if (rule.find(expectedTargetB) != std::string::npos) {
- matchCount++;
- }
- }
- }
- return matchCount == expectedCount;
- }
- void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
- std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
- std::string result = "";
- EXPECT_TRUE(ReadFileToString(path, &result));
-
- EXPECT_GE(quotaBytes, std::stol(Trim(result)));
- }
- void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
- std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
- std::string quotaRule = StringPrintf("quota %s", ifname);
- for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
- EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
- BANDWIDTH_COSTLY_IF));
- EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
- BANDWIDTH_COSTLY_IF));
- EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
- BANDWIDTH_COSTLY_IF));
- EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
- EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
- }
- expectXtQuotaValueEqual(ifname, quotaBytes);
- }
- void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
- std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
- std::string quotaRule = StringPrintf("quota %s", ifname);
- for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
- EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
- BANDWIDTH_COSTLY_IF));
- EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
- BANDWIDTH_COSTLY_IF));
- EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
- BANDWIDTH_COSTLY_IF));
- EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
- EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
- }
- }
- void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
- std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
- std::string alertRule = StringPrintf("quota %sAlert", ifname);
- std::string alertName = StringPrintf("%sAlert", ifname);
- for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
- EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
- }
- expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
- }
- void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
- std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
- std::string alertRule = StringPrintf("quota %sAlert", ifname);
- for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
- EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
- }
- }
- void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
- static const char globalAlertRule[] = "quota globalAlert";
- static const char globalAlertName[] = "globalAlert";
- for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
- EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
- }
- expectXtQuotaValueEqual(globalAlertName, alertBytes);
- }
- void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
- std::string uidRule = StringPrintf("owner UID match %u", uid);
- for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
- EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
- }
- }
- void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
- std::string uidRule = StringPrintf("owner UID match %u", uid);
- for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
- EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
- }
- }
- }
- TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
- long testQuotaBytes = 5550;
-
- EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
- EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
- binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
- status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
-
- EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
- }
- TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
- long testAlertBytes = 373;
-
- EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
- EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
-
- binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
- status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
- status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
-
- status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
-
- EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
- }
- TEST_F(BinderTest, BandwidthSetGlobalAlert) {
- long testAlertBytes = 2097149;
- binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectBandwidthGlobalAlertRuleExists(testAlertBytes);
- testAlertBytes = 2097152;
- status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectBandwidthGlobalAlertRuleExists(testAlertBytes);
- }
- TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
- SKIP_IF_BPF_SUPPORTED;
- int32_t uid = randomUid();
- static const char targetReject[] = "REJECT";
- static const char targetReturn[] = "RETURN";
-
- binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
-
- status = mNetd->bandwidthRemoveNaughtyApp(uid);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
-
- status = mNetd->bandwidthAddNiceApp(uid);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
-
- status = mNetd->bandwidthRemoveNiceApp(uid);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
- }
- namespace {
- std::vector<std::string> listIpRoutes(const char* ipVersion, const char* table) {
- std::string command = StringPrintf("%s %s route ls table %s", IP_PATH, ipVersion, table);
- return runCommand(command);
- }
- bool ipRouteExists(const char* ipVersion, const char* table, const std::string& ipRoute) {
- std::vector<std::string> routes = listIpRoutes(ipVersion, table);
- for (const auto& route : routes) {
- if (route.find(ipRoute) != std::string::npos) {
- return true;
- }
- }
- return false;
- }
- std::string ipRouteString(const std::string& ifName, const std::string& dst,
- const std::string& nextHop) {
- std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
- if (!nextHop.empty()) {
- dstString += " via " + nextHop;
- }
- return dstString + " dev " + ifName;
- }
- void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
- const std::string& dst, const std::string& nextHop,
- const char* table) {
- EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
- }
- void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
- const std::string& dst, const std::string& nextHop,
- const char* table) {
- EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
- }
- bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
- std::vector<std::string> rules = listIpRules(ipVersion);
- for (const auto& rule : rules) {
- if (rule.find(ipRule) != std::string::npos) {
- return true;
- }
- }
- return false;
- }
- void expectNetworkDefaultIpRuleExists(const char* ifName) {
- std::string networkDefaultRule =
- StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
- for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
- EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
- }
- }
- void expectNetworkDefaultIpRuleDoesNotExist() {
- static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
- for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
- EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
- }
- }
- void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
- std::string networkPermissionRule = "";
- switch (permission) {
- case INetd::PERMISSION_NONE:
- networkPermissionRule = StringPrintf(
- "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
- break;
- case INetd::PERMISSION_NETWORK:
- networkPermissionRule = StringPrintf(
- "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
- break;
- case INetd::PERMISSION_SYSTEM:
- networkPermissionRule = StringPrintf(
- "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
- break;
- }
- for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
- EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
- }
- }
- bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
- const std::string& expectedInterface,
- const std::string& expectedRule,
- const char* table) {
- std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
- for (const auto& rule : rules) {
- if (rule.find(expectedInterface) != std::string::npos) {
- if (rule.find(expectedRule) != std::string::npos) {
- return true;
- }
- }
- }
- return false;
- }
- void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
- static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
- std::string networkIncomingPacketMarkRule = "";
- switch (permission) {
- case INetd::PERMISSION_NONE:
- networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
- break;
- case INetd::PERMISSION_NETWORK:
- networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
- break;
- case INetd::PERMISSION_SYSTEM:
- networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
- break;
- }
- for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
- EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
- binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
- }
- }
- }
- TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
- static const struct {
- const char* ipVersion;
- const char* testDest;
- const char* testNextHop;
- const bool expectSuccess;
- } kTestData[] = {
- {IP_RULE_V4, "0.0.0.0/0", "", true},
- {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
- {IP_RULE_V4, "10.251.0.0/16", "", true},
- {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
- {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
- {IP_RULE_V6, "::/0", "", true},
- {IP_RULE_V6, "::/0", "2001:db8::", true},
- {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
- {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
- };
- static const struct {
- const char* ipVersion;
- const char* testDest;
- const char* testNextHop;
- } kTestDataWithNextHop[] = {
- {IP_RULE_V4, "10.251.10.0/30", ""},
- {IP_RULE_V6, "2001:db8::/32", ""},
- };
- static const char testTableLegacySystem[] = "legacy_system";
- static const char testTableLegacyNetwork[] = "legacy_network";
- const int testUid = randomUid();
- const std::vector<int32_t> testUids = {testUid};
-
- EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
- EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
-
- for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
- const auto& td = kTestDataWithNextHop[i];
-
- binder::Status status =
- mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
- sTun.name().c_str());
-
- EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
- status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
- testUid);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
- testTableLegacySystem);
-
- EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
- status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
- testUid);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
- testTableLegacyNetwork);
- }
- for (size_t i = 0; i < std::size(kTestData); i++) {
- const auto& td = kTestData[i];
- binder::Status status =
- mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
- if (td.expectSuccess) {
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
- sTun.name().c_str());
- } else {
- EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
- EXPECT_NE(0, status.serviceSpecificErrorCode());
- }
- status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
- if (td.expectSuccess) {
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
- sTun.name().c_str());
- } else {
- EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
- EXPECT_NE(0, status.serviceSpecificErrorCode());
- }
-
- EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
- status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
- testUid);
- if (td.expectSuccess) {
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
- testTableLegacySystem);
- } else {
- EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
- EXPECT_NE(0, status.serviceSpecificErrorCode());
- }
- status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
- td.testNextHop, testUid);
- if (td.expectSuccess) {
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
- testTableLegacySystem);
- } else {
- EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
- EXPECT_NE(0, status.serviceSpecificErrorCode());
- }
-
- EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
- status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
- testUid);
- if (td.expectSuccess) {
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
- testTableLegacyNetwork);
- } else {
- EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
- EXPECT_NE(0, status.serviceSpecificErrorCode());
- }
- status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
- td.testNextHop, testUid);
- if (td.expectSuccess) {
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
- testTableLegacyNetwork);
- } else {
- EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
- EXPECT_NE(0, status.serviceSpecificErrorCode());
- }
- }
-
- EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
- }
- TEST_F(BinderTest, NetworkPermissionDefault) {
-
- EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
- EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
-
- binder::Status status = mNetd->networkGetDefault(&mStoredDefaultNetwork);
- ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
-
- status = mNetd->networkSetDefault(TEST_NETID1);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectNetworkDefaultIpRuleExists(sTun.name().c_str());
- status = mNetd->networkClearDefault();
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectNetworkDefaultIpRuleDoesNotExist();
-
- status = mNetd->networkSetDefault(mStoredDefaultNetwork);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
-
- status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
- expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
- status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
- expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
-
- EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
- }
- TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
- const int testUid = randomUid();
- binder::Status status = mNetd->networkSetProtectAllow(testUid);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- bool ret = false;
- status = mNetd->networkCanProtect(testUid, &ret);
- EXPECT_TRUE(ret);
- status = mNetd->networkSetProtectDeny(testUid);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- status = mNetd->networkCanProtect(testUid, &ret);
- EXPECT_FALSE(ret);
- }
- namespace {
- int readIntFromPath(const std::string& path) {
- std::string result = "";
- EXPECT_TRUE(ReadFileToString(path, &result));
- return std::stoi(result);
- }
- int getTetherAcceptIPv6Ra(const std::string& ifName) {
- std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
- return readIntFromPath(path);
- }
- bool getTetherAcceptIPv6Dad(const std::string& ifName) {
- std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
- return readIntFromPath(path);
- }
- int getTetherIPv6DadTransmits(const std::string& ifName) {
- std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
- return readIntFromPath(path);
- }
- bool getTetherEnableIPv6(const std::string& ifName) {
- std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
- int disableIPv6 = readIntFromPath(path);
- return !disableIPv6;
- }
- bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
- for (const auto& iface : ifList) {
- if (iface == ifName) {
- return true;
- }
- }
- return false;
- }
- void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
- EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
- EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
- EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
- EXPECT_TRUE(getTetherEnableIPv6(ifName));
- }
- void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
- EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
- EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
- EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
- EXPECT_FALSE(getTetherEnableIPv6(ifName));
- }
- void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
- const std::string& ifName) {
- EXPECT_TRUE(interfaceListContains(ifList, ifName));
- }
- void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
- const std::string& ifName) {
- EXPECT_FALSE(interfaceListContains(ifList, ifName));
- }
- void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
- const std::vector<std::string>& testDnsAddrs) {
- EXPECT_TRUE(dnsList == testDnsAddrs);
- }
- }
- TEST_F(BinderTest, TetherStartStopStatus) {
- std::vector<std::string> noDhcpRange = {};
- static const char dnsdName[] = "dnsmasq";
- binder::Status status = mNetd->tetherStart(noDhcpRange);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectProcessExists(dnsdName);
- bool tetherEnabled;
- status = mNetd->tetherIsEnabled(&tetherEnabled);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- EXPECT_TRUE(tetherEnabled);
- status = mNetd->tetherStop();
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectProcessDoesNotExist(dnsdName);
- status = mNetd->tetherIsEnabled(&tetherEnabled);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- EXPECT_FALSE(tetherEnabled);
- }
- TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
-
- binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectTetherInterfaceConfigureForIPv6Router(sTun.name());
- std::vector<std::string> ifList;
- status = mNetd->tetherInterfaceList(&ifList);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectTetherInterfaceExists(ifList, sTun.name());
- status = mNetd->tetherInterfaceRemove(sTun.name());
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectTetherInterfaceConfigureForIPv6Client(sTun.name());
- status = mNetd->tetherInterfaceList(&ifList);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectTetherInterfaceNotExists(ifList, sTun.name());
- }
- TEST_F(BinderTest, TetherDnsSetList) {
-
- std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3",
- "fe80::1%" + sTun.name()};
- binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- std::vector<std::string> dnsList;
- status = mNetd->tetherDnsList(&dnsList);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectTetherDnsListEquals(dnsList, testDnsAddrs);
- }
- namespace {
- constexpr char FIREWALL_INPUT[] = "fw_INPUT";
- constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
- constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
- constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
- constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
- constexpr char FIREWALL_STANDBY[] = "fw_standby";
- constexpr char targetReturn[] = "RETURN";
- constexpr char targetDrop[] = "DROP";
- void expectFirewallWhitelistMode() {
- static const char dropRule[] = "DROP all";
- static const char rejectRule[] = "REJECT all";
- for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
- EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
- EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
- EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
- }
- }
- void expectFirewallBlacklistMode() {
- for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
- EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
- EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
- EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
- }
- }
- bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
- const std::string& expectedInterface,
- const std::string& expectedRule) {
- std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
-
-
-
-
-
- int firstRuleIndex = 2;
- if (rules.size() < 4) return false;
- if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
- if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
- return true;
- }
- }
- return false;
- }
- bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
- const std::string& expectedInterface,
- const std::string& expectedRule) {
- std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
- for (const auto& rule : rules) {
- if (rule.find(expectedInterface) != std::string::npos) {
- if (rule.find(expectedRule) != std::string::npos) {
- return true;
- }
- }
- }
- return false;
- }
- void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
- static const char returnRule[] = "RETURN all";
- for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
- EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
- returnRule));
- EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
- returnRule));
- }
- }
- void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
- static const char returnRule[] = "RETURN all";
- for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
- EXPECT_FALSE(
- iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
- EXPECT_FALSE(
- iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
- }
- }
- bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
- const std::string& expectedTarget,
- const std::string& expectedRule) {
- std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
- int firstRuleIndex = 2;
- if (rules.size() < 4) return false;
- if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
- if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
- return true;
- }
- }
- return false;
- }
- bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
- const std::string& expectedTarget,
- const std::string& expectedRule) {
- std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
- int lastRuleIndex = rules.size() - 1;
- if (lastRuleIndex < 0) return false;
- if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
- if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
- return true;
- }
- }
- return false;
- }
- void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
- std::string uidRule = StringPrintf("owner UID match %u", uid);
- for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
- EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
- }
- void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
- std::string uidRule = StringPrintf("owner UID match %u", uid);
- for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
- EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
- }
- void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
- std::string uidRule = StringPrintf("owner UID match %u", uid);
- for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
- EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
- }
- void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
- std::string uidRule = StringPrintf("owner UID match %u", uid);
- for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
- EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
- }
- bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
- std::vector<std::string> inputRules =
- listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
- std::vector<std::string> outputRules =
- listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
- int inputLastRuleIndex = inputRules.size() - 1;
- int outputLastRuleIndex = outputRules.size() - 1;
- if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
- if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
- if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
- return true;
- }
- }
- return false;
- }
- void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
- for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
- EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
- }
- void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
- for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
- EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
- EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
- }
- }
- }
- TEST_F(BinderTest, FirewallSetFirewallType) {
- binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallWhitelistMode();
- status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallBlacklistMode();
-
- mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
- status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallBlacklistMode();
-
- mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
- status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallWhitelistMode();
-
- status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallBlacklistMode();
- }
- TEST_F(BinderTest, FirewallSetInterfaceRule) {
-
- binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
- EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
-
- status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallInterfaceRuleAllowExists(sTun.name());
- status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
-
- status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallBlacklistMode();
- }
- TEST_F(BinderTest, FirewallSetUidRule) {
- SKIP_IF_BPF_SUPPORTED;
- int32_t uid = randomUid();
-
- binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
- INetd::FIREWALL_RULE_ALLOW);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
-
- status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
- INetd::FIREWALL_RULE_DENY);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
-
- status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
- INetd::FIREWALL_RULE_ALLOW);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
-
- status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
- INetd::FIREWALL_RULE_DENY);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
-
- status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
- INetd::FIREWALL_RULE_DENY);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
-
- status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
- INetd::FIREWALL_RULE_ALLOW);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
-
- status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
- expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
-
- status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
- expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
-
- status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallWhitelistMode();
-
- status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
- expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
-
- status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
- expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
-
- status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallBlacklistMode();
- }
- TEST_F(BinderTest, FirewallEnableDisableChildChains) {
- SKIP_IF_BPF_SUPPORTED;
- binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
- status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
- status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
- status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
- status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
- status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
- }
- namespace {
- std::string hwAddrToStr(unsigned char* hwaddr) {
- return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
- hwaddr[4], hwaddr[5]);
- }
- int ipv4NetmaskToPrefixLength(in_addr_t mask) {
- int prefixLength = 0;
- uint32_t m = ntohl(mask);
- while (m & (1 << 31)) {
- prefixLength++;
- m = m << 1;
- }
- return prefixLength;
- }
- std::string toStdString(const String16& s) {
- return std::string(String8(s.string()));
- }
- android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
- const auto& sys = sSyscalls.get();
- auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
- EXPECT_TRUE(isOk(fd.status()));
- struct ifreq ifr = {};
- strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
- return sys.ioctl(fd.value(), flag, &ifr);
- }
- std::string getInterfaceHwAddr(const std::string& ifName) {
- auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
- unsigned char hwaddr[ETH_ALEN] = {};
- if (isOk(res.status())) {
- memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
- }
- return hwAddrToStr(hwaddr);
- }
- int getInterfaceIPv4Prefix(const std::string& ifName) {
- auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
- int prefixLength = 0;
- if (isOk(res.status())) {
- prefixLength = ipv4NetmaskToPrefixLength(
- ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
- }
- return prefixLength;
- }
- std::string getInterfaceIPv4Addr(const std::string& ifName) {
- auto res = ioctlByIfName(ifName, SIOCGIFADDR);
- struct in_addr addr = {};
- if (isOk(res.status())) {
- addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
- }
- return std::string(inet_ntoa(addr));
- }
- std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
- auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
- unsigned flags = 0;
- if (isOk(res.status())) {
- flags = res.value().ifr_flags;
- }
- std::vector<std::string> ifFlags;
- ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
- : toStdString(INetd::IF_STATE_DOWN()));
- if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
- if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
- if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
- if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
- if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
- return ifFlags;
- }
- bool compareListInterface(const std::vector<std::string>& interfaceList) {
- const auto& res = InterfaceController::getIfaceNames();
- EXPECT_TRUE(isOk(res));
- std::vector<std::string> resIfList;
- resIfList.reserve(res.value().size());
- resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
- return resIfList == interfaceList;
- }
- int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
- std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
- return readIntFromPath(path);
- }
- bool getInterfaceEnableIPv6(const std::string& ifName) {
- std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
- int disableIPv6 = readIntFromPath(path);
- return !disableIPv6;
- }
- int getInterfaceMtu(const std::string& ifName) {
- std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
- return readIntFromPath(path);
- }
- void expectInterfaceList(const std::vector<std::string>& interfaceList) {
- EXPECT_TRUE(compareListInterface(interfaceList));
- }
- void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
- const InterfaceConfigurationParcel& interfaceCfg) {
- EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
- EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
- EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
- EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
- }
- void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
- EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
- EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
- const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
- for (const auto& flag : setCfg.flags) {
- EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
- }
- }
- void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
- int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
- EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
- }
- void expectInterfaceNoAddr(const std::string& ifName) {
-
- EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
-
- EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
- }
- void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
- int enableIPv6 = getInterfaceEnableIPv6(ifName);
- EXPECT_EQ(enableIPv6, enable);
- }
- void expectInterfaceMtu(const std::string& ifName, const int mtu) {
- int mtuSize = getInterfaceMtu(ifName);
- EXPECT_EQ(mtu, mtuSize);
- }
- InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
- const std::string& addr, int prefixLength,
- const std::vector<std::string>& flags) {
- InterfaceConfigurationParcel cfg;
- cfg.ifName = ifName;
- cfg.hwAddr = "";
- cfg.ipv4Addr = addr;
- cfg.prefixLength = prefixLength;
- cfg.flags = flags;
- return cfg;
- }
- void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
- std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
- std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
- for (const auto& flag : expectedFlags) {
- EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
- interfaceCfg.flags.end());
- }
- for (const auto& flag : unexpectedFlags) {
- EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
- interfaceCfg.flags.end());
- }
- }
- }
- TEST_F(BinderTest, InterfaceList) {
- std::vector<std::string> interfaceListResult;
- binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectInterfaceList(interfaceListResult);
- }
- TEST_F(BinderTest, InterfaceGetCfg) {
- InterfaceConfigurationParcel interfaceCfgResult;
-
- EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
- EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
- binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
- expectTunFlags(interfaceCfgResult);
-
- EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
- }
- TEST_F(BinderTest, InterfaceSetCfg) {
- const std::string testAddr = "192.0.2.3";
- const int testPrefixLength = 24;
- std::vector<std::string> upFlags = {"up"};
- std::vector<std::string> downFlags = {"down"};
-
- EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
- EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
-
- auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
- binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
-
- interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
- status = mNetd->interfaceSetCfg(interfaceCfg);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- status = mNetd->interfaceClearAddrs(sTun.name());
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
-
- EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
- }
- TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
-
- binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
-
- status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
- }
- TEST_F(BinderTest, InterfaceClearAddr) {
- const std::string testAddr = "192.0.2.3";
- const int testPrefixLength = 24;
- std::vector<std::string> noFlags{};
-
- EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
- EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
- auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
- binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
- status = mNetd->interfaceClearAddrs(sTun.name());
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectInterfaceNoAddr(sTun.name());
-
- EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
- }
- TEST_F(BinderTest, InterfaceSetEnableIPv6) {
-
- EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
- EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
-
- binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectInterfaceEnableIPv6(sTun.name(), false);
-
- status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectInterfaceEnableIPv6(sTun.name(), true);
-
- EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
- }
- TEST_F(BinderTest, InterfaceSetMtu) {
- const int testMtu = 1200;
-
- EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
- EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
- binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectInterfaceMtu(sTun.name(), testMtu);
-
- EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
- }
- namespace {
- constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
- constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
- constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
- constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
- int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
- return listIptablesRuleByTable(binary, table, chainName).size();
- }
- bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
- const std::vector<std::string>& targetVec) {
- std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
- if (targetVec.size() != rules.size() - 2) {
- return false;
- }
-
- int rIndex = 2;
- for (const auto& target : targetVec) {
- if (rules[rIndex].find(target) == std::string::npos) {
- return false;
- }
- rIndex++;
- }
- return true;
- }
- void expectNatEnable(const std::string& intIf, const std::string& extIf) {
- std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
- std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
- std::vector<std::string> forwardV4Match = {
- "bw_global_alert", "state RELATED", "state INVALID",
- StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
- "DROP"};
-
- EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
- postroutingV4Match));
- EXPECT_TRUE(
- iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
- EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
- std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
- std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
-
- EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
- EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
- preroutingV6Match));
- for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
- EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
- extIf));
- }
- }
- void expectNatDisable() {
-
-
-
-
- std::vector<std::string> forwardV4Match = {"DROP"};
- EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
-
- EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
- EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
- EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
- EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
-
- }
- }
- TEST_F(BinderTest, TetherForwardAddRemove) {
- binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectNatEnable(sTun.name(), sTun2.name());
- status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectNatDisable();
- }
- namespace {
- using TripleInt = std::array<int, 3>;
- TripleInt readProcFileToTripleInt(const std::string& path) {
- std::string valueString;
- int min, def, max;
- EXPECT_TRUE(ReadFileToString(path, &valueString));
- EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
- return {min, def, max};
- }
- void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
- std::string testRmemValues =
- StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
- std::string testWmemValues =
- StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
- EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
- TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
- TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
- for (int i = 0; i < 3; i++) {
- SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
- EXPECT_EQ(rmemValues[i], newRmemValues[i]);
- EXPECT_EQ(wmemValues[i], newWmemValues[i]);
- }
- }
- }
- TEST_F(BinderTest, TcpBufferSet) {
- TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
- TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
- TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
- TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
- updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
- updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
- }
- namespace {
- void checkUidsInPermissionMap(std::vector<int32_t>& uids, bool exist) {
- android::bpf::BpfMap<uint32_t, uint8_t> uidPermissionMap(
- android::bpf::mapRetrieve(UID_PERMISSION_MAP_PATH, 0));
- for (int32_t uid : uids) {
- android::netdutils::StatusOr<uint8_t> permission = uidPermissionMap.readValue(uid);
- if (exist) {
- EXPECT_TRUE(isOk(permission));
- EXPECT_EQ(INetd::PERMISSION_NONE, permission.value());
- } else {
- EXPECT_FALSE(isOk(permission));
- EXPECT_EQ(ENOENT, permission.status().code());
- }
- }
- }
- }
- TEST_F(BinderTest, TestInternetPermission) {
- SKIP_IF_BPF_NOT_SUPPORTED;
- std::vector<int32_t> appUids = {TEST_UID1, TEST_UID2};
- mNetd->trafficSetNetPermForUids(INetd::PERMISSION_INTERNET, appUids);
- checkUidsInPermissionMap(appUids, false);
- mNetd->trafficSetNetPermForUids(INetd::PERMISSION_NONE, appUids);
- checkUidsInPermissionMap(appUids, true);
- mNetd->trafficSetNetPermForUids(INetd::PERMISSION_UNINSTALLED, appUids);
- checkUidsInPermissionMap(appUids, false);
- }
- TEST_F(BinderTest, UnsolEvents) {
- auto testUnsolService = android::net::TestUnsolService::start();
- std::string oldTunName = sTun.name();
- std::string newTunName = "unsolTest";
- testUnsolService->tarVec.push_back(oldTunName);
- testUnsolService->tarVec.push_back(newTunName);
- auto& cv = testUnsolService->getCv();
- auto& cvMutex = testUnsolService->getCvMutex();
- binder::Status status = mNetd->registerUnsolicitedEventListener(
- android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
-
-
-
- {
- std::unique_lock lock(cvMutex);
-
-
- sTun.destroy();
-
- sTun.init(newTunName);
- EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
- }
-
-
- const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
- InterfaceLinkStatusChanged | RouteChanged;
- EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
-
- sTun.destroy();
- sTun.init();
- }
- TEST_F(BinderTest, NDC) {
- struct Command {
- const std::string cmdString;
- const std::string expectedResult;
- };
-
-
- const Command networkCmds[] = {
- {StringPrintf("ndc network create %d", TEST_NETID1),
- "200 0 success"},
- {StringPrintf("ndc network interface add %d %s", TEST_NETID1, sTun.name().c_str()),
- "200 0 success"},
- {StringPrintf("ndc network interface remove %d %s", TEST_NETID1, sTun.name().c_str()),
- "200 0 success"},
- {StringPrintf("ndc network interface add %d %s", TEST_NETID2, sTun.name().c_str()),
- "400 0 addInterfaceToNetwork() failed (Machine is not on the network)"},
- {StringPrintf("ndc network destroy %d", TEST_NETID1),
- "200 0 success"},
- };
- const std::vector<Command> ipfwdCmds = {
- {"ndc ipfwd enable " + sTun.name(),
- "200 0 ipfwd operation succeeded"},
- {"ndc ipfwd disable " + sTun.name(),
- "200 0 ipfwd operation succeeded"},
- {"ndc ipfwd add lo2 lo3",
- "400 0 ipfwd operation failed (No such process)"},
- {"ndc ipfwd add " + sTun.name() + " " + sTun2.name(),
- "200 0 ipfwd operation succeeded"},
- {"ndc ipfwd remove " + sTun.name() + " " + sTun2.name(),
- "200 0 ipfwd operation succeeded"},
- };
- static const struct {
- const char* ipVersion;
- const char* testDest;
- const char* testNextHop;
- const bool expectSuccess;
- const std::string expectedResult;
- } kTestData[] = {
- {IP_RULE_V4, "0.0.0.0/0", "", true,
- "200 0 success"},
- {IP_RULE_V4, "10.251.0.0/16", "", true,
- "200 0 success"},
- {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false,
- "400 0 addRoute() failed (Invalid argument)",},
- {IP_RULE_V6, "::/0", "", true,
- "200 0 success"},
- {IP_RULE_V6, "2001:db8:cafe::/64", "", true,
- "200 0 success"},
- {IP_RULE_V6, "fe80::/64", "0.0.0.0", false,
- "400 0 addRoute() failed (Invalid argument)"},
- };
-
- for (const auto& cmd : networkCmds) {
- const std::vector<std::string> result = runCommand(cmd.cmdString);
- SCOPED_TRACE(cmd.cmdString);
- EXPECT_EQ(result.size(), 1U);
- EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
- }
- for (const auto& cmd : ipfwdCmds) {
- const std::vector<std::string> result = runCommand(cmd.cmdString);
- SCOPED_TRACE(cmd.cmdString);
- EXPECT_EQ(result.size(), 1U);
- EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
- }
-
- EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
- EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
- for (const auto& td : kTestData) {
- const std::string routeAddCmd =
- StringPrintf("ndc network route add %d %s %s %s", TEST_NETID1, sTun.name().c_str(),
- td.testDest, td.testNextHop);
- const std::string routeRemoveCmd =
- StringPrintf("ndc network route remove %d %s %s %s", TEST_NETID1,
- sTun.name().c_str(), td.testDest, td.testNextHop);
- std::vector<std::string> result = runCommand(routeAddCmd);
- SCOPED_TRACE(routeAddCmd);
- EXPECT_EQ(result.size(), 1U);
- EXPECT_EQ(td.expectedResult, Trim(result[0]));
- if (td.expectSuccess) {
- expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
- sTun.name().c_str());
- result = runCommand(routeRemoveCmd);
- EXPECT_EQ(result.size(), 1U);
- EXPECT_EQ(td.expectedResult, Trim(result[0]));
- expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
- sTun.name().c_str());
- }
- }
-
- EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
- }
- TEST_F(BinderTest, OemNetdRelated) {
- sp<IBinder> binder;
- binder::Status status = mNetd->getOemNetd(&binder);
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- sp<com::android::internal::net::IOemNetd> oemNetd;
- if (binder != nullptr) {
- oemNetd = android::interface_cast<com::android::internal::net::IOemNetd>(binder);
- }
- ASSERT_NE(nullptr, oemNetd.get());
- TimedOperation t("OemNetd isAlive RPC");
- bool isAlive = false;
- oemNetd->isAlive(&isAlive);
- ASSERT_TRUE(isAlive);
- class TestOemUnsolListener
- : public com::android::internal::net::BnOemNetdUnsolicitedEventListener {
- public:
- android::binder::Status onRegistered() override {
- std::lock_guard lock(mCvMutex);
- mCv.notify_one();
- return android::binder::Status::ok();
- }
- std::condition_variable& getCv() { return mCv; }
- std::mutex& getCvMutex() { return mCvMutex; }
- private:
- std::mutex mCvMutex;
- std::condition_variable mCv;
- };
-
- android::ProcessState::self()->startThreadPool();
- android::sp<TestOemUnsolListener> testListener = new TestOemUnsolListener();
- auto& cv = testListener->getCv();
- auto& cvMutex = testListener->getCvMutex();
- {
- std::unique_lock lock(cvMutex);
- status = oemNetd->registerOemUnsolicitedEventListener(
- ::android::interface_cast<
- com::android::internal::net::IOemNetdUnsolicitedEventListener>(
- testListener));
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
-
- EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
- }
- }
- void BinderTest::createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId,
- int fallthroughNetId) {
-
- sTun.destroy();
- sTun.init();
- sTun2.destroy();
- sTun2.init();
-
- EXPECT_TRUE(mNetd->networkCreatePhysical(fallthroughNetId, INetd::PERMISSION_NONE).isOk());
- EXPECT_TRUE(mNetd->networkAddInterface(fallthroughNetId, sTun.name()).isOk());
-
- EXPECT_TRUE(mNetd->networkCreateVpn(vpnNetId, secure).isOk());
-
- EXPECT_TRUE(mNetd->networkAddUidRanges(vpnNetId, {makeUidRangeParcel(uid, uid)}).isOk());
- EXPECT_TRUE(mNetd->networkAddInterface(vpnNetId, sTun2.name()).isOk());
-
- EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
-
- EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID2, sTun2.name(), "2001:db8::/32", "").isOk());
- }
- namespace {
- class ScopedUidChange {
- public:
- explicit ScopedUidChange(uid_t uid) : mInputUid(uid) {
- mStoredUid = getuid();
- if (mInputUid == mStoredUid) return;
- EXPECT_TRUE(seteuid(uid) == 0);
- }
- ~ScopedUidChange() {
- if (mInputUid == mStoredUid) return;
- EXPECT_TRUE(seteuid(mStoredUid) == 0);
- }
- private:
- uid_t mInputUid;
- uid_t mStoredUid;
- };
- constexpr uint32_t RULE_PRIORITY_VPN_FALLTHROUGH = 21000;
- void clearQueue(int tunFd) {
- char buf[4096];
- int ret;
- do {
- ret = read(tunFd, buf, sizeof(buf));
- } while (ret > 0);
- }
- void checkDataReceived(int udpSocket, int tunFd) {
- char buf[4096] = {};
-
-
- clearQueue(tunFd);
- EXPECT_EQ(4, write(udpSocket, "foo", sizeof("foo")));
-
- EXPECT_GT(read(tunFd, buf, sizeof(buf)), 0);
- }
- bool sendIPv6PacketFromUid(uid_t uid, const in6_addr& dstAddr, Fwmark* fwmark, int tunFd) {
- ScopedUidChange scopedUidChange(uid);
- android::base::unique_fd testSocket(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
- if (testSocket < 0) return false;
- const sockaddr_in6 dst6 = {.sin6_family = AF_INET6, .sin6_addr = dstAddr, .sin6_port = 42};
- int res = connect(testSocket, (sockaddr*)&dst6, sizeof(dst6));
- socklen_t fwmarkLen = sizeof(fwmark->intValue);
- EXPECT_NE(-1, getsockopt(testSocket, SOL_SOCKET, SO_MARK, &(fwmark->intValue), &fwmarkLen));
- if (res == -1) return false;
- char addr[INET6_ADDRSTRLEN];
- inet_ntop(AF_INET6, &dstAddr, addr, INET6_ADDRSTRLEN);
- SCOPED_TRACE(StringPrintf("sendIPv6PacketFromUid, addr: %s, uid: %u", addr, uid));
- checkDataReceived(testSocket, tunFd);
- return true;
- }
- void expectVpnFallthroughRuleExists(const std::string& ifName, int vpnNetId) {
- std::string vpnFallthroughRule =
- StringPrintf("%d:\tfrom all fwmark 0x%x/0xffff lookup %s",
- RULE_PRIORITY_VPN_FALLTHROUGH, vpnNetId, ifName.c_str());
- for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
- EXPECT_TRUE(ipRuleExists(ipVersion, vpnFallthroughRule));
- }
- }
- void expectVpnFallthroughWorks(android::net::INetd* netdService, bool bypassable, uid_t uid,
- const TunInterface& fallthroughNetwork,
- const TunInterface& vpnNetwork, int vpnNetId = TEST_NETID2,
- int fallthroughNetId = TEST_NETID1) {
-
- EXPECT_TRUE(netdService->networkSetDefault(NETID_UNSET).isOk());
-
- in6_addr insideVpnAddr = {
- {
- .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}};
-
-
- in6_addr outsideVpnAddr = {
- {
- .u6_addr8 = {0x26, 0x07, 0xf0, 0xd0, 0x10, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4}}};
- int fallthroughFd = fallthroughNetwork.getFdForTesting();
- int vpnFd = vpnNetwork.getFdForTesting();
-
-
- Fwmark fwmark;
- EXPECT_FALSE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
- EXPECT_FALSE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
-
- EXPECT_TRUE(netdService->networkSetDefault(fallthroughNetId).isOk());
-
- EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
- EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
- EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
- EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
-
- expectVpnFallthroughRuleExists(fallthroughNetwork.name(), vpnNetId);
-
-
- EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
- EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
-
- EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, vpnFd));
- EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
-
- setNetworkForProcess(vpnNetId);
-
- EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
-
- EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
-
- EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, vpnFd));
-
- EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
-
- setNetworkForProcess(fallthroughNetId);
-
- EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
- EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
-
- if (bypassable) {
- EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
- EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
- } else {
-
- EXPECT_FALSE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
- EXPECT_FALSE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
- }
- }
- }
- TEST_F(BinderTest, SecureVPNFallthrough) {
- createVpnNetworkWithUid(true , TEST_UID1);
-
- ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
- expectVpnFallthroughWorks(mNetd.get(), false , TEST_UID1, sTun, sTun2);
- }
- TEST_F(BinderTest, BypassableVPNFallthrough) {
- createVpnNetworkWithUid(false , TEST_UID1);
-
- ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
- expectVpnFallthroughWorks(mNetd.get(), true , TEST_UID1, sTun, sTun2);
- }
|