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 "loghelper.h"
17 #include "app_data_parser.h"
18 #include "external_deps_proxy.h"
19 #include "host_card_emulation_manager.h"
20 #include "ability_manager_client.h"
21 #include "nfc_sdk_common.h"
22 #include "accesstoken_kit.h"
23 #include "hap_token_info.h"
24 
25 namespace OHOS {
26 namespace NFC {
27 #ifdef VENDOR_APPLICATIONS_ENABLED
28 static const int CODE_SEND_FIELD_DEACTIVATE = 0;
29 static const int CODE_SEND_FIELD_ACTIVATE = 1;
30 static const int CODE_SEND_APDU_DATA = 2;
31 #endif
32 const uint32_t SELECT_APDU_HDR_LENGTH = 5;
33 const uint8_t INSTR_SELECT = 0xA4;
34 const uint32_t MINIMUM_AID_LENGTH = 5;
35 const uint8_t SELECT_00 = 0x00;
36 const uint8_t SELECT_P1 = 0x04;
37 const uint32_t INDEX_CLASS_BYTE = 0;
38 const uint32_t INDEX_CHAIN_INSTRUCTION = 1;
39 const uint32_t INDEX_P1 = 2;
40 const uint32_t INDEX_3 = 3;
41 const uint32_t INDEX_AID_LEN = 4;
42 using OHOS::AppExecFwk::ElementName;
HostCardEmulationManager(std::weak_ptr<NfcService> nfcService,std::weak_ptr<NCI::INciCeInterface> nciCeProxy,std::weak_ptr<CeService> ceService)43 HostCardEmulationManager::HostCardEmulationManager(std::weak_ptr<NfcService> nfcService,
44                                                    std::weak_ptr<NCI::INciCeInterface> nciCeProxy,
45                                                    std::weak_ptr<CeService> ceService)
46     : nfcService_(nfcService), nciCeProxy_(nciCeProxy), ceService_(ceService)
47 {
48     hceState_ = HostCardEmulationManager::INITIAL_STATE;
49     queueHceData_.clear();
50     abilityConnection_ = new (std::nothrow) NfcAbilityConnectionCallback();
51 }
~HostCardEmulationManager()52 HostCardEmulationManager::~HostCardEmulationManager()
53 {
54     hceState_ = HostCardEmulationManager::INITIAL_STATE;
55     queueHceData_.clear();
56     abilityConnection_ = nullptr;
57     bundleNameToHceCmdRegData_.clear();
58 }
59 
OnHostCardEmulationDataNfcA(const std::vector<uint8_t> & data)60 void HostCardEmulationManager::OnHostCardEmulationDataNfcA(const std::vector<uint8_t>& data)
61 {
62     if (data.empty()) {
63         InfoLog("onHostCardEmulationDataNfcA: no data");
64         return;
65     }
66     std::string dataStr = KITS::NfcSdkCommon::BytesVecToHexString(&data[0], data.size());
67     InfoLog("onHostCardEmulationDataNfcA: Data Length = %{public}zu; Data as "
68             "String = %{public}s",
69             data.size(), dataStr.c_str());
70 
71 #ifdef VENDOR_APPLICATIONS_ENABLED
72     // send data to vendor
73     sptr<IOnCardEmulationNotifyCb> notifyApduDataCallback =
74         ExternalDepsProxy::GetInstance().GetNotifyCardEmulationCallback();
75     if (notifyApduDataCallback && notifyApduDataCallback->OnCardEmulationNotify(CODE_SEND_APDU_DATA, dataStr)) {
76         InfoLog("onHostCardEmulationDataNfcA: data to vendor");
77         return;
78     }
79 #endif
80 
81     std::string aid = ParseSelectAid(data);
82     InfoLog("onHostCardEmulationDataNfcA: selectAid = %{public}s, state %{public}d", aid.c_str(), hceState_);
83     ElementName aidElement;
84     if (ceService_.expired()) {
85         ErrorLog("ce service expired.");
86         return;
87     }
88     ceService_.lock()->SearchElementByAid(aid, aidElement);
89 
90     std::lock_guard<std::mutex> lock(hceStateMutex_);
91     switch (hceState_) {
92         case HostCardEmulationManager::INITIAL_STATE: {
93             InfoLog("got data on state INITIAL_STATE");
94             return;
95         }
96         case HostCardEmulationManager::WAIT_FOR_SELECT: {
97             HandleDataOnW4Select(aid, aidElement, data);
98             break;
99         }
100         case HostCardEmulationManager::WAIT_FOR_SERVICE: {
101             InfoLog("got data on state w4 service");
102             return;
103         }
104         case HostCardEmulationManager::DATA_TRANSFER: {
105             HandleDataOnDataTransfer(aid, aidElement, data);
106             break;
107         }
108         case HostCardEmulationManager::WAIT_FOR_DEACTIVATE: {
109             InfoLog("got data on state w4 deactivate");
110             return;
111         }
112         default: break;
113     }
114 }
115 
OnCardEmulationActivated()116 void HostCardEmulationManager::OnCardEmulationActivated()
117 {
118     InfoLog("OnCardEmulationActivated: state %{public}d", hceState_);
119     std::lock_guard<std::mutex> lock(hceStateMutex_);
120     hceState_ = HostCardEmulationManager::WAIT_FOR_SELECT;
121     InfoLog("hce state is %{public}d.", hceState_);
122 
123 #ifdef VENDOR_APPLICATIONS_ENABLED
124     // send data to vendor
125     sptr<IOnCardEmulationNotifyCb> notifyApduDataCallback =
126         ExternalDepsProxy::GetInstance().GetNotifyCardEmulationCallback();
127     if (notifyApduDataCallback != nullptr) {
128         std::string data{};
129         notifyApduDataCallback->OnCardEmulationNotify(CODE_SEND_FIELD_ACTIVATE, data);
130     }
131 #endif
132 
133     queueHceData_.clear();
134 }
135 
OnCardEmulationDeactivated()136 void HostCardEmulationManager::OnCardEmulationDeactivated()
137 {
138     InfoLog("OnCardEmulationDeactivated: state %{public}d", hceState_);
139     std::lock_guard<std::mutex> lock(hceStateMutex_);
140     hceState_ = HostCardEmulationManager::INITIAL_STATE;
141     InfoLog("hce state is %{public}d.", hceState_);
142 
143 #ifdef VENDOR_APPLICATIONS_ENABLED
144     // send data to vendor
145     sptr<IOnCardEmulationNotifyCb> notifyApduDataCallback =
146         ExternalDepsProxy::GetInstance().GetNotifyCardEmulationCallback();
147     if (notifyApduDataCallback != nullptr) {
148         std::string data{};
149         notifyApduDataCallback->OnCardEmulationNotify(CODE_SEND_FIELD_DEACTIVATE, data);
150     }
151 #endif
152 
153     queueHceData_.clear();
154     if (abilityConnection_ == nullptr) {
155         ErrorLog("OnCardEmulationDeactivated abilityConnection_ nullptr.");
156         return;
157     }
158     ErrCode releaseCallRet = AAFwk::AbilityManagerClient::GetInstance()->ReleaseCall(
159         abilityConnection_, abilityConnection_->GetConnectedElement());
160     InfoLog("Release call end. ret = %{public}d", releaseCallRet);
161 }
162 
HandleDataOnW4Select(const std::string & aid,ElementName & aidElement,const std::vector<uint8_t> & data)163 void HostCardEmulationManager::HandleDataOnW4Select(const std::string& aid, ElementName& aidElement,
164                                                     const std::vector<uint8_t>& data)
165 {
166     bool exitService = ExistService(aidElement);
167     if (!aid.empty()) {
168         if (exitService) {
169             InfoLog("HandleDataOnW4Select: existing service, try to send data "
170                     "directly.");
171             hceState_ = HostCardEmulationManager::DATA_TRANSFER;
172             InfoLog("hce state is %{public}d.", hceState_);
173             SendDataToService(data);
174             return;
175         } else {
176             InfoLog("HandleDataOnW4Select: try to connect service.");
177             queueHceData_ = std::move(data);
178             DispatchAbilitySingleApp(aidElement);
179             return;
180         }
181     } else if (exitService) {
182         InfoLog("HandleDataOnW4Select: existing service, try to send data "
183                 "directly.");
184         hceState_ = HostCardEmulationManager::DATA_TRANSFER;
185         SendDataToService(data);
186         return;
187     } else {
188         InfoLog("no aid got");
189         std::string unknowError = "6F00";
190         nciCeProxy_.lock()->SendRawFrame(unknowError);
191     }
192 }
193 
HandleDataOnDataTransfer(const std::string & aid,ElementName & aidElement,const std::vector<uint8_t> & data)194 void HostCardEmulationManager::HandleDataOnDataTransfer(const std::string& aid, ElementName& aidElement,
195                                                         const std::vector<uint8_t>& data)
196 {
197     bool exitService = ExistService(aidElement);
198     if (!aid.empty()) {
199         if (exitService) {
200             InfoLog("HandleDataOnDataTransfer: existing service, try to send "
201                     "data directly.");
202             hceState_ = HostCardEmulationManager::DATA_TRANSFER;
203             InfoLog("hce state is %{public}d.", hceState_);
204             SendDataToService(data);
205             return;
206         } else {
207             InfoLog("HandleDataOnDataTransfer: existing service, try to "
208                     "connect service.");
209             queueHceData_ = std::move(data);
210             DispatchAbilitySingleApp(aidElement);
211             return;
212         }
213     } else if (exitService) {
214         InfoLog("HandleDataOnDataTransfer: existing service, try to send data "
215                 "directly.");
216         hceState_ = HostCardEmulationManager::DATA_TRANSFER;
217         InfoLog("hce state is %{public}d.", hceState_);
218         SendDataToService(data);
219         return;
220     } else {
221         InfoLog("no service, drop apdu data.");
222     }
223 }
ExistService(ElementName & aidElement)224 bool HostCardEmulationManager::ExistService(ElementName& aidElement)
225 {
226     if (abilityConnection_ == nullptr || (!abilityConnection_->ServiceConnected())) {
227         InfoLog("no service connected.");
228         return false;
229     }
230     std::string bundleName = abilityConnection_->GetConnectedElement().GetBundleName();
231     std::lock_guard<std::mutex> lock(regInfoMutex_);
232     auto it = bundleNameToHceCmdRegData_.find(bundleName);
233     if (it == bundleNameToHceCmdRegData_.end()) {
234         ErrorLog("no register data for %{public}s", abilityConnection_->GetConnectedElement().GetURI().c_str());
235         return false;
236     }
237     if (it->second.callback_ == nullptr) {
238         ErrorLog("callback is null");
239         return false;
240     }
241 
242     if (aidElement.GetBundleName().empty()) {
243         InfoLog("aid is empty.");
244         // normal data not select data
245         return true;
246     }
247     // only verify the element name for select data
248     if (aidElement.GetBundleName() == abilityConnection_->GetConnectedElement().GetBundleName() &&
249         aidElement.GetAbilityName() == abilityConnection_->GetConnectedElement().GetAbilityName()) {
250         InfoLog("ability is already connected.");
251         return true;
252     } else {
253         WarnLog("not the same element");
254         return false;
255     }
256 }
257 
ParseSelectAid(const std::vector<uint8_t> & data)258 std::string HostCardEmulationManager::ParseSelectAid(const std::vector<uint8_t>& data)
259 {
260     if (data.empty() || data.size() < SELECT_APDU_HDR_LENGTH + MINIMUM_AID_LENGTH) {
261         InfoLog("invalid data. Data size less than hdr length plus minumum length.");
262         return "";
263     }
264 
265     if (data[INDEX_CLASS_BYTE] == SELECT_00 && data[INDEX_CHAIN_INSTRUCTION] == INSTR_SELECT &&
266         data[INDEX_P1] == SELECT_P1) {
267         if (data[INDEX_3] != SELECT_00) {
268             InfoLog("not supported aid");
269             return "";
270         }
271 
272         uint8_t aidLength = data[INDEX_AID_LEN];
273         if (data.size() < SELECT_APDU_HDR_LENGTH + aidLength) {
274             InfoLog("invalid data. Data size less than hdr length plus aid declared length.");
275             return "";
276         }
277 
278         std::vector<uint8_t> aidVec(data.begin() + SELECT_APDU_HDR_LENGTH,
279                                     data.begin() + SELECT_APDU_HDR_LENGTH + aidLength);
280         return KITS::NfcSdkCommon::BytesVecToHexString(&aidVec[0], aidVec.size());
281     }
282 
283     return "";
284 }
285 
RegHceCmdCallback(const sptr<KITS::IHceCmdCallback> & callback,const std::string & type,Security::AccessToken::AccessTokenID callerToken)286 bool HostCardEmulationManager::RegHceCmdCallback(const sptr<KITS::IHceCmdCallback>& callback,
287                                                  const std::string& type,
288                                                  Security::AccessToken::AccessTokenID callerToken)
289 {
290     if (nfcService_.expired()) {
291         ErrorLog("RegHceCmdCallback: nfcService_ is nullptr.");
292         return false;
293     }
294     if (!nfcService_.lock()->IsNfcEnabled()) {
295         ErrorLog("RegHceCmdCallback: NFC not enabled, do not set ");
296         return false;
297     }
298     InfoLog("RegHceCmdCallback start, register size =%{public}zu.", bundleNameToHceCmdRegData_.size());
299     Security::AccessToken::HapTokenInfo hapTokenInfo;
300     int result = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(callerToken, hapTokenInfo);
301 
302     InfoLog("get hap token info, result = %{public}d", result);
303     if (result) {
304         return false;
305     }
306     if (hapTokenInfo.bundleName.empty()) {
307         ErrorLog("RegHceCmdCallback: not got bundle name");
308         return false;
309     }
310     HostCardEmulationManager::HceCmdRegistryData regData;
311 
312     regData.callback_ = callback;
313     regData.callerToken_ = callerToken;
314     std::lock_guard<std::mutex> lock(regInfoMutex_);
315     if (bundleNameToHceCmdRegData_.find(hapTokenInfo.bundleName) != bundleNameToHceCmdRegData_.end()) {
316         InfoLog("override the register data for  %{public}s", hapTokenInfo.bundleName.c_str());
317     }
318     bundleNameToHceCmdRegData_[hapTokenInfo.bundleName] = regData;
319 
320     InfoLog("RegHceCmdCallback end, register size =%{public}zu.", bundleNameToHceCmdRegData_.size());
321     return true;
322 }
323 
SendHostApduData(std::string hexCmdData,bool raw,std::string & hexRespData,Security::AccessToken::AccessTokenID callerToken)324 bool HostCardEmulationManager::SendHostApduData(std::string hexCmdData, bool raw, std::string& hexRespData,
325                                                 Security::AccessToken::AccessTokenID callerToken)
326 {
327     if (nfcService_.expired()) {
328         ErrorLog("SendHostApduData: nfcService_ is nullptr.");
329         return false;
330     }
331     if (!nfcService_.lock()->IsNfcEnabled()) {
332         ErrorLog("SendHostApduData: NFC not enabled, do not send.");
333         return false;
334     }
335     if (!IsCorrespondentService(callerToken)) {
336         ErrorLog("SendHostApduData: not the connected app, do not send.");
337         return false;
338     }
339 
340     return nciCeProxy_.lock()->SendRawFrame(hexCmdData);
341 }
IsCorrespondentService(Security::AccessToken::AccessTokenID callerToken)342 bool HostCardEmulationManager::IsCorrespondentService(Security::AccessToken::AccessTokenID callerToken)
343 {
344     Security::AccessToken::HapTokenInfo hapTokenInfo;
345     int result = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(callerToken, hapTokenInfo);
346 
347     InfoLog("get hap token info, result = %{public}d", result);
348 #ifdef VENDOR_APPLICATIONS_ENABLED
349     if (result) {
350         WarnLog("vendor application, allow to send raw frame.");
351         return true;
352     }
353 #endif
354     if (abilityConnection_ == nullptr) {
355         ErrorLog("IsCorrespondentService abilityConnection_ is null");
356         return false;
357     }
358     if (!hapTokenInfo.bundleName.empty() &&
359         hapTokenInfo.bundleName == abilityConnection_->GetConnectedElement().GetBundleName()) {
360         return true;
361     }
362     ErrorLog("SendHostApduData: diff app, the call app %{public}s , the connected app %{public}s",
363              hapTokenInfo.bundleName.c_str(), abilityConnection_->GetConnectedElement().GetBundleName().c_str());
364     return false;
365 }
366 
HandleQueueData()367 void HostCardEmulationManager::HandleQueueData()
368 {
369     bool shouldSendQueueData = hceState_ == HostCardEmulationManager::WAIT_FOR_SERVICE && !queueHceData_.empty();
370 
371     std::string queueData = KITS::NfcSdkCommon::BytesVecToHexString(&queueHceData_[0], queueHceData_.size());
372     if (abilityConnection_ == nullptr) {
373         ErrorLog("HandleQueueData abilityConnection_ is null");
374         return;
375     }
376     InfoLog("RegHceCmdCallback queue data %{public}s, hceState= %{public}d, "
377             "service connected= %{public}d",
378             queueData.c_str(), hceState_, abilityConnection_->ServiceConnected());
379     if (shouldSendQueueData) {
380         InfoLog("RegHceCmdCallback should send queue data");
381         hceState_ = HostCardEmulationManager::DATA_TRANSFER;
382         InfoLog("hce state is %{public}d.", hceState_);
383         SendDataToService(queueHceData_);
384         queueHceData_.clear();
385         return;
386     }
387     WarnLog("HandleQueueData can not send the data.");
388 }
389 
SendDataToService(const std::vector<uint8_t> & data)390 void HostCardEmulationManager::SendDataToService(const std::vector<uint8_t>& data)
391 {
392     if (abilityConnection_ == nullptr) {
393         ErrorLog("SendDataToService abilityConnection_ is null");
394         return;
395     }
396     std::string bundleName = abilityConnection_->GetConnectedElement().GetBundleName();
397     InfoLog("SendDataToService register size =%{public}zu.", bundleNameToHceCmdRegData_.size());
398     std::lock_guard<std::mutex> lock(regInfoMutex_);
399     auto it = bundleNameToHceCmdRegData_.find(bundleName);
400     if (it == bundleNameToHceCmdRegData_.end()) {
401         ErrorLog("no register data for %{public}s", abilityConnection_->GetConnectedElement().GetURI().c_str());
402         return;
403     }
404     if (it->second.callback_ == nullptr) {
405         ErrorLog("callback is null");
406         return;
407     }
408     it->second.callback_->OnCeApduData(data);
409 }
410 
DispatchAbilitySingleApp(ElementName & element)411 bool HostCardEmulationManager::DispatchAbilitySingleApp(ElementName& element)
412 {
413     if (abilityConnection_ == nullptr) {
414         ErrorLog("DispatchAbilitySingleApp abilityConnection_ is null");
415         return false;
416     }
417     abilityConnection_->SetHceManager(shared_from_this());
418     if (element.GetBundleName().empty()) {
419         ErrorLog("DispatchAbilitySingleApp element empty");
420         std::string aidNotFound = "6A82";
421         nciCeProxy_.lock()->SendRawFrame(aidNotFound);
422         return false;
423     }
424 
425     InfoLog("DispatchAbilitySingleApp for element  %{public}s", element.GetURI().c_str());
426     AAFwk::Want want;
427     want.SetElement(element);
428 
429     if (AAFwk::AbilityManagerClient::GetInstance() == nullptr) {
430         ErrorLog("DispatchAbilitySingleApp AbilityManagerClient is null");
431         return false;
432     }
433     ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbilityByCall(want, abilityConnection_);
434     InfoLog("DispatchAbilitySingleApp call StartAbility end. ret = %{public}d", err);
435     if (err == ERR_NONE) {
436         hceState_ = HostCardEmulationManager::WAIT_FOR_SERVICE;
437         InfoLog("hce state is %{public}d.", hceState_);
438         ExternalDepsProxy::GetInstance().WriteHceSwipeResultHiSysEvent(element.GetBundleName(), DEFAULT_COUNT);
439 
440         NfcFailedParams params;
441         ExternalDepsProxy::GetInstance().BuildFailedParams(params, MainErrorCode::HCE_SWIPE_CARD,
442                                                            SubErrorCode::DEFAULT_ERR_DEF);
443         params.appPackageName = element.GetBundleName();
444         ExternalDepsProxy::GetInstance().WriteNfcFailedHiSysEvent(&params);
445         return true;
446     }
447     return false;
448 }
UnRegHceCmdCallback(const std::string & type,Security::AccessToken::AccessTokenID callerToken)449 bool HostCardEmulationManager::UnRegHceCmdCallback(const std::string& type,
450                                                    Security::AccessToken::AccessTokenID callerToken)
451 {
452     return EraseHceCmdCallback(callerToken);
453 }
EraseHceCmdCallback(Security::AccessToken::AccessTokenID callerToken)454 bool HostCardEmulationManager::EraseHceCmdCallback(Security::AccessToken::AccessTokenID callerToken)
455 {
456     InfoLog("EraseHceCmdCallback start, register size =%{public}zu.", bundleNameToHceCmdRegData_.size());
457     Security::AccessToken::HapTokenInfo hapTokenInfo;
458     int result = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(callerToken, hapTokenInfo);
459 
460     InfoLog("get hap token info, result = %{public}d", result);
461     if (result) {
462         return false;
463     }
464     if (hapTokenInfo.bundleName.empty()) {
465         ErrorLog("EraseHceCmdCallback: not got bundle name");
466         return false;
467     }
468     std::lock_guard<std::mutex> lock(regInfoMutex_);
469 
470     if (bundleNameToHceCmdRegData_.find(hapTokenInfo.bundleName) != bundleNameToHceCmdRegData_.end()) {
471         InfoLog("unregister data for  %{public}s", hapTokenInfo.bundleName.c_str());
472     }
473     bundleNameToHceCmdRegData_.erase(hapTokenInfo.bundleName);
474     InfoLog("EraseHceCmdCallback end, register size =%{public}zu.", bundleNameToHceCmdRegData_.size());
475     return true;
476 }
477 
UnRegAllCallback(Security::AccessToken::AccessTokenID callerToken)478 bool HostCardEmulationManager::UnRegAllCallback(Security::AccessToken::AccessTokenID callerToken)
479 {
480     return EraseHceCmdCallback(callerToken);
481 }
482 } // namespace NFC
483 } // namespace OHOS