1 /*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "oaid_service_stub.h"
17 #include <singleton.h>
18 #include "bundle_mgr_helper.h"
19 #include "bundle_mgr_client.h"
20 #include "accesstoken_kit.h"
21 #include "privacy_kit.h"
22 #include "tokenid_kit.h"
23 #include "oaid_common.h"
24 #include "oaid_service_define.h"
25 #include "oaid_service.h"
26 #include "oaid_service_ipc_interface_code.h"
27 #include "config_policy_utils.h"
28 #include "iservice_registry.h"
29 #include "oaid_remote_config_observer_stub.h"
30 #include "oaid_remote_config_observer_proxy.h"
31 #include "oaid_observer_manager.h"
32
33 using namespace OHOS::Security::AccessToken;
34
35 namespace OHOS {
36 namespace Cloud {
37 using namespace OHOS::HiviewDFX;
OAIDServiceStub()38 OAIDServiceStub::OAIDServiceStub()
39 {}
40
~OAIDServiceStub()41 OAIDServiceStub::~OAIDServiceStub()
42 {}
43
CheckPermission(const std::string &permissionName)44 bool OAIDServiceStub::CheckPermission(const std::string &permissionName)
45 {
46 // Verify the invoker's permission.
47 AccessTokenID firstCallToken = IPCSkeleton::GetFirstTokenID();
48 AccessTokenID callingToken = IPCSkeleton::GetCallingTokenID();
49 ATokenTypeEnum callingType = AccessTokenKit::GetTokenTypeFlag(callingToken);
50
51 ErrCode result = TypePermissionState::PERMISSION_DENIED;
52
53 if (firstCallToken == 0) {
54 if (callingType == TOKEN_INVALID) {
55 OAID_HILOGE(OAID_MODULE_SERVICE, "callingToken is invalid");
56 return false;
57 } else {
58 result = AccessTokenKit::VerifyAccessToken(callingToken, permissionName);
59 }
60 } else {
61 result = AccessTokenKit::VerifyAccessToken(callingToken, firstCallToken, permissionName);
62 }
63
64 if (callingType == TOKEN_HAP) {
65 int32_t successCnt = (int32_t)(result == TypePermissionState::PERMISSION_GRANTED);
66 int32_t failCnt = 1 - successCnt; // 1 means that there is only one visit in total
67 // AddPermissionUsedRecord needs to transfer both the number of successful and failed permission access requests
68 int32_t ret = PrivacyKit::AddPermissionUsedRecord(callingToken, permissionName, successCnt, failCnt);
69 OAID_HILOGI(OAID_MODULE_SERVICE, "AddPermissionUsedRecord ret=%{public}d", ret);
70 }
71
72 if (result == TypePermissionState::PERMISSION_DENIED) {
73 OAID_HILOGI(OAID_MODULE_SERVICE, "the caller not granted the app tracking permission");
74 return false;
75 }
76 return true;
77 }
78
CheckSystemApp()79 bool OAIDServiceStub::CheckSystemApp()
80 {
81 FullTokenID callingFullToken = IPCSkeleton::GetCallingFullTokenID();
82 auto tokenType = AccessTokenKit::GetTokenTypeFlag(IPCSkeleton::GetCallingTokenID());
83 if (TokenIdKit::IsSystemAppByFullTokenID(callingFullToken) && tokenType == TOKEN_HAP) {
84 return true;
85 }
86 OAID_HILOGW(OAID_MODULE_SERVICE, "the caller App is not system app");
87 return false;
88 }
89
LoadAndCheckOaidTrustList(const std::string &bundleName)90 bool LoadAndCheckOaidTrustList(const std::string &bundleName)
91 {
92 char pathBuff[MAX_PATH_LEN];
93 GetOneCfgFile(OAID_TRUSTLIST_EXTENSION_CONFIG_PATH.c_str(), pathBuff, MAX_PATH_LEN);
94 char realPath[PATH_MAX];
95 if (realpath(pathBuff, realPath) == nullptr) {
96 GetOneCfgFile(OAID_TRUSTLIST_CONFIG_PATH.c_str(), pathBuff, MAX_PATH_LEN);
97 if (realpath(pathBuff, realPath) == nullptr) {
98 OAID_HILOGE(OAID_MODULE_SERVICE, "Parse realpath fail");
99 return false;
100 }
101 }
102 std::ifstream inFile(realPath, std::ios::in);
103 if (!inFile.is_open()) {
104 OAID_HILOGE(OAID_MODULE_SERVICE, "Open file error.");
105 return false;
106 }
107 std::string fileContent((std::istreambuf_iterator<char>(inFile)), std::istreambuf_iterator<char>());
108 cJSON *root = cJSON_Parse(fileContent.c_str());
109 inFile.close();
110 if (root == nullptr) {
111 OAID_HILOGE(OAID_MODULE_SERVICE, "ParseJsonFromFile is not in JSON format.");
112 return false;
113 }
114 cJSON *oaidTrustConfig = cJSON_GetObjectItem(root, "resetOAIDBundleName");
115 if (oaidTrustConfig == nullptr || !cJSON_IsArray(oaidTrustConfig)) {
116 OAID_HILOGE(OAID_MODULE_SERVICE, "not contain resetOAIDBundleName node.");
117 cJSON_Delete(root);
118 return false;
119 }
120 int arraySize = cJSON_GetArraySize(oaidTrustConfig);
121 if (arraySize == 0) {
122 OAID_HILOGI(OAID_MODULE_SERVICE, "oaidTrustConfig list is empty.");
123 cJSON_Delete(root);
124 return true;
125 }
126 for (int i = 0; i < arraySize; i++) {
127 cJSON *item = cJSON_GetArrayItem(oaidTrustConfig, i);
128 if (cJSON_IsString(item)) {
129 if (bundleName.compare(item->valuestring) == 0) {
130 OAID_HILOGI(OAID_MODULE_SERVICE, "the oaidWhiteList contains this bundle name");
131 cJSON_Delete(root);
132 return true;
133 }
134 }
135 }
136 cJSON_Delete(root);
137 return false;
138 }
139
SendCode(uint32_t code, MessageParcel &data, MessageParcel &reply)140 int32_t OAIDServiceStub::SendCode(uint32_t code, MessageParcel &data, MessageParcel &reply)
141 {
142 switch (code) {
143 case static_cast<uint32_t>(OAIDInterfaceCode::GET_OAID): {
144 return OAIDServiceStub::OnGetOAID(data, reply);
145 break;
146 }
147 case static_cast<uint32_t>(OAIDInterfaceCode::RESET_OAID): {
148 return OAIDServiceStub::OnResetOAID(data, reply);
149 break;
150 }
151 case static_cast<uint32_t>(OAIDInterfaceCode::REGISTER_CONTROL_CONFIG_OBSERVER): {
152 return OAIDServiceStub::HandleRegisterControlConfigObserver(data, reply);
153 break;
154 }
155 }
156 return ERR_SYSYTEM_ERROR;
157 }
158
OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)159 int32_t OAIDServiceStub::OnRemoteRequest(
160 uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
161 {
162 ExitIdleState();
163 PostDelayUnloadTask();
164 OAID_HILOGI(OAID_MODULE_SERVICE, "Start, code is %{public}u.", code);
165 std::string bundleName;
166 pid_t uid = IPCSkeleton::GetCallingUid();
167 DelayedSingleton<BundleMgrHelper>::GetInstance()->GetBundleNameByUid(static_cast<int>(uid), bundleName);
168 if (code == static_cast<uint32_t>(OAIDInterfaceCode::GET_OAID) &&
169 !CheckPermission(OAID_TRACKING_CONSENT_PERMISSION)) {
170 OAID_HILOGW(
171 OAID_MODULE_SERVICE, "bundleName %{public}s not granted the app tracking permission", bundleName.c_str());
172 return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
173 }
174 if (code == static_cast<uint32_t>(OAIDInterfaceCode::RESET_OAID)) {
175 int32_t validateResult = ValidateResetOAIDPermission(bundleName, reply);
176 if (validateResult == ERR_SYSYTEM_ERROR) {
177 return ERR_SYSYTEM_ERROR;
178 }
179 if (validateResult == ERR_PERMISSION_ERROR) {
180 return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
181 }
182 }
183 std::u16string myDescripter = OAIDServiceStub::GetDescriptor();
184 std::u16string remoteDescripter = data.ReadInterfaceToken();
185 if (myDescripter != remoteDescripter) {
186 OAID_HILOGE(OAID_MODULE_SERVICE, "Descriptor checked fail.");
187 return ERR_SYSYTEM_ERROR;
188 }
189 OAID_HILOGI(OAID_MODULE_SERVICE, "Remote bundleName is %{public}s.", bundleName.c_str());
190 return SendCode(code, data, reply);
191 }
192
ValidateResetOAIDPermission(std::string bundleName, MessageParcel &reply)193 int32_t OAIDServiceStub::ValidateResetOAIDPermission(std::string bundleName, MessageParcel &reply)
194 {
195 if (!LoadAndCheckOaidTrustList(bundleName)) {
196 OAID_HILOGW(
197 OAID_MODULE_SERVICE, "CheckOaidTrustList fail.errorCode = %{public}d", OAID_ERROR_NOT_IN_TRUST_LIST);
198 if (!reply.WriteInt32(OAID_ERROR_NOT_IN_TRUST_LIST)) {
199 OAID_HILOGE(OAID_MODULE_SERVICE, "write errorCode to reply failed.");
200 return ERR_SYSYTEM_ERROR;
201 }
202 return ERR_PERMISSION_ERROR;
203 }
204
205 if (!CheckSystemApp()) {
206 OAID_HILOGW(OAID_MODULE_SERVICE, "CheckSystemApp fail.errorCode = %{public}d", OAID_ERROR_CODE_NOT_SYSTEM_APP);
207 if (!reply.WriteInt32(OAID_ERROR_CODE_NOT_SYSTEM_APP)) {
208 OAID_HILOGE(OAID_MODULE_SERVICE, "write errorCode to reply failed.");
209 return ERR_SYSYTEM_ERROR;
210 }
211 return ERR_PERMISSION_ERROR;
212 }
213 return ERR_OK;
214 }
215
OnGetOAID(MessageParcel &data, MessageParcel &reply)216 int32_t OAIDServiceStub::OnGetOAID(MessageParcel &data, MessageParcel &reply)
217 {
218 OAID_HILOGI(OAID_MODULE_SERVICE, "Start.");
219
220 auto oaid = GetOAID();
221 if (oaid == "") {
222 OAID_HILOGE(OAID_MODULE_SERVICE, "Get OAID failed.");
223 return ERR_SYSYTEM_ERROR;
224 }
225
226 if (!reply.WriteString(oaid)) {
227 OAID_HILOGE(OAID_MODULE_SERVICE, "Failed to write parcelable.");
228 return ERR_SYSYTEM_ERROR;
229 }
230 OAID_HILOGI(OAID_MODULE_SERVICE, "End.");
231 return ERR_OK;
232 }
233
OnResetOAID(MessageParcel &data, MessageParcel &reply)234 int32_t OAIDServiceStub::OnResetOAID(MessageParcel &data, MessageParcel &reply)
235 {
236 OAID_HILOGI(OAID_MODULE_SERVICE, "Reset OAID Start.");
237
238 ResetOAID();
239
240 OAID_HILOGI(OAID_MODULE_SERVICE, "Reset OAID End.");
241 return ERR_OK;
242 }
243
ExitIdleState()244 void OAIDServiceStub::ExitIdleState()
245 {
246 auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
247 if (samgrProxy == nullptr) {
248 OAID_HILOGE(OAID_MODULE_SERVICE, "Get samgr failed.");
249 return;
250 }
251 int32_t ret = samgrProxy->CancelUnloadSystemAbility(OAID_SYSTME_ID);
252 if (ret != ERR_OK) {
253 OAID_HILOGE(OAID_MODULE_SERVICE,
254 "CancelUnload system ability %{public}d failed, result: %{public}d.",
255 OAID_SYSTME_ID,
256 ret);
257 return;
258 }
259 }
260
PostDelayUnloadTask()261 void OAIDServiceStub::PostDelayUnloadTask()
262 {
263 init_eventHandler_Mutex_.lock();
264 if (unloadHandler_ == nullptr) {
265 const char *runnerName = "unlock";
266 auto runner = AppExecFwk::EventRunner::Create(runnerName);
267 unloadHandler_ = std::make_shared<AppExecFwk::EventHandler>(runner);
268 }
269 init_eventHandler_Mutex_.unlock();
270 auto task = [this]() {
271 auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
272 if (samgrProxy == nullptr) {
273 OAID_HILOGE(OAID_MODULE_SERVICE, "Get samgr failed.");
274 return;
275 }
276 int32_t ret = samgrProxy->UnloadSystemAbility(OAID_SYSTME_ID);
277 if (ret != ERR_OK) {
278 OAID_HILOGE(OAID_MODULE_SERVICE,
279 "Unload system ability %{public}d failed, result: %{public}d.",
280 OAID_SYSTME_ID,
281 ret);
282 return;
283 }
284 };
285 unloadHandler_->RemoveTask(TASK_ID);
286 unloadHandler_->PostTask(task, TASK_ID, DELAY_TIME);
287 }
288
HandleRegisterControlConfigObserver(MessageParcel &data, MessageParcel &reply)289 int32_t OAIDServiceStub::HandleRegisterControlConfigObserver(MessageParcel &data, MessageParcel &reply)
290 {
291 int32_t uid = IPCSkeleton::GetCallingUid();
292 if (uid != HA_UID) {
293 OAID_HILOGE(OAID_MODULE_SERVICE, "callingUid error, error code is: %{public}d", ERR_INVALID_PARAM);
294 return ERR_INVALID_PARAM;
295 }
296 auto remoteObject = data.ReadRemoteObject();
297 if (!remoteObject) {
298 OAID_HILOGI(OAID_MODULE_SERVICE, "Observer is null, error code is: %{public}d", ERR_NULL_POINTER);
299 return ERR_NULL_POINTER;
300 }
301 auto observer = iface_cast<IRemoteConfigObserver>(remoteObject);
302 if (observer == nullptr) {
303 OAID_HILOGI(OAID_MODULE_SERVICE, "Observer is null, error code is: %{public}d", ERR_NULL_POINTER);
304 return ERR_NULL_POINTER;
305 }
306 return RegisterObserver(observer);
307 }
308
RegisterObserver(const sptr<IRemoteConfigObserver> &observer)309 int32_t OAIDServiceStub::RegisterObserver(const sptr<IRemoteConfigObserver> &observer)
310 {
311 OAID_HILOGI(OAID_MODULE_SERVICE, "registerObserver success.");
312 return DelayedSingleton<OaidObserverManager>::GetInstance()->RegisterObserver(observer);
313 }
314 } // namespace Cloud
315 } // namespace OHOS