binder_test.cpp 130 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285
  1. /*
  2. * Copyright 2016 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. * binder_test.cpp - unit tests for netd binder RPCs.
  17. */
  18. #include <cerrno>
  19. #include <chrono>
  20. #include <cinttypes>
  21. #include <condition_variable>
  22. #include <cstdint>
  23. #include <cstdio>
  24. #include <cstdlib>
  25. #include <mutex>
  26. #include <set>
  27. #include <vector>
  28. #include <dirent.h>
  29. #include <fcntl.h>
  30. #include <ifaddrs.h>
  31. #include <linux/if.h>
  32. #include <linux/if_tun.h>
  33. #include <net/if.h>
  34. #include <netdb.h>
  35. #include <netinet/in.h>
  36. #include <openssl/base64.h>
  37. #include <sys/socket.h>
  38. #include <sys/types.h>
  39. #include <android-base/file.h>
  40. #include <android-base/macros.h>
  41. #include <android-base/stringprintf.h>
  42. #include <android-base/strings.h>
  43. #include <binder/IPCThreadState.h>
  44. #include <bpf/BpfMap.h>
  45. #include <bpf/BpfUtils.h>
  46. #include <com/android/internal/net/BnOemNetdUnsolicitedEventListener.h>
  47. #include <com/android/internal/net/IOemNetd.h>
  48. #include <cutils/multiuser.h>
  49. #include <gtest/gtest.h>
  50. #include <logwrap/logwrap.h>
  51. #include <netdbpf/bpf_shared.h>
  52. #include <netutils/ifc.h>
  53. #include "Fwmark.h"
  54. #include "InterfaceController.h"
  55. #include "NetdClient.h"
  56. #include "NetdConstants.h"
  57. #include "TestUnsolService.h"
  58. #include "XfrmController.h"
  59. #include "android/net/INetd.h"
  60. #include "binder/IServiceManager.h"
  61. #include "netdutils/Stopwatch.h"
  62. #include "netdutils/Syscalls.h"
  63. #include "netid_client.h" // NETID_UNSET
  64. #include "tun_interface.h"
  65. #define IP_PATH "/system/bin/ip"
  66. #define IP6TABLES_PATH "/system/bin/ip6tables"
  67. #define IPTABLES_PATH "/system/bin/iptables"
  68. #define TUN_DEV "/dev/tun"
  69. #define RAW_TABLE "raw"
  70. #define MANGLE_TABLE "mangle"
  71. #define FILTER_TABLE "filter"
  72. #define NAT_TABLE "nat"
  73. namespace binder = android::binder;
  74. using android::IBinder;
  75. using android::IServiceManager;
  76. using android::sp;
  77. using android::String16;
  78. using android::String8;
  79. using android::base::Join;
  80. using android::base::ReadFileToString;
  81. using android::base::StartsWith;
  82. using android::base::StringPrintf;
  83. using android::base::Trim;
  84. using android::net::INetd;
  85. using android::net::InterfaceConfigurationParcel;
  86. using android::net::InterfaceController;
  87. using android::net::TetherStatsParcel;
  88. using android::net::TunInterface;
  89. using android::net::UidRangeParcel;
  90. using android::netdutils::sSyscalls;
  91. using android::netdutils::Stopwatch;
  92. static const char* IP_RULE_V4 = "-4";
  93. static const char* IP_RULE_V6 = "-6";
  94. static const int TEST_NETID1 = 65501;
  95. static const int TEST_NETID2 = 65502;
  96. // Use maximum reserved appId for applications to avoid conflict with existing
  97. // uids.
  98. static const int TEST_UID1 = 99999;
  99. static const int TEST_UID2 = 99998;
  100. constexpr int BASE_UID = AID_USER_OFFSET * 5;
  101. static const std::string NO_SOCKET_ALLOW_RULE("! owner UID match 0-4294967294");
  102. static const std::string ESP_ALLOW_RULE("esp");
  103. class BinderTest : public ::testing::Test {
  104. public:
  105. BinderTest() {
  106. sp<IServiceManager> sm = android::defaultServiceManager();
  107. sp<IBinder> binder = sm->getService(String16("netd"));
  108. if (binder != nullptr) {
  109. mNetd = android::interface_cast<INetd>(binder);
  110. }
  111. }
  112. void SetUp() override {
  113. ASSERT_NE(nullptr, mNetd.get());
  114. }
  115. void TearDown() override {
  116. mNetd->networkDestroy(TEST_NETID1);
  117. mNetd->networkDestroy(TEST_NETID2);
  118. setNetworkForProcess(NETID_UNSET);
  119. // Restore default network
  120. if (mStoredDefaultNetwork >= 0) mNetd->networkSetDefault(mStoredDefaultNetwork);
  121. }
  122. bool allocateIpSecResources(bool expectOk, int32_t* spi);
  123. // Static because setting up the tun interface takes about 40ms.
  124. static void SetUpTestCase() {
  125. ASSERT_EQ(0, sTun.init());
  126. ASSERT_EQ(0, sTun2.init());
  127. ASSERT_LE(sTun.name().size(), static_cast<size_t>(IFNAMSIZ));
  128. ASSERT_LE(sTun2.name().size(), static_cast<size_t>(IFNAMSIZ));
  129. }
  130. static void TearDownTestCase() {
  131. // Closing the socket removes the interface and IP addresses.
  132. sTun.destroy();
  133. sTun2.destroy();
  134. }
  135. static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
  136. void createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId = TEST_NETID2,
  137. int fallthroughNetId = TEST_NETID1);
  138. protected:
  139. // Use -1 to represent that default network was not modified because
  140. // real netId must be an unsigned value.
  141. int mStoredDefaultNetwork = -1;
  142. sp<INetd> mNetd;
  143. static TunInterface sTun;
  144. static TunInterface sTun2;
  145. };
  146. TunInterface BinderTest::sTun;
  147. TunInterface BinderTest::sTun2;
  148. class TimedOperation : public Stopwatch {
  149. public:
  150. explicit TimedOperation(const std::string &name): mName(name) {}
  151. virtual ~TimedOperation() {
  152. fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken());
  153. }
  154. private:
  155. std::string mName;
  156. };
  157. TEST_F(BinderTest, IsAlive) {
  158. TimedOperation t("isAlive RPC");
  159. bool isAlive = false;
  160. mNetd->isAlive(&isAlive);
  161. ASSERT_TRUE(isAlive);
  162. }
  163. static int randomUid() {
  164. return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
  165. }
  166. static std::vector<std::string> runCommand(const std::string& command) {
  167. std::vector<std::string> lines;
  168. FILE *f = popen(command.c_str(), "r"); // NOLINT(cert-env33-c)
  169. if (f == nullptr) {
  170. perror("popen");
  171. return lines;
  172. }
  173. char *line = nullptr;
  174. size_t bufsize = 0;
  175. ssize_t linelen = 0;
  176. while ((linelen = getline(&line, &bufsize, f)) >= 0) {
  177. lines.push_back(std::string(line, linelen));
  178. free(line);
  179. line = nullptr;
  180. }
  181. pclose(f);
  182. return lines;
  183. }
  184. static std::vector<std::string> listIpRules(const char *ipVersion) {
  185. std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
  186. return runCommand(command);
  187. }
  188. static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
  189. std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
  190. return runCommand(command);
  191. }
  192. static int iptablesRuleLineLength(const char *binary, const char *chainName) {
  193. return listIptablesRule(binary, chainName).size();
  194. }
  195. static bool iptablesRuleExists(const char *binary,
  196. const char *chainName,
  197. const std::string& expectedRule) {
  198. std::vector<std::string> rules = listIptablesRule(binary, chainName);
  199. for (const auto& rule : rules) {
  200. if(rule.find(expectedRule) != std::string::npos) {
  201. return true;
  202. }
  203. }
  204. return false;
  205. }
  206. static bool iptablesNoSocketAllowRuleExists(const char *chainName){
  207. return iptablesRuleExists(IPTABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE) &&
  208. iptablesRuleExists(IP6TABLES_PATH, chainName, NO_SOCKET_ALLOW_RULE);
  209. }
  210. static bool iptablesEspAllowRuleExists(const char *chainName){
  211. return iptablesRuleExists(IPTABLES_PATH, chainName, ESP_ALLOW_RULE) &&
  212. iptablesRuleExists(IP6TABLES_PATH, chainName, ESP_ALLOW_RULE);
  213. }
  214. TEST_F(BinderTest, FirewallReplaceUidChain) {
  215. SKIP_IF_BPF_SUPPORTED;
  216. std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
  217. const int kNumUids = 500;
  218. std::vector<int32_t> noUids(0);
  219. std::vector<int32_t> uids(kNumUids);
  220. for (int i = 0; i < kNumUids; i++) {
  221. uids[i] = randomUid();
  222. }
  223. bool ret;
  224. {
  225. TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
  226. mNetd->firewallReplaceUidChain(chainName, true, uids, &ret);
  227. }
  228. EXPECT_EQ(true, ret);
  229. EXPECT_EQ((int) uids.size() + 9, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
  230. EXPECT_EQ((int) uids.size() + 15, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
  231. EXPECT_EQ(true, iptablesNoSocketAllowRuleExists(chainName.c_str()));
  232. EXPECT_EQ(true, iptablesEspAllowRuleExists(chainName.c_str()));
  233. {
  234. TimedOperation op("Clearing whitelist chain");
  235. mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
  236. }
  237. EXPECT_EQ(true, ret);
  238. EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
  239. EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
  240. {
  241. TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
  242. mNetd->firewallReplaceUidChain(chainName, false, uids, &ret);
  243. }
  244. EXPECT_EQ(true, ret);
  245. EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
  246. EXPECT_EQ((int) uids.size() + 5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
  247. EXPECT_EQ(false, iptablesNoSocketAllowRuleExists(chainName.c_str()));
  248. EXPECT_EQ(false, iptablesEspAllowRuleExists(chainName.c_str()));
  249. {
  250. TimedOperation op("Clearing blacklist chain");
  251. mNetd->firewallReplaceUidChain(chainName, false, noUids, &ret);
  252. }
  253. EXPECT_EQ(true, ret);
  254. EXPECT_EQ(5, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
  255. EXPECT_EQ(5, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
  256. // Check that the call fails if iptables returns an error.
  257. std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
  258. mNetd->firewallReplaceUidChain(veryLongStringName, true, noUids, &ret);
  259. EXPECT_EQ(false, ret);
  260. }
  261. TEST_F(BinderTest, IpSecTunnelInterface) {
  262. const struct TestData {
  263. const std::string family;
  264. const std::string deviceName;
  265. const std::string localAddress;
  266. const std::string remoteAddress;
  267. int32_t iKey;
  268. int32_t oKey;
  269. int32_t ifId;
  270. } kTestData[] = {
  271. {"IPV4", "ipsec_test", "127.0.0.1", "8.8.8.8", 0x1234 + 53, 0x1234 + 53, 0xFFFE},
  272. {"IPV6", "ipsec_test6", "::1", "2001:4860:4860::8888", 0x1234 + 50, 0x1234 + 50,
  273. 0xFFFE},
  274. };
  275. for (size_t i = 0; i < std::size(kTestData); i++) {
  276. const auto& td = kTestData[i];
  277. binder::Status status;
  278. // Create Tunnel Interface.
  279. status = mNetd->ipSecAddTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
  280. td.iKey, td.oKey, td.ifId);
  281. EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
  282. // Check that the interface exists
  283. EXPECT_NE(0U, if_nametoindex(td.deviceName.c_str()));
  284. // Update Tunnel Interface.
  285. status = mNetd->ipSecUpdateTunnelInterface(td.deviceName, td.localAddress, td.remoteAddress,
  286. td.iKey, td.oKey, td.ifId);
  287. EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
  288. // Remove Tunnel Interface.
  289. status = mNetd->ipSecRemoveTunnelInterface(td.deviceName);
  290. EXPECT_TRUE(status.isOk()) << td.family << status.exceptionMessage();
  291. // Check that the interface no longer exists
  292. EXPECT_EQ(0U, if_nametoindex(td.deviceName.c_str()));
  293. }
  294. }
  295. TEST_F(BinderTest, IpSecSetEncapSocketOwner) {
  296. android::base::unique_fd uniqueFd(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
  297. android::os::ParcelFileDescriptor sockFd(std::move(uniqueFd));
  298. int sockOptVal = UDP_ENCAP_ESPINUDP;
  299. setsockopt(sockFd.get(), IPPROTO_UDP, UDP_ENCAP, &sockOptVal, sizeof(sockOptVal));
  300. binder::Status res = mNetd->ipSecSetEncapSocketOwner(sockFd, 1001);
  301. EXPECT_TRUE(res.isOk());
  302. struct stat info;
  303. EXPECT_EQ(0, fstat(sockFd.get(), &info));
  304. EXPECT_EQ(1001, (int) info.st_uid);
  305. }
  306. // IPsec tests are not run in 32 bit mode; both 32-bit kernels and
  307. // mismatched ABIs (64-bit kernel with 32-bit userspace) are unsupported.
  308. #if INTPTR_MAX != INT32_MAX
  309. using android::net::XfrmController;
  310. static const int XFRM_DIRECTIONS[] = {static_cast<int>(android::net::XfrmDirection::IN),
  311. static_cast<int>(android::net::XfrmDirection::OUT)};
  312. static const int ADDRESS_FAMILIES[] = {AF_INET, AF_INET6};
  313. #define RETURN_FALSE_IF_NEQ(_expect_, _ret_) \
  314. do { if ((_expect_) != (_ret_)) return false; } while(false)
  315. bool BinderTest::allocateIpSecResources(bool expectOk, int32_t* spi) {
  316. android::netdutils::Status status = XfrmController::ipSecAllocateSpi(0, "::", "::1", 123, spi);
  317. SCOPED_TRACE(status);
  318. RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
  319. // Add a policy
  320. status = XfrmController::ipSecAddSecurityPolicy(0, AF_INET6, 0, "::", "::1", 123, 0, 0, 0);
  321. SCOPED_TRACE(status);
  322. RETURN_FALSE_IF_NEQ(status.ok(), expectOk);
  323. // Add an ipsec interface
  324. return expectOk == XfrmController::ipSecAddTunnelInterface("ipsec_test", "::", "::1", 0xF00D,
  325. 0xD00D, 0xE00D, false)
  326. .ok();
  327. }
  328. TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV4) {
  329. android::binder::Status status;
  330. // Repeat to ensure cleanup and recreation works correctly
  331. for (int i = 0; i < 2; i++) {
  332. for (int direction : XFRM_DIRECTIONS) {
  333. for (int addrFamily : ADDRESS_FAMILIES) {
  334. status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "127.0.0.5",
  335. "127.0.0.6", 123, 0, 0, 0);
  336. EXPECT_TRUE(status.isOk())
  337. << " family: " << addrFamily << " direction: " << direction;
  338. }
  339. }
  340. // Cleanup
  341. for (int direction : XFRM_DIRECTIONS) {
  342. for (int addrFamily : ADDRESS_FAMILIES) {
  343. status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
  344. EXPECT_TRUE(status.isOk());
  345. }
  346. }
  347. }
  348. }
  349. TEST_F(BinderTest, XfrmDualSelectorTunnelModePoliciesV6) {
  350. binder::Status status;
  351. // Repeat to ensure cleanup and recreation works correctly
  352. for (int i = 0; i < 2; i++) {
  353. for (int direction : XFRM_DIRECTIONS) {
  354. for (int addrFamily : ADDRESS_FAMILIES) {
  355. status = mNetd->ipSecAddSecurityPolicy(0, addrFamily, direction, "2001:db8::f00d",
  356. "2001:db8::d00d", 123, 0, 0, 0);
  357. EXPECT_TRUE(status.isOk())
  358. << " family: " << addrFamily << " direction: " << direction;
  359. }
  360. }
  361. // Cleanup
  362. for (int direction : XFRM_DIRECTIONS) {
  363. for (int addrFamily : ADDRESS_FAMILIES) {
  364. status = mNetd->ipSecDeleteSecurityPolicy(0, addrFamily, direction, 0, 0, 0);
  365. EXPECT_TRUE(status.isOk());
  366. }
  367. }
  368. }
  369. }
  370. TEST_F(BinderTest, XfrmControllerInit) {
  371. android::netdutils::Status status;
  372. status = XfrmController::Init();
  373. SCOPED_TRACE(status);
  374. // Older devices or devices with mismatched Kernel/User ABI cannot support the IPsec
  375. // feature.
  376. if (status.code() == EOPNOTSUPP) return;
  377. ASSERT_TRUE(status.ok());
  378. int32_t spi = 0;
  379. ASSERT_TRUE(allocateIpSecResources(true, &spi));
  380. ASSERT_TRUE(allocateIpSecResources(false, &spi));
  381. status = XfrmController::Init();
  382. ASSERT_TRUE(status.ok());
  383. ASSERT_TRUE(allocateIpSecResources(true, &spi));
  384. // Clean up
  385. status = XfrmController::ipSecDeleteSecurityAssociation(0, "::", "::1", 123, spi, 0, 0);
  386. SCOPED_TRACE(status);
  387. ASSERT_TRUE(status.ok());
  388. status = XfrmController::ipSecDeleteSecurityPolicy(0, AF_INET6, 0, 0, 0, 0);
  389. SCOPED_TRACE(status);
  390. ASSERT_TRUE(status.ok());
  391. // Remove Virtual Tunnel Interface.
  392. ASSERT_TRUE(XfrmController::ipSecRemoveTunnelInterface("ipsec_test").ok());
  393. }
  394. #endif // INTPTR_MAX != INT32_MAX
  395. static int bandwidthDataSaverEnabled(const char *binary) {
  396. std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
  397. // Output looks like this:
  398. //
  399. // Chain bw_data_saver (1 references)
  400. // target prot opt source destination
  401. // RETURN all -- 0.0.0.0/0 0.0.0.0/0
  402. //
  403. // or:
  404. //
  405. // Chain bw_data_saver (1 references)
  406. // target prot opt source destination
  407. // ... possibly connectivity critical packet rules here ...
  408. // REJECT all -- ::/0 ::/0
  409. EXPECT_GE(lines.size(), 3U);
  410. if (lines.size() == 3 && StartsWith(lines[2], "RETURN ")) {
  411. // Data saver disabled.
  412. return 0;
  413. }
  414. size_t minSize = (std::string(binary) == IPTABLES_PATH) ? 3 : 9;
  415. if (lines.size() >= minSize && StartsWith(lines[lines.size() -1], "REJECT ")) {
  416. // Data saver enabled.
  417. return 1;
  418. }
  419. return -1;
  420. }
  421. bool enableDataSaver(sp<INetd>& netd, bool enable) {
  422. TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
  423. bool ret;
  424. netd->bandwidthEnableDataSaver(enable, &ret);
  425. return ret;
  426. }
  427. int getDataSaverState() {
  428. const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
  429. const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
  430. EXPECT_EQ(enabled4, enabled6);
  431. EXPECT_NE(-1, enabled4);
  432. EXPECT_NE(-1, enabled6);
  433. if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
  434. return -1;
  435. }
  436. return enabled6;
  437. }
  438. TEST_F(BinderTest, BandwidthEnableDataSaver) {
  439. const int wasEnabled = getDataSaverState();
  440. ASSERT_NE(-1, wasEnabled);
  441. if (wasEnabled) {
  442. ASSERT_TRUE(enableDataSaver(mNetd, false));
  443. EXPECT_EQ(0, getDataSaverState());
  444. }
  445. ASSERT_TRUE(enableDataSaver(mNetd, false));
  446. EXPECT_EQ(0, getDataSaverState());
  447. ASSERT_TRUE(enableDataSaver(mNetd, true));
  448. EXPECT_EQ(1, getDataSaverState());
  449. ASSERT_TRUE(enableDataSaver(mNetd, true));
  450. EXPECT_EQ(1, getDataSaverState());
  451. if (!wasEnabled) {
  452. ASSERT_TRUE(enableDataSaver(mNetd, false));
  453. EXPECT_EQ(0, getDataSaverState());
  454. }
  455. }
  456. static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
  457. const std::string& action, const char* ipVersion) {
  458. // Output looks like this:
  459. // "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
  460. std::vector<std::string> rules = listIpRules(ipVersion);
  461. std::string prefix = StringPrintf("%" PRIu32 ":", priority);
  462. std::string suffix =
  463. StringPrintf(" iif lo uidrange %d-%d %s\n", range.start, range.stop, action.c_str());
  464. for (const auto& line : rules) {
  465. if (android::base::StartsWith(line, prefix) && android::base::EndsWith(line, suffix)) {
  466. return true;
  467. }
  468. }
  469. return false;
  470. }
  471. static bool ipRuleExistsForRange(const uint32_t priority, const UidRangeParcel& range,
  472. const std::string& action) {
  473. bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
  474. bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
  475. EXPECT_EQ(existsIp4, existsIp6);
  476. return existsIp4;
  477. }
  478. namespace {
  479. UidRangeParcel makeUidRangeParcel(int start, int stop) {
  480. UidRangeParcel res;
  481. res.start = start;
  482. res.stop = stop;
  483. return res;
  484. }
  485. } // namespace
  486. TEST_F(BinderTest, NetworkInterfaces) {
  487. EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
  488. EXPECT_EQ(EEXIST, mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE)
  489. .serviceSpecificErrorCode());
  490. EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
  491. EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID2, true).isOk());
  492. EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
  493. EXPECT_EQ(EBUSY,
  494. mNetd->networkAddInterface(TEST_NETID2, sTun.name()).serviceSpecificErrorCode());
  495. EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
  496. EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun.name()).isOk());
  497. EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID2).isOk());
  498. EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
  499. }
  500. TEST_F(BinderTest, NetworkUidRules) {
  501. const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
  502. EXPECT_TRUE(mNetd->networkCreateVpn(TEST_NETID1, true).isOk());
  503. EXPECT_EQ(EEXIST, mNetd->networkCreateVpn(TEST_NETID1, true).serviceSpecificErrorCode());
  504. EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
  505. std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 8005, BASE_UID + 8012),
  506. makeUidRangeParcel(BASE_UID + 8090, BASE_UID + 8099)};
  507. UidRangeParcel otherRange = makeUidRangeParcel(BASE_UID + 8190, BASE_UID + 8299);
  508. std::string suffix = StringPrintf("lookup %s ", sTun.name().c_str());
  509. EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
  510. EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
  511. EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, otherRange, suffix));
  512. EXPECT_TRUE(mNetd->networkRemoveUidRanges(TEST_NETID1, uidRanges).isOk());
  513. EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[0], suffix));
  514. EXPECT_TRUE(mNetd->networkAddUidRanges(TEST_NETID1, uidRanges).isOk());
  515. EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
  516. EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
  517. EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY_SECURE_VPN, uidRanges[1], suffix));
  518. EXPECT_EQ(ENONET, mNetd->networkDestroy(TEST_NETID1).serviceSpecificErrorCode());
  519. }
  520. TEST_F(BinderTest, NetworkRejectNonSecureVpn) {
  521. constexpr uint32_t RULE_PRIORITY = 12500;
  522. std::vector<UidRangeParcel> uidRanges = {makeUidRangeParcel(BASE_UID + 150, BASE_UID + 224),
  523. makeUidRangeParcel(BASE_UID + 226, BASE_UID + 300)};
  524. const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
  525. const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
  526. // Create two valid rules.
  527. ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
  528. EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
  529. EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
  530. for (auto const& range : uidRanges) {
  531. EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
  532. }
  533. // Remove the rules.
  534. ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
  535. EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
  536. EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
  537. for (auto const& range : uidRanges) {
  538. EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
  539. }
  540. // Fail to remove the rules a second time after they are already deleted.
  541. binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
  542. ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
  543. EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
  544. // All rules should be the same as before.
  545. EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
  546. EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
  547. }
  548. // Create a socket pair that isLoopbackSocket won't think is local.
  549. void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
  550. *serverSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
  551. struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.dstAddr() };
  552. ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
  553. socklen_t addrlen = sizeof(server6);
  554. ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
  555. ASSERT_EQ(0, listen(*serverSocket, 10));
  556. *clientSocket = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
  557. struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sTun.srcAddr() };
  558. ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
  559. ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
  560. ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
  561. *acceptedSocket = accept4(*serverSocket, (struct sockaddr *) &server6, &addrlen, SOCK_CLOEXEC);
  562. ASSERT_NE(-1, *acceptedSocket);
  563. ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
  564. }
  565. void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
  566. char buf[4096];
  567. EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
  568. EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
  569. EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
  570. }
  571. void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
  572. // Check that the client socket was closed with ECONNABORTED.
  573. int ret = write(clientSocket, "foo", sizeof("foo"));
  574. int err = errno;
  575. EXPECT_EQ(-1, ret);
  576. EXPECT_EQ(ECONNABORTED, err);
  577. // Check that it sent a RST to the server.
  578. ret = write(acceptedSocket, "foo", sizeof("foo"));
  579. err = errno;
  580. EXPECT_EQ(-1, ret);
  581. EXPECT_EQ(ECONNRESET, err);
  582. }
  583. TEST_F(BinderTest, SocketDestroy) {
  584. int clientSocket, serverSocket, acceptedSocket;
  585. ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
  586. // Pick a random UID in the system UID range.
  587. constexpr int baseUid = AID_APP - 2000;
  588. static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
  589. int uid = baseUid + 500 + arc4random_uniform(1000);
  590. EXPECT_EQ(0, fchown(clientSocket, uid, -1));
  591. // UID ranges that don't contain uid.
  592. std::vector<UidRangeParcel> uidRanges = {
  593. makeUidRangeParcel(baseUid + 42, baseUid + 449),
  594. makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
  595. makeUidRangeParcel(baseUid + 498, uid - 1),
  596. makeUidRangeParcel(uid + 1, baseUid + 1520),
  597. };
  598. // A skip list that doesn't contain UID.
  599. std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
  600. // Close sockets. Our test socket should be intact.
  601. EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
  602. checkSocketpairOpen(clientSocket, acceptedSocket);
  603. // UID ranges that do contain uid.
  604. uidRanges = {
  605. makeUidRangeParcel(baseUid + 42, baseUid + 449),
  606. makeUidRangeParcel(baseUid + 1536, AID_APP - 4),
  607. makeUidRangeParcel(baseUid + 498, baseUid + 1520),
  608. };
  609. // Add uid to the skip list.
  610. skipUids.push_back(uid);
  611. // Close sockets. Our test socket should still be intact because it's in the skip list.
  612. EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
  613. checkSocketpairOpen(clientSocket, acceptedSocket);
  614. // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
  615. skipUids.resize(skipUids.size() - 1);
  616. EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
  617. checkSocketpairClosed(clientSocket, acceptedSocket);
  618. close(clientSocket);
  619. close(serverSocket);
  620. close(acceptedSocket);
  621. }
  622. namespace {
  623. int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
  624. if (buf == nullptr) return -1;
  625. int prefixLength = 0;
  626. bool endOfContiguousBits = false;
  627. for (unsigned int i = 0; i < buflen; i++) {
  628. const uint8_t value = buf[i];
  629. // Bad bit sequence: check for a contiguous set of bits from the high
  630. // end by verifying that the inverted value + 1 is a power of 2
  631. // (power of 2 iff. (v & (v - 1)) == 0).
  632. const uint8_t inverse = ~value + 1;
  633. if ((inverse & (inverse - 1)) != 0) return -1;
  634. prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
  635. // Bogus netmask.
  636. if (endOfContiguousBits && value != 0) return -1;
  637. if (value != 0xff) endOfContiguousBits = true;
  638. }
  639. return prefixLength;
  640. }
  641. template<typename T>
  642. int netmaskToPrefixLength(const T *p) {
  643. return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
  644. }
  645. static bool interfaceHasAddress(
  646. const std::string &ifname, const char *addrString, int prefixLength) {
  647. struct addrinfo *addrinfoList = nullptr;
  648. const struct addrinfo hints = {
  649. .ai_flags = AI_NUMERICHOST,
  650. .ai_family = AF_UNSPEC,
  651. .ai_socktype = SOCK_DGRAM,
  652. };
  653. if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
  654. addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
  655. return false;
  656. }
  657. ScopedAddrinfo addrinfoCleanup(addrinfoList);
  658. struct ifaddrs *ifaddrsList = nullptr;
  659. ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
  660. if (getifaddrs(&ifaddrsList) != 0) {
  661. return false;
  662. }
  663. for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
  664. if (std::string(addr->ifa_name) != ifname ||
  665. addr->ifa_addr == nullptr ||
  666. addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
  667. continue;
  668. }
  669. switch (addr->ifa_addr->sa_family) {
  670. case AF_INET: {
  671. auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
  672. auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
  673. if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
  674. continue;
  675. }
  676. if (prefixLength < 0) return true; // not checking prefix lengths
  677. if (addr->ifa_netmask == nullptr) return false;
  678. auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
  679. EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
  680. return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
  681. }
  682. case AF_INET6: {
  683. auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
  684. auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
  685. if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
  686. continue;
  687. }
  688. if (prefixLength < 0) return true; // not checking prefix lengths
  689. if (addr->ifa_netmask == nullptr) return false;
  690. auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
  691. EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
  692. return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
  693. }
  694. default:
  695. // Cannot happen because we have already screened for matching
  696. // address families at the top of each iteration.
  697. continue;
  698. }
  699. }
  700. return false;
  701. }
  702. } // namespace
  703. TEST_F(BinderTest, InterfaceAddRemoveAddress) {
  704. static const struct TestData {
  705. const char *addrString;
  706. const int prefixLength;
  707. const bool expectSuccess;
  708. } kTestData[] = {
  709. { "192.0.2.1", 24, true },
  710. { "192.0.2.2", 25, true },
  711. { "192.0.2.3", 32, true },
  712. { "192.0.2.4", 33, false },
  713. { "192.not.an.ip", 24, false },
  714. { "2001:db8::1", 64, true },
  715. { "2001:db8::2", 65, true },
  716. { "2001:db8::3", 128, true },
  717. { "2001:db8::4", 129, false },
  718. { "foo:bar::bad", 64, false },
  719. };
  720. for (size_t i = 0; i < std::size(kTestData); i++) {
  721. const auto &td = kTestData[i];
  722. // [1.a] Add the address.
  723. binder::Status status = mNetd->interfaceAddAddress(
  724. sTun.name(), td.addrString, td.prefixLength);
  725. if (td.expectSuccess) {
  726. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  727. } else {
  728. ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
  729. ASSERT_NE(0, status.serviceSpecificErrorCode());
  730. }
  731. // [1.b] Verify the addition meets the expectation.
  732. if (td.expectSuccess) {
  733. EXPECT_TRUE(interfaceHasAddress(sTun.name(), td.addrString, td.prefixLength));
  734. } else {
  735. EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
  736. }
  737. // [2.a] Try to remove the address. If it was not previously added, removing it fails.
  738. status = mNetd->interfaceDelAddress(sTun.name(), td.addrString, td.prefixLength);
  739. if (td.expectSuccess) {
  740. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  741. } else {
  742. ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
  743. ASSERT_NE(0, status.serviceSpecificErrorCode());
  744. }
  745. // [2.b] No matter what, the address should not be present.
  746. EXPECT_FALSE(interfaceHasAddress(sTun.name(), td.addrString, -1));
  747. }
  748. }
  749. TEST_F(BinderTest, GetProcSysNet) {
  750. const char LOOPBACK[] = "lo";
  751. static const struct {
  752. const int ipversion;
  753. const int which;
  754. const char* ifname;
  755. const char* parameter;
  756. const char* expectedValue;
  757. const int expectedReturnCode;
  758. } kTestData[] = {
  759. {INetd::IPV4, INetd::CONF, LOOPBACK, "arp_ignore", "0", 0},
  760. {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", nullptr, EAFNOSUPPORT},
  761. {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", nullptr, EINVAL},
  762. {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", nullptr, EINVAL},
  763. {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", nullptr, EINVAL},
  764. {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", nullptr, EINVAL},
  765. {INetd::IPV6, INetd::NEIGH, LOOPBACK, "ucast_solicit", "3", 0},
  766. };
  767. for (size_t i = 0; i < std::size(kTestData); i++) {
  768. const auto& td = kTestData[i];
  769. std::string value;
  770. const binder::Status status =
  771. mNetd->getProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, &value);
  772. if (td.expectedReturnCode == 0) {
  773. SCOPED_TRACE(String8::format("test case %zu should have passed", i));
  774. EXPECT_EQ(0, status.exceptionCode());
  775. EXPECT_EQ(0, status.serviceSpecificErrorCode());
  776. EXPECT_EQ(td.expectedValue, value);
  777. } else {
  778. SCOPED_TRACE(String8::format("test case %zu should have failed", i));
  779. EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
  780. EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
  781. }
  782. }
  783. }
  784. TEST_F(BinderTest, SetProcSysNet) {
  785. static const struct {
  786. const int ipversion;
  787. const int which;
  788. const char* ifname;
  789. const char* parameter;
  790. const char* value;
  791. const int expectedReturnCode;
  792. } kTestData[] = {
  793. {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", 0},
  794. {-1, INetd::CONF, sTun.name().c_str(), "arp_ignore", "1", EAFNOSUPPORT},
  795. {INetd::IPV4, -1, sTun.name().c_str(), "arp_ignore", "1", EINVAL},
  796. {INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL},
  797. {INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL},
  798. {INetd::IPV4, INetd::CONF, sTun.name().c_str(), "../all/arp_ignore", "1", EINVAL},
  799. {INetd::IPV6, INetd::NEIGH, sTun.name().c_str(), "ucast_solicit", "7", 0},
  800. };
  801. for (size_t i = 0; i < std::size(kTestData); i++) {
  802. const auto& td = kTestData[i];
  803. const binder::Status status =
  804. mNetd->setProcSysNet(td.ipversion, td.which, td.ifname, td.parameter, td.value);
  805. if (td.expectedReturnCode == 0) {
  806. SCOPED_TRACE(String8::format("test case %zu should have passed", i));
  807. EXPECT_EQ(0, status.exceptionCode());
  808. EXPECT_EQ(0, status.serviceSpecificErrorCode());
  809. } else {
  810. SCOPED_TRACE(String8::format("test case %zu should have failed", i));
  811. EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
  812. EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
  813. }
  814. }
  815. }
  816. TEST_F(BinderTest, GetSetProcSysNet) {
  817. const int ipversion = INetd::IPV6;
  818. const int category = INetd::NEIGH;
  819. const std::string& tun = sTun.name();
  820. const std::string parameter("ucast_solicit");
  821. std::string value{};
  822. EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
  823. ASSERT_FALSE(value.empty());
  824. const int ival = std::stoi(value);
  825. EXPECT_GT(ival, 0);
  826. // Try doubling the parameter value (always best!).
  827. EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(2 * ival))
  828. .isOk());
  829. EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
  830. EXPECT_EQ(2 * ival, std::stoi(value));
  831. // Try resetting the parameter.
  832. EXPECT_TRUE(mNetd->setProcSysNet(ipversion, category, tun, parameter, std::to_string(ival))
  833. .isOk());
  834. EXPECT_TRUE(mNetd->getProcSysNet(ipversion, category, tun, parameter, &value).isOk());
  835. EXPECT_EQ(ival, std::stoi(value));
  836. }
  837. namespace {
  838. void expectNoTestCounterRules() {
  839. for (const auto& binary : { IPTABLES_PATH, IP6TABLES_PATH }) {
  840. std::string command = StringPrintf("%s -w -nvL tetherctrl_counters", binary);
  841. std::string allRules = Join(runCommand(command), "\n");
  842. EXPECT_EQ(std::string::npos, allRules.find("netdtest_"));
  843. }
  844. }
  845. void addTetherCounterValues(const char* path, const std::string& if1, const std::string& if2,
  846. int byte, int pkt) {
  847. runCommand(StringPrintf("%s -w -A tetherctrl_counters -i %s -o %s -j RETURN -c %d %d",
  848. path, if1.c_str(), if2.c_str(), pkt, byte));
  849. }
  850. void delTetherCounterValues(const char* path, const std::string& if1, const std::string& if2) {
  851. runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
  852. path, if1.c_str(), if2.c_str()));
  853. runCommand(StringPrintf("%s -w -D tetherctrl_counters -i %s -o %s -j RETURN",
  854. path, if2.c_str(), if1.c_str()));
  855. }
  856. std::vector<int64_t> getStatsVectorByIf(const std::vector<TetherStatsParcel>& statsVec,
  857. const std::string& iface) {
  858. for (auto& stats : statsVec) {
  859. if (stats.iface == iface) {
  860. return {stats.rxBytes, stats.rxPackets, stats.txBytes, stats.txPackets};
  861. }
  862. }
  863. return {};
  864. }
  865. } // namespace
  866. TEST_F(BinderTest, TetherGetStats) {
  867. expectNoTestCounterRules();
  868. // TODO: fold this into more comprehensive tests once we have binder RPCs for enabling and
  869. // disabling tethering. We don't check the return value because these commands will fail if
  870. // tethering is already enabled.
  871. runCommand(StringPrintf("%s -w -N tetherctrl_counters", IPTABLES_PATH));
  872. runCommand(StringPrintf("%s -w -N tetherctrl_counters", IP6TABLES_PATH));
  873. std::string intIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
  874. std::string intIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
  875. std::string intIface3 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
  876. std::string extIface1 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
  877. std::string extIface2 = StringPrintf("netdtest_%u", arc4random_uniform(10000));
  878. addTetherCounterValues(IPTABLES_PATH, intIface1, extIface1, 123, 111);
  879. addTetherCounterValues(IP6TABLES_PATH, intIface1, extIface1, 456, 10);
  880. addTetherCounterValues(IPTABLES_PATH, extIface1, intIface1, 321, 222);
  881. addTetherCounterValues(IP6TABLES_PATH, extIface1, intIface1, 654, 20);
  882. // RX is from external to internal, and TX is from internal to external.
  883. // So rxBytes is 321 + 654 = 975, txBytes is 123 + 456 = 579, etc.
  884. std::vector<int64_t> expected1 = { 975, 242, 579, 121 };
  885. addTetherCounterValues(IPTABLES_PATH, intIface2, extIface2, 1000, 333);
  886. addTetherCounterValues(IP6TABLES_PATH, intIface2, extIface2, 3000, 30);
  887. addTetherCounterValues(IPTABLES_PATH, extIface2, intIface2, 2000, 444);
  888. addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface2, 4000, 40);
  889. addTetherCounterValues(IP6TABLES_PATH, intIface3, extIface2, 1000, 25);
  890. addTetherCounterValues(IP6TABLES_PATH, extIface2, intIface3, 2000, 35);
  891. std::vector<int64_t> expected2 = { 8000, 519, 5000, 388 };
  892. std::vector<TetherStatsParcel> statsVec;
  893. binder::Status status = mNetd->tetherGetStats(&statsVec);
  894. EXPECT_TRUE(status.isOk()) << "Getting tethering stats failed: " << status;
  895. EXPECT_EQ(expected1, getStatsVectorByIf(statsVec, extIface1));
  896. EXPECT_EQ(expected2, getStatsVectorByIf(statsVec, extIface2));
  897. for (const auto& path : { IPTABLES_PATH, IP6TABLES_PATH }) {
  898. delTetherCounterValues(path, intIface1, extIface1);
  899. delTetherCounterValues(path, intIface2, extIface2);
  900. if (path == IP6TABLES_PATH) {
  901. delTetherCounterValues(path, intIface3, extIface2);
  902. }
  903. }
  904. expectNoTestCounterRules();
  905. }
  906. namespace {
  907. constexpr char IDLETIMER_RAW_PREROUTING[] = "idletimer_raw_PREROUTING";
  908. constexpr char IDLETIMER_MANGLE_POSTROUTING[] = "idletimer_mangle_POSTROUTING";
  909. static std::vector<std::string> listIptablesRuleByTable(const char* binary, const char* table,
  910. const char* chainName) {
  911. std::string command = StringPrintf("%s -t %s -w -n -v -L %s", binary, table, chainName);
  912. return runCommand(command);
  913. }
  914. // TODO: It is a duplicate function, need to remove it
  915. bool iptablesIdleTimerInterfaceRuleExists(const char* binary, const char* chainName,
  916. const std::string& expectedInterface,
  917. const std::string& expectedRule, const char* table) {
  918. std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
  919. for (const auto& rule : rules) {
  920. if (rule.find(expectedInterface) != std::string::npos) {
  921. if (rule.find(expectedRule) != std::string::npos) {
  922. return true;
  923. }
  924. }
  925. }
  926. return false;
  927. }
  928. void expectIdletimerInterfaceRuleExists(const std::string& ifname, int timeout,
  929. const std::string& classLabel) {
  930. std::string IdletimerRule =
  931. StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
  932. for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
  933. EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
  934. IdletimerRule, RAW_TABLE));
  935. EXPECT_TRUE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
  936. ifname, IdletimerRule, MANGLE_TABLE));
  937. }
  938. }
  939. void expectIdletimerInterfaceRuleNotExists(const std::string& ifname, int timeout,
  940. const std::string& classLabel) {
  941. std::string IdletimerRule =
  942. StringPrintf("timeout:%u label:%s send_nl_msg:1", timeout, classLabel.c_str());
  943. for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
  944. EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_RAW_PREROUTING, ifname,
  945. IdletimerRule, RAW_TABLE));
  946. EXPECT_FALSE(iptablesIdleTimerInterfaceRuleExists(binary, IDLETIMER_MANGLE_POSTROUTING,
  947. ifname, IdletimerRule, MANGLE_TABLE));
  948. }
  949. }
  950. } // namespace
  951. TEST_F(BinderTest, IdletimerAddRemoveInterface) {
  952. // TODO: We will get error in if expectIdletimerInterfaceRuleNotExists if there are the same
  953. // rule in the table. Because we only check the result after calling remove function. We might
  954. // check the actual rule which is removed by our function (maybe compare the results between
  955. // calling function before and after)
  956. binder::Status status;
  957. const struct TestData {
  958. const std::string ifname;
  959. int32_t timeout;
  960. const std::string classLabel;
  961. } idleTestData[] = {
  962. {"wlan0", 1234, "happyday"},
  963. {"rmnet_data0", 4567, "friday"},
  964. };
  965. for (const auto& td : idleTestData) {
  966. status = mNetd->idletimerAddInterface(td.ifname, td.timeout, td.classLabel);
  967. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  968. expectIdletimerInterfaceRuleExists(td.ifname, td.timeout, td.classLabel);
  969. status = mNetd->idletimerRemoveInterface(td.ifname, td.timeout, td.classLabel);
  970. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  971. expectIdletimerInterfaceRuleNotExists(td.ifname, td.timeout, td.classLabel);
  972. }
  973. }
  974. namespace {
  975. constexpr char STRICT_OUTPUT[] = "st_OUTPUT";
  976. constexpr char STRICT_CLEAR_CAUGHT[] = "st_clear_caught";
  977. void expectStrictSetUidAccept(const int uid) {
  978. std::string uidRule = StringPrintf("owner UID match %u", uid);
  979. std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
  980. for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
  981. EXPECT_FALSE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
  982. EXPECT_FALSE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
  983. EXPECT_EQ(0, iptablesRuleLineLength(binary, perUidChain.c_str()));
  984. }
  985. }
  986. void expectStrictSetUidLog(const int uid) {
  987. static const char logRule[] = "st_penalty_log all";
  988. std::string uidRule = StringPrintf("owner UID match %u", uid);
  989. std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
  990. for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
  991. EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
  992. EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
  993. EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), logRule));
  994. }
  995. }
  996. void expectStrictSetUidReject(const int uid) {
  997. static const char rejectRule[] = "st_penalty_reject all";
  998. std::string uidRule = StringPrintf("owner UID match %u", uid);
  999. std::string perUidChain = StringPrintf("st_clear_caught_%u", uid);
  1000. for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
  1001. EXPECT_TRUE(iptablesRuleExists(binary, STRICT_OUTPUT, uidRule));
  1002. EXPECT_TRUE(iptablesRuleExists(binary, STRICT_CLEAR_CAUGHT, uidRule));
  1003. EXPECT_TRUE(iptablesRuleExists(binary, perUidChain.c_str(), rejectRule));
  1004. }
  1005. }
  1006. } // namespace
  1007. TEST_F(BinderTest, StrictSetUidCleartextPenalty) {
  1008. binder::Status status;
  1009. int32_t uid = randomUid();
  1010. // setUidCleartextPenalty Policy:Log with randomUid
  1011. status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_LOG);
  1012. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1013. expectStrictSetUidLog(uid);
  1014. // setUidCleartextPenalty Policy:Accept with randomUid
  1015. status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
  1016. expectStrictSetUidAccept(uid);
  1017. // setUidCleartextPenalty Policy:Reject with randomUid
  1018. status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_REJECT);
  1019. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1020. expectStrictSetUidReject(uid);
  1021. // setUidCleartextPenalty Policy:Accept with randomUid
  1022. status = mNetd->strictUidCleartextPenalty(uid, INetd::PENALTY_POLICY_ACCEPT);
  1023. expectStrictSetUidAccept(uid);
  1024. // test wrong policy
  1025. int32_t wrongPolicy = -123;
  1026. status = mNetd->strictUidCleartextPenalty(uid, wrongPolicy);
  1027. EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
  1028. }
  1029. namespace {
  1030. std::vector<std::string> tryToFindProcesses(const std::string& processName, uint32_t maxTries = 1,
  1031. uint32_t intervalMs = 50) {
  1032. // Output looks like:(clatd)
  1033. // clat 4963 850 1 12:16:51 ? 00:00:00 clatd-netd10a88 -i netd10a88 ...
  1034. // ...
  1035. // root 5221 5219 0 12:18:12 ? 00:00:00 sh -c ps -Af | grep ' clatd-netdcc1a0'
  1036. // (dnsmasq)
  1037. // dns_tether 4620 792 0 16:51:28 ? 00:00:00 dnsmasq --keep-in-foreground ...
  1038. if (maxTries == 0) return {};
  1039. std::string cmd = StringPrintf("ps -Af | grep '[0-9] %s'", processName.c_str());
  1040. std::vector<std::string> result;
  1041. for (uint32_t run = 1;;) {
  1042. result = runCommand(cmd);
  1043. if (result.size() || ++run > maxTries) {
  1044. break;
  1045. }
  1046. usleep(intervalMs * 1000);
  1047. }
  1048. return result;
  1049. }
  1050. void expectProcessExists(const std::string& processName) {
  1051. EXPECT_EQ(1U, tryToFindProcesses(processName, 5 /*maxTries*/).size());
  1052. }
  1053. void expectProcessDoesNotExist(const std::string& processName) {
  1054. EXPECT_FALSE(tryToFindProcesses(processName).size());
  1055. }
  1056. } // namespace
  1057. TEST_F(BinderTest, ClatdStartStop) {
  1058. binder::Status status;
  1059. const std::string clatdName = StringPrintf("clatd-%s", sTun.name().c_str());
  1060. std::string clatAddress;
  1061. std::string nat64Prefix = "2001:db8:cafe:f00d:1:2::/96";
  1062. // Can't start clatd on an interface that's not part of any network...
  1063. status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
  1064. EXPECT_FALSE(status.isOk());
  1065. EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
  1066. // ... so create a test physical network and add our tun to it.
  1067. EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
  1068. EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
  1069. // Prefix must be 96 bits long.
  1070. status = mNetd->clatdStart(sTun.name(), "2001:db8:cafe:f00d::/64", &clatAddress);
  1071. EXPECT_FALSE(status.isOk());
  1072. EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
  1073. // Can't start clatd unless there's a default route...
  1074. status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
  1075. EXPECT_FALSE(status.isOk());
  1076. EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
  1077. // so add a default route.
  1078. EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
  1079. // Can't start clatd unless there's a global address...
  1080. status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
  1081. EXPECT_FALSE(status.isOk());
  1082. EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
  1083. // ... so add a global address.
  1084. const std::string v6 = "2001:db8:1:2:f076:ae99:124e:aa99";
  1085. EXPECT_EQ(0, sTun.addAddress(v6.c_str(), 64));
  1086. // Now expect clatd to start successfully.
  1087. status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
  1088. EXPECT_TRUE(status.isOk());
  1089. EXPECT_EQ(0, status.serviceSpecificErrorCode());
  1090. // Starting it again returns EBUSY.
  1091. status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
  1092. EXPECT_FALSE(status.isOk());
  1093. EXPECT_EQ(EBUSY, status.serviceSpecificErrorCode());
  1094. expectProcessExists(clatdName);
  1095. // Expect clatd to stop successfully.
  1096. status = mNetd->clatdStop(sTun.name());
  1097. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1098. expectProcessDoesNotExist(clatdName);
  1099. // Stopping a clatd that doesn't exist returns ENODEV.
  1100. status = mNetd->clatdStop(sTun.name());
  1101. EXPECT_FALSE(status.isOk());
  1102. EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
  1103. expectProcessDoesNotExist(clatdName);
  1104. // Clean up.
  1105. EXPECT_TRUE(mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
  1106. EXPECT_EQ(0, ifc_del_address(sTun.name().c_str(), v6.c_str(), 64));
  1107. EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
  1108. }
  1109. namespace {
  1110. bool getIpfwdV4Enable() {
  1111. static const char ipv4IpfwdCmd[] = "cat /proc/sys/net/ipv4/ip_forward";
  1112. std::vector<std::string> result = runCommand(ipv4IpfwdCmd);
  1113. EXPECT_TRUE(!result.empty());
  1114. int v4Enable = std::stoi(result[0]);
  1115. return v4Enable;
  1116. }
  1117. bool getIpfwdV6Enable() {
  1118. static const char ipv6IpfwdCmd[] = "cat /proc/sys/net/ipv6/conf/all/forwarding";
  1119. std::vector<std::string> result = runCommand(ipv6IpfwdCmd);
  1120. EXPECT_TRUE(!result.empty());
  1121. int v6Enable = std::stoi(result[0]);
  1122. return v6Enable;
  1123. }
  1124. void expectIpfwdEnable(bool enable) {
  1125. int enableIPv4 = getIpfwdV4Enable();
  1126. int enableIPv6 = getIpfwdV6Enable();
  1127. EXPECT_EQ(enable, enableIPv4);
  1128. EXPECT_EQ(enable, enableIPv6);
  1129. }
  1130. bool ipRuleIpfwdExists(const char* ipVersion, const std::string& ipfwdRule) {
  1131. std::vector<std::string> rules = listIpRules(ipVersion);
  1132. for (const auto& rule : rules) {
  1133. if (rule.find(ipfwdRule) != std::string::npos) {
  1134. return true;
  1135. }
  1136. }
  1137. return false;
  1138. }
  1139. void expectIpfwdRuleExists(const char* fromIf, const char* toIf) {
  1140. std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
  1141. for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
  1142. EXPECT_TRUE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
  1143. }
  1144. }
  1145. void expectIpfwdRuleNotExists(const char* fromIf, const char* toIf) {
  1146. std::string ipfwdRule = StringPrintf("18000:\tfrom all iif %s lookup %s ", fromIf, toIf);
  1147. for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
  1148. EXPECT_FALSE(ipRuleIpfwdExists(ipVersion, ipfwdRule));
  1149. }
  1150. }
  1151. } // namespace
  1152. TEST_F(BinderTest, TestIpfwdEnableDisableStatusForwarding) {
  1153. // Get ipfwd requester list from Netd
  1154. std::vector<std::string> requesterList;
  1155. binder::Status status = mNetd->ipfwdGetRequesterList(&requesterList);
  1156. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1157. bool ipfwdEnabled;
  1158. if (requesterList.size() == 0) {
  1159. // No requester in Netd, ipfwd should be disabled
  1160. // So add one test requester and verify
  1161. status = mNetd->ipfwdEnableForwarding("TestRequester");
  1162. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1163. expectIpfwdEnable(true);
  1164. status = mNetd->ipfwdEnabled(&ipfwdEnabled);
  1165. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1166. EXPECT_TRUE(ipfwdEnabled);
  1167. // Remove test one, verify again
  1168. status = mNetd->ipfwdDisableForwarding("TestRequester");
  1169. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1170. expectIpfwdEnable(false);
  1171. status = mNetd->ipfwdEnabled(&ipfwdEnabled);
  1172. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1173. EXPECT_FALSE(ipfwdEnabled);
  1174. } else {
  1175. // Disable all requesters
  1176. for (const auto& requester : requesterList) {
  1177. status = mNetd->ipfwdDisableForwarding(requester);
  1178. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1179. }
  1180. // After disable all requester, ipfwd should be disabled
  1181. expectIpfwdEnable(false);
  1182. status = mNetd->ipfwdEnabled(&ipfwdEnabled);
  1183. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1184. EXPECT_FALSE(ipfwdEnabled);
  1185. // Enable them back
  1186. for (const auto& requester : requesterList) {
  1187. status = mNetd->ipfwdEnableForwarding(requester);
  1188. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1189. }
  1190. // ipfwd should be enabled
  1191. expectIpfwdEnable(true);
  1192. status = mNetd->ipfwdEnabled(&ipfwdEnabled);
  1193. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1194. EXPECT_TRUE(ipfwdEnabled);
  1195. }
  1196. }
  1197. TEST_F(BinderTest, TestIpfwdAddRemoveInterfaceForward) {
  1198. // Add test physical network
  1199. EXPECT_TRUE(
  1200. mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
  1201. EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
  1202. EXPECT_TRUE(
  1203. mNetd->networkCreatePhysical(TEST_NETID2, INetd::PERMISSION_NONE).isOk());
  1204. EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID2, sTun2.name()).isOk());
  1205. binder::Status status =
  1206. mNetd->ipfwdAddInterfaceForward(sTun.name(), sTun2.name());
  1207. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1208. expectIpfwdRuleExists(sTun.name().c_str(), sTun2.name().c_str());
  1209. status = mNetd->ipfwdRemoveInterfaceForward(sTun.name(), sTun2.name());
  1210. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1211. expectIpfwdRuleNotExists(sTun.name().c_str(), sTun2.name().c_str());
  1212. }
  1213. namespace {
  1214. constexpr char BANDWIDTH_INPUT[] = "bw_INPUT";
  1215. constexpr char BANDWIDTH_OUTPUT[] = "bw_OUTPUT";
  1216. constexpr char BANDWIDTH_FORWARD[] = "bw_FORWARD";
  1217. constexpr char BANDWIDTH_NAUGHTY[] = "bw_penalty_box";
  1218. constexpr char BANDWIDTH_NICE[] = "bw_happy_box";
  1219. constexpr char BANDWIDTH_ALERT[] = "bw_global_alert";
  1220. // TODO: Move iptablesTargetsExists and listIptablesRuleByTable to the top.
  1221. // Use either a std::vector<std::string> of things to match, or a variadic function.
  1222. bool iptablesTargetsExists(const char* binary, int expectedCount, const char* table,
  1223. const char* chainName, const std::string& expectedTargetA,
  1224. const std::string& expectedTargetB) {
  1225. std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
  1226. int matchCount = 0;
  1227. for (const auto& rule : rules) {
  1228. if (rule.find(expectedTargetA) != std::string::npos) {
  1229. if (rule.find(expectedTargetB) != std::string::npos) {
  1230. matchCount++;
  1231. }
  1232. }
  1233. }
  1234. return matchCount == expectedCount;
  1235. }
  1236. void expectXtQuotaValueEqual(const char* ifname, long quotaBytes) {
  1237. std::string path = StringPrintf("/proc/net/xt_quota/%s", ifname);
  1238. std::string result = "";
  1239. EXPECT_TRUE(ReadFileToString(path, &result));
  1240. // Quota value might be decreased while matching packets
  1241. EXPECT_GE(quotaBytes, std::stol(Trim(result)));
  1242. }
  1243. void expectBandwidthInterfaceQuotaRuleExists(const char* ifname, long quotaBytes) {
  1244. std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
  1245. std::string quotaRule = StringPrintf("quota %s", ifname);
  1246. for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
  1247. EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
  1248. BANDWIDTH_COSTLY_IF));
  1249. EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
  1250. BANDWIDTH_COSTLY_IF));
  1251. EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
  1252. BANDWIDTH_COSTLY_IF));
  1253. EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
  1254. EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
  1255. }
  1256. expectXtQuotaValueEqual(ifname, quotaBytes);
  1257. }
  1258. void expectBandwidthInterfaceQuotaRuleDoesNotExist(const char* ifname) {
  1259. std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
  1260. std::string quotaRule = StringPrintf("quota %s", ifname);
  1261. for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
  1262. EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_INPUT, ifname,
  1263. BANDWIDTH_COSTLY_IF));
  1264. EXPECT_FALSE(iptablesTargetsExists(binary, 1, FILTER_TABLE, BANDWIDTH_OUTPUT, ifname,
  1265. BANDWIDTH_COSTLY_IF));
  1266. EXPECT_FALSE(iptablesTargetsExists(binary, 2, FILTER_TABLE, BANDWIDTH_FORWARD, ifname,
  1267. BANDWIDTH_COSTLY_IF));
  1268. EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), BANDWIDTH_NAUGHTY));
  1269. EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), quotaRule));
  1270. }
  1271. }
  1272. void expectBandwidthInterfaceAlertRuleExists(const char* ifname, long alertBytes) {
  1273. std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
  1274. std::string alertRule = StringPrintf("quota %sAlert", ifname);
  1275. std::string alertName = StringPrintf("%sAlert", ifname);
  1276. for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
  1277. EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
  1278. }
  1279. expectXtQuotaValueEqual(alertName.c_str(), alertBytes);
  1280. }
  1281. void expectBandwidthInterfaceAlertRuleDoesNotExist(const char* ifname) {
  1282. std::string BANDWIDTH_COSTLY_IF = StringPrintf("bw_costly_%s", ifname);
  1283. std::string alertRule = StringPrintf("quota %sAlert", ifname);
  1284. for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
  1285. EXPECT_FALSE(iptablesRuleExists(binary, BANDWIDTH_COSTLY_IF.c_str(), alertRule));
  1286. }
  1287. }
  1288. void expectBandwidthGlobalAlertRuleExists(long alertBytes) {
  1289. static const char globalAlertRule[] = "quota globalAlert";
  1290. static const char globalAlertName[] = "globalAlert";
  1291. for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
  1292. EXPECT_TRUE(iptablesRuleExists(binary, BANDWIDTH_ALERT, globalAlertRule));
  1293. }
  1294. expectXtQuotaValueEqual(globalAlertName, alertBytes);
  1295. }
  1296. void expectBandwidthManipulateSpecialAppRuleExists(const char* chain, const char* target, int uid) {
  1297. std::string uidRule = StringPrintf("owner UID match %u", uid);
  1298. for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
  1299. EXPECT_TRUE(iptablesTargetsExists(binary, 1, FILTER_TABLE, chain, target, uidRule));
  1300. }
  1301. }
  1302. void expectBandwidthManipulateSpecialAppRuleDoesNotExist(const char* chain, int uid) {
  1303. std::string uidRule = StringPrintf("owner UID match %u", uid);
  1304. for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
  1305. EXPECT_FALSE(iptablesRuleExists(binary, chain, uidRule));
  1306. }
  1307. }
  1308. } // namespace
  1309. TEST_F(BinderTest, BandwidthSetRemoveInterfaceQuota) {
  1310. long testQuotaBytes = 5550;
  1311. // Add test physical network
  1312. EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
  1313. EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
  1314. binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testQuotaBytes);
  1315. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1316. expectBandwidthInterfaceQuotaRuleExists(sTun.name().c_str(), testQuotaBytes);
  1317. status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
  1318. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1319. expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
  1320. // Remove test physical network
  1321. EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
  1322. }
  1323. TEST_F(BinderTest, BandwidthSetRemoveInterfaceAlert) {
  1324. long testAlertBytes = 373;
  1325. // Add test physical network
  1326. EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
  1327. EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
  1328. // Need to have a prior interface quota set to set an alert
  1329. binder::Status status = mNetd->bandwidthSetInterfaceQuota(sTun.name(), testAlertBytes);
  1330. status = mNetd->bandwidthSetInterfaceAlert(sTun.name(), testAlertBytes);
  1331. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1332. expectBandwidthInterfaceAlertRuleExists(sTun.name().c_str(), testAlertBytes);
  1333. status = mNetd->bandwidthRemoveInterfaceAlert(sTun.name());
  1334. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1335. expectBandwidthInterfaceAlertRuleDoesNotExist(sTun.name().c_str());
  1336. // Remove interface quota
  1337. status = mNetd->bandwidthRemoveInterfaceQuota(sTun.name());
  1338. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1339. expectBandwidthInterfaceQuotaRuleDoesNotExist(sTun.name().c_str());
  1340. // Remove test physical network
  1341. EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
  1342. }
  1343. TEST_F(BinderTest, BandwidthSetGlobalAlert) {
  1344. long testAlertBytes = 2097149;
  1345. binder::Status status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
  1346. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1347. expectBandwidthGlobalAlertRuleExists(testAlertBytes);
  1348. testAlertBytes = 2097152;
  1349. status = mNetd->bandwidthSetGlobalAlert(testAlertBytes);
  1350. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1351. expectBandwidthGlobalAlertRuleExists(testAlertBytes);
  1352. }
  1353. TEST_F(BinderTest, BandwidthManipulateSpecialApp) {
  1354. SKIP_IF_BPF_SUPPORTED;
  1355. int32_t uid = randomUid();
  1356. static const char targetReject[] = "REJECT";
  1357. static const char targetReturn[] = "RETURN";
  1358. // add NaughtyApp
  1359. binder::Status status = mNetd->bandwidthAddNaughtyApp(uid);
  1360. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1361. expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NAUGHTY, targetReject, uid);
  1362. // remove NaughtyApp
  1363. status = mNetd->bandwidthRemoveNaughtyApp(uid);
  1364. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1365. expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NAUGHTY, uid);
  1366. // add NiceApp
  1367. status = mNetd->bandwidthAddNiceApp(uid);
  1368. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1369. expectBandwidthManipulateSpecialAppRuleExists(BANDWIDTH_NICE, targetReturn, uid);
  1370. // remove NiceApp
  1371. status = mNetd->bandwidthRemoveNiceApp(uid);
  1372. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1373. expectBandwidthManipulateSpecialAppRuleDoesNotExist(BANDWIDTH_NICE, uid);
  1374. }
  1375. namespace {
  1376. std::vector<std::string> listIpRoutes(const char* ipVersion, const char* table) {
  1377. std::string command = StringPrintf("%s %s route ls table %s", IP_PATH, ipVersion, table);
  1378. return runCommand(command);
  1379. }
  1380. bool ipRouteExists(const char* ipVersion, const char* table, const std::string& ipRoute) {
  1381. std::vector<std::string> routes = listIpRoutes(ipVersion, table);
  1382. for (const auto& route : routes) {
  1383. if (route.find(ipRoute) != std::string::npos) {
  1384. return true;
  1385. }
  1386. }
  1387. return false;
  1388. }
  1389. std::string ipRouteString(const std::string& ifName, const std::string& dst,
  1390. const std::string& nextHop) {
  1391. std::string dstString = (dst == "0.0.0.0/0" || dst == "::/0") ? "default" : dst;
  1392. if (!nextHop.empty()) {
  1393. dstString += " via " + nextHop;
  1394. }
  1395. return dstString + " dev " + ifName;
  1396. }
  1397. void expectNetworkRouteExists(const char* ipVersion, const std::string& ifName,
  1398. const std::string& dst, const std::string& nextHop,
  1399. const char* table) {
  1400. EXPECT_TRUE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
  1401. }
  1402. void expectNetworkRouteDoesNotExist(const char* ipVersion, const std::string& ifName,
  1403. const std::string& dst, const std::string& nextHop,
  1404. const char* table) {
  1405. EXPECT_FALSE(ipRouteExists(ipVersion, table, ipRouteString(ifName, dst, nextHop)));
  1406. }
  1407. bool ipRuleExists(const char* ipVersion, const std::string& ipRule) {
  1408. std::vector<std::string> rules = listIpRules(ipVersion);
  1409. for (const auto& rule : rules) {
  1410. if (rule.find(ipRule) != std::string::npos) {
  1411. return true;
  1412. }
  1413. }
  1414. return false;
  1415. }
  1416. void expectNetworkDefaultIpRuleExists(const char* ifName) {
  1417. std::string networkDefaultRule =
  1418. StringPrintf("22000:\tfrom all fwmark 0x0/0xffff iif lo lookup %s", ifName);
  1419. for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
  1420. EXPECT_TRUE(ipRuleExists(ipVersion, networkDefaultRule));
  1421. }
  1422. }
  1423. void expectNetworkDefaultIpRuleDoesNotExist() {
  1424. static const char networkDefaultRule[] = "22000:\tfrom all fwmark 0x0/0xffff iif lo";
  1425. for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
  1426. EXPECT_FALSE(ipRuleExists(ipVersion, networkDefaultRule));
  1427. }
  1428. }
  1429. void expectNetworkPermissionIpRuleExists(const char* ifName, int permission) {
  1430. std::string networkPermissionRule = "";
  1431. switch (permission) {
  1432. case INetd::PERMISSION_NONE:
  1433. networkPermissionRule = StringPrintf(
  1434. "13000:\tfrom all fwmark 0x1ffdd/0x1ffff iif lo lookup %s", ifName);
  1435. break;
  1436. case INetd::PERMISSION_NETWORK:
  1437. networkPermissionRule = StringPrintf(
  1438. "13000:\tfrom all fwmark 0x5ffdd/0x5ffff iif lo lookup %s", ifName);
  1439. break;
  1440. case INetd::PERMISSION_SYSTEM:
  1441. networkPermissionRule = StringPrintf(
  1442. "13000:\tfrom all fwmark 0xdffdd/0xdffff iif lo lookup %s", ifName);
  1443. break;
  1444. }
  1445. for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
  1446. EXPECT_TRUE(ipRuleExists(ipVersion, networkPermissionRule));
  1447. }
  1448. }
  1449. // TODO: It is a duplicate function, need to remove it
  1450. bool iptablesNetworkPermissionIptablesRuleExists(const char* binary, const char* chainName,
  1451. const std::string& expectedInterface,
  1452. const std::string& expectedRule,
  1453. const char* table) {
  1454. std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
  1455. for (const auto& rule : rules) {
  1456. if (rule.find(expectedInterface) != std::string::npos) {
  1457. if (rule.find(expectedRule) != std::string::npos) {
  1458. return true;
  1459. }
  1460. }
  1461. }
  1462. return false;
  1463. }
  1464. void expectNetworkPermissionIptablesRuleExists(const char* ifName, int permission) {
  1465. static const char ROUTECTRL_INPUT[] = "routectrl_mangle_INPUT";
  1466. std::string networkIncomingPacketMarkRule = "";
  1467. switch (permission) {
  1468. case INetd::PERMISSION_NONE:
  1469. networkIncomingPacketMarkRule = "MARK xset 0x3ffdd/0xffefffff";
  1470. break;
  1471. case INetd::PERMISSION_NETWORK:
  1472. networkIncomingPacketMarkRule = "MARK xset 0x7ffdd/0xffefffff";
  1473. break;
  1474. case INetd::PERMISSION_SYSTEM:
  1475. networkIncomingPacketMarkRule = "MARK xset 0xfffdd/0xffefffff";
  1476. break;
  1477. }
  1478. for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
  1479. EXPECT_TRUE(iptablesNetworkPermissionIptablesRuleExists(
  1480. binary, ROUTECTRL_INPUT, ifName, networkIncomingPacketMarkRule, MANGLE_TABLE));
  1481. }
  1482. }
  1483. } // namespace
  1484. TEST_F(BinderTest, NetworkAddRemoveRouteUserPermission) {
  1485. static const struct {
  1486. const char* ipVersion;
  1487. const char* testDest;
  1488. const char* testNextHop;
  1489. const bool expectSuccess;
  1490. } kTestData[] = {
  1491. {IP_RULE_V4, "0.0.0.0/0", "", true},
  1492. {IP_RULE_V4, "0.0.0.0/0", "10.251.10.0", true},
  1493. {IP_RULE_V4, "10.251.0.0/16", "", true},
  1494. {IP_RULE_V4, "10.251.0.0/16", "10.251.10.0", true},
  1495. {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false},
  1496. {IP_RULE_V6, "::/0", "", true},
  1497. {IP_RULE_V6, "::/0", "2001:db8::", true},
  1498. {IP_RULE_V6, "2001:db8:cafe::/64", "2001:db8::", true},
  1499. {IP_RULE_V4, "fe80::/64", "0.0.0.0", false},
  1500. };
  1501. static const struct {
  1502. const char* ipVersion;
  1503. const char* testDest;
  1504. const char* testNextHop;
  1505. } kTestDataWithNextHop[] = {
  1506. {IP_RULE_V4, "10.251.10.0/30", ""},
  1507. {IP_RULE_V6, "2001:db8::/32", ""},
  1508. };
  1509. static const char testTableLegacySystem[] = "legacy_system";
  1510. static const char testTableLegacyNetwork[] = "legacy_network";
  1511. const int testUid = randomUid();
  1512. const std::vector<int32_t> testUids = {testUid};
  1513. // Add test physical network
  1514. EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
  1515. EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
  1516. // Setup route for testing nextHop
  1517. for (size_t i = 0; i < std::size(kTestDataWithNextHop); i++) {
  1518. const auto& td = kTestDataWithNextHop[i];
  1519. // All route for test tun will disappear once the tun interface is deleted.
  1520. binder::Status status =
  1521. mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
  1522. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1523. expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
  1524. sTun.name().c_str());
  1525. // Add system permission for test uid, setup route in legacy system table.
  1526. EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
  1527. status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
  1528. testUid);
  1529. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1530. expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
  1531. testTableLegacySystem);
  1532. // Remove system permission for test uid, setup route in legacy network table.
  1533. EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
  1534. status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
  1535. testUid);
  1536. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1537. expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
  1538. testTableLegacyNetwork);
  1539. }
  1540. for (size_t i = 0; i < std::size(kTestData); i++) {
  1541. const auto& td = kTestData[i];
  1542. binder::Status status =
  1543. mNetd->networkAddRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
  1544. if (td.expectSuccess) {
  1545. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1546. expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
  1547. sTun.name().c_str());
  1548. } else {
  1549. EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
  1550. EXPECT_NE(0, status.serviceSpecificErrorCode());
  1551. }
  1552. status = mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop);
  1553. if (td.expectSuccess) {
  1554. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1555. expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
  1556. sTun.name().c_str());
  1557. } else {
  1558. EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
  1559. EXPECT_NE(0, status.serviceSpecificErrorCode());
  1560. }
  1561. // Add system permission for test uid, route will be added into legacy system table.
  1562. EXPECT_TRUE(mNetd->networkSetPermissionForUser(INetd::PERMISSION_SYSTEM, testUids).isOk());
  1563. status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
  1564. testUid);
  1565. if (td.expectSuccess) {
  1566. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1567. expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
  1568. testTableLegacySystem);
  1569. } else {
  1570. EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
  1571. EXPECT_NE(0, status.serviceSpecificErrorCode());
  1572. }
  1573. status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
  1574. td.testNextHop, testUid);
  1575. if (td.expectSuccess) {
  1576. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1577. expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
  1578. testTableLegacySystem);
  1579. } else {
  1580. EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
  1581. EXPECT_NE(0, status.serviceSpecificErrorCode());
  1582. }
  1583. // Remove system permission for test uid, route will be added into legacy network table.
  1584. EXPECT_TRUE(mNetd->networkClearPermissionForUser(testUids).isOk());
  1585. status = mNetd->networkAddLegacyRoute(TEST_NETID1, sTun.name(), td.testDest, td.testNextHop,
  1586. testUid);
  1587. if (td.expectSuccess) {
  1588. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1589. expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
  1590. testTableLegacyNetwork);
  1591. } else {
  1592. EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
  1593. EXPECT_NE(0, status.serviceSpecificErrorCode());
  1594. }
  1595. status = mNetd->networkRemoveLegacyRoute(TEST_NETID1, sTun.name(), td.testDest,
  1596. td.testNextHop, testUid);
  1597. if (td.expectSuccess) {
  1598. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1599. expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
  1600. testTableLegacyNetwork);
  1601. } else {
  1602. EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
  1603. EXPECT_NE(0, status.serviceSpecificErrorCode());
  1604. }
  1605. }
  1606. // Remove test physical network
  1607. EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
  1608. }
  1609. TEST_F(BinderTest, NetworkPermissionDefault) {
  1610. // Add test physical network
  1611. EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
  1612. EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
  1613. // Get current default network NetId
  1614. binder::Status status = mNetd->networkGetDefault(&mStoredDefaultNetwork);
  1615. ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
  1616. // Test SetDefault
  1617. status = mNetd->networkSetDefault(TEST_NETID1);
  1618. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1619. expectNetworkDefaultIpRuleExists(sTun.name().c_str());
  1620. status = mNetd->networkClearDefault();
  1621. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1622. expectNetworkDefaultIpRuleDoesNotExist();
  1623. // Set default network back
  1624. status = mNetd->networkSetDefault(mStoredDefaultNetwork);
  1625. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1626. // Test SetPermission
  1627. status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_SYSTEM);
  1628. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1629. expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
  1630. expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_SYSTEM);
  1631. status = mNetd->networkSetPermissionForNetwork(TEST_NETID1, INetd::PERMISSION_NONE);
  1632. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1633. expectNetworkPermissionIpRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
  1634. expectNetworkPermissionIptablesRuleExists(sTun.name().c_str(), INetd::PERMISSION_NONE);
  1635. // Remove test physical network
  1636. EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
  1637. }
  1638. TEST_F(BinderTest, NetworkSetProtectAllowDeny) {
  1639. const int testUid = randomUid();
  1640. binder::Status status = mNetd->networkSetProtectAllow(testUid);
  1641. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1642. bool ret = false;
  1643. status = mNetd->networkCanProtect(testUid, &ret);
  1644. EXPECT_TRUE(ret);
  1645. status = mNetd->networkSetProtectDeny(testUid);
  1646. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1647. status = mNetd->networkCanProtect(testUid, &ret);
  1648. EXPECT_FALSE(ret);
  1649. }
  1650. namespace {
  1651. int readIntFromPath(const std::string& path) {
  1652. std::string result = "";
  1653. EXPECT_TRUE(ReadFileToString(path, &result));
  1654. return std::stoi(result);
  1655. }
  1656. int getTetherAcceptIPv6Ra(const std::string& ifName) {
  1657. std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_ra", ifName.c_str());
  1658. return readIntFromPath(path);
  1659. }
  1660. bool getTetherAcceptIPv6Dad(const std::string& ifName) {
  1661. std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/accept_dad", ifName.c_str());
  1662. return readIntFromPath(path);
  1663. }
  1664. int getTetherIPv6DadTransmits(const std::string& ifName) {
  1665. std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/dad_transmits", ifName.c_str());
  1666. return readIntFromPath(path);
  1667. }
  1668. bool getTetherEnableIPv6(const std::string& ifName) {
  1669. std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
  1670. int disableIPv6 = readIntFromPath(path);
  1671. return !disableIPv6;
  1672. }
  1673. bool interfaceListContains(const std::vector<std::string>& ifList, const std::string& ifName) {
  1674. for (const auto& iface : ifList) {
  1675. if (iface == ifName) {
  1676. return true;
  1677. }
  1678. }
  1679. return false;
  1680. }
  1681. void expectTetherInterfaceConfigureForIPv6Router(const std::string& ifName) {
  1682. EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 0);
  1683. EXPECT_FALSE(getTetherAcceptIPv6Dad(ifName));
  1684. EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 0);
  1685. EXPECT_TRUE(getTetherEnableIPv6(ifName));
  1686. }
  1687. void expectTetherInterfaceConfigureForIPv6Client(const std::string& ifName) {
  1688. EXPECT_EQ(getTetherAcceptIPv6Ra(ifName), 2);
  1689. EXPECT_TRUE(getTetherAcceptIPv6Dad(ifName));
  1690. EXPECT_EQ(getTetherIPv6DadTransmits(ifName), 1);
  1691. EXPECT_FALSE(getTetherEnableIPv6(ifName));
  1692. }
  1693. void expectTetherInterfaceExists(const std::vector<std::string>& ifList,
  1694. const std::string& ifName) {
  1695. EXPECT_TRUE(interfaceListContains(ifList, ifName));
  1696. }
  1697. void expectTetherInterfaceNotExists(const std::vector<std::string>& ifList,
  1698. const std::string& ifName) {
  1699. EXPECT_FALSE(interfaceListContains(ifList, ifName));
  1700. }
  1701. void expectTetherDnsListEquals(const std::vector<std::string>& dnsList,
  1702. const std::vector<std::string>& testDnsAddrs) {
  1703. EXPECT_TRUE(dnsList == testDnsAddrs);
  1704. }
  1705. } // namespace
  1706. TEST_F(BinderTest, TetherStartStopStatus) {
  1707. std::vector<std::string> noDhcpRange = {};
  1708. static const char dnsdName[] = "dnsmasq";
  1709. binder::Status status = mNetd->tetherStart(noDhcpRange);
  1710. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1711. expectProcessExists(dnsdName);
  1712. bool tetherEnabled;
  1713. status = mNetd->tetherIsEnabled(&tetherEnabled);
  1714. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1715. EXPECT_TRUE(tetherEnabled);
  1716. status = mNetd->tetherStop();
  1717. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1718. expectProcessDoesNotExist(dnsdName);
  1719. status = mNetd->tetherIsEnabled(&tetherEnabled);
  1720. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1721. EXPECT_FALSE(tetherEnabled);
  1722. }
  1723. TEST_F(BinderTest, TetherInterfaceAddRemoveList) {
  1724. // TODO: verify if dnsmasq update interface successfully
  1725. binder::Status status = mNetd->tetherInterfaceAdd(sTun.name());
  1726. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1727. expectTetherInterfaceConfigureForIPv6Router(sTun.name());
  1728. std::vector<std::string> ifList;
  1729. status = mNetd->tetherInterfaceList(&ifList);
  1730. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1731. expectTetherInterfaceExists(ifList, sTun.name());
  1732. status = mNetd->tetherInterfaceRemove(sTun.name());
  1733. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1734. expectTetherInterfaceConfigureForIPv6Client(sTun.name());
  1735. status = mNetd->tetherInterfaceList(&ifList);
  1736. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1737. expectTetherInterfaceNotExists(ifList, sTun.name());
  1738. }
  1739. TEST_F(BinderTest, TetherDnsSetList) {
  1740. // TODO: verify if dnsmasq update dns successfully
  1741. std::vector<std::string> testDnsAddrs = {"192.168.1.37", "213.137.100.3",
  1742. "fe80::1%" + sTun.name()};
  1743. binder::Status status = mNetd->tetherDnsSet(TEST_NETID1, testDnsAddrs);
  1744. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1745. std::vector<std::string> dnsList;
  1746. status = mNetd->tetherDnsList(&dnsList);
  1747. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1748. expectTetherDnsListEquals(dnsList, testDnsAddrs);
  1749. }
  1750. namespace {
  1751. constexpr char FIREWALL_INPUT[] = "fw_INPUT";
  1752. constexpr char FIREWALL_OUTPUT[] = "fw_OUTPUT";
  1753. constexpr char FIREWALL_FORWARD[] = "fw_FORWARD";
  1754. constexpr char FIREWALL_DOZABLE[] = "fw_dozable";
  1755. constexpr char FIREWALL_POWERSAVE[] = "fw_powersave";
  1756. constexpr char FIREWALL_STANDBY[] = "fw_standby";
  1757. constexpr char targetReturn[] = "RETURN";
  1758. constexpr char targetDrop[] = "DROP";
  1759. void expectFirewallWhitelistMode() {
  1760. static const char dropRule[] = "DROP all";
  1761. static const char rejectRule[] = "REJECT all";
  1762. for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
  1763. EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_INPUT, dropRule));
  1764. EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_OUTPUT, rejectRule));
  1765. EXPECT_TRUE(iptablesRuleExists(binary, FIREWALL_FORWARD, rejectRule));
  1766. }
  1767. }
  1768. void expectFirewallBlacklistMode() {
  1769. for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
  1770. EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_INPUT));
  1771. EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_OUTPUT));
  1772. EXPECT_EQ(2, iptablesRuleLineLength(binary, FIREWALL_FORWARD));
  1773. }
  1774. }
  1775. bool iptablesFirewallInterfaceFirstRuleExists(const char* binary, const char* chainName,
  1776. const std::string& expectedInterface,
  1777. const std::string& expectedRule) {
  1778. std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
  1779. // Expected rule:
  1780. // Chain fw_INPUT (1 references)
  1781. // pkts bytes target prot opt in out source destination
  1782. // 0 0 RETURN all -- expectedInterface * 0.0.0.0/0 0.0.0.0/0
  1783. // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
  1784. int firstRuleIndex = 2;
  1785. if (rules.size() < 4) return false;
  1786. if (rules[firstRuleIndex].find(expectedInterface) != std::string::npos) {
  1787. if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
  1788. return true;
  1789. }
  1790. }
  1791. return false;
  1792. }
  1793. // TODO: It is a duplicate function, need to remove it
  1794. bool iptablesFirewallInterfaceRuleExists(const char* binary, const char* chainName,
  1795. const std::string& expectedInterface,
  1796. const std::string& expectedRule) {
  1797. std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
  1798. for (const auto& rule : rules) {
  1799. if (rule.find(expectedInterface) != std::string::npos) {
  1800. if (rule.find(expectedRule) != std::string::npos) {
  1801. return true;
  1802. }
  1803. }
  1804. }
  1805. return false;
  1806. }
  1807. void expectFirewallInterfaceRuleAllowExists(const std::string& ifname) {
  1808. static const char returnRule[] = "RETURN all";
  1809. for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
  1810. EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_INPUT, ifname,
  1811. returnRule));
  1812. EXPECT_TRUE(iptablesFirewallInterfaceFirstRuleExists(binary, FIREWALL_OUTPUT, ifname,
  1813. returnRule));
  1814. }
  1815. }
  1816. void expectFireWallInterfaceRuleAllowDoesNotExist(const std::string& ifname) {
  1817. static const char returnRule[] = "RETURN all";
  1818. for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
  1819. EXPECT_FALSE(
  1820. iptablesFirewallInterfaceRuleExists(binary, FIREWALL_INPUT, ifname, returnRule));
  1821. EXPECT_FALSE(
  1822. iptablesFirewallInterfaceRuleExists(binary, FIREWALL_OUTPUT, ifname, returnRule));
  1823. }
  1824. }
  1825. bool iptablesFirewallUidFirstRuleExists(const char* binary, const char* chainName,
  1826. const std::string& expectedTarget,
  1827. const std::string& expectedRule) {
  1828. std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
  1829. int firstRuleIndex = 2;
  1830. if (rules.size() < 4) return false;
  1831. if (rules[firstRuleIndex].find(expectedTarget) != std::string::npos) {
  1832. if (rules[firstRuleIndex].find(expectedRule) != std::string::npos) {
  1833. return true;
  1834. }
  1835. }
  1836. return false;
  1837. }
  1838. bool iptablesFirewallUidLastRuleExists(const char* binary, const char* chainName,
  1839. const std::string& expectedTarget,
  1840. const std::string& expectedRule) {
  1841. std::vector<std::string> rules = listIptablesRuleByTable(binary, FILTER_TABLE, chainName);
  1842. int lastRuleIndex = rules.size() - 1;
  1843. if (lastRuleIndex < 0) return false;
  1844. if (rules[lastRuleIndex].find(expectedTarget) != std::string::npos) {
  1845. if (rules[lastRuleIndex].find(expectedRule) != std::string::npos) {
  1846. return true;
  1847. }
  1848. }
  1849. return false;
  1850. }
  1851. void expectFirewallUidFirstRuleExists(const char* chainName, int32_t uid) {
  1852. std::string uidRule = StringPrintf("owner UID match %u", uid);
  1853. for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
  1854. EXPECT_TRUE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
  1855. }
  1856. void expectFirewallUidFirstRuleDoesNotExist(const char* chainName, int32_t uid) {
  1857. std::string uidRule = StringPrintf("owner UID match %u", uid);
  1858. for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
  1859. EXPECT_FALSE(iptablesFirewallUidFirstRuleExists(binary, chainName, targetReturn, uidRule));
  1860. }
  1861. void expectFirewallUidLastRuleExists(const char* chainName, int32_t uid) {
  1862. std::string uidRule = StringPrintf("owner UID match %u", uid);
  1863. for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
  1864. EXPECT_TRUE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
  1865. }
  1866. void expectFirewallUidLastRuleDoesNotExist(const char* chainName, int32_t uid) {
  1867. std::string uidRule = StringPrintf("owner UID match %u", uid);
  1868. for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
  1869. EXPECT_FALSE(iptablesFirewallUidLastRuleExists(binary, chainName, targetDrop, uidRule));
  1870. }
  1871. bool iptablesFirewallChildChainsLastRuleExists(const char* binary, const char* chainName) {
  1872. std::vector<std::string> inputRules =
  1873. listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_INPUT);
  1874. std::vector<std::string> outputRules =
  1875. listIptablesRuleByTable(binary, FILTER_TABLE, FIREWALL_OUTPUT);
  1876. int inputLastRuleIndex = inputRules.size() - 1;
  1877. int outputLastRuleIndex = outputRules.size() - 1;
  1878. if (inputLastRuleIndex < 0 || outputLastRuleIndex < 0) return false;
  1879. if (inputRules[inputLastRuleIndex].find(chainName) != std::string::npos) {
  1880. if (outputRules[outputLastRuleIndex].find(chainName) != std::string::npos) {
  1881. return true;
  1882. }
  1883. }
  1884. return false;
  1885. }
  1886. void expectFirewallChildChainsLastRuleExists(const char* chainRule) {
  1887. for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH})
  1888. EXPECT_TRUE(iptablesFirewallChildChainsLastRuleExists(binary, chainRule));
  1889. }
  1890. void expectFirewallChildChainsLastRuleDoesNotExist(const char* chainRule) {
  1891. for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
  1892. EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_INPUT, chainRule));
  1893. EXPECT_FALSE(iptablesRuleExists(binary, FIREWALL_OUTPUT, chainRule));
  1894. }
  1895. }
  1896. } // namespace
  1897. TEST_F(BinderTest, FirewallSetFirewallType) {
  1898. binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
  1899. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1900. expectFirewallWhitelistMode();
  1901. status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
  1902. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1903. expectFirewallBlacklistMode();
  1904. // set firewall type blacklist twice
  1905. mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
  1906. status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
  1907. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1908. expectFirewallBlacklistMode();
  1909. // set firewall type whitelist twice
  1910. mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
  1911. status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
  1912. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1913. expectFirewallWhitelistMode();
  1914. // reset firewall type to default
  1915. status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
  1916. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1917. expectFirewallBlacklistMode();
  1918. }
  1919. TEST_F(BinderTest, FirewallSetInterfaceRule) {
  1920. // setinterfaceRule is not supported in BLACKLIST MODE
  1921. binder::Status status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
  1922. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1923. status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
  1924. EXPECT_FALSE(status.isOk()) << status.exceptionMessage();
  1925. // set WHITELIST mode first
  1926. status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
  1927. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1928. status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_ALLOW);
  1929. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1930. expectFirewallInterfaceRuleAllowExists(sTun.name());
  1931. status = mNetd->firewallSetInterfaceRule(sTun.name(), INetd::FIREWALL_RULE_DENY);
  1932. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1933. expectFireWallInterfaceRuleAllowDoesNotExist(sTun.name());
  1934. // reset firewall mode to default
  1935. status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
  1936. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1937. expectFirewallBlacklistMode();
  1938. }
  1939. TEST_F(BinderTest, FirewallSetUidRule) {
  1940. SKIP_IF_BPF_SUPPORTED;
  1941. int32_t uid = randomUid();
  1942. // Doze allow
  1943. binder::Status status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
  1944. INetd::FIREWALL_RULE_ALLOW);
  1945. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1946. expectFirewallUidFirstRuleExists(FIREWALL_DOZABLE, uid);
  1947. // Doze deny
  1948. status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_DOZABLE, uid,
  1949. INetd::FIREWALL_RULE_DENY);
  1950. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1951. expectFirewallUidFirstRuleDoesNotExist(FIREWALL_DOZABLE, uid);
  1952. // Powersave allow
  1953. status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
  1954. INetd::FIREWALL_RULE_ALLOW);
  1955. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1956. expectFirewallUidFirstRuleExists(FIREWALL_POWERSAVE, uid);
  1957. // Powersave deny
  1958. status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_POWERSAVE, uid,
  1959. INetd::FIREWALL_RULE_DENY);
  1960. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1961. expectFirewallUidFirstRuleDoesNotExist(FIREWALL_POWERSAVE, uid);
  1962. // Standby deny
  1963. status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
  1964. INetd::FIREWALL_RULE_DENY);
  1965. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1966. expectFirewallUidLastRuleExists(FIREWALL_STANDBY, uid);
  1967. // Standby allow
  1968. status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_STANDBY, uid,
  1969. INetd::FIREWALL_RULE_ALLOW);
  1970. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1971. expectFirewallUidLastRuleDoesNotExist(FIREWALL_STANDBY, uid);
  1972. // None deny in BLACKLIST
  1973. status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
  1974. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1975. expectFirewallUidLastRuleExists(FIREWALL_INPUT, uid);
  1976. expectFirewallUidLastRuleExists(FIREWALL_OUTPUT, uid);
  1977. // None allow in BLACKLIST
  1978. status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
  1979. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1980. expectFirewallUidLastRuleDoesNotExist(FIREWALL_INPUT, uid);
  1981. expectFirewallUidLastRuleDoesNotExist(FIREWALL_OUTPUT, uid);
  1982. // set firewall type whitelist twice
  1983. status = mNetd->firewallSetFirewallType(INetd::FIREWALL_WHITELIST);
  1984. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1985. expectFirewallWhitelistMode();
  1986. // None allow in WHITELIST
  1987. status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_ALLOW);
  1988. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1989. expectFirewallUidFirstRuleExists(FIREWALL_INPUT, uid);
  1990. expectFirewallUidFirstRuleExists(FIREWALL_OUTPUT, uid);
  1991. // None deny in WHITELIST
  1992. status = mNetd->firewallSetUidRule(INetd::FIREWALL_CHAIN_NONE, uid, INetd::FIREWALL_RULE_DENY);
  1993. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1994. expectFirewallUidFirstRuleDoesNotExist(FIREWALL_INPUT, uid);
  1995. expectFirewallUidFirstRuleDoesNotExist(FIREWALL_OUTPUT, uid);
  1996. // reset firewall mode to default
  1997. status = mNetd->firewallSetFirewallType(INetd::FIREWALL_BLACKLIST);
  1998. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  1999. expectFirewallBlacklistMode();
  2000. }
  2001. TEST_F(BinderTest, FirewallEnableDisableChildChains) {
  2002. SKIP_IF_BPF_SUPPORTED;
  2003. binder::Status status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, true);
  2004. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  2005. expectFirewallChildChainsLastRuleExists(FIREWALL_DOZABLE);
  2006. status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, true);
  2007. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  2008. expectFirewallChildChainsLastRuleExists(FIREWALL_STANDBY);
  2009. status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, true);
  2010. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  2011. expectFirewallChildChainsLastRuleExists(FIREWALL_POWERSAVE);
  2012. status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_DOZABLE, false);
  2013. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  2014. expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_DOZABLE);
  2015. status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_STANDBY, false);
  2016. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  2017. expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_STANDBY);
  2018. status = mNetd->firewallEnableChildChain(INetd::FIREWALL_CHAIN_POWERSAVE, false);
  2019. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  2020. expectFirewallChildChainsLastRuleDoesNotExist(FIREWALL_POWERSAVE);
  2021. }
  2022. namespace {
  2023. std::string hwAddrToStr(unsigned char* hwaddr) {
  2024. return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
  2025. hwaddr[4], hwaddr[5]);
  2026. }
  2027. int ipv4NetmaskToPrefixLength(in_addr_t mask) {
  2028. int prefixLength = 0;
  2029. uint32_t m = ntohl(mask);
  2030. while (m & (1 << 31)) {
  2031. prefixLength++;
  2032. m = m << 1;
  2033. }
  2034. return prefixLength;
  2035. }
  2036. std::string toStdString(const String16& s) {
  2037. return std::string(String8(s.string()));
  2038. }
  2039. android::netdutils::StatusOr<ifreq> ioctlByIfName(const std::string& ifName, unsigned long flag) {
  2040. const auto& sys = sSyscalls.get();
  2041. auto fd = sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
  2042. EXPECT_TRUE(isOk(fd.status()));
  2043. struct ifreq ifr = {};
  2044. strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
  2045. return sys.ioctl(fd.value(), flag, &ifr);
  2046. }
  2047. std::string getInterfaceHwAddr(const std::string& ifName) {
  2048. auto res = ioctlByIfName(ifName, SIOCGIFHWADDR);
  2049. unsigned char hwaddr[ETH_ALEN] = {};
  2050. if (isOk(res.status())) {
  2051. memcpy((void*) hwaddr, &res.value().ifr_hwaddr.sa_data, ETH_ALEN);
  2052. }
  2053. return hwAddrToStr(hwaddr);
  2054. }
  2055. int getInterfaceIPv4Prefix(const std::string& ifName) {
  2056. auto res = ioctlByIfName(ifName, SIOCGIFNETMASK);
  2057. int prefixLength = 0;
  2058. if (isOk(res.status())) {
  2059. prefixLength = ipv4NetmaskToPrefixLength(
  2060. ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr);
  2061. }
  2062. return prefixLength;
  2063. }
  2064. std::string getInterfaceIPv4Addr(const std::string& ifName) {
  2065. auto res = ioctlByIfName(ifName, SIOCGIFADDR);
  2066. struct in_addr addr = {};
  2067. if (isOk(res.status())) {
  2068. addr.s_addr = ((struct sockaddr_in*) &res.value().ifr_addr)->sin_addr.s_addr;
  2069. }
  2070. return std::string(inet_ntoa(addr));
  2071. }
  2072. std::vector<std::string> getInterfaceFlags(const std::string& ifName) {
  2073. auto res = ioctlByIfName(ifName, SIOCGIFFLAGS);
  2074. unsigned flags = 0;
  2075. if (isOk(res.status())) {
  2076. flags = res.value().ifr_flags;
  2077. }
  2078. std::vector<std::string> ifFlags;
  2079. ifFlags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
  2080. : toStdString(INetd::IF_STATE_DOWN()));
  2081. if (flags & IFF_BROADCAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
  2082. if (flags & IFF_LOOPBACK) ifFlags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
  2083. if (flags & IFF_POINTOPOINT) ifFlags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
  2084. if (flags & IFF_RUNNING) ifFlags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
  2085. if (flags & IFF_MULTICAST) ifFlags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
  2086. return ifFlags;
  2087. }
  2088. bool compareListInterface(const std::vector<std::string>& interfaceList) {
  2089. const auto& res = InterfaceController::getIfaceNames();
  2090. EXPECT_TRUE(isOk(res));
  2091. std::vector<std::string> resIfList;
  2092. resIfList.reserve(res.value().size());
  2093. resIfList.insert(end(resIfList), begin(res.value()), end(res.value()));
  2094. return resIfList == interfaceList;
  2095. }
  2096. int getInterfaceIPv6PrivacyExtensions(const std::string& ifName) {
  2097. std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/use_tempaddr", ifName.c_str());
  2098. return readIntFromPath(path);
  2099. }
  2100. bool getInterfaceEnableIPv6(const std::string& ifName) {
  2101. std::string path = StringPrintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifName.c_str());
  2102. int disableIPv6 = readIntFromPath(path);
  2103. return !disableIPv6;
  2104. }
  2105. int getInterfaceMtu(const std::string& ifName) {
  2106. std::string path = StringPrintf("/sys/class/net/%s/mtu", ifName.c_str());
  2107. return readIntFromPath(path);
  2108. }
  2109. void expectInterfaceList(const std::vector<std::string>& interfaceList) {
  2110. EXPECT_TRUE(compareListInterface(interfaceList));
  2111. }
  2112. void expectCurrentInterfaceConfigurationEquals(const std::string& ifName,
  2113. const InterfaceConfigurationParcel& interfaceCfg) {
  2114. EXPECT_EQ(getInterfaceIPv4Addr(ifName), interfaceCfg.ipv4Addr);
  2115. EXPECT_EQ(getInterfaceIPv4Prefix(ifName), interfaceCfg.prefixLength);
  2116. EXPECT_EQ(getInterfaceHwAddr(ifName), interfaceCfg.hwAddr);
  2117. EXPECT_EQ(getInterfaceFlags(ifName), interfaceCfg.flags);
  2118. }
  2119. void expectCurrentInterfaceConfigurationAlmostEqual(const InterfaceConfigurationParcel& setCfg) {
  2120. EXPECT_EQ(getInterfaceIPv4Addr(setCfg.ifName), setCfg.ipv4Addr);
  2121. EXPECT_EQ(getInterfaceIPv4Prefix(setCfg.ifName), setCfg.prefixLength);
  2122. const auto& ifFlags = getInterfaceFlags(setCfg.ifName);
  2123. for (const auto& flag : setCfg.flags) {
  2124. EXPECT_TRUE(std::find(ifFlags.begin(), ifFlags.end(), flag) != ifFlags.end());
  2125. }
  2126. }
  2127. void expectInterfaceIPv6PrivacyExtensions(const std::string& ifName, bool enable) {
  2128. int v6PrivacyExtensions = getInterfaceIPv6PrivacyExtensions(ifName);
  2129. EXPECT_EQ(v6PrivacyExtensions, enable ? 2 : 0);
  2130. }
  2131. void expectInterfaceNoAddr(const std::string& ifName) {
  2132. // noAddr
  2133. EXPECT_EQ(getInterfaceIPv4Addr(ifName), "0.0.0.0");
  2134. // noPrefix
  2135. EXPECT_EQ(getInterfaceIPv4Prefix(ifName), 0);
  2136. }
  2137. void expectInterfaceEnableIPv6(const std::string& ifName, bool enable) {
  2138. int enableIPv6 = getInterfaceEnableIPv6(ifName);
  2139. EXPECT_EQ(enableIPv6, enable);
  2140. }
  2141. void expectInterfaceMtu(const std::string& ifName, const int mtu) {
  2142. int mtuSize = getInterfaceMtu(ifName);
  2143. EXPECT_EQ(mtu, mtuSize);
  2144. }
  2145. InterfaceConfigurationParcel makeInterfaceCfgParcel(const std::string& ifName,
  2146. const std::string& addr, int prefixLength,
  2147. const std::vector<std::string>& flags) {
  2148. InterfaceConfigurationParcel cfg;
  2149. cfg.ifName = ifName;
  2150. cfg.hwAddr = "";
  2151. cfg.ipv4Addr = addr;
  2152. cfg.prefixLength = prefixLength;
  2153. cfg.flags = flags;
  2154. return cfg;
  2155. }
  2156. void expectTunFlags(const InterfaceConfigurationParcel& interfaceCfg) {
  2157. std::vector<std::string> expectedFlags = {"up", "point-to-point", "running", "multicast"};
  2158. std::vector<std::string> unexpectedFlags = {"down", "broadcast"};
  2159. for (const auto& flag : expectedFlags) {
  2160. EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) !=
  2161. interfaceCfg.flags.end());
  2162. }
  2163. for (const auto& flag : unexpectedFlags) {
  2164. EXPECT_TRUE(std::find(interfaceCfg.flags.begin(), interfaceCfg.flags.end(), flag) ==
  2165. interfaceCfg.flags.end());
  2166. }
  2167. }
  2168. } // namespace
  2169. TEST_F(BinderTest, InterfaceList) {
  2170. std::vector<std::string> interfaceListResult;
  2171. binder::Status status = mNetd->interfaceGetList(&interfaceListResult);
  2172. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  2173. expectInterfaceList(interfaceListResult);
  2174. }
  2175. TEST_F(BinderTest, InterfaceGetCfg) {
  2176. InterfaceConfigurationParcel interfaceCfgResult;
  2177. // Add test physical network
  2178. EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
  2179. EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
  2180. binder::Status status = mNetd->interfaceGetCfg(sTun.name(), &interfaceCfgResult);
  2181. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  2182. expectCurrentInterfaceConfigurationEquals(sTun.name(), interfaceCfgResult);
  2183. expectTunFlags(interfaceCfgResult);
  2184. // Remove test physical network
  2185. EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
  2186. }
  2187. TEST_F(BinderTest, InterfaceSetCfg) {
  2188. const std::string testAddr = "192.0.2.3";
  2189. const int testPrefixLength = 24;
  2190. std::vector<std::string> upFlags = {"up"};
  2191. std::vector<std::string> downFlags = {"down"};
  2192. // Add test physical network
  2193. EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
  2194. EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
  2195. // Set tun interface down.
  2196. auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, downFlags);
  2197. binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
  2198. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  2199. expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
  2200. // Set tun interface up again.
  2201. interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, upFlags);
  2202. status = mNetd->interfaceSetCfg(interfaceCfg);
  2203. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  2204. status = mNetd->interfaceClearAddrs(sTun.name());
  2205. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  2206. // Remove test physical network
  2207. EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
  2208. }
  2209. TEST_F(BinderTest, InterfaceSetIPv6PrivacyExtensions) {
  2210. // enable
  2211. binder::Status status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), true);
  2212. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  2213. expectInterfaceIPv6PrivacyExtensions(sTun.name(), true);
  2214. // disable
  2215. status = mNetd->interfaceSetIPv6PrivacyExtensions(sTun.name(), false);
  2216. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  2217. expectInterfaceIPv6PrivacyExtensions(sTun.name(), false);
  2218. }
  2219. TEST_F(BinderTest, InterfaceClearAddr) {
  2220. const std::string testAddr = "192.0.2.3";
  2221. const int testPrefixLength = 24;
  2222. std::vector<std::string> noFlags{};
  2223. // Add test physical network
  2224. EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
  2225. EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
  2226. auto interfaceCfg = makeInterfaceCfgParcel(sTun.name(), testAddr, testPrefixLength, noFlags);
  2227. binder::Status status = mNetd->interfaceSetCfg(interfaceCfg);
  2228. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  2229. expectCurrentInterfaceConfigurationAlmostEqual(interfaceCfg);
  2230. status = mNetd->interfaceClearAddrs(sTun.name());
  2231. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  2232. expectInterfaceNoAddr(sTun.name());
  2233. // Remove test physical network
  2234. EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
  2235. }
  2236. TEST_F(BinderTest, InterfaceSetEnableIPv6) {
  2237. // Add test physical network
  2238. EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
  2239. EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
  2240. // disable
  2241. binder::Status status = mNetd->interfaceSetEnableIPv6(sTun.name(), false);
  2242. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  2243. expectInterfaceEnableIPv6(sTun.name(), false);
  2244. // enable
  2245. status = mNetd->interfaceSetEnableIPv6(sTun.name(), true);
  2246. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  2247. expectInterfaceEnableIPv6(sTun.name(), true);
  2248. // Remove test physical network
  2249. EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
  2250. }
  2251. TEST_F(BinderTest, InterfaceSetMtu) {
  2252. const int testMtu = 1200;
  2253. // Add test physical network
  2254. EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
  2255. EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
  2256. binder::Status status = mNetd->interfaceSetMtu(sTun.name(), testMtu);
  2257. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  2258. expectInterfaceMtu(sTun.name(), testMtu);
  2259. // Remove test physical network
  2260. EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
  2261. }
  2262. namespace {
  2263. constexpr const char TETHER_FORWARD[] = "tetherctrl_FORWARD";
  2264. constexpr const char TETHER_NAT_POSTROUTING[] = "tetherctrl_nat_POSTROUTING";
  2265. constexpr const char TETHER_RAW_PREROUTING[] = "tetherctrl_raw_PREROUTING";
  2266. constexpr const char TETHER_COUNTERS_CHAIN[] = "tetherctrl_counters";
  2267. int iptablesCountRules(const char* binary, const char* table, const char* chainName) {
  2268. return listIptablesRuleByTable(binary, table, chainName).size();
  2269. }
  2270. bool iptablesChainMatch(const char* binary, const char* table, const char* chainName,
  2271. const std::vector<std::string>& targetVec) {
  2272. std::vector<std::string> rules = listIptablesRuleByTable(binary, table, chainName);
  2273. if (targetVec.size() != rules.size() - 2) {
  2274. return false;
  2275. }
  2276. /*
  2277. * Check that the rules match. Note that this function matches substrings, not entire rules,
  2278. * because otherwise rules where "pkts" or "bytes" are nonzero would not match.
  2279. * Skip first two lines since rules start from third line.
  2280. * Chain chainName (x references)
  2281. * pkts bytes target prot opt in out source destination
  2282. * ...
  2283. */
  2284. int rIndex = 2;
  2285. for (const auto& target : targetVec) {
  2286. if (rules[rIndex].find(target) == std::string::npos) {
  2287. return false;
  2288. }
  2289. rIndex++;
  2290. }
  2291. return true;
  2292. }
  2293. void expectNatEnable(const std::string& intIf, const std::string& extIf) {
  2294. std::vector<std::string> postroutingV4Match = {"MASQUERADE"};
  2295. std::vector<std::string> preroutingV4Match = {"CT helper ftp", "CT helper pptp"};
  2296. std::vector<std::string> forwardV4Match = {
  2297. "bw_global_alert", "state RELATED", "state INVALID",
  2298. StringPrintf("tetherctrl_counters all -- %s %s", intIf.c_str(), extIf.c_str()),
  2299. "DROP"};
  2300. // V4
  2301. EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING,
  2302. postroutingV4Match));
  2303. EXPECT_TRUE(
  2304. iptablesChainMatch(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING, preroutingV4Match));
  2305. EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
  2306. std::vector<std::string> forwardV6Match = {"bw_global_alert", "tetherctrl_counters"};
  2307. std::vector<std::string> preroutingV6Match = {"rpfilter invert"};
  2308. // V6
  2309. EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV6Match));
  2310. EXPECT_TRUE(iptablesChainMatch(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING,
  2311. preroutingV6Match));
  2312. for (const auto& binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
  2313. EXPECT_TRUE(iptablesTargetsExists(binary, 2, FILTER_TABLE, TETHER_COUNTERS_CHAIN, intIf,
  2314. extIf));
  2315. }
  2316. }
  2317. void expectNatDisable() {
  2318. // It is the default DROP rule with tethering disable.
  2319. // Chain tetherctrl_FORWARD (1 references)
  2320. // pkts bytes target prot opt in out source destination
  2321. // 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
  2322. std::vector<std::string> forwardV4Match = {"DROP"};
  2323. EXPECT_TRUE(iptablesChainMatch(IPTABLES_PATH, FILTER_TABLE, TETHER_FORWARD, forwardV4Match));
  2324. // We expect that these chains should be empty.
  2325. EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, NAT_TABLE, TETHER_NAT_POSTROUTING));
  2326. EXPECT_EQ(2, iptablesCountRules(IPTABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
  2327. EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, FILTER_TABLE, TETHER_FORWARD));
  2328. EXPECT_EQ(2, iptablesCountRules(IP6TABLES_PATH, RAW_TABLE, TETHER_RAW_PREROUTING));
  2329. // Netd won't clear tether quota rule, we don't care rule in tetherctrl_counters.
  2330. }
  2331. } // namespace
  2332. TEST_F(BinderTest, TetherForwardAddRemove) {
  2333. binder::Status status = mNetd->tetherAddForward(sTun.name(), sTun2.name());
  2334. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  2335. expectNatEnable(sTun.name(), sTun2.name());
  2336. status = mNetd->tetherRemoveForward(sTun.name(), sTun2.name());
  2337. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  2338. expectNatDisable();
  2339. }
  2340. namespace {
  2341. using TripleInt = std::array<int, 3>;
  2342. TripleInt readProcFileToTripleInt(const std::string& path) {
  2343. std::string valueString;
  2344. int min, def, max;
  2345. EXPECT_TRUE(ReadFileToString(path, &valueString));
  2346. EXPECT_EQ(3, sscanf(valueString.c_str(), "%d %d %d", &min, &def, &max));
  2347. return {min, def, max};
  2348. }
  2349. void updateAndCheckTcpBuffer(sp<INetd>& netd, TripleInt& rmemValues, TripleInt& wmemValues) {
  2350. std::string testRmemValues =
  2351. StringPrintf("%u %u %u", rmemValues[0], rmemValues[1], rmemValues[2]);
  2352. std::string testWmemValues =
  2353. StringPrintf("%u %u %u", wmemValues[0], wmemValues[1], wmemValues[2]);
  2354. EXPECT_TRUE(netd->setTcpRWmemorySize(testRmemValues, testWmemValues).isOk());
  2355. TripleInt newRmemValues = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
  2356. TripleInt newWmemValues = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
  2357. for (int i = 0; i < 3; i++) {
  2358. SCOPED_TRACE(StringPrintf("tcp_mem value %d should be equal", i));
  2359. EXPECT_EQ(rmemValues[i], newRmemValues[i]);
  2360. EXPECT_EQ(wmemValues[i], newWmemValues[i]);
  2361. }
  2362. }
  2363. } // namespace
  2364. TEST_F(BinderTest, TcpBufferSet) {
  2365. TripleInt rmemValue = readProcFileToTripleInt(TCP_RMEM_PROC_FILE);
  2366. TripleInt testRmemValue{rmemValue[0] + 42, rmemValue[1] + 42, rmemValue[2] + 42};
  2367. TripleInt wmemValue = readProcFileToTripleInt(TCP_WMEM_PROC_FILE);
  2368. TripleInt testWmemValue{wmemValue[0] + 42, wmemValue[1] + 42, wmemValue[2] + 42};
  2369. updateAndCheckTcpBuffer(mNetd, testRmemValue, testWmemValue);
  2370. updateAndCheckTcpBuffer(mNetd, rmemValue, wmemValue);
  2371. }
  2372. namespace {
  2373. void checkUidsInPermissionMap(std::vector<int32_t>& uids, bool exist) {
  2374. android::bpf::BpfMap<uint32_t, uint8_t> uidPermissionMap(
  2375. android::bpf::mapRetrieve(UID_PERMISSION_MAP_PATH, 0));
  2376. for (int32_t uid : uids) {
  2377. android::netdutils::StatusOr<uint8_t> permission = uidPermissionMap.readValue(uid);
  2378. if (exist) {
  2379. EXPECT_TRUE(isOk(permission));
  2380. EXPECT_EQ(INetd::PERMISSION_NONE, permission.value());
  2381. } else {
  2382. EXPECT_FALSE(isOk(permission));
  2383. EXPECT_EQ(ENOENT, permission.status().code());
  2384. }
  2385. }
  2386. }
  2387. } // namespace
  2388. TEST_F(BinderTest, TestInternetPermission) {
  2389. SKIP_IF_BPF_NOT_SUPPORTED;
  2390. std::vector<int32_t> appUids = {TEST_UID1, TEST_UID2};
  2391. mNetd->trafficSetNetPermForUids(INetd::PERMISSION_INTERNET, appUids);
  2392. checkUidsInPermissionMap(appUids, false);
  2393. mNetd->trafficSetNetPermForUids(INetd::PERMISSION_NONE, appUids);
  2394. checkUidsInPermissionMap(appUids, true);
  2395. mNetd->trafficSetNetPermForUids(INetd::PERMISSION_UNINSTALLED, appUids);
  2396. checkUidsInPermissionMap(appUids, false);
  2397. }
  2398. TEST_F(BinderTest, UnsolEvents) {
  2399. auto testUnsolService = android::net::TestUnsolService::start();
  2400. std::string oldTunName = sTun.name();
  2401. std::string newTunName = "unsolTest";
  2402. testUnsolService->tarVec.push_back(oldTunName);
  2403. testUnsolService->tarVec.push_back(newTunName);
  2404. auto& cv = testUnsolService->getCv();
  2405. auto& cvMutex = testUnsolService->getCvMutex();
  2406. binder::Status status = mNetd->registerUnsolicitedEventListener(
  2407. android::interface_cast<android::net::INetdUnsolicitedEventListener>(testUnsolService));
  2408. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  2409. // TODO: Add test for below events
  2410. // StrictCleartextDetected / InterfaceDnsServersAdded
  2411. // InterfaceClassActivity / QuotaLimitReached / InterfaceAddressRemoved
  2412. {
  2413. std::unique_lock lock(cvMutex);
  2414. // Re-init test Tun, and we expect that we will get some unsol events.
  2415. // Use the test Tun device name to verify if we receive its unsol events.
  2416. sTun.destroy();
  2417. // Use predefined name
  2418. sTun.init(newTunName);
  2419. EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
  2420. }
  2421. // bit mask 1101101000
  2422. // Test only covers below events currently
  2423. const uint32_t kExpectedEvents = InterfaceAddressUpdated | InterfaceAdded | InterfaceRemoved |
  2424. InterfaceLinkStatusChanged | RouteChanged;
  2425. EXPECT_EQ(kExpectedEvents, testUnsolService->getReceived());
  2426. // Re-init sTun to clear predefined name
  2427. sTun.destroy();
  2428. sTun.init();
  2429. }
  2430. TEST_F(BinderTest, NDC) {
  2431. struct Command {
  2432. const std::string cmdString;
  2433. const std::string expectedResult;
  2434. };
  2435. // clang-format off
  2436. // Do not change the commands order
  2437. const Command networkCmds[] = {
  2438. {StringPrintf("ndc network create %d", TEST_NETID1),
  2439. "200 0 success"},
  2440. {StringPrintf("ndc network interface add %d %s", TEST_NETID1, sTun.name().c_str()),
  2441. "200 0 success"},
  2442. {StringPrintf("ndc network interface remove %d %s", TEST_NETID1, sTun.name().c_str()),
  2443. "200 0 success"},
  2444. {StringPrintf("ndc network interface add %d %s", TEST_NETID2, sTun.name().c_str()),
  2445. "400 0 addInterfaceToNetwork() failed (Machine is not on the network)"},
  2446. {StringPrintf("ndc network destroy %d", TEST_NETID1),
  2447. "200 0 success"},
  2448. };
  2449. const std::vector<Command> ipfwdCmds = {
  2450. {"ndc ipfwd enable " + sTun.name(),
  2451. "200 0 ipfwd operation succeeded"},
  2452. {"ndc ipfwd disable " + sTun.name(),
  2453. "200 0 ipfwd operation succeeded"},
  2454. {"ndc ipfwd add lo2 lo3",
  2455. "400 0 ipfwd operation failed (No such process)"},
  2456. {"ndc ipfwd add " + sTun.name() + " " + sTun2.name(),
  2457. "200 0 ipfwd operation succeeded"},
  2458. {"ndc ipfwd remove " + sTun.name() + " " + sTun2.name(),
  2459. "200 0 ipfwd operation succeeded"},
  2460. };
  2461. static const struct {
  2462. const char* ipVersion;
  2463. const char* testDest;
  2464. const char* testNextHop;
  2465. const bool expectSuccess;
  2466. const std::string expectedResult;
  2467. } kTestData[] = {
  2468. {IP_RULE_V4, "0.0.0.0/0", "", true,
  2469. "200 0 success"},
  2470. {IP_RULE_V4, "10.251.0.0/16", "", true,
  2471. "200 0 success"},
  2472. {IP_RULE_V4, "10.251.0.0/16", "fe80::/64", false,
  2473. "400 0 addRoute() failed (Invalid argument)",},
  2474. {IP_RULE_V6, "::/0", "", true,
  2475. "200 0 success"},
  2476. {IP_RULE_V6, "2001:db8:cafe::/64", "", true,
  2477. "200 0 success"},
  2478. {IP_RULE_V6, "fe80::/64", "0.0.0.0", false,
  2479. "400 0 addRoute() failed (Invalid argument)"},
  2480. };
  2481. // clang-format on
  2482. for (const auto& cmd : networkCmds) {
  2483. const std::vector<std::string> result = runCommand(cmd.cmdString);
  2484. SCOPED_TRACE(cmd.cmdString);
  2485. EXPECT_EQ(result.size(), 1U);
  2486. EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
  2487. }
  2488. for (const auto& cmd : ipfwdCmds) {
  2489. const std::vector<std::string> result = runCommand(cmd.cmdString);
  2490. SCOPED_TRACE(cmd.cmdString);
  2491. EXPECT_EQ(result.size(), 1U);
  2492. EXPECT_EQ(cmd.expectedResult, Trim(result[0]));
  2493. }
  2494. // Add test physical network
  2495. EXPECT_TRUE(mNetd->networkCreatePhysical(TEST_NETID1, INetd::PERMISSION_NONE).isOk());
  2496. EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
  2497. for (const auto& td : kTestData) {
  2498. const std::string routeAddCmd =
  2499. StringPrintf("ndc network route add %d %s %s %s", TEST_NETID1, sTun.name().c_str(),
  2500. td.testDest, td.testNextHop);
  2501. const std::string routeRemoveCmd =
  2502. StringPrintf("ndc network route remove %d %s %s %s", TEST_NETID1,
  2503. sTun.name().c_str(), td.testDest, td.testNextHop);
  2504. std::vector<std::string> result = runCommand(routeAddCmd);
  2505. SCOPED_TRACE(routeAddCmd);
  2506. EXPECT_EQ(result.size(), 1U);
  2507. EXPECT_EQ(td.expectedResult, Trim(result[0]));
  2508. if (td.expectSuccess) {
  2509. expectNetworkRouteExists(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
  2510. sTun.name().c_str());
  2511. result = runCommand(routeRemoveCmd);
  2512. EXPECT_EQ(result.size(), 1U);
  2513. EXPECT_EQ(td.expectedResult, Trim(result[0]));
  2514. expectNetworkRouteDoesNotExist(td.ipVersion, sTun.name(), td.testDest, td.testNextHop,
  2515. sTun.name().c_str());
  2516. }
  2517. }
  2518. // Remove test physical network
  2519. EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
  2520. }
  2521. TEST_F(BinderTest, OemNetdRelated) {
  2522. sp<IBinder> binder;
  2523. binder::Status status = mNetd->getOemNetd(&binder);
  2524. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  2525. sp<com::android::internal::net::IOemNetd> oemNetd;
  2526. if (binder != nullptr) {
  2527. oemNetd = android::interface_cast<com::android::internal::net::IOemNetd>(binder);
  2528. }
  2529. ASSERT_NE(nullptr, oemNetd.get());
  2530. TimedOperation t("OemNetd isAlive RPC");
  2531. bool isAlive = false;
  2532. oemNetd->isAlive(&isAlive);
  2533. ASSERT_TRUE(isAlive);
  2534. class TestOemUnsolListener
  2535. : public com::android::internal::net::BnOemNetdUnsolicitedEventListener {
  2536. public:
  2537. android::binder::Status onRegistered() override {
  2538. std::lock_guard lock(mCvMutex);
  2539. mCv.notify_one();
  2540. return android::binder::Status::ok();
  2541. }
  2542. std::condition_variable& getCv() { return mCv; }
  2543. std::mutex& getCvMutex() { return mCvMutex; }
  2544. private:
  2545. std::mutex mCvMutex;
  2546. std::condition_variable mCv;
  2547. };
  2548. // Start the Binder thread pool.
  2549. android::ProcessState::self()->startThreadPool();
  2550. android::sp<TestOemUnsolListener> testListener = new TestOemUnsolListener();
  2551. auto& cv = testListener->getCv();
  2552. auto& cvMutex = testListener->getCvMutex();
  2553. {
  2554. std::unique_lock lock(cvMutex);
  2555. status = oemNetd->registerOemUnsolicitedEventListener(
  2556. ::android::interface_cast<
  2557. com::android::internal::net::IOemNetdUnsolicitedEventListener>(
  2558. testListener));
  2559. EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
  2560. // Wait for receiving expected events.
  2561. EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
  2562. }
  2563. }
  2564. void BinderTest::createVpnNetworkWithUid(bool secure, uid_t uid, int vpnNetId,
  2565. int fallthroughNetId) {
  2566. // Re-init sTun* to ensure route rule exists.
  2567. sTun.destroy();
  2568. sTun.init();
  2569. sTun2.destroy();
  2570. sTun2.init();
  2571. // Create physical network with fallthroughNetId but not set it as default network
  2572. EXPECT_TRUE(mNetd->networkCreatePhysical(fallthroughNetId, INetd::PERMISSION_NONE).isOk());
  2573. EXPECT_TRUE(mNetd->networkAddInterface(fallthroughNetId, sTun.name()).isOk());
  2574. // Create VPN with vpnNetId
  2575. EXPECT_TRUE(mNetd->networkCreateVpn(vpnNetId, secure).isOk());
  2576. // Add uid to VPN
  2577. EXPECT_TRUE(mNetd->networkAddUidRanges(vpnNetId, {makeUidRangeParcel(uid, uid)}).isOk());
  2578. EXPECT_TRUE(mNetd->networkAddInterface(vpnNetId, sTun2.name()).isOk());
  2579. // Add default route to fallthroughNetwork
  2580. EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
  2581. // Add limited route
  2582. EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID2, sTun2.name(), "2001:db8::/32", "").isOk());
  2583. }
  2584. namespace {
  2585. class ScopedUidChange {
  2586. public:
  2587. explicit ScopedUidChange(uid_t uid) : mInputUid(uid) {
  2588. mStoredUid = getuid();
  2589. if (mInputUid == mStoredUid) return;
  2590. EXPECT_TRUE(seteuid(uid) == 0);
  2591. }
  2592. ~ScopedUidChange() {
  2593. if (mInputUid == mStoredUid) return;
  2594. EXPECT_TRUE(seteuid(mStoredUid) == 0);
  2595. }
  2596. private:
  2597. uid_t mInputUid;
  2598. uid_t mStoredUid;
  2599. };
  2600. constexpr uint32_t RULE_PRIORITY_VPN_FALLTHROUGH = 21000;
  2601. void clearQueue(int tunFd) {
  2602. char buf[4096];
  2603. int ret;
  2604. do {
  2605. ret = read(tunFd, buf, sizeof(buf));
  2606. } while (ret > 0);
  2607. }
  2608. void checkDataReceived(int udpSocket, int tunFd) {
  2609. char buf[4096] = {};
  2610. // Clear tunFd's queue before write something because there might be some
  2611. // arbitrary packets in the queue. (e.g. ICMPv6 packet)
  2612. clearQueue(tunFd);
  2613. EXPECT_EQ(4, write(udpSocket, "foo", sizeof("foo")));
  2614. // TODO: extract header and verify data
  2615. EXPECT_GT(read(tunFd, buf, sizeof(buf)), 0);
  2616. }
  2617. bool sendIPv6PacketFromUid(uid_t uid, const in6_addr& dstAddr, Fwmark* fwmark, int tunFd) {
  2618. ScopedUidChange scopedUidChange(uid);
  2619. android::base::unique_fd testSocket(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
  2620. if (testSocket < 0) return false;
  2621. const sockaddr_in6 dst6 = {.sin6_family = AF_INET6, .sin6_addr = dstAddr, .sin6_port = 42};
  2622. int res = connect(testSocket, (sockaddr*)&dst6, sizeof(dst6));
  2623. socklen_t fwmarkLen = sizeof(fwmark->intValue);
  2624. EXPECT_NE(-1, getsockopt(testSocket, SOL_SOCKET, SO_MARK, &(fwmark->intValue), &fwmarkLen));
  2625. if (res == -1) return false;
  2626. char addr[INET6_ADDRSTRLEN];
  2627. inet_ntop(AF_INET6, &dstAddr, addr, INET6_ADDRSTRLEN);
  2628. SCOPED_TRACE(StringPrintf("sendIPv6PacketFromUid, addr: %s, uid: %u", addr, uid));
  2629. checkDataReceived(testSocket, tunFd);
  2630. return true;
  2631. }
  2632. void expectVpnFallthroughRuleExists(const std::string& ifName, int vpnNetId) {
  2633. std::string vpnFallthroughRule =
  2634. StringPrintf("%d:\tfrom all fwmark 0x%x/0xffff lookup %s",
  2635. RULE_PRIORITY_VPN_FALLTHROUGH, vpnNetId, ifName.c_str());
  2636. for (const auto& ipVersion : {IP_RULE_V4, IP_RULE_V6}) {
  2637. EXPECT_TRUE(ipRuleExists(ipVersion, vpnFallthroughRule));
  2638. }
  2639. }
  2640. void expectVpnFallthroughWorks(android::net::INetd* netdService, bool bypassable, uid_t uid,
  2641. const TunInterface& fallthroughNetwork,
  2642. const TunInterface& vpnNetwork, int vpnNetId = TEST_NETID2,
  2643. int fallthroughNetId = TEST_NETID1) {
  2644. // Set default network to NETID_UNSET
  2645. EXPECT_TRUE(netdService->networkSetDefault(NETID_UNSET).isOk());
  2646. // insideVpnAddr based on the route we added in createVpnNetworkWithUid
  2647. in6_addr insideVpnAddr = {
  2648. {// 2001:db8:cafe::1
  2649. .u6_addr8 = {0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}};
  2650. // outsideVpnAddr will hit the route in the fallthrough network route table
  2651. // because we added default route in createVpnNetworkWithUid
  2652. in6_addr outsideVpnAddr = {
  2653. {// 2607:f0d0:1002::4
  2654. .u6_addr8 = {0x26, 0x07, 0xf0, 0xd0, 0x10, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4}}};
  2655. int fallthroughFd = fallthroughNetwork.getFdForTesting();
  2656. int vpnFd = vpnNetwork.getFdForTesting();
  2657. // Expect all connections to fail because UID 0 is not routed to the VPN and there is no
  2658. // default network.
  2659. Fwmark fwmark;
  2660. EXPECT_FALSE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
  2661. EXPECT_FALSE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
  2662. // Set default network
  2663. EXPECT_TRUE(netdService->networkSetDefault(fallthroughNetId).isOk());
  2664. // Connections go on the default network because UID 0 is not subject to the VPN.
  2665. EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
  2666. EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
  2667. EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
  2668. EXPECT_EQ(fallthroughNetId | 0xC0000, static_cast<int>(fwmark.intValue));
  2669. // Check if fallthrough rule exists
  2670. expectVpnFallthroughRuleExists(fallthroughNetwork.name(), vpnNetId);
  2671. // Expect fallthrough to default network
  2672. // The fwmark differs depending on whether the VPN is bypassable or not.
  2673. EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
  2674. EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
  2675. // Expect connect success, packet will be sent to vpnFd.
  2676. EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, vpnFd));
  2677. EXPECT_EQ(bypassable ? vpnNetId : fallthroughNetId, static_cast<int>(fwmark.intValue));
  2678. // Explicitly select vpn network
  2679. setNetworkForProcess(vpnNetId);
  2680. // Expect fallthrough to default network
  2681. EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
  2682. // Expect the mark contains all the bit because we've selected network.
  2683. EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
  2684. // Expect connect success, packet will be sent to vpnFd.
  2685. EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, vpnFd));
  2686. // Expect the mark contains all the bit because we've selected network.
  2687. EXPECT_EQ(vpnNetId | 0xF0000, static_cast<int>(fwmark.intValue));
  2688. // Explicitly select fallthrough network
  2689. setNetworkForProcess(fallthroughNetId);
  2690. // The mark is set to fallthrough network because we've selected it.
  2691. EXPECT_TRUE(sendIPv6PacketFromUid(0, outsideVpnAddr, &fwmark, fallthroughFd));
  2692. EXPECT_TRUE(sendIPv6PacketFromUid(0, insideVpnAddr, &fwmark, fallthroughFd));
  2693. // If vpn is BypassableVPN, connections can also go on the fallthrough network under vpn uid.
  2694. if (bypassable) {
  2695. EXPECT_TRUE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
  2696. EXPECT_TRUE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
  2697. } else {
  2698. // If not, no permission to bypass vpn.
  2699. EXPECT_FALSE(sendIPv6PacketFromUid(uid, outsideVpnAddr, &fwmark, fallthroughFd));
  2700. EXPECT_FALSE(sendIPv6PacketFromUid(uid, insideVpnAddr, &fwmark, fallthroughFd));
  2701. }
  2702. }
  2703. } // namespace
  2704. TEST_F(BinderTest, SecureVPNFallthrough) {
  2705. createVpnNetworkWithUid(true /* secure */, TEST_UID1);
  2706. // Get current default network NetId
  2707. ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
  2708. expectVpnFallthroughWorks(mNetd.get(), false /* bypassable */, TEST_UID1, sTun, sTun2);
  2709. }
  2710. TEST_F(BinderTest, BypassableVPNFallthrough) {
  2711. createVpnNetworkWithUid(false /* secure */, TEST_UID1);
  2712. // Get current default network NetId
  2713. ASSERT_TRUE(mNetd->networkGetDefault(&mStoredDefaultNetwork).isOk());
  2714. expectVpnFallthroughWorks(mNetd.get(), true /* bypassable */, TEST_UID1, sTun, sTun2);
  2715. }