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 #include "connect_ads_stub.h"
33
34 using namespace OHOS::Security::AccessToken;
35
36 namespace OHOS {
37 namespace Cloud {
38 using namespace OHOS::HiviewDFX;
OAIDServiceStub()39 OAIDServiceStub::OAIDServiceStub()
40 {}
41
~OAIDServiceStub()42 OAIDServiceStub::~OAIDServiceStub()
43 {}
44
CheckPermission(const std::string & permissionName)45 bool OAIDServiceStub::CheckPermission(const std::string &permissionName)
46 {
47 // Verify the invoker's permission.
48 AccessTokenID firstCallToken = IPCSkeleton::GetFirstTokenID();
49 AccessTokenID callingToken = IPCSkeleton::GetCallingTokenID();
50 ATokenTypeEnum callingType = AccessTokenKit::GetTokenTypeFlag(callingToken);
51
52 ErrCode result = TypePermissionState::PERMISSION_DENIED;
53
54 if (firstCallToken == 0) {
55 if (callingType == TOKEN_INVALID) {
56 OAID_HILOGE(OAID_MODULE_SERVICE, "callingToken is invalid");
57 return false;
58 } else {
59 result = AccessTokenKit::VerifyAccessToken(callingToken, permissionName);
60 }
61 } else {
62 result = AccessTokenKit::VerifyAccessToken(callingToken, firstCallToken, permissionName);
63 }
64
65 if (callingType == TOKEN_HAP) {
66 int32_t successCnt = (int32_t)(result == TypePermissionState::PERMISSION_GRANTED);
67 int32_t failCnt = 1 - successCnt; // 1 means that there is only one visit in total
68 // AddPermissionUsedRecord needs to transfer both the number of successful and failed permission access requests
69 int32_t ret = PrivacyKit::AddPermissionUsedRecord(callingToken, permissionName, successCnt, failCnt);
70 if (ret != 0) {
71 OAID_HILOGI(OAID_MODULE_SERVICE, "AddPermissionUsedRecord ret=%{public}d", ret);
72 }
73 }
74
75 if (result == TypePermissionState::PERMISSION_DENIED) {
76 OAID_HILOGI(OAID_MODULE_SERVICE, "the caller not granted the app tracking permission");
77 return false;
78 }
79 return true;
80 }
81
CheckSystemApp()82 bool OAIDServiceStub::CheckSystemApp()
83 {
84 FullTokenID callingFullToken = IPCSkeleton::GetCallingFullTokenID();
85 auto tokenType = AccessTokenKit::GetTokenTypeFlag(IPCSkeleton::GetCallingTokenID());
86 if (TokenIdKit::IsSystemAppByFullTokenID(callingFullToken) && tokenType == TOKEN_HAP) {
87 return true;
88 }
89 OAID_HILOGW(OAID_MODULE_SERVICE, "the caller App is not system app");
90 return false;
91 }
92
LoadAndCheckOaidTrustList(const std::string & bundleName)93 bool LoadAndCheckOaidTrustList(const std::string &bundleName)
94 {
95 char pathBuff[PATH_MAX] = {0};
96 GetOneCfgFile(OAID_TRUSTLIST_EXTENSION_CONFIG_PATH.c_str(), pathBuff, PATH_MAX);
97 char realPath[PATH_MAX] = {0};
98 if (realpath(pathBuff, realPath) == nullptr) {
99 GetOneCfgFile(OAID_TRUSTLIST_CONFIG_PATH.c_str(), pathBuff, PATH_MAX);
100 if (realpath(pathBuff, realPath) == nullptr) {
101 OAID_HILOGE(OAID_MODULE_SERVICE, "Parse realpath fail");
102 return false;
103 }
104 }
105 std::ifstream inFile(realPath, std::ios::in);
106 if (!inFile.is_open()) {
107 OAID_HILOGE(OAID_MODULE_SERVICE, "Open file error.");
108 return false;
109 }
110 std::string fileContent((std::istreambuf_iterator<char>(inFile)), std::istreambuf_iterator<char>());
111 cJSON *root = cJSON_Parse(fileContent.c_str());
112 inFile.close();
113 if (root == nullptr) {
114 OAID_HILOGE(OAID_MODULE_SERVICE, "ParseJsonFromFile is not in JSON format.");
115 return false;
116 }
117 cJSON *oaidTrustConfig = cJSON_GetObjectItem(root, "resetOAIDBundleName");
118 if (oaidTrustConfig == nullptr || !cJSON_IsArray(oaidTrustConfig)) {
119 OAID_HILOGE(OAID_MODULE_SERVICE, "not contain resetOAIDBundleName node.");
120 cJSON_Delete(root);
121 return false;
122 }
123 int arraySize = cJSON_GetArraySize(oaidTrustConfig);
124 if (arraySize == 0) {
125 OAID_HILOGI(OAID_MODULE_SERVICE, "oaidTrustConfig list is empty.");
126 cJSON_Delete(root);
127 return true;
128 }
129 for (int i = 0; i < arraySize; i++) {
130 cJSON *item = cJSON_GetArrayItem(oaidTrustConfig, i);
131 if (cJSON_IsString(item)) {
132 if (bundleName.compare(item->valuestring) == 0) {
133 OAID_HILOGI(OAID_MODULE_SERVICE, "the oaidWhiteList contains this bundle name");
134 cJSON_Delete(root);
135 return true;
136 }
137 }
138 }
139 cJSON_Delete(root);
140 return false;
141 }
142
SendCode(uint32_t code,MessageParcel & data,MessageParcel & reply)143 int32_t OAIDServiceStub::SendCode(uint32_t code, MessageParcel &data, MessageParcel &reply)
144 {
145 switch (code) {
146 case static_cast<uint32_t>(OAIDInterfaceCode::GET_OAID): {
147 return OAIDServiceStub::OnGetOAID(data, reply);
148 break;
149 }
150 case static_cast<uint32_t>(OAIDInterfaceCode::RESET_OAID): {
151 return OAIDServiceStub::OnResetOAID(data, reply);
152 break;
153 }
154 case static_cast<uint32_t>(OAIDInterfaceCode::REGISTER_CONTROL_CONFIG_OBSERVER): {
155 return OAIDServiceStub::HandleRegisterControlConfigObserver(data, reply);
156 break;
157 }
158 }
159 return ERR_SYSYTEM_ERROR;
160 }
161
OnRemoteRequest(uint32_t code,MessageParcel & data,MessageParcel & reply,MessageOption & option)162 int32_t OAIDServiceStub::OnRemoteRequest(
163 uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
164 {
165 ExitIdleState();
166 PostDelayUnloadTask();
167 OAID_HILOGI(OAID_MODULE_SERVICE, "Start, code is %{public}u.", code);
168 std::string bundleName;
169 pid_t uid = IPCSkeleton::GetCallingUid();
170 DelayedSingleton<BundleMgrHelper>::GetInstance()->GetBundleNameByUid(static_cast<int>(uid), bundleName);
171 if (code == static_cast<uint32_t>(OAIDInterfaceCode::GET_OAID) &&
172 !CheckPermission(OAID_TRACKING_CONSENT_PERMISSION)) {
173 OAID_HILOGW(
174 OAID_MODULE_SERVICE, "bundleName %{public}s not granted the app tracking permission", bundleName.c_str());
175 return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
176 }
177 if (code == static_cast<uint32_t>(OAIDInterfaceCode::RESET_OAID)) {
178 int32_t validateResult = ValidateResetOAIDPermission(bundleName, reply);
179 if (validateResult == ERR_SYSYTEM_ERROR) {
180 return ERR_SYSYTEM_ERROR;
181 }
182 if (validateResult == ERR_PERMISSION_ERROR) {
183 return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
184 }
185 }
186 std::u16string myDescripter = OAIDServiceStub::GetDescriptor();
187 std::u16string remoteDescripter = data.ReadInterfaceToken();
188 if (myDescripter != remoteDescripter) {
189 OAID_HILOGE(OAID_MODULE_SERVICE, "Descriptor checked fail.");
190 return ERR_SYSYTEM_ERROR;
191 }
192 OAID_HILOGI(OAID_MODULE_SERVICE, "Remote bundleName is %{public}s.", bundleName.c_str());
193 return SendCode(code, data, reply);
194 }
195
ValidateResetOAIDPermission(std::string bundleName,MessageParcel & reply)196 int32_t OAIDServiceStub::ValidateResetOAIDPermission(std::string bundleName, MessageParcel &reply)
197 {
198 if (!LoadAndCheckOaidTrustList(bundleName)) {
199 OAID_HILOGW(
200 OAID_MODULE_SERVICE, "CheckOaidTrustList fail.errorCode = %{public}d", OAID_ERROR_NOT_IN_TRUST_LIST);
201 if (!reply.WriteInt32(OAID_ERROR_NOT_IN_TRUST_LIST)) {
202 OAID_HILOGE(OAID_MODULE_SERVICE, "write errorCode to reply failed.");
203 return ERR_SYSYTEM_ERROR;
204 }
205 return ERR_PERMISSION_ERROR;
206 }
207
208 if (!CheckSystemApp()) {
209 OAID_HILOGW(OAID_MODULE_SERVICE, "CheckSystemApp fail.errorCode = %{public}d", OAID_ERROR_CODE_NOT_SYSTEM_APP);
210 if (!reply.WriteInt32(OAID_ERROR_CODE_NOT_SYSTEM_APP)) {
211 OAID_HILOGE(OAID_MODULE_SERVICE, "write errorCode to reply failed.");
212 return ERR_SYSYTEM_ERROR;
213 }
214 return ERR_PERMISSION_ERROR;
215 }
216 return ERR_OK;
217 }
218
OnGetOAID(MessageParcel & data,MessageParcel & reply)219 int32_t OAIDServiceStub::OnGetOAID(MessageParcel &data, MessageParcel &reply)
220 {
221 OAID_HILOGI(OAID_MODULE_SERVICE, "Start.");
222
223 auto oaid = GetOAID();
224 if (oaid == "") {
225 OAID_HILOGE(OAID_MODULE_SERVICE, "Get OAID failed.");
226 return ERR_SYSYTEM_ERROR;
227 }
228
229 if (!reply.WriteString(oaid)) {
230 OAID_HILOGE(OAID_MODULE_SERVICE, "Failed to write parcelable.");
231 return ERR_SYSYTEM_ERROR;
232 }
233 checkProviderBundleName();
234 OAID_HILOGI(OAID_MODULE_SERVICE, "End.");
235 return ERR_OK;
236 }
237
checkProviderBundleName()238 void OAIDServiceStub::checkProviderBundleName()
239 {
240 OAID_HILOGI(OAID_MODULE_SERVICE, "enter checkProviderBundleName ");
241 char pathBuff[PATH_MAX] = {0};
242 GetOneCfgFile(OAID_TRUSTLIST_EXTENSION_CONFIG_PATH.c_str(), pathBuff, PATH_MAX);
243 char realPath[PATH_MAX] = {0};
244 if (realpath(pathBuff, realPath) == nullptr) {
245 GetOneCfgFile(OAID_TRUSTLIST_CONFIG_PATH.c_str(), pathBuff, PATH_MAX);
246 if (realpath(pathBuff, realPath) == nullptr) {
247 OAID_HILOGE(OAID_MODULE_SERVICE, "Parse realpath fail");
248 return;
249 }
250 }
251 std::ifstream inFile(realPath, std::ios::in);
252 if (!inFile.is_open()) {
253 OAID_HILOGE(OAID_MODULE_SERVICE, "Open file error.");
254 return;
255 }
256 std::string fileContent((std::istreambuf_iterator<char>{inFile}), std::istreambuf_iterator<char>{});
257 cJSON *root = cJSON_Parse(fileContent.c_str());
258 inFile.close();
259 if (root == nullptr) {
260 OAID_HILOGE(OAID_MODULE_SERVICE, "ParseJsonFromFile is not in JSON format.");
261 return;
262 }
263 cJSON *oaidProviderBundleNameConfig = cJSON_GetObjectItem(root, "providerBundleName");
264 if (oaidProviderBundleNameConfig == nullptr || oaidProviderBundleNameConfig->type != cJSON_String) {
265 OAID_HILOGE(OAID_MODULE_SERVICE, "not contain providerBundleName node.");
266 cJSON_Delete(root);
267 return;
268 }
269 std::string bundleName;
270 const char *providerBundleName = oaidProviderBundleNameConfig->valuestring;
271 pid_t uid = IPCSkeleton::GetCallingUid();
272 DelayedSingleton<BundleMgrHelper>::GetInstance()->GetBundleNameByUid(static_cast<int>(uid), bundleName);
273 if (bundleName.compare(providerBundleName) == 0) {
274 OAID_HILOGI(OAID_MODULE_SERVICE, "match current bundleName success");
275 ConnectAdsManager::GetInstance()->notifyKit(NOTIFY_GET_OAID_CODE);
276 }
277 cJSON_Delete(root);
278 OAID_HILOGI(OAID_MODULE_SERVICE, "end checkProviderBundleName ");
279 }
280
OnResetOAID(MessageParcel & data,MessageParcel & reply)281 int32_t OAIDServiceStub::OnResetOAID(MessageParcel &data, MessageParcel &reply)
282 {
283 OAID_HILOGI(OAID_MODULE_SERVICE, "Reset OAID Start.");
284
285 ResetOAID();
286
287 OAID_HILOGI(OAID_MODULE_SERVICE, "Reset OAID End.");
288 return ERR_OK;
289 }
290
ExitIdleState()291 void OAIDServiceStub::ExitIdleState()
292 {
293 auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
294 if (samgrProxy == nullptr) {
295 OAID_HILOGE(OAID_MODULE_SERVICE, "Get samgr failed.");
296 return;
297 }
298 int32_t ret = samgrProxy->CancelUnloadSystemAbility(OAID_SYSTME_ID);
299 if (ret != ERR_OK) {
300 OAID_HILOGE(OAID_MODULE_SERVICE,
301 "CancelUnload system ability %{public}d failed, result: %{public}d.",
302 OAID_SYSTME_ID,
303 ret);
304 return;
305 }
306 }
307
PostDelayUnloadTask()308 void OAIDServiceStub::PostDelayUnloadTask()
309 {
310 init_eventHandler_Mutex_.lock();
311 if (unloadHandler_ == nullptr) {
312 const char *runnerName = "unlock";
313 auto runner = AppExecFwk::EventRunner::Create(runnerName);
314 unloadHandler_ = std::make_shared<AppExecFwk::EventHandler>(runner);
315 }
316 init_eventHandler_Mutex_.unlock();
317 auto task = [this]() {
318 auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
319 if (samgrProxy == nullptr) {
320 OAID_HILOGE(OAID_MODULE_SERVICE, "Get samgr failed.");
321 return;
322 }
323 int32_t ret = samgrProxy->UnloadSystemAbility(OAID_SYSTME_ID);
324 if (ret != ERR_OK) {
325 OAID_HILOGE(OAID_MODULE_SERVICE,
326 "Unload system ability %{public}d failed, result: %{public}d.",
327 OAID_SYSTME_ID,
328 ret);
329 return;
330 }
331 };
332 unloadHandler_->RemoveTask(TASK_ID);
333 unloadHandler_->PostTask(task, TASK_ID, DELAY_TIME);
334 }
335
HandleRegisterControlConfigObserver(MessageParcel & data,MessageParcel & reply)336 int32_t OAIDServiceStub::HandleRegisterControlConfigObserver(MessageParcel &data, MessageParcel &reply)
337 {
338 int32_t uid = IPCSkeleton::GetCallingUid();
339 if (uid != HA_UID) {
340 OAID_HILOGE(OAID_MODULE_SERVICE, "callingUid error, error code is: %{public}d", ERR_INVALID_PARAM);
341 return ERR_INVALID_PARAM;
342 }
343 auto remoteObject = data.ReadRemoteObject();
344 if (!remoteObject) {
345 OAID_HILOGI(OAID_MODULE_SERVICE, "Observer is null, error code is: %{public}d", ERR_NULL_POINTER);
346 return ERR_NULL_POINTER;
347 }
348 auto observer = iface_cast<IRemoteConfigObserver>(remoteObject);
349 if (observer == nullptr) {
350 OAID_HILOGI(OAID_MODULE_SERVICE, "Observer is null, error code is: %{public}d", ERR_NULL_POINTER);
351 return ERR_NULL_POINTER;
352 }
353 return RegisterObserver(observer);
354 }
355
RegisterObserver(const sptr<IRemoteConfigObserver> & observer)356 int32_t OAIDServiceStub::RegisterObserver(const sptr<IRemoteConfigObserver> &observer)
357 {
358 OAID_HILOGI(OAID_MODULE_SERVICE, "registerObserver success.");
359 return DelayedSingleton<OaidObserverManager>::GetInstance()->RegisterObserver(observer);
360 }
361 } // namespace Cloud
362 } // namespace OHOS