1 /*
2  * Copyright (C) 2022 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  */
17 
18 #include "firewall.h"
19 
20 #include <android-base/result.h>
21 #include <gtest/gtest.h>
22 
Firewall()23 Firewall::Firewall() {
24     std::lock_guard guard(mMutex);
25     auto result = mConfigurationMap.init(CONFIGURATION_MAP_PATH);
26     EXPECT_RESULT_OK(result) << "init mConfigurationMap failed";
27 
28     result = mUidOwnerMap.init(UID_OWNER_MAP_PATH);
29     EXPECT_RESULT_OK(result) << "init mUidOwnerMap failed";
30 
31     // Do not check whether DATA_SAVER_ENABLED_MAP_PATH init succeeded or failed since the map is
32     // defined in tethering module, but the user of this class may be in other modules. For example,
33     // DNS resolver tests statically link to this class. But when running MTS, the test infra
34     // installs only DNS resolver module without installing tethering module together.
35     mDataSaverEnabledMap.init(DATA_SAVER_ENABLED_MAP_PATH);
36 }
37 
getInstance()38 Firewall* Firewall::getInstance() {
39     static Firewall instance;
40     return &instance;
41 }
42 
toggleStandbyMatch(bool enable)43 Result<void> Firewall::toggleStandbyMatch(bool enable) {
44     std::lock_guard guard(mMutex);
45     uint32_t key = UID_RULES_CONFIGURATION_KEY;
46     auto oldConfiguration = mConfigurationMap.readValue(key);
47     if (!oldConfiguration.ok()) {
48         return Errorf("Cannot read the old configuration: {}", oldConfiguration.error().message());
49     }
50 
51     BpfConfig newConfiguration = enable ? (oldConfiguration.value() | STANDBY_MATCH)
52                                         : (oldConfiguration.value() & (~STANDBY_MATCH));
53     auto res = mConfigurationMap.writeValue(key, newConfiguration, BPF_EXIST);
54     if (!res.ok()) return Errorf("Failed to toggle STANDBY_MATCH: {}", res.error().message());
55 
56     return {};
57 }
58 
addRule(uint32_t uid,UidOwnerMatchType match,uint32_t iif)59 Result<void> Firewall::addRule(uint32_t uid, UidOwnerMatchType match, uint32_t iif) {
60     // iif should be non-zero if and only if match == MATCH_IIF
61     if (match == IIF_MATCH && iif == 0) {
62         return Errorf("Interface match {} must have nonzero interface index",
63                       static_cast<uint32_t>(match));
64     } else if (match != IIF_MATCH && iif != 0) {
65         return Errorf("Non-interface match {} must have zero interface index",
66                       static_cast<uint32_t>(match));
67     }
68 
69     std::lock_guard guard(mMutex);
70     auto oldMatch = mUidOwnerMap.readValue(uid);
71     if (oldMatch.ok()) {
72         UidOwnerValue newMatch = {
73                 .iif = iif ? iif : oldMatch.value().iif,
74                 .rule = oldMatch.value().rule | match,
75         };
76         auto res = mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY);
77         if (!res.ok()) return Errorf("Failed to update rule: {}", res.error().message());
78     } else {
79         UidOwnerValue newMatch = {
80                 .iif = iif,
81                 .rule = match,
82         };
83         auto res = mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY);
84         if (!res.ok()) return Errorf("Failed to add rule: {}", res.error().message());
85     }
86     return {};
87 }
88 
removeRule(uint32_t uid,UidOwnerMatchType match)89 Result<void> Firewall::removeRule(uint32_t uid, UidOwnerMatchType match) {
90     std::lock_guard guard(mMutex);
91     auto oldMatch = mUidOwnerMap.readValue(uid);
92     if (!oldMatch.ok()) return Errorf("uid: %u does not exist in map", uid);
93 
94     UidOwnerValue newMatch = {
95             .iif = (match == IIF_MATCH) ? 0 : oldMatch.value().iif,
96             .rule = oldMatch.value().rule & ~match,
97     };
98     if (newMatch.rule == 0) {
99         auto res = mUidOwnerMap.deleteValue(uid);
100         if (!res.ok()) return Errorf("Failed to remove rule: {}", res.error().message());
101     } else {
102         auto res = mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY);
103         if (!res.ok()) return Errorf("Failed to update rule: {}", res.error().message());
104     }
105     return {};
106 }
107 
addUidInterfaceRules(const std::string & ifName,const std::vector<int32_t> & uids)108 Result<void> Firewall::addUidInterfaceRules(const std::string& ifName,
109                                             const std::vector<int32_t>& uids) {
110     unsigned int iif = if_nametoindex(ifName.c_str());
111     if (!iif) return Errorf("Failed to get interface index: {}", ifName);
112 
113     for (auto uid : uids) {
114         auto res = addRule(uid, IIF_MATCH, iif);
115         if (!res.ok()) return res;
116     }
117     return {};
118 }
119 
removeUidInterfaceRules(const std::vector<int32_t> & uids)120 Result<void> Firewall::removeUidInterfaceRules(const std::vector<int32_t>& uids) {
121     for (auto uid : uids) {
122         auto res = removeRule(uid, IIF_MATCH);
123         if (!res.ok()) return res;
124     }
125     return {};
126 }
127 
getDataSaverSetting()128 Result<bool> Firewall::getDataSaverSetting() {
129     std::lock_guard guard(mMutex);
130     if (!mDataSaverEnabledMap.isValid()) {
131         return Errorf("init mDataSaverEnabledMap failed");
132     }
133 
134     auto dataSaverSetting = mDataSaverEnabledMap.readValue(DATA_SAVER_ENABLED_KEY);
135     if (!dataSaverSetting.ok()) {
136         return Errorf("Cannot read the data saver setting: {}", dataSaverSetting.error().message());
137     }
138     return dataSaverSetting;
139 }
140 
setDataSaver(bool enabled)141 Result<void> Firewall::setDataSaver(bool enabled) {
142     std::lock_guard guard(mMutex);
143     if (!mDataSaverEnabledMap.isValid()) {
144         return Errorf("init mDataSaverEnabledMap failed");
145     }
146 
147     auto res = mDataSaverEnabledMap.writeValue(DATA_SAVER_ENABLED_KEY, enabled, BPF_EXIST);
148     if (!res.ok()) return Errorf("Failed to set data saver: {}", res.error().message());
149 
150     return {};
151 }
152