mod_AccessAuth.cpp 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032
  1. #include "stdafx.h"
  2. #include "SpBase.h"
  3. #include "mod_AccessAuth.h"
  4. #include "RVCComm.h"
  5. #include "access_basefun.h"
  6. #include <fileutil.h>
  7. #include <cmath>
  8. #include "Event.h"
  9. #include "comm.h"
  10. #include "TokenKeeper_client_g.h"
  11. using namespace TokenKeeper;
  12. #include "PinPad_client_g.h"
  13. using namespace PinPad;
  14. #ifdef RVC_OS_WIN
  15. #include "WMIDeviceQuery.h"
  16. #include <WinCrypt.h>
  17. #include <Strsafe.h>
  18. #include "DeviceBaseClass.h"
  19. #include "MyBase64.h"
  20. #else
  21. #include "CommEntityRestful.hpp"
  22. #include "DeviceBaseClass.h"
  23. #include <iniutil.h>
  24. #endif
  25. #define KEY_SIZE 16
  26. #define BUF_SIZE 256
  27. extern int HexBuf2StrBuf(PBYTE hexBuf, char** strBuf, DWORD len);
  28. extern int StrBuf2HexBuf(LPCTSTR strBuf, PBYTE* hexBuf);
  29. struct InitializerInitMKTask : ITaskSp
  30. {
  31. CAccessAuthFSM* m_fsm;
  32. CAccessAuthEntity* m_entity;
  33. InitializerInitMKTask(CAccessAuthFSM* fsm, CAccessAuthEntity* entity) :m_fsm(fsm), m_entity(entity) {}
  34. void Process()
  35. {
  36. CSystemStaticInfo si;
  37. m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(si);
  38. #ifdef RVC_OS_WIN
  39. IHttpFunc* client;
  40. client = create_http(m_fsm->HttpsLogCallBack);
  41. CInitlizerMKReq initMKReq;
  42. CInitlizerMKRet initMKRet;
  43. bool initFlag = m_entity->SendInitMKReqACS(initMKReq);
  44. if (!initFlag)
  45. {
  46. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5204")("连接密码键盘异常");
  47. m_entity->EndInitMK(ERR_ACCESSAUTH_CONNECT_PINPAD, "连接密码键盘异常,请检查");//,待完善细化错误码oiltest
  48. client->Destory();
  49. }
  50. auto tmkpair = m_entity->GenerateTmkToKMC();
  51. initMKReq.encRandom = tmkpair.first;
  52. initMKReq.m_url = m_entity->GetInitUrl();
  53. initMKReq.m_url += "/api/v5/initmk";
  54. long beg = GetTickCount();
  55. bool ret = client->Post(initMKReq, initMKRet);
  56. long end = GetTickCount();
  57. if (ret) {
  58. if (initMKRet.m_userCode.compare(ACS_SUCCESS)) {
  59. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("InitializerInitMKTask")("initmk failed.");
  60. if (client) client->Destory();
  61. m_entity->EndInitMK(ERR_INITIALIZER_INIT_EXCEPTION, CSimpleStringA::Format("%s,%s"
  62. , initMKRet.m_userCode.c_str(), initMKRet.m_errMsg.c_str()));
  63. return;
  64. }
  65. //服务端返回成功再将数据写入AcessAuthourization.ini
  66. CSmartPointer<IConfigInfo> pConfig;
  67. auto rc = m_entity->GetFunction()->OpenConfig(Config_Run, pConfig);
  68. rc = pConfig->WriteConfigValue("TerminalPD", "PrivateKey", m_entity->m_privateKey);
  69. if (rc != Error_Succeed) {
  70. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("write pri key failed.");
  71. m_entity->EndInitMK(ERR_INITIALIZER_INIT_EXCEPTION, "私钥写入失败,请重新初始化。");
  72. return;
  73. }
  74. if (m_entity->HasPinPad()) {
  75. if (m_entity->LoadKeysToPinPadACS(tmkpair.second, initMKRet.tpk, initMKRet.edk, initMKRet.keyIndex) == Error_Succeed)
  76. m_entity->EndInitMK(Error_Succeed, "");
  77. else
  78. {
  79. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5204")("连接密码键盘异常");
  80. m_entity->EndInitMK(ERR_ACCESSAUTH_CONNECT_PINPAD, "密钥加载失败,请检查密码键盘连接。");//,待完善细化错误码oiltest
  81. }
  82. }
  83. else
  84. m_entity->EndInitMK(Error_Succeed, "");
  85. }
  86. else {
  87. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI("InitializerInitMKTask").setBeginTime(beg).setEndTime(end).
  88. setResultCode(std::to_string(LONGLONG(initMKRet.m_sysCode)).c_str()).
  89. setResultMsg(initMKRet.m_errMsg.c_str())("InitializerInitMKTask Connect Failed.");
  90. m_entity->EndInitMK(ERR_INITIALIZER_INIT_EXCEPTION, CSimpleStringA::Format("初始化服务连接失败。%d", ret).GetData());
  91. }
  92. client->Destory();
  93. #else
  94. CInitlizerMKReq initMKReq;//oiltest dev module count
  95. bool initFlag = m_entity->SendInitMKReqACS(initMKReq);
  96. if (!initFlag)
  97. {
  98. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5204")("连接密码键盘异常");
  99. m_entity->EndInitMK(ERR_ACCESSAUTH_CONNECT_PINPAD, "连接密码键盘异常,请检查");//,待完善细化错误码oiltest
  100. }
  101. auto tmkpair = m_entity->GenerateTmkToKMC();
  102. struct InstanceReqJson
  103. {
  104. string enrolAddr;
  105. string enrolGPS;
  106. string installVersion;
  107. string ip;
  108. string machineModel;
  109. string machineType;
  110. string padDeviceID;
  111. string site;
  112. string terminalNo;
  113. string factory;
  114. string modal;
  115. string type;
  116. string version;
  117. string terminalCharacter; //终端特征值(fingerPrint + fingerPrintSM)
  118. string pinPadID;
  119. string publicKey;
  120. string user; //操作人
  121. string password; //密码
  122. string auth;//预留鉴权
  123. int loginWay;//1表示错误页发起,需要传入登录密码;0表示用户桌面发起,不需要传入登录密码
  124. string encRandom; //tmk pk加密的随机密钥
  125. string tpkKeyCheck; //密钥校验值
  126. string edkKeyCheck; //密钥校验值
  127. string keyIndex; //密钥序号
  128. JSONCONVERT2OBJECT_MEMEBER_REGISTER(enrolAddr, enrolGPS, installVersion, ip, machineModel, machineType,
  129. padDeviceID, site, terminalNo, factory, modal, type, version, terminalCharacter, pinPadID, publicKey,
  130. user, password, auth, loginWay, encRandom, tpkKeyCheck, edkKeyCheck, keyIndex)
  131. } instanceReq;
  132. instanceReq.enrolAddr = initMKReq.enrolAddr;
  133. instanceReq.enrolGPS = initMKReq.enrolGPS;
  134. instanceReq.installVersion = initMKReq.installVersion;
  135. instanceReq.ip = initMKReq.ip;
  136. instanceReq.machineModel = initMKReq.machineModel;
  137. instanceReq.machineType = initMKReq.machineType;
  138. instanceReq.padDeviceID = initMKReq.padDeviceID;
  139. instanceReq.site = initMKReq.site;
  140. instanceReq.terminalNo = initMKReq.terminalNo;
  141. instanceReq.factory = initMKReq.factory;
  142. instanceReq.modal = initMKReq.modal;
  143. instanceReq.type = initMKReq.type;
  144. instanceReq.version = initMKReq.version;
  145. instanceReq.terminalCharacter = initMKReq.terminalCharacter;
  146. instanceReq.pinPadID = initMKReq.pinPadID;
  147. instanceReq.publicKey = initMKReq.publicKey;
  148. instanceReq.user = initMKReq.user;
  149. instanceReq.password = initMKReq.password;
  150. instanceReq.auth = initMKReq.auth;
  151. instanceReq.loginWay = initMKReq.loginWay;
  152. instanceReq.encRandom = tmkpair.first;
  153. instanceReq.tpkKeyCheck = initMKReq.tpkKeyCheck;
  154. instanceReq.edkKeyCheck = initMKReq.edkKeyCheck;
  155. instanceReq.keyIndex = initMKReq.keyIndex;
  156. struct InstanceAnsJson
  157. {
  158. string TMK;
  159. string TPK;
  160. string EDK;
  161. string tpkKeyCheck;
  162. string edkKeyCheck;
  163. string keyIndex;
  164. string reserved;
  165. JSONCONVERT2OBJECT_MEMEBER_REGISTER(TMK, TPK, EDK, tpkKeyCheck, edkKeyCheck, keyIndex)
  166. JSONCONVERT2OBJECT_MEMEBER_RENAME_REGISTER("tmk", "tpk", "edk", "tpkKeyCheck", "edkKeyCheck", "keyIndex")
  167. } instanceAns;
  168. HttpClientResponseResult result;
  169. HttpClientRequestConfig config(HttpRequestMethod::POST, m_entity->GetInitUrl().GetData(), &SpGetToken);
  170. config.SetChildUri("/api/v5/initmk");
  171. SP::Module::Restful::FulfillRequestJsonBody(&config, instanceReq);
  172. std::string test;
  173. test = config.GetRequestUri();
  174. RestfulClient client = RestfulClient::getInstance();
  175. config.PreDo();
  176. client.Do(&config, &result);
  177. if (result.ResponseOK()) {
  178. SP::Module::Restful::CommResponseJson responseStatus;
  179. SP::Module::Restful::GetStatusFromDebranchResponse(result.content, responseStatus);
  180. if (!responseStatus.IsOperatedOK()) {
  181. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("update wk failed: %s", responseStatus.errorMsg.c_str());
  182. m_entity->EndInitMK(ERR_INITIALIZER_INIT_EXCEPTION, responseStatus.errorMsg.c_str());
  183. }
  184. else {
  185. //服务端返回成功再将数据写入AcessAuthourization.ini
  186. CSmartPointer<IConfigInfo> pConfig;
  187. auto rc = m_entity->GetFunction()->OpenConfig(Config_Run, pConfig);
  188. rc = pConfig->WriteConfigValue("TerminalPD", "PrivateKey", m_entity->m_privateKey);
  189. if (rc != Error_Succeed) {
  190. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("write pri key failed.");
  191. m_entity->EndInitMK(ERR_INITIALIZER_INIT_EXCEPTION, "私钥写入失败,请重新初始化。");
  192. return;
  193. }
  194. if (m_entity->HasPinPad()) {
  195. const bool testResult = SP::Module::Restful::ExtractDataFromDebranchResponse(result.content, instanceAns);
  196. if (m_entity->LoadKeysToPinPadACS(tmkpair.second, instanceAns.TPK, instanceAns.EDK, instanceAns.keyIndex) == Error_Succeed) {
  197. m_entity->EndInitMK(Error_Succeed, "");
  198. }
  199. else {
  200. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5204")("连接密码键盘异常");
  201. m_entity->EndInitMK(ERR_ACCESSAUTH_CONNECT_PINPAD, "密钥加载失败,请检查密码键盘连接。");//,待完善细化错误码oiltest
  202. }
  203. }
  204. else {
  205. m_entity->EndInitMK(Error_Succeed, "");
  206. }
  207. }
  208. }
  209. else {
  210. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("post wk failed: %s", result.WhatError().c_str());
  211. m_entity->EndInitMK(ERR_INITIALIZER_INIT_EXCEPTION, CSimpleStringA::Format("初始化服务连接失败。%s", result.WhatError().c_str()).GetData());
  212. }
  213. #endif //RVC_OS_WIN
  214. }
  215. };
  216. #ifdef RVC_OS_WIN
  217. struct GetTermSysInfoTask : ITaskSp
  218. {
  219. CAccessAuthEntity* m_entity;
  220. GetTermSysInfoTask(CAccessAuthEntity* entity) :m_entity(entity) {}
  221. void Process()
  222. {
  223. m_entity->GetTermSysInfo();
  224. }
  225. };
  226. #endif // RVC_OS_WIN
  227. typedef struct _REG_TZI_FORMAT
  228. {
  229. LONG Bias;
  230. LONG StandardBias;
  231. LONG DaylightBias;
  232. SYSTEMTIME StandardDate;
  233. SYSTEMTIME DaylightDate;
  234. } REG_TZI_FORMAT;
  235. void CAccessAuthSession::Handle_Regist(SpOnewayCallContext<AccessAuthService_Regist_Info>::Pointer ctx)
  236. {
  237. DbgToBeidou(ctx->link, __FUNCTION__)();
  238. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setAPI(__FUNCTION__)("call Handle_Regist");
  239. m_pEntity->Regist();
  240. }
  241. void CAccessAuthSession::Handle_UpdateWK(SpOnewayCallContext<AccessAuthService_UpdateWK_Info>::Pointer ctx)
  242. {
  243. DbgToBeidou(ctx->link, __FUNCTION__)();
  244. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setAPI(__FUNCTION__)("call Handle_UpdateWK");
  245. m_pEntity->UpdateWK();
  246. }
  247. void CAccessAuthSession::Handle_InitializeNew(SpReqAnsContext<AccessAuthService_InitializeNew_Req, AccessAuthService_InitializeNew_Ans>::Pointer ctx)
  248. {
  249. DbgToBeidou(ctx->link, __FUNCTION__)();
  250. DbgWithLink(LOG_LEVEL_INFO, ctx->link.checkEmpty() ? LOG_TYPE_SYSTEM : LOG_TYPE_USER).setAPI(__FUNCTION__)("Handle_InitializeNew");
  251. m_pEntity->m_ctx = ctx;
  252. m_pEntity->m_strUserID = ctx->Req.strUserID.GetData();
  253. m_pEntity->m_strPassword = ctx->Req.strPassword.GetData();
  254. m_pEntity->BeginInitMKACS();
  255. }
  256. void CAccessAuthSession::Handle_InitDev(SpReqAnsContext<AccessAuthService_InitDev_Req, AccessAuthService_InitDev_Ans>::Pointer ctx)
  257. {
  258. DbgToBeidou(ctx->link, __FUNCTION__)();
  259. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setAPI(__FUNCTION__)("call Handle_InitDev");
  260. m_pEntity->InitDevice(ctx);
  261. }
  262. void CAccessAuthSession::Handle_GetNetMsg(SpReqAnsContext<AccessAuthService_GetNetMsg_Req, AccessAuthService_GetNetMsg_Ans>::Pointer ctx)
  263. {
  264. DbgToBeidou(ctx->link, __FUNCTION__)();
  265. m_pEntity->GetNetMsg(ctx);
  266. }
  267. void CAccessAuthEntity::OnStarted()
  268. {
  269. //设置时区为北京标准时区
  270. if (!SetLocalTimeZoneByKeyName("China Standard Time", FALSE))
  271. {
  272. m_FSM.doWarnMsg(ERR_ACCESSAUTH_SETTIMEZONE,GetOutPutStr("%s%s","设置时区错误","False").c_str());
  273. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5202")(GetOutPutStr("%s%s", "设置时区错误", "False").c_str());
  274. }
  275. m_FSM.Init(this);
  276. CSimpleStringA strErrMsg;
  277. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  278. memset(&m_info,0, sizeof(CSystemStaticInfo));
  279. auto rc = GetFunction()->GetSystemStaticInfo(m_info);
  280. if (rc != Error_Succeed)
  281. {
  282. strErrMsg = "GetSystemStaticInfo fail";
  283. SetAuthErrMsg((const char*)strErrMsg);
  284. m_FSM.doWarnMsg(ERR_ACCESSAUTH_GET_SYSTEM_STATIC_INFO,
  285. GetOutPutStr("%s%08X", "获取系统静态信息错误", rc).c_str(), strErrMsg.GetData());
  286. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)(GetOutPutStr("%s%08X", "获取系统静态信息错误", rc).c_str());
  287. }
  288. #ifdef RVC_OS_WIN
  289. spFunction->RegistSysVarEvent("NetState", this);
  290. CSmartPointer<GetTermSysInfoTask> getTermSysInfoTask = new GetTermSysInfoTask(this);
  291. GetFunction()->PostThreadPoolTask(getTermSysInfoTask.GetRawPointer());
  292. #endif // RVC_OS_WIN
  293. }
  294. void CAccessAuthEntity::OnPreStart(CAutoArray<CSimpleStringA> strArgs,CSmartPointer<ITransactionContext> pTransactionContext)
  295. {
  296. ErrorCodeEnum Error = Error_Succeed;
  297. pTransactionContext->SendAnswer(Error) ;
  298. }
  299. void CAccessAuthEntity::OnPreClose(EntityCloseCauseEnum eCloseCause,CSmartPointer<ITransactionContext> pTransactionContext)
  300. {
  301. #ifdef RVC_OS_WIN
  302. GetFunction()->UnregistSysVarEvent("NetState");
  303. #endif // RVC_OS_WIN
  304. m_FSM.PostExitEvent();
  305. pTransactionContext->SendAnswer(Error_Succeed);
  306. }
  307. void CAccessAuthEntity::OnSysVarEvent(const char *pszKey, const char *pszValue,const char *pszOldValue,const char *pszEntityName)
  308. {
  309. }
  310. // 开始准入
  311. ErrorCodeEnum CAccessAuthEntity::Regist()
  312. {
  313. m_FSM.PostEventFIFO(new FSMEvent(CAccessAuthFSM::Event_StartRegist));
  314. return Error_Succeed;
  315. }
  316. string CAccessAuthEntity::ByteArrayToHexStr(BYTE *pBuf, int nBufLen)
  317. {
  318. char szBuf[1024];
  319. memset(szBuf, 0, sizeof(szBuf));
  320. for(int i=0; i<nBufLen; i++)
  321. {
  322. BYTE b1 = (pBuf[i] >> 4) & 0x0F;
  323. BYTE b2 = pBuf[i] & 0x0F;
  324. if (b1 <= 9)
  325. szBuf[i*2] = '0' + b1;
  326. else
  327. szBuf[i*2] = 'A' + b1 - 10;
  328. if (b2 <= 9)
  329. szBuf[i*2+1] = '0' + b2;
  330. else
  331. szBuf[i*2+1] = 'A' + b2 - 10;
  332. }
  333. return szBuf;
  334. }
  335. // 生成临时SM2密钥对
  336. DWORD CAccessAuthEntity::CreateSM2KeyPair(CBlob &pubKey, CBlob &priKey)
  337. {
  338. int nPubKeyLen = 256;
  339. int nPriKeyLen = 256;
  340. pubKey.Alloc(nPubKeyLen);
  341. priKey.Alloc(nPriKeyLen);
  342. if (!::CreateSM2KeyPair((BYTE*)(pubKey.m_pData), &nPubKeyLen, (BYTE*)(priKey.m_pData), &nPriKeyLen))
  343. {
  344. SetAuthErrMsg("创建SM2密钥对失败");
  345. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  346. m_FSM.doWarnMsg(ERR_ACCESSAUTH_CREATE_RSA_KEY_PAIR,
  347. GetOutPutStr("%s%s","CreateRsaKeyPair","False").c_str(), true, "创建SM2密钥对失败");
  348. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("创建SM2密钥对失败");
  349. return ERR_ACCESSAUTH_CREATE_RSA_KEY_PAIR;
  350. }
  351. pubKey.Resize(nPubKeyLen);
  352. priKey.Resize(nPriKeyLen);
  353. return Error_Succeed;
  354. }
  355. // 保存到令牌管理实体中
  356. DWORD CAccessAuthEntity::SaveSM2KeyPair(const CBlob &pubKey, const CBlob &priKey)
  357. {
  358. LOG_FUNCTION();
  359. CSimpleStringA strErrMsg;
  360. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  361. TokenService_ClientBase *pTokenServiceClient = new TokenService_ClientBase(this);
  362. DWORD rc = pTokenServiceClient->Connect();
  363. if (rc != Error_Succeed)
  364. {
  365. strErrMsg = "连接令牌管理实体失败";
  366. SetAuthErrMsg((const char *)strErrMsg);
  367. rc = ERR_ACCESSAUTH_CONNECT_TOKEN_SERVICE;
  368. m_FSM.doWarnMsg(rc,
  369. "连接令牌管理实体失败", true);
  370. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5206")
  371. (GetOutPutStr("%s%08X%s%s", "Connect", rc, "strErrMsg", strErrMsg).c_str());
  372. pTokenServiceClient->SafeDelete();
  373. }
  374. else
  375. {
  376. TokenService_SetKeyPair_Req req;
  377. req.pub_key = pubKey;
  378. req.pri_key = priKey;
  379. TokenService_SetKeyPair_Ans ans;
  380. rc = pTokenServiceClient->SetKeyPair(req, ans, 3000);
  381. pTokenServiceClient->GetFunction()->CloseSession();
  382. if (rc != Error_Succeed)
  383. {
  384. strErrMsg = "保存密钥对失败";
  385. SetAuthErrMsg((const char *)strErrMsg);
  386. rc = ERR_ACCESSAUTH_FROM_TOKEN_SERVICE_SET_KEYS;
  387. m_FSM.doWarnMsg(rc,
  388. "保存密钥对失败", true);
  389. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5207")
  390. (GetOutPutStr("%s%08X%s%s", "SetKeyPair", rc, "strErrMsg", (const char*)strErrMsg).c_str());
  391. }
  392. }
  393. return rc;
  394. }
  395. ErrorCodeEnum CAccessAuthEntity::SaveTokenAndSharedSK(const CBlob &token, const CBlob &sharedSK)
  396. {
  397. LOG_FUNCTION();
  398. CSimpleStringA strErrMsg;
  399. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  400. TokenService_ClientBase *pTokenServiceClient = new TokenService_ClientBase(this);
  401. ErrorCodeEnum rc = pTokenServiceClient->Connect();
  402. if (rc != Error_Succeed)
  403. {
  404. strErrMsg = "连接令牌管理实体失败";
  405. SetAuthErrMsg((const char *)strErrMsg);
  406. m_FSM.doWarnMsg(ERR_ACCESSAUTH_CONNECT_TOKEN_SERVICE,
  407. GetOutPutStr("%s%08X%s%s", "Connect", rc,"strErrMsg", (const char*)strErrMsg).c_str());
  408. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)(GetOutPutStr("%s%08X%s%s", "Connect", rc, "strErrMsg", (const char*)strErrMsg).c_str());
  409. pTokenServiceClient->SafeDelete();
  410. }
  411. else
  412. {
  413. TokenService_SetToken_Req req = {};
  414. req.token = token;
  415. TokenService_SetToken_Ans ans;
  416. rc = pTokenServiceClient->SetToken(req, ans, 5000);
  417. if (rc == Error_Succeed)
  418. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI("SetToken")
  419. ("save token succ, token: [%s]", ByteArrayToHexStr((BYTE*)token.m_pData, token.m_iLength).c_str());
  420. else
  421. {
  422. strErrMsg = "保存令牌失败";
  423. SetAuthErrMsg((const char *)strErrMsg);
  424. m_FSM.doWarnMsg(ERR_ACCESSAUTH_FROM_TOKEN_SERVICE_SET_TOKEN,
  425. GetOutPutStr("%s%08X%s%s", "SetToken", rc,"strErrMsg", strErrMsg).c_str());
  426. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)(GetOutPutStr("%s%08X%s%s", "SetToken", rc, "strErrMsg", strErrMsg).c_str());
  427. }
  428. TokenService_SetSharedSK_Req req2 = {};
  429. req2.ssk = sharedSK;
  430. TokenService_SetSharedSK_Ans ans2 = {};
  431. rc = pTokenServiceClient->SetSharedSK(req2, ans2, 5000);
  432. if (rc != Error_Succeed)
  433. {
  434. strErrMsg = "保存会话密钥失败";
  435. SetAuthErrMsg((const char *)strErrMsg);
  436. m_FSM.doWarnMsg(ERR_ACCESSAUTH_FROM_TOKEN_SERVICE_SET_SHAREKEY,
  437. GetOutPutStr("%s%08X%s%s", "SetSharedSK", rc,"strErrMsg", (const char*)strErrMsg).c_str());
  438. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)(GetOutPutStr("%s%08X%s%s", "SetSharedSK", rc, "strErrMsg", (const char*)strErrMsg).c_str());
  439. }
  440. pTokenServiceClient->GetFunction()->CloseSession();
  441. }
  442. return rc;
  443. }
  444. bool CAccessAuthEntity::HasPinPad()
  445. {
  446. CSimpleStringA strErrMsg;
  447. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  448. //oilyang@20210514
  449. if (!IsMachineTypeConfigurePinPad(m_info.strMachineType))
  450. {
  451. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("MachineType[%s], not exist pinpad", m_info.strMachineType);
  452. return false;
  453. }
  454. else if (stricmp(m_info.strMachineType, "RVC.PAD") == 0) // Pad机型
  455. {
  456. // 根据PinPad实体状态确定是否连接密码键盘
  457. bool bPinPadExist = false;
  458. auto pPinPadClient = new PinPadService_ClientBase(this);
  459. if (pPinPadClient->Connect() != Error_Succeed)
  460. {
  461. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5204")("连接密码键盘异常");
  462. m_FSM.doWarnMsg(ERR_ACCESSAUTH_CONNECT_PINPAD,
  463. GetOutPutStr("%s%s", "连接pinpad错误", "False").c_str());
  464. pPinPadClient->SafeDelete();
  465. }
  466. else
  467. {
  468. PinPadService_GetDevInfo_Req req = {};
  469. PinPadService_GetDevInfo_Ans ans = {};
  470. #ifdef RVC_OS_WIN
  471. auto rc = pPinPadClient->GetDevInfo(req, ans, 3000);
  472. #else
  473. auto rc = (*pPinPadClient)(EntityResource::getLink().upgradeLink())->GetDevInfo(req, ans, 3000);
  474. #endif // RVC_OS_WIN
  475. if (rc != Error_Succeed)
  476. {
  477. strErrMsg = "PinPad::GetDevInfo() fail";
  478. SetAuthErrMsg((const char *)strErrMsg);
  479. m_FSM.doWarnMsg(ERR_ACCESSAUTH_FROM_PINPAD,
  480. GetOutPutStr("%s%08X%s", "来自pinpad的错误", rc, strErrMsg.GetData()).c_str());
  481. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5205")
  482. (GetOutPutStr("%s%08X%s", "来自pinpad的错误", rc, strErrMsg.GetData()).c_str());
  483. }
  484. else
  485. {
  486. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("PinPad::GetDevInfo() return state: %d", ans.state);
  487. bPinPadExist = ans.state != DEVICE_STATUS_NOT_READY;
  488. }
  489. pPinPadClient->GetFunction()->CloseSession();
  490. }
  491. pPinPadClient = NULL;
  492. return bPinPadExist;
  493. }
  494. else
  495. {
  496. // 其它VTM机型,全部有内置密码键盘
  497. return true;
  498. }
  499. }
  500. // 1:3des only; 2: sm4 only; 3: both 3des and sm4
  501. // 由当前已初始化的密钥文件决定,兼容旧版本终端
  502. int CAccessAuthEntity::GetPinPadCapability()
  503. {
  504. LOG_FUNCTION();
  505. int nCapability = 0;
  506. if (!IsMachineTypeConfigurePinPad(m_info.strMachineType))
  507. return nCapability;
  508. PinPadService_ClientBase *pPinPad = new PinPadService_ClientBase(this);
  509. auto rc = pPinPad->Connect();
  510. if (rc == Error_Succeed)
  511. {
  512. PinPadService_QueryFunc_Req req;
  513. PinPadService_QueryFunc_Ans ans;
  514. rc = pPinPad->QueryFunc(req, ans, 3000);
  515. if (rc == Error_Succeed)
  516. {
  517. nCapability = ans.encryptkey;
  518. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("QueryFunc from pinpad succ, nCapability[%d]", nCapability);
  519. }
  520. else if (rc != Error_DevNotAvailable)
  521. {
  522. SetAuthErrMsg("从PinPad获取主密钥类型失败");
  523. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  524. m_FSM.doWarnMsg(ERR_ACCESSAUTH_FROM_PINPAD,
  525. GetOutPutStr("%s%s%s%s", "QueryFunc", "False", "AuthErrMsg", "从PinPad获取主密钥类型失败").c_str());
  526. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5205")
  527. (GetOutPutStr("%s%s%s%s", "QueryFunc", "False", "AuthErrMsg", "从PinPad获取主密钥类型失败").c_str());
  528. }
  529. pPinPad->GetFunction()->CloseSession();
  530. }
  531. else
  532. {
  533. SetAuthErrMsg("连接PinPad实体失败");
  534. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  535. m_FSM.doWarnMsg(ERR_ACCESSAUTH_CONNECT_PINPAD,
  536. GetOutPutStr("%s%08X%s%s", "Connect", rc,"AuthErrMsg", "连接PinPad实体失败").c_str());
  537. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)(GetOutPutStr("%s%08X%s%s", "Connect", rc, "AuthErrMsg", "连接PinPad实体失败").c_str());
  538. pPinPad->SafeDelete();
  539. }
  540. return nCapability;
  541. }
  542. void CAccessAuthEntity::printPasswdError(const string& strErrMsg){
  543. //string strErrMsg = "密钥集丢失,请重新初始化密钥!";
  544. SetAuthErrMsg(strErrMsg.c_str());
  545. GetFunction()->SetSysVar("AuthErrMsg", strErrMsg.c_str(), true);
  546. m_FSM.doWarnMsg( ERROR_ACCESSAUTH_OPENCRYPTCONTEXT, strErrMsg.c_str(),true, strErrMsg);
  547. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA520C")("密钥集丢失(私钥为空)");
  548. }
  549. int Char2Int(char * ch) {
  550. int num = 0;
  551. for (int i = 0;i < strlen(ch);i++) {
  552. num += ((int)(ch[i] - '0')) * pow((float)10, (float)(strlen(ch) - i - 1));
  553. }
  554. return num;
  555. }
  556. bool CAccessAuthEntity::SaveAuthKey(BYTE *pKey)
  557. {
  558. memset(m_AuthSessionKey, 0, 140);
  559. CSimpleStringA runInfoPath, iniPath;
  560. auto rc = GetFunction()->GetPath("runinfo", runInfoPath);
  561. if (rc != Error_Succeed) {
  562. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("GetPath runinfo error=%d.", rc);
  563. return false;
  564. }
  565. char privateKey[BUF_SIZE] = { 0 };
  566. #ifdef RVC_OS_WIN
  567. iniPath = runInfoPath + "\\runcfg\\AccessAuthorization.ini";
  568. GetPrivateProfileString("TerminalPD", "PrivateKey", "", privateKey, BUF_SIZE, iniPath.GetData());
  569. #else
  570. iniPath = runInfoPath + SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR "AccessAuthorization.ini";
  571. char* tmp = inifile_read_str(iniPath.GetData(), "TerminalPD", "PrivateKey", "");
  572. strcpy(privateKey, tmp);
  573. delete tmp;
  574. #endif // RVC_OS_WIN
  575. if (strlen(privateKey) <= 0) {
  576. #ifdef RVC_OS_WIN
  577. iniPath = runInfoPath + "\\runcfg\\Initializer.ini";
  578. GetPrivateProfileString("TerminalPD", "PrivateKey", "", privateKey, BUF_SIZE, iniPath.GetData());
  579. #else
  580. iniPath = runInfoPath + SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR "Initializer.ini";
  581. char* tmp2 = inifile_read_str(iniPath.GetData(), "TerminalPD", "PrivateKey", "");
  582. strcpy(privateKey, tmp2);
  583. delete tmp2;
  584. #endif // RVC_OS_WIN
  585. if (strlen(privateKey) <= 0)
  586. {
  587. printPasswdError("密钥集丢失(私钥为空),请重置秘钥进行初始化");
  588. return false;
  589. }
  590. }
  591. int decodedPrivateKeyLen;
  592. #ifdef RVC_OS_WIN
  593. char* pDecodedPrivateKey = MyBase64::Hex2Str(privateKey, decodedPrivateKeyLen);
  594. #else
  595. char* pDecodedPrivateKey = Hex2Str(privateKey, decodedPrivateKeyLen);
  596. #endif // RVC_OS_WIN
  597. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("privateKey len:%d, decodedPrivateKeyLen=%d", strlen(privateKey), decodedPrivateKeyLen);
  598. char pDecryptPrivateKey[BUF_SIZE] = { 0 };
  599. int decryprtLen = BUF_SIZE;
  600. if (!DecWithSM4_ECB("s5da69gnh4!963@6s5da69gnh4!963@6", (BYTE*)pDecodedPrivateKey, decodedPrivateKeyLen, (BYTE*)pDecryptPrivateKey, &decryprtLen)) {
  601. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("DecWithSM4_ECB decrypt privateKey error. SM4解密私钥失败");
  602. printPasswdError("终端初始化未完成,请重置秘钥进行初始化");
  603. delete[] pDecodedPrivateKey;
  604. return false;
  605. }
  606. delete[] pDecodedPrivateKey;
  607. char pPlainKey[KEY_SIZE];
  608. int plainKeyLen = KEY_SIZE;
  609. char pKeyLen[4] = { 0 };
  610. memcpy(pKeyLen, pKey, 4);
  611. int kenLen = Char2Int(pKeyLen);
  612. #ifdef RVC_OS_WIN
  613. char* pEncodeKey = MyBase64::Str2Hex((char*)pKey,kenLen + 4);
  614. #else
  615. char* pEncodeKey = Str2Hex((char*)pKey, kenLen + 4);
  616. #endif
  617. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("kenLen=%d", kenLen);
  618. delete pEncodeKey;
  619. char* key = new char[kenLen + 1];
  620. memset(key, 0, kenLen + 1);
  621. memcpy(key, pKey + 4, kenLen);
  622. if (!DecWithSM2PriKey((BYTE*)key, kenLen, (BYTE*)pPlainKey, &plainKeyLen, (BYTE*)pDecryptPrivateKey, decryprtLen)) {
  623. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("使用私钥解密失败!");
  624. printPasswdError("终端初始化未完成,请重置秘钥进行初始化");
  625. return false;
  626. }
  627. if (plainKeyLen != KEY_SIZE) {
  628. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI("SaveAuthVerAndKey")("私钥解密后的会话密钥长度不等于16!");
  629. }
  630. memcpy(m_AuthSessionKey, pPlainKey, KEY_SIZE);
  631. return true;
  632. }
  633. static BYTE* ConvertHexStrToBytes(const char *pszStr)
  634. {
  635. if (pszStr == NULL || strlen(pszStr) == 0)
  636. return NULL;
  637. int nLen = strlen(pszStr) / 2;
  638. BYTE *pRet = (BYTE*)malloc(nLen);
  639. memset(pRet, 0, nLen);
  640. for (int i = 0; i < nLen; i++)
  641. {
  642. int nTmp(0);
  643. if (sscanf(&pszStr[i * 2], "%2X", &nTmp) != 1)
  644. {
  645. free(pRet);
  646. return NULL;
  647. }
  648. pRet[i] = (BYTE)nTmp;
  649. }
  650. return pRet;
  651. }
  652. // 使用准入会话密钥加密
  653. ErrorCodeEnum CAccessAuthEntity::EncryptDataWithSessionKey(const CBlob &raw, CBlob &enc)
  654. {
  655. LOG_FUNCTION();
  656. //这里不需要delete,由CBlob析构函数去执行
  657. BYTE* pEncData = new BYTE[1024];
  658. int pEncDataSize = 1024;
  659. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("pEncDataSize=%d", pEncDataSize);
  660. #ifdef RVC_OS_WIN
  661. char* pPlainInfo = MyBase64::Str2Hex((char*)raw.m_pData, raw.m_iLength);
  662. #else
  663. char* pPlainInfo = Str2Hex((char*)raw.m_pData, raw.m_iLength);
  664. #endif
  665. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("raw Length=%d", raw.m_iLength);
  666. delete[] pPlainInfo;
  667. char sessionKey[KEY_SIZE] = { 0 };
  668. memcpy(sessionKey,m_AuthSessionKey,KEY_SIZE);
  669. #ifdef RVC_OS_WIN
  670. char* tmpKey = MyBase64::Str2Hex((char*)m_AuthSessionKey, KEY_SIZE);
  671. #else
  672. char* tmpKey = Str2Hex((char*)m_AuthSessionKey, KEY_SIZE);
  673. #endif // RVC_OS_WIN
  674. delete[] tmpKey;
  675. if (!EncWithSM4_ECB((BYTE*)sessionKey, (BYTE*)(raw.m_pData), raw.m_iLength, pEncData, &pEncDataSize)) {
  676. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("会话密钥加密准入信息失败!");
  677. return Error_Unexpect;
  678. }
  679. enc.Attach(pEncData,pEncDataSize);
  680. #ifdef RVC_OS_WIN
  681. char* tmp = MyBase64::Str2Hex((char*)pEncData, pEncDataSize);
  682. #else
  683. char* tmp = Str2Hex((char*)pEncData, pEncDataSize);
  684. #endif // RVC_OS_WIN
  685. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("pEncData size:%d", pEncDataSize);
  686. delete[] tmp;
  687. #ifdef RVC_OS_WIN
  688. tmp = MyBase64::Str2Hex((char*)enc.m_pData, enc.m_iLength);
  689. #else
  690. tmp = Str2Hex((char*)enc.m_pData, enc.m_iLength);
  691. #endif // RVC_OS_WIN
  692. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("EncWithSM4_ECB data size:%d", enc.m_iLength);
  693. delete[] tmp;
  694. return Error_Succeed;
  695. }
  696. static char* ConvertBytesToHexStr(BYTE *pBuf, int nLen)
  697. {
  698. char *pRet = (char*)malloc(nLen * 2 + 1);
  699. memset(pRet, 0, nLen * 2 + 1);
  700. char *p = pRet;
  701. for (int i = 0; i < nLen; i++)
  702. {
  703. BYTE b = pBuf[i];
  704. BYTE l = (b >> 4) & 0x0F;
  705. if (l >= 10)
  706. *p = l - 10 + 'A';
  707. else
  708. *p = l + '0';
  709. p++;
  710. BYTE r = b & 0x0F;
  711. if (r >= 10)
  712. *p = r - 10 + 'A';
  713. else
  714. *p = r + '0';
  715. p++;
  716. }
  717. return pRet;
  718. }
  719. bool CAccessAuthEntity::GetTerminalFingerPrint(BYTE *pBuf, int &nBufLen)
  720. {
  721. #ifdef RVC_OS_LINUX
  722. char szTmp[1024] = {};
  723. string strTmp;
  724. int nTmpBufLen = 1024;
  725. CSimpleStringA strErrMsg;
  726. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  727. CSimpleStringA strRet;
  728. CSimpleStringA runInfoPath;
  729. auto rc = GetFunction()->GetPath("runinfo", runInfoPath);
  730. if (rc != Error_Succeed) {
  731. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("GetPath runinfo error=%d.", rc);
  732. return false;
  733. }
  734. runInfoPath += SPLIT_SLASH_STR "runcfg";
  735. if (!get_cpu_id_by_system(strTmp, runInfoPath.GetData()))
  736. {
  737. strErrMsg = CSimpleStringA::Format("查询CPU ID失败,请重启机器并重新初始化");
  738. SetAuthErrMsg((const char*)strErrMsg);
  739. m_FSM.doWarnMsg(ERR_ACCESSAUTH_GET_TERMINAL_FINGERPRINT,
  740. GetOutPutStr("%s%s", "Processor", "False").c_str());
  741. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5203")
  742. (GetOutPutStr("%s%s", "Processor", "False").c_str());
  743. return false;
  744. }
  745. strRet = strTmp.c_str();
  746. strTmp.clear();
  747. if (!get_board_serial_by_system(strTmp, runInfoPath.GetData()))
  748. {
  749. strErrMsg = CSimpleStringA::Format("查询主板序列号失败, 请重启机器并重新初始化");
  750. SetAuthErrMsg((const char*)strErrMsg);
  751. m_FSM.doWarnMsg(ERR_ACCESSAUTH_GET_TERMINAL_FINGERPRINT,
  752. GetOutPutStr("%s%s", "BaseBoard", "False").c_str());
  753. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5203")
  754. (GetOutPutStr("%s%s", "BaseBoard", "False").c_str());
  755. return false;
  756. }
  757. strRet += "|";
  758. strRet += strTmp.c_str();
  759. vector<string> disk;
  760. int errCode = 0;
  761. if (!get_disk_serial_by_system(disk, errCode, runInfoPath.GetData()))
  762. {
  763. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("get_disk_serial_by_system errCode:%d", errCode);
  764. strErrMsg = CSimpleStringA::Format("查询磁盘序列号失败, 请重启机器并重新初始化");
  765. SetAuthErrMsg((const char*)strErrMsg);
  766. m_FSM.doWarnMsg(ERR_INITIALIZER_GET_DISKDRIVE_ID,
  767. GetOutPutStr("%s%s", "DiskDrive", "False").c_str());
  768. return false;
  769. }
  770. strRet += "|";
  771. strTmp = "";
  772. vector<string>::iterator it = disk.begin();
  773. while (it != disk.end()) {
  774. strTmp += *it;
  775. it++;
  776. }
  777. strRet += strTmp.c_str();
  778. BYTE m_btTermSysInfoSM3[32] = { 0 };
  779. if (!SM3Hash(reinterpret_cast<BYTE*>(const_cast<char*>(strRet.GetData())), strRet.GetLength(), m_btTermSysInfoSM3))
  780. {
  781. strErrMsg = "get sm3 hash as fingerprint fail";
  782. SetAuthErrMsg((const char*)strErrMsg);
  783. spFunction->SetSysVar("AuthErrMsg", (const char*)strErrMsg, true);
  784. m_FSM.doWarnMsg(ERROR_ACCESSAUTH_GETSM3HASH, (const char*)strErrMsg);
  785. return false;
  786. }
  787. #endif // RVC_OS_LINUX
  788. if (nBufLen < 32)
  789. {
  790. m_FSM.doWarnMsg(ERROR_ACCESSAUTH_GETSM3HASH, "buf len is too small fail");
  791. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("buf len is too small fail");
  792. return false;
  793. }
  794. #ifdef RVC_OS_WIN
  795. while (1)
  796. {
  797. if (m_iGetTermSysInfo == -1)
  798. return false;
  799. else if (m_iGetTermSysInfo == 1)
  800. break;
  801. else if (m_iGetTermSysInfo == 0)
  802. Sleep(1000);//oiltmp@20220917 之前的逻辑是不跳出去,现在要加么?暂时不加,连调用系统接口都有问题,让其他逻辑处理
  803. }
  804. #endif // RVC_OS_WIN
  805. nBufLen = 32;
  806. memcpy(pBuf, m_btTermSysInfoSM3, nBufLen);
  807. char *pszSM3 = ConvertBytesToHexStr(m_btTermSysInfoSM3, nBufLen);
  808. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("fringerprint: [%s]", pszSM3);
  809. free(pszSM3);
  810. return true;
  811. }
  812. #ifdef RVC_OS_WIN
  813. #define RSAPUBKEY_BITLEN 1024
  814. struct PublicKeyBlob
  815. {
  816. PUBLICKEYSTRUC publickeystruc;
  817. RSAPUBKEY rsapubkey;
  818. BYTE modulus[RSAPUBKEY_BITLEN / 8];
  819. };
  820. #endif // RVC_OS_WIN
  821. // 生成SM2密钥对,并导出公钥
  822. bool CAccessAuthEntity::GetTerminalPublicKey(BYTE* pBuf, int& nBufLen)
  823. {
  824. CSimpleStringA runInfoPath, iniPath;
  825. auto rc = GetFunction()->GetPath("runinfo", runInfoPath);
  826. if (rc != Error_Succeed) {
  827. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")
  828. ("GetPath runinfo error=%d.", rc);
  829. return false;
  830. }
  831. char publicKey[BUF_SIZE] = { 0 };
  832. #ifdef RVC_OS_WIN
  833. iniPath = runInfoPath + "\\runcfg\\AccessAuthorization.ini";
  834. GetPrivateProfileString("TerminalPD", "PublicKey", "", publicKey, BUF_SIZE, iniPath.GetData());
  835. #else
  836. iniPath = runInfoPath + SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR "AccessAuthorization.ini";
  837. char* tmp = inifile_read_str(iniPath.GetData(), "TerminalPD", "PublicKey", "");
  838. strcpy(publicKey, tmp);
  839. delete tmp;
  840. #endif // RVC_OS_WIN
  841. if (strlen(publicKey) <= 0) {
  842. #ifdef RVC_OS_WIN
  843. iniPath = runInfoPath + "\\runcfg\\Initializer.ini";
  844. GetPrivateProfileString("TerminalPD", "PublicKey", "", publicKey, BUF_SIZE, iniPath.GetData());
  845. #else
  846. iniPath = runInfoPath + SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR "Initializer.ini";
  847. char* tmp2 = inifile_read_str(iniPath.GetData(), "TerminalPD", "PublicKey", "");
  848. strcpy(publicKey, tmp2);
  849. delete tmp2;
  850. #endif // RVC_OS_WIN
  851. if (strlen(publicKey) <= 0)
  852. {
  853. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("读取公钥失败,公钥长度小于等于零!");
  854. if (!ExistsFileA(iniPath))
  855. printPasswdError("密钥集丢失(公钥为空),请重置秘钥进行初始化");
  856. return false;
  857. }
  858. }
  859. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("publickey=%s,%d", publicKey, strlen(publicKey));
  860. #ifdef RVC_OS_WIN
  861. char* pDecodedPublickey = MyBase64::Hex2Str(publicKey, nBufLen);
  862. #else
  863. char* pDecodedPublickey = Hex2Str(publicKey, nBufLen);
  864. #endif // RVC_OS_WIN
  865. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("pDecodedPublickey len=%d", nBufLen);
  866. memcpy(pBuf, pDecodedPublickey, nBufLen);
  867. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("pBuf[0]=%02X,nBufLen=%d", pBuf[0], nBufLen);
  868. delete[] pDecodedPublickey;
  869. return true;
  870. }
  871. // 生成RSA密钥对,并导出公钥
  872. bool CAccessAuthEntity::GetTerminalPublicKey(BYTE* pBuf, int& nBufLen, string& pubkey)
  873. {
  874. LOG_FUNCTION();
  875. CSimpleString runInfoPath;
  876. auto rc = GetFunction()->GetPath("runinfo", runInfoPath);
  877. if (rc != Error_Succeed) {
  878. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("GetPath runinfo error=%d.", rc);
  879. return false;
  880. }
  881. #ifdef RVC_OS_WIN
  882. runInfoPath += "\\runcfg\\";
  883. DWORD dwAttr = GetFileAttributes(runInfoPath.GetData());
  884. if (dwAttr == 0xFFFFFFFF) //目录不存在则创建
  885. {
  886. if (!CreateDirectory(runInfoPath.GetData(), NULL))
  887. {
  888. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("Create %s dir failed!", runInfoPath.GetData());
  889. }
  890. }
  891. #else
  892. runInfoPath += SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR;
  893. if (!dir_is_exist(runInfoPath.GetData()))
  894. {
  895. if (dir_create(runInfoPath.GetData()) != 0)
  896. {
  897. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("Create %s dir failed!", runInfoPath.GetData());
  898. }
  899. }
  900. #endif // RVC_OS_WIN
  901. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("Dir=%s", runInfoPath.GetData());
  902. CSmartPointer<IConfigInfo> pConfig;
  903. rc = GetFunction()->OpenConfig(Config_Run, pConfig);
  904. if (rc != Error_Succeed) {
  905. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("OpenConfig Config_Run error=%d.", rc);
  906. return false;
  907. }
  908. CSimpleString publicKey;
  909. rc = pConfig->ReadConfigValue("TerminalPD", "PublicKey", publicKey);
  910. if (rc != Error_Succeed || publicKey.IsNullOrEmpty()) {
  911. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("ReadConfig publicKey error=%d or publicKey is NULL.", rc);
  912. }
  913. BYTE btPublicKey[BUF_SIZE] = { 0 }, btPrivateKey[BUF_SIZE] = { 0 };
  914. int iPublicKeyLen = sizeof(btPublicKey);
  915. int iPrivateKeyLen = sizeof(btPrivateKey);
  916. if (!::CreateSM2KeyPair(btPublicKey, &iPublicKeyLen, btPrivateKey, &iPrivateKeyLen)) {
  917. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("Create SM2 key pair error.");
  918. return false;
  919. }
  920. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("iPublicKeyLen=%d,iPrivateKeyLen=%d", iPublicKeyLen, iPrivateKeyLen);
  921. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("[btPublicKey=%s]", (char*)btPublicKey);
  922. #ifdef RVC_OS_WIN
  923. char* pEncode = MyBase64::Str2Hex((char*)btPublicKey, iPublicKeyLen);
  924. #else
  925. char* pEncode = Str2Hex((char*)btPublicKey, iPublicKeyLen);
  926. #endif // RVC_OS_WIN
  927. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("pEncode=%s,%d", pEncode, strlen(pEncode));
  928. /*rc = pConfig->WriteConfigValue("TerminalPD", "PublicKey", pEncode);
  929. assert(rc == Error_Succeed);*/
  930. m_publicKey = pEncode;
  931. pubkey = pEncode;
  932. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("write public key success.");
  933. BYTE pCryptPrivateKey[BUF_SIZE] = { 0 };
  934. int cryptPrivateKeyLen = BUF_SIZE;
  935. if (!EncWithSM4_ECB("s5da69gnh4!963@6s5da69gnh4!963@6", btPrivateKey, iPrivateKeyLen, pCryptPrivateKey, &cryptPrivateKeyLen)) {
  936. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("sm4 crypt privateKey error.");
  937. /*rc = pConfig->WriteConfigValue("TerminalPD", "PublicKey", "");*/
  938. m_publicKey = "";
  939. delete[] pEncode;
  940. return false;
  941. }
  942. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("sm4 encrypt pri key success.");
  943. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("cryptPrivateKeyLen=%d", cryptPrivateKeyLen);
  944. #ifdef RVC_OS_WIN
  945. char* pEncodedCryptPrivateKey = MyBase64::Str2Hex((char*)pCryptPrivateKey, cryptPrivateKeyLen);
  946. #else
  947. char* pEncodedCryptPrivateKey = Str2Hex((char*)pCryptPrivateKey, cryptPrivateKeyLen);
  948. #endif // RVC_OS_WIN
  949. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("encode pri key success.");
  950. m_privateKey = pEncodedCryptPrivateKey;
  951. /*rc = pConfig->WriteConfigValue("TerminalPD", "PrivateKey", pEncodedCryptPrivateKey);
  952. if (rc != Error_Succeed) {
  953. rc = pConfig->WriteConfigValue("TerminalPD", "PublicKey", "");
  954. delete[] pEncodedCryptPrivateKey;
  955. return false;
  956. }
  957. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("write pri key success.");*/
  958. publicKey = pEncode;
  959. delete[] pEncode;
  960. delete[] pEncodedCryptPrivateKey;
  961. #ifdef RVC_OS_WIN
  962. char* pDecode = MyBase64::Hex2Str(publicKey.GetData(), nBufLen);
  963. #else
  964. char* pDecode = Hex2Str(publicKey.GetData(), nBufLen);
  965. #endif // RVC_OS_WIN
  966. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("pDecode=[%s],len=%d", pDecode, nBufLen);
  967. memcpy(pBuf, pDecode, nBufLen);
  968. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("pBuf[0]=%02X,nBufLen=%d", pBuf[0], nBufLen);
  969. return true;
  970. }
  971. //oilyang@20210510 嵌入"bool CAccessAuthEntity::HasPinPad()"的逻辑
  972. // 返回1:只有PinPadID;2:只有DeviceID;3:两者都有;0:没有;-1表示失败
  973. int CAccessAuthEntity::GetPinPadIDAndDeviceID(CSimpleStringA &strPinPadID, CSimpleStringA &strDeviceID, bool& bHasPinPad)
  974. {
  975. bHasPinPad = false;
  976. m_bNewSMFWB = false;
  977. CSimpleStringA strErrMsg;
  978. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  979. //oilyang@20210514
  980. if (!IsMachineTypeConfigurePinPad(m_info.strMachineType))
  981. return 0;
  982. int nRet = -1;
  983. auto pPinPadClient = new PinPadService_ClientBase(this);
  984. bool bPinPadID = false;
  985. bool bDeviceID = false;
  986. bool bVendor = false;
  987. bool bBluetooth = false;
  988. CSimpleStringA strVendor;
  989. CSimpleStringA strBluetoothID;
  990. CSimpleStringA strPID;
  991. CSimpleStringA strMID;
  992. bHasPinPad = true;
  993. auto rc = 0;
  994. if ((rc = pPinPadClient->Connect()) == Error_Succeed)
  995. {
  996. PinPadService_GetDevInfo_Req req = {};
  997. PinPadService_GetDevInfo_Ans ans = {};
  998. rc = pPinPadClient->GetDevInfo(req, ans, 3000);
  999. if (rc == Error_Succeed)
  1000. {
  1001. if (ans.state == DEVICE_STATUS_NORMAL)
  1002. {
  1003. nRet = 0;
  1004. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("pinpad model: %s", (const char*)ans.model);
  1005. // CM = V2.0#PM = V1.0#MID = 75500001#PID = 12345678#FWID = V1234567#Vendor = nantian
  1006. // 密码键盘ID,PID,8到16字节; 设备ID,MID,8到16字节; 固件版本号,FWID,8字节
  1007. CSimpleStringA str = ans.model;
  1008. if (!str.IsNullOrEmpty())
  1009. {
  1010. auto arr = str.Split('#');
  1011. if (arr.GetCount() > 0)
  1012. {
  1013. for (int i = 0; i < arr.GetCount(); i++)
  1014. {
  1015. auto arr2 = arr[i].Split('=');
  1016. if (arr2.GetCount() != 2)
  1017. continue;
  1018. //if (arr2[0] == "PID")
  1019. if (!strnicmp((LPCTSTR)arr2[0], "PID", strlen("PID")))
  1020. {
  1021. strPID = arr2[1];
  1022. if (!strPID.IsNullOrEmpty())
  1023. bPinPadID = true;
  1024. }
  1025. //else if (arr2[0] == "MID")
  1026. else if (!strnicmp((LPCTSTR)arr2[0], "MID", strlen("MID")))
  1027. {
  1028. strMID = arr2[1];
  1029. if (!strMID.IsNullOrEmpty())
  1030. bDeviceID = true;
  1031. }
  1032. //else if (arr2[0] == "Vendor")
  1033. else if (!strnicmp((LPCTSTR)arr2[0], "Vendor", strlen("Vendor")))
  1034. {
  1035. strVendor = arr2[1];
  1036. if (!strVendor.IsNullOrEmpty())
  1037. bVendor = true;
  1038. }
  1039. else if (!strnicmp((LPCTSTR)arr2[0], "FWBID", strlen("FWBID")))
  1040. {
  1041. strBluetoothID = arr2[1];
  1042. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("strBluetoothID=%s", strBluetoothID);
  1043. if (!strBluetoothID.IsNullOrEmpty())
  1044. bBluetooth = true;
  1045. }
  1046. #ifdef RVC_OS_WIN
  1047. else if (!strnicmp((LPCTSTR)arr2[0], "PM", strlen("PM")))
  1048. {
  1049. CSimpleStringA strPM = arr2[1];
  1050. if (!strPM.IsNullOrEmpty() && strPM.Compare("V3.0", true) == 0)
  1051. m_bNewSMFWB = true;
  1052. }
  1053. #endif // RVC_OS_WIN
  1054. }
  1055. }
  1056. }
  1057. }
  1058. else
  1059. {
  1060. if (m_info.strMachineType.IsStartWith("RVC.PAD", true))
  1061. bHasPinPad = false;
  1062. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("pinpad not exist, state: %d", ans.state);
  1063. return nRet; //此时nRet = -1, pinpad调用失败
  1064. }
  1065. }
  1066. else
  1067. {
  1068. if (m_info.strMachineType.IsStartWith("RVC.PAD", true))
  1069. bHasPinPad = false;
  1070. strErrMsg = "调用PinPad实体的GetDevInfo方法失败";
  1071. SetAuthErrMsg((const char*)strErrMsg);
  1072. m_FSM.doWarnMsg(ERR_ACCESSAUTH_FROM_PINPAD,
  1073. GetOutPutStr("%s%08X%s%s", "GetDevInfo", rc, "strErrMsg", (const char*)strErrMsg).c_str());
  1074. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5205")
  1075. (GetOutPutStr("%s%08X%s%s", "GetDevInfo", rc, "strErrMsg", (const char*)strErrMsg).c_str());
  1076. return nRet; //此时nRet = -1, pinpad调用失败
  1077. }
  1078. pPinPadClient->GetFunction()->CloseSession();
  1079. }
  1080. else
  1081. {
  1082. if (m_info.strMachineType.IsStartWith("RVC.PAD", true))
  1083. bHasPinPad = false;
  1084. strErrMsg = "连接PinPad实体失败";
  1085. SetAuthErrMsg((const char*)strErrMsg);
  1086. m_FSM.doWarnMsg(ERR_ACCESSAUTH_CONNECT_PINPAD,
  1087. GetOutPutStr("%s%08X%s%s", "Connect", rc, "strErrMsg", "连接PinPad实体失败").c_str());
  1088. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5204")("连接密码键盘异常");
  1089. pPinPadClient->SafeDelete();
  1090. return nRet; //此时nRet = -1, pinpad调用失败
  1091. }
  1092. pPinPadClient = NULL;
  1093. if (bPinPadID)
  1094. {
  1095. if (bVendor)
  1096. strPinPadID = strVendor + "_" + strPID;
  1097. else
  1098. strPinPadID = strPID;
  1099. nRet += 1;
  1100. }
  1101. if (bDeviceID)
  1102. {
  1103. if (bVendor)
  1104. strDeviceID = strVendor + "_" + strMID;
  1105. else
  1106. strDeviceID = strMID;
  1107. if (bBluetooth)
  1108. strDeviceID = strDeviceID + "_" + strBluetoothID;
  1109. nRet += 2;
  1110. }
  1111. else if (bBluetooth)
  1112. {
  1113. strDeviceID = strDeviceID + "_" + strBluetoothID;
  1114. nRet += 2;
  1115. }
  1116. return nRet;
  1117. }
  1118. wstring CAccessAuthEntity::ANSIToUnicode(const string& str)
  1119. {
  1120. int len = 0;
  1121. len = str.length();
  1122. int unicodeLen = ::MultiByteToWideChar(CP_ACP,
  1123. 0,
  1124. str.c_str(),
  1125. -1,
  1126. NULL,
  1127. 0);
  1128. wchar_t * pUnicode;
  1129. pUnicode = new wchar_t[unicodeLen+1];
  1130. memset(pUnicode,0,(unicodeLen+1)*sizeof(wchar_t));
  1131. ::MultiByteToWideChar( CP_ACP,
  1132. 0,
  1133. str.c_str(),
  1134. -1,
  1135. (LPWSTR)pUnicode,
  1136. unicodeLen);
  1137. wstring rt;
  1138. rt = (wchar_t*)pUnicode;
  1139. delete pUnicode;
  1140. return rt;
  1141. }
  1142. //China Standard Time
  1143. BOOL CAccessAuthEntity::SetLocalTimeZoneByKeyName(const TCHAR* szTimeZoneKeyName, BOOL isDaylightSavingTime)
  1144. {
  1145. #ifdef RVC_OS_WIN
  1146. HKEY hKey;
  1147. LONG ErrorCode;
  1148. TCHAR szSubKey[256];
  1149. TCHAR szStandardName[32];
  1150. TCHAR szDaylightName[32];
  1151. REG_TZI_FORMAT regTZI;
  1152. DWORD dwByteLen;
  1153. // 检测入口参数
  1154. if ((szTimeZoneKeyName == NULL) || (strlen(szTimeZoneKeyName) == 0))
  1155. {
  1156. // 时区标识符不能为空
  1157. return FALSE;
  1158. }
  1159. StringCchCopy(szSubKey, 256, TEXT("Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\"));
  1160. StringCchCat(szSubKey, 256, szTimeZoneKeyName);
  1161. ErrorCode = RegOpenKeyEx(HKEY_LOCAL_MACHINE, szSubKey, 0, KEY_QUERY_VALUE, &hKey);
  1162. if (ErrorCode != ERROR_SUCCESS)
  1163. {
  1164. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("RegOpenKeyEx Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\China Standard Time fail");
  1165. return FALSE;
  1166. }
  1167. // 标准名
  1168. dwByteLen = sizeof(szStandardName);
  1169. ErrorCode = RegQueryValueEx(hKey, TEXT("Std"), NULL, NULL, reinterpret_cast<LPBYTE>(&szStandardName), &dwByteLen);
  1170. if (ErrorCode != ERROR_SUCCESS)
  1171. {
  1172. RegCloseKey(hKey);
  1173. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("RegQueryValueEx Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\China Standard Time\\Std fail");
  1174. return FALSE;
  1175. }
  1176. // 夏时制名
  1177. dwByteLen = sizeof(szDaylightName);
  1178. ErrorCode = RegQueryValueEx(hKey, TEXT("Dlt"), NULL, NULL, reinterpret_cast<LPBYTE>(&szDaylightName), &dwByteLen);
  1179. if (ErrorCode != ERROR_SUCCESS)
  1180. {
  1181. RegCloseKey(hKey);
  1182. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("RegQueryValueEx Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\China Standard Time\\Dlt fail");
  1183. return FALSE;
  1184. }
  1185. // 时区信息
  1186. dwByteLen = sizeof(regTZI);
  1187. ErrorCode = RegQueryValueEx(hKey, TEXT("TZI"), NULL, NULL, reinterpret_cast<LPBYTE>(&regTZI), &dwByteLen);
  1188. RegCloseKey(hKey);
  1189. if ((ErrorCode != ERROR_SUCCESS) || (dwByteLen > sizeof(regTZI)))
  1190. {
  1191. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("RegQueryValueEx Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\China Standard Time\\TZI fail");
  1192. return FALSE;
  1193. }
  1194. // 开启权限
  1195. HANDLE hToken;
  1196. TOKEN_PRIVILEGES tkp;
  1197. BOOL isOK;
  1198. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
  1199. {
  1200. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("OpenProcessToken Standard Time\\Dlt fail");
  1201. return FALSE;
  1202. }
  1203. LookupPrivilegeValue(NULL, SE_TIME_ZONE_NAME, &tkp.Privileges[0].Luid);
  1204. tkp.PrivilegeCount = 1;
  1205. tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1206. AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
  1207. if (GetLastError() != ERROR_SUCCESS)
  1208. {
  1209. CloseHandle(hToken);
  1210. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("AdjustTokenPrivileges fail");
  1211. return FALSE;
  1212. }
  1213. // 设置新时区
  1214. DYNAMIC_TIME_ZONE_INFORMATION tzi;
  1215. tzi.Bias = regTZI.Bias;
  1216. tzi.StandardDate = regTZI.StandardDate;
  1217. tzi.StandardBias = regTZI.StandardBias;
  1218. tzi.DaylightDate = regTZI.DaylightDate;
  1219. tzi.DaylightBias = regTZI.DaylightBias;
  1220. tzi.DynamicDaylightTimeDisabled = !isDaylightSavingTime;
  1221. wcscpy(tzi.StandardName, ANSIToUnicode(szStandardName).c_str());
  1222. wcscpy(tzi.DaylightName, ANSIToUnicode(szDaylightName).c_str());
  1223. wcscpy(tzi.TimeZoneKeyName, ANSIToUnicode(szTimeZoneKeyName).c_str());
  1224. isOK = SetDynamicTimeZoneInformation(&tzi); // 设置动态时区
  1225. if (!isOK)
  1226. {
  1227. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("SetDynamicTimeZoneInformation fail");
  1228. }
  1229. // 关闭权限
  1230. tkp.Privileges[0].Attributes = 0;
  1231. AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
  1232. CloseHandle(hToken);
  1233. return isOK;
  1234. #else
  1235. //temporarily not relased at linux
  1236. return TRUE;
  1237. #endif // RVC_OS_WIN
  1238. }
  1239. bool CAccessAuthEntity::IsMachineTypeConfigurePinPad(CSimpleStringA strMachineType)
  1240. {
  1241. // PAD单独判定
  1242. if (strMachineType.Compare("RVC.PAD", true) == 0)
  1243. {
  1244. #ifdef RVC_OS_WIN
  1245. //oilyang@20220413 except RVC.PAD without FWB
  1246. CSimpleStringA tmpFWBDevSN("");
  1247. GetFunction()->GetSysVar("FWBDevSN", tmpFWBDevSN);
  1248. if (tmpFWBDevSN.IsNullOrEmpty())
  1249. {
  1250. return false;
  1251. }
  1252. else
  1253. {
  1254. return true;
  1255. }
  1256. #endif // RVC_OS_WIN
  1257. }
  1258. else
  1259. {
  1260. CSmartPointer<IConfigInfo> spConfig;
  1261. ErrorCodeEnum Error = GetFunction()->OpenConfig(Config_CenterSetting, spConfig);
  1262. CSimpleStringA mcType = CSimpleStringA("CoreBootList.") + strMachineType;
  1263. CSimpleStringA loaderConifg("");
  1264. ErrorCodeEnum errCode = spConfig->ReadConfigValue("VtmLoader", mcType.GetData(), loaderConifg);
  1265. if (errCode != Error_Succeed)
  1266. {
  1267. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Get VtmLoader config failed!");
  1268. }
  1269. if (string(loaderConifg.GetData()).find("PinPad") != string::npos) //集中配置配了启动pinpad实体
  1270. {
  1271. return true;
  1272. }
  1273. else
  1274. {
  1275. return false;
  1276. }
  1277. }
  1278. }
  1279. void CAccessAuthEntity::UpdateWK()
  1280. {
  1281. m_FSM.UpdateWK();
  1282. }
  1283. void CAccessAuthEntity::BeginInitMKACS()
  1284. {
  1285. LOG_FUNCTION();
  1286. // 1:3des only; 2: sm4 only; 3: both 3des and sm4
  1287. int nCapability = GetPinPadCapability();
  1288. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("pinpad capability: %d", nCapability);
  1289. CSmartPointer<IConfigInfo> spConfig;
  1290. ErrorCodeEnum Error = GetFunction()->OpenConfig(Config_CenterSetting, spConfig);
  1291. if (Error_Succeed == Error)
  1292. {
  1293. Error = spConfig->ReadConfigValue("AccessAuthorization", "HostInitUrl", m_strInitUrl);
  1294. if (Error_Succeed != Error)
  1295. {
  1296. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("get InitUrl from CenterSetting failed");
  1297. return;
  1298. }
  1299. } else {
  1300. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("open InitUrl from CenterSetting.ini failed");
  1301. return;
  1302. }
  1303. CSmartPointer<InitializerInitMKTask> initUpdateWKTask = new InitializerInitMKTask(&this->m_FSM, this);
  1304. GetFunction()->PostThreadPoolTask(initUpdateWKTask.GetRawPointer());
  1305. }
  1306. bool CAccessAuthEntity::SendInitMKReqACS(CInitlizerMKReq& initMKReq)
  1307. {
  1308. LOG_FUNCTION();
  1309. CSmartPointer<IEntityFunction> pFunc = GetFunction();
  1310. #ifdef RVC_OS_LINUX
  1311. if (HasPinPad())
  1312. {
  1313. CSmartPointer<IConfigInfo> pConfig;
  1314. DWORD rc = pFunc->OpenConfig(Config_CenterSetting, pConfig);
  1315. if (rc != Error_Succeed)
  1316. {
  1317. LogWarn(Severity_Middle, (ErrorCodeEnum)rc, ERR_INITIALIZER_READ_WRITE_FILE,
  1318. GetOutPutStr("%s%08X%s%s", "OpenConfig", rc, "File", "Config_CenterSetting").c_str());
  1319. rc = ERR_INITIALIZER_READ_WRITE_FILE;
  1320. return rc;
  1321. }
  1322. CSimpleStringA strSubBankNo, strBranchNo;
  1323. rc = pConfig->ReadConfigValue("Initializer", "SubBankNo", strSubBankNo);
  1324. if (rc == Error_Succeed)
  1325. rc = pConfig->ReadConfigValue("Initializer", "BranchNo", strBranchNo);
  1326. if (rc != Error_Succeed)
  1327. {
  1328. LogWarn(Severity_Low, (ErrorCodeEnum)rc, ERR_INITIALIZER_READ_WRITE_FILE,
  1329. GetOutPutStr("%s%08X%s%s", "ReadConfigValue", rc, "File", "SubBankNo & BranchNo").c_str());
  1330. rc = ERR_INITIALIZER_READ_WRITE_FILE;
  1331. return rc;
  1332. }
  1333. // 1:3des only; 2: sm4 only; 3: both 3des and sm4
  1334. int nCapability = GetPinPadCapability();
  1335. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("pinpad capability: %d", nCapability);
  1336. }
  1337. else
  1338. {
  1339. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("has no pinpad, not need init MK");
  1340. }
  1341. #endif // RVC_OS_LINUX
  1342. CSimpleStringA strPinPadID = "", strDeviceID = "";
  1343. bool hasPinPad;
  1344. int nRet = GetPinPadIDAndDeviceID(strPinPadID, strDeviceID, hasPinPad);
  1345. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("GetPinPadIDAndDeviceID ret: %d, PinPadID: %s, DeviceID: %s", nRet, (const char*)strPinPadID, (const char*)strDeviceID);
  1346. if (nRet < 0)
  1347. {
  1348. return false; //具有pinpad的设备调用pinpad失败
  1349. }
  1350. // 从系统获取设备信息和硬件信息
  1351. // 变长结构初始化
  1352. char buf2[512];
  1353. memset(buf2, 0, 512);
  1354. CSystemStaticInfo si;
  1355. pFunc->GetSystemStaticInfo(si);
  1356. initMKReq.enrolGPS = "00000A4500000A4E";//oiltmp
  1357. initMKReq.enrolAddr = si.strEnrolAddr;
  1358. initMKReq.installVersion = si.InstallVersion.ToString();
  1359. #ifdef RVC_OS_WIN
  1360. hostent* ent = gethostbyname(NULL);
  1361. if (ent && ent->h_addr_list[0] != NULL)
  1362. {
  1363. int i = 0;
  1364. for (; ent->h_addr_list[i] != NULL; ++i)
  1365. {
  1366. struct in_addr* in = (struct in_addr*)ent->h_addr_list[i];
  1367. if (in->S_un.S_un_b.s_b1 == 99 || in->S_un.S_un_b.s_b1 == 10)
  1368. break;
  1369. }
  1370. if (ent->h_addr_list[i] == NULL)
  1371. i = 0;
  1372. auto in = (struct in_addr*)ent->h_addr_list[i];
  1373. char xIP[64] = {};
  1374. sprintf(xIP, "%d.%d.%d.%d", in->S_un.S_un_b.s_b1, in->S_un.S_un_b.s_b2, in->S_un.S_un_b.s_b3, in->S_un.S_un_b.s_b4);
  1375. initMKReq.ip = xIP;
  1376. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("ip:%s", xIP);
  1377. }
  1378. #else
  1379. BYTE xIP[64] = {};
  1380. char ip[32] = { 0 };
  1381. if (getIPFromLinux(ip)) DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Get IP From Linux Error ex.");
  1382. else {
  1383. if (ip2byte(ip, xIP)) DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Ip 2 Byte Error");
  1384. else {
  1385. for (int i = 0; i < 4; i++) {
  1386. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("ip[%d]=%d", i, xIP[i]);
  1387. }
  1388. char strIP[64];
  1389. memset(strIP, 0, 64);
  1390. sprintf(strIP, "%d.%d.%d.%d", xIP[0], xIP[1], xIP[2], xIP[3]);
  1391. initMKReq.ip = strIP;
  1392. }
  1393. }
  1394. #endif // RVC_OS_WIN
  1395. initMKReq.machineType = si.strMachineType;
  1396. if (nRet == 2 || nRet == 3)
  1397. initMKReq.padDeviceID = strDeviceID;
  1398. initMKReq.site = si.strSite;
  1399. initMKReq.terminalNo = si.strTerminalID;
  1400. BYTE fingerPrint[32] = { 0 };
  1401. int nBufLen = sizeof(fingerPrint);
  1402. if (!GetTerminalFingerPrint(fingerPrint, nBufLen))
  1403. {
  1404. LogWarn(Severity_Middle, Error_Unexpect, ERR_INITIALIZER_GET_TERMINAL_FINGERPRINT,
  1405. GetOutPutStr("%s%s", "GetTerminalFingerPrint", "False").c_str());
  1406. return ERR_INITIALIZER_GET_TERMINAL_FINGERPRINT;
  1407. }
  1408. initMKReq.terminalCharacter = ConvertBytesToHexStr(fingerPrint, nBufLen);
  1409. if (nRet == 1 || nRet == 3)
  1410. initMKReq.pinPadID = strPinPadID;
  1411. BYTE xPublicKey[148];
  1412. nBufLen = sizeof(xPublicKey);
  1413. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SendInitMKReqACS")("开始获取公钥。。。");
  1414. memset(xPublicKey, 0, nBufLen);
  1415. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SendInitMKReqACS")("nBufLen=%d", nBufLen);
  1416. if (!GetTerminalPublicKey(xPublicKey, nBufLen, initMKReq.publicKey))
  1417. {
  1418. LogWarn(Severity_Middle, Error_Unexpect, ERR_INITIALIZER_GET_TERMINAL_PUBKEY,
  1419. GetOutPutStr("%s%s", "GetTerminalPublicKey", "False").c_str());
  1420. return ERR_INITIALIZER_GET_TERMINAL_PUBKEY;
  1421. }
  1422. initMKReq.user = m_strUserID.GetData();
  1423. initMKReq.password = m_strPassword.GetData();
  1424. if (!m_strUserID.IsNullOrEmpty() && !m_strPassword.IsNullOrEmpty())
  1425. {
  1426. LogWarn(Severity_Low, Error_Succeed, AccessAuthorization_UserErrorCode_Init_From_ClosePage, "Init by ClosePage.");
  1427. initMKReq.loginWay = 1;
  1428. }
  1429. else
  1430. {
  1431. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("no need to call login again as User Desktop have logined.");
  1432. initMKReq.loginWay = 0;
  1433. }
  1434. PinPadService_ClientBase* pPinPad = new PinPadService_ClientBase(this);
  1435. auto errRc = pPinPad->Connect();
  1436. if (errRc == Error_Succeed)
  1437. {
  1438. PinPadService_GetCheckCode_Req req = {};
  1439. PinPadService_GetCheckCode_Ans ans = {};
  1440. req.mSN.Init(1);
  1441. req.wSN.Init(1);
  1442. req.mSN[0] = 1;
  1443. req.wSN[0] = 0;
  1444. errRc = (*pPinPad)(EntityResource::getLink().upgradeLink())->GetCheckCode(req, ans, 10000);
  1445. if (errRc == Error_Succeed)
  1446. {
  1447. initMKReq.tpkKeyCheck = ans.checkcode[0].GetData();
  1448. initMKReq.keyIndex = ans.index[0].GetData();
  1449. }
  1450. else
  1451. {
  1452. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Get keyChek && keyIndex failed.");
  1453. }
  1454. pPinPad->GetFunction()->CloseSession();
  1455. }
  1456. else
  1457. {
  1458. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("connect to pinpad failed.error code:%d", errRc);
  1459. }
  1460. return true;
  1461. }
  1462. void CAccessAuthEntity::EndInitMK(DWORD rc, const char *pszErrMsg)
  1463. {
  1464. LOG_FUNCTION();
  1465. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("EndInitMK:rc:%d,errMsg:%s", rc, pszErrMsg);
  1466. GetFunction()->KillTimer(22);
  1467. m_strLastErrMsg = pszErrMsg;
  1468. if (rc != Error_Succeed)
  1469. {
  1470. LogWarn(Severity_Middle, Error_Unexpect, ERR_INITIALIZER_INIT_MK,
  1471. GetOutPutStr("%s%08X%s%s", "EndInitMK", rc,"pszErrMsg", pszErrMsg).c_str());
  1472. GetFunction()->ShowFatalError(pszErrMsg);
  1473. }
  1474. else
  1475. {
  1476. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("初始化成功。。。");
  1477. }
  1478. m_eErrNum = rc;
  1479. bool bSuc = rc == Error_Succeed;
  1480. // 通知UI窗口
  1481. if (m_ctx != NULL) {
  1482. m_ctx->Ans.Errcode = rc;
  1483. m_ctx->Ans.ErrMsg = m_strLastErrMsg;
  1484. m_ctx->Answer(Error_Succeed);
  1485. }
  1486. }
  1487. ErrorCodeEnum CAccessAuthEntity::LoadKeysToPinPadACS(string TMK, string TPK, string EDK, string index)
  1488. {
  1489. LOG_FUNCTION();
  1490. #ifdef RVC_OS_WIN
  1491. if (m_bNewSMFWB && m_FSM.GetDevPubKey().GetLength() <= 0)
  1492. {
  1493. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("新蓝牙多合一密钥初始化依赖加密通道建立时的设备公钥,不具备,跳过密钥初始化");
  1494. return Error_Succeed;
  1495. }
  1496. #endif // RVC_OS_WIN
  1497. //加载到密码键盘
  1498. PinPadService_ClientBase* pPinPad = new PinPadService_ClientBase(this);
  1499. auto rc = pPinPad->Connect();
  1500. if (rc == Error_Succeed)
  1501. {
  1502. PinPadService_LoadKeysSM_Req req = {};
  1503. req.initializeflag = true;
  1504. if (m_bNewSMFWB)
  1505. {
  1506. //oilyang@20220902 to encrypte tmp using device public key
  1507. req.smflag = 11;
  1508. auto tmkpairDev = GenerateTmkToDevice();
  1509. if (tmkpairDev.first.length() <= 0)
  1510. {
  1511. //oiltest todo 补充错误信息
  1512. return Error_Unexpect;
  1513. }
  1514. else
  1515. req.masterkey = tmkpairDev.first.c_str();
  1516. }
  1517. else
  1518. {
  1519. req.smflag = 1;
  1520. req.masterkey = TMK.c_str();
  1521. }
  1522. req.workingkey1 = TPK.c_str();
  1523. req.workingkey2 = EDK.c_str();
  1524. req.reserved3 = index.c_str();
  1525. if (!req.initializeflag) DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("LoadKeysToPinPadACS")("initializeflag is false");
  1526. PinPadService_LoadKeysSM_Ans ans = {};
  1527. rc = pPinPad->LoadKeysSM(req, ans, 30000);
  1528. if (rc != Error_Succeed)
  1529. {
  1530. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("load sm key to pinpad failed.");
  1531. return Error_Unexpect;
  1532. }
  1533. pPinPad->GetFunction()->CloseSession();
  1534. }
  1535. else
  1536. {
  1537. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("connect to pinpad failed %x", rc);
  1538. return Error_Unexpect;
  1539. }
  1540. return Error_Succeed;
  1541. }
  1542. DWORD CAccessAuthEntity::InitDevice(SpReqAnsContext<AccessAuthService_InitDev_Req, AccessAuthService_InitDev_Ans>::Pointer& ctx)
  1543. {
  1544. return m_FSM.InitDevice(ctx);
  1545. }
  1546. void CAccessAuthEntity::GetNetMsg(SpReqAnsContext<AccessAuthService_GetNetMsg_Req, AccessAuthService_GetNetMsg_Ans>::Pointer& ctx)
  1547. {
  1548. m_FSM.GetNetMsg(ctx);
  1549. return;
  1550. }
  1551. bool CAccessAuthEntity::GenerateRandomNum()
  1552. {
  1553. LOG_FUNCTION();
  1554. const int MAX_KEY_SIZE = 256;
  1555. //get public key-->send random number --> set working key
  1556. int ret1, ret2, ret3, ret4;
  1557. unsigned int ram[4];
  1558. #ifdef RVC_OS_WIN
  1559. ret1 = rand_s(&ram[0]);
  1560. ret2 = rand_s(&ram[1]);
  1561. ret3 = rand_s(&ram[2]);
  1562. ret4 = rand_s(&ram[3]);
  1563. if ((ret1 != 0) || (ret2 != 0) || (ret3 != 0) || (ret4 != 0))
  1564. return false;
  1565. ZeroMemory(m_btRam, 16);
  1566. #else
  1567. ram[0] = rand();
  1568. ram[1] = rand();
  1569. ram[2] = rand();
  1570. ram[3] = rand();
  1571. memset(m_btRam, 0, 16);
  1572. #endif // RVC_OS_WIN
  1573. for (int i = 0, j = 0; j < 4; ++j)
  1574. {
  1575. m_btRam[i + 0] = ((ram[j] & 0xff000000) >> 24);
  1576. m_btRam[i + 1] = ((ram[j] & 0x00ff0000) >> 16);
  1577. m_btRam[i + 2] = ((ram[j] & 0x0000ff00) >> 8);
  1578. m_btRam[i + 3] = (ram[j] & 0x000000ff);
  1579. i += 4;
  1580. }
  1581. return true;
  1582. }
  1583. pair<string, string> CAccessAuthEntity::GenerateTmkToKMC()
  1584. {
  1585. LOG_FUNCTION();
  1586. if (!GenerateRandomNum())
  1587. return make_pair("", "");
  1588. #ifdef DEVOPS_ON_ST /*DevOps流水线编译,ST环境*/
  1589. CSimpleStringA tmpPubKey = "0445FAF2B721207A39A9F3DEE3B3D89E2EF8924882968D31FC54FDA4F41D3D94AED4DA1B3C38B17193AD2952BD24407B7C01A80E65630A2FAD5073691613EAA814";
  1590. #elif defined(DEVOPS_ON_UAT)/*DevOps流水线编译,UAT环境*/
  1591. CSimpleStringA tmpPubKey = "040AEC50A1FC9C5E9B1162FE4520C9E18E6F471A3F6DB77B147F0A464B5BFD0EDBE08AE8377C458CA204456E7A86568AAA9240F1C843E47988A6A197B232539DC8";
  1592. #elif defined(DEVOPS_ON_PRD)/*DevOps流水线编译,PRD环境*/
  1593. CSimpleStringA tmpPubKey = "04E0A4FDA2484A1A0FAB0844F59110AEB7A08D314B5E451E816FC0E78CBA383B461474E1167B86FC48D704CB482DD5164A73AB9E019CCE26EE382B89C394B5ACE1";
  1594. #elif defined(DEVOPS_ON_DEV)/*DevOps流水线编译,Dev环境*/
  1595. CSimpleStringA tmpPubKey = "0445FAF2B721207A39A9F3DEE3B3D89E2EF8924882968D31FC54FDA4F41D3D94AED4DA1B3C38B17193AD2952BD24407B7C01A80E65630A2FAD5073691613EAA814";
  1596. #else/*本地编译等非DevOps环境编译的版本*/
  1597. CSimpleStringA tmpPubKey = "0445FAF2B721207A39A9F3DEE3B3D89E2EF8924882968D31FC54FDA4F41D3D94AED4DA1B3C38B17193AD2952BD24407B7C01A80E65630A2FAD5073691613EAA814";
  1598. #endif
  1599. return EncryptedByPubKey(tmpPubKey);
  1600. }
  1601. pair<string, string> CAccessAuthEntity::GenerateTmkToDevice()
  1602. {
  1603. if (m_FSM.GetDevPubKey().GetLength() <= 0)
  1604. return make_pair("", "");
  1605. return EncryptedByPubKey(m_FSM.GetDevPubKey(), true);
  1606. }
  1607. pair<string, string> CAccessAuthEntity::EncryptedByPubKey(CSimpleStringA pubKey, bool bNeed04Head)
  1608. {
  1609. LOG_FUNCTION();
  1610. if (pubKey.GetLength() <= 0)
  1611. return make_pair("", "");
  1612. PCHAR strRam = new CHAR[512];
  1613. #ifdef RVC_OS_WIN
  1614. ZeroMemory(strRam, 512);
  1615. #else
  1616. memset(strRam, 0, 512);
  1617. #endif // RVC_OS_WIN
  1618. memcpy(strRam, &(m_btRam[0]), 16);
  1619. HexBuf2StrBuf((PBYTE)m_btRam, &strRam, 16);
  1620. const int MAX_KEY_SIZE = 256;
  1621. char random_enc_bypbk[MAX_KEY_SIZE];
  1622. #ifdef RVC_OS_WIN
  1623. ZeroMemory(random_enc_bypbk, MAX_KEY_SIZE);
  1624. #else
  1625. memset(random_enc_bypbk, 0, MAX_KEY_SIZE);
  1626. #endif // RVC_OS_WIN
  1627. //公钥加密随机数
  1628. int outMsgLen = MAX_KEY_SIZE;
  1629. PBYTE pxxKey = new BYTE[256];
  1630. PBYTE pOldPubKey = new BYTE[256];
  1631. #ifdef RVC_OS_WIN
  1632. ZeroMemory(pxxKey, 256);
  1633. ZeroMemory(pOldPubKey, 256);
  1634. #else
  1635. memset(pOldPubKey, 0, 256);
  1636. memset(pxxKey, 0, 256);
  1637. #endif // RVC_OS_WIN
  1638. int size = StrBuf2HexBuf(pubKey.GetData(), &pOldPubKey);
  1639. if (bNeed04Head)
  1640. {
  1641. pxxKey[0] = 0x04;
  1642. memcpy(pxxKey + 1, pOldPubKey, size);
  1643. }
  1644. else
  1645. memcpy(pxxKey, pOldPubKey, 65);
  1646. int retSM2 = EncWithSM2PubKey((unsigned char*)m_btRam, 16, (unsigned char*)random_enc_bypbk, &outMsgLen, (unsigned char*)pxxKey, 65);
  1647. if (!retSM2 || outMsgLen != 113)
  1648. {
  1649. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("EncWithSM2PubKey failed outMsgLen:%d.", outMsgLen);
  1650. return make_pair("", "");
  1651. }
  1652. PBYTE tmp_enc_bypbk = new BYTE[112];
  1653. #ifdef RVC_OS_WIN
  1654. ZeroMemory(tmp_enc_bypbk, 112);
  1655. #else
  1656. memset(tmp_enc_bypbk, 0, 112);
  1657. #endif // RVC_OS_WIN
  1658. //tmp_enc_bypbk[0] = 0x04;
  1659. if (bNeed04Head)
  1660. {
  1661. memcpy(tmp_enc_bypbk, &(random_enc_bypbk[1]), 112);
  1662. }
  1663. else
  1664. {
  1665. memcpy(tmp_enc_bypbk, &(random_enc_bypbk[1]), 64);
  1666. memcpy(tmp_enc_bypbk + 64, &(random_enc_bypbk[97]), 16);
  1667. memcpy(tmp_enc_bypbk + 80, &(random_enc_bypbk[65]), 32);
  1668. }
  1669. PCHAR pBlock = new CHAR[512];
  1670. #ifdef RVC_OS_WIN
  1671. ZeroMemory(pBlock, 512);
  1672. #else
  1673. memset(pBlock, 0, 512);
  1674. #endif // RVC_OS_WIN
  1675. BYTE tmpRandomEnc[512];
  1676. memset(tmpRandomEnc, 0, 512);
  1677. memcpy(tmpRandomEnc, &(tmp_enc_bypbk[0]), outMsgLen - 1);
  1678. size = HexBuf2StrBuf((PBYTE)tmpRandomEnc, &pBlock, 112);
  1679. return make_pair(pBlock, strRam);
  1680. }
  1681. #ifdef RVC_OS_WIN
  1682. void CAccessAuthEntity::GetTermSysInfo()
  1683. {
  1684. //oilyang@20231008 to get system info from runcfg first
  1685. //no matter calculating from runcfg succeed or not,we also get system info from system api for update runcfg
  1686. bool bCalcFromRunCfg = false;
  1687. CSimpleString csInfo, strErrMsg, strRet;
  1688. CSmartPointer<IConfigInfo> pConfigRun;
  1689. ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, pConfigRun);
  1690. if (eErr == Error_Succeed && pConfigRun->ReadConfigValue("system", "info", csInfo) == Error_Succeed && !csInfo.IsNullOrEmpty()) {
  1691. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("read device info from runcfg: [%s]", csInfo.GetData());
  1692. ZeroMemory(m_btTermSysInfoSM3, sizeof(m_btTermSysInfoSM3));
  1693. if (!SM3Hash(reinterpret_cast<BYTE*>(const_cast<char*>(csInfo.GetData())), csInfo.GetLength(), m_btTermSysInfoSM3))
  1694. {
  1695. strErrMsg = "get sm3 hash as fingerprint fail";
  1696. SetAuthErrMsg((const char*)strErrMsg);
  1697. this->GetFunction()->SetSysVar("AuthErrMsg", (const char*)strErrMsg, true);
  1698. m_FSM.doWarnMsg(ERROR_ACCESSAUTH_GETSM3HASH, (const char*)strErrMsg);
  1699. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI("GetTerminalFingerPrint")((const char*)strErrMsg);
  1700. m_iGetTermSysInfo = -1;
  1701. }
  1702. else
  1703. {
  1704. m_iGetTermSysInfo = 1;
  1705. bCalcFromRunCfg = true;
  1706. }
  1707. }
  1708. else
  1709. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetTermSysInfo, OpenConfig Config_Run error=%d.", eErr);
  1710. ULONGLONG ullStart = GetTickCount64();
  1711. char szTmp[1024] = {};
  1712. int nTmpBufLen = 1024;
  1713. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  1714. if (!QueryWMIDevice(Processor, "ProcessorId", szTmp, &nTmpBufLen))
  1715. {
  1716. strErrMsg = CSimpleStringA::Format("查询 cpu id 失败: %d, 请尝试重启应用", GetLastError());
  1717. SetAuthErrMsg((const char*)strErrMsg);
  1718. m_FSM.doWarnMsg(ERR_ACCESSAUTH_GET_TERMINAL_FINGERPRINT,
  1719. GetOutPutStr("%s%s%s%d", "QueryWMIDevice", "False", "Processor", GetLastError()).c_str(), true, strErrMsg.GetData());
  1720. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5203")
  1721. (GetOutPutStr("%s%s%s%d", "QueryWMIDevice", "False", "Processor", GetLastError()).c_str());
  1722. if (!bCalcFromRunCfg)
  1723. m_iGetTermSysInfo = -1;
  1724. return;
  1725. }
  1726. strRet = szTmp;
  1727. nTmpBufLen = 1024;
  1728. memset(szTmp, 0, sizeof(szTmp));
  1729. if (!QueryWMIDevice(BaseBoard, "SerialNumber", szTmp, &nTmpBufLen))
  1730. {
  1731. strErrMsg = CSimpleStringA::Format("查询 baseboard sn 失败: %d, 请尝试重启应用", GetLastError());
  1732. SetAuthErrMsg((const char*)strErrMsg);
  1733. m_FSM.doWarnMsg(ERR_ACCESSAUTH_GET_TERMINAL_FINGERPRINT,
  1734. GetOutPutStr("%s%s%s%d", "QueryWMIDevice", "False", "BaseBoard", GetLastError()).c_str(), true, strErrMsg.GetData());
  1735. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5203")
  1736. (GetOutPutStr("%s%s%s%d", "QueryWMIDevice", "False", "BaseBoard", GetLastError()).c_str());
  1737. if (!bCalcFromRunCfg)\
  1738. m_iGetTermSysInfo = -1;
  1739. return;
  1740. }
  1741. strRet += "|";
  1742. strRet += szTmp;
  1743. nTmpBufLen = 1024;
  1744. memset(szTmp, 0, sizeof(szTmp));
  1745. if (!QueryWMIDevice(DiskDrive, "SerialNumber", szTmp, &nTmpBufLen))
  1746. {
  1747. strErrMsg = CSimpleStringA::Format("查询 harddisk sn 失败: %d, 请尝试重启应用", GetLastError());
  1748. SetAuthErrMsg((const char*)strErrMsg);
  1749. m_FSM.doWarnMsg(ERR_ACCESSAUTH_GET_TERMINAL_FINGERPRINT,
  1750. GetOutPutStr("%s%s%s%d", "QueryWMIDevice", "False", "DiskDrive", GetLastError()).c_str(), true, strErrMsg.GetData());
  1751. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)(GetOutPutStr("%s%s%s%d", "QueryWMIDevice", "False", "DiskDrive", GetLastError()).c_str());
  1752. if (!bCalcFromRunCfg)
  1753. m_iGetTermSysInfo = -1;
  1754. return;
  1755. }
  1756. strRet += "|";
  1757. strRet += szTmp;
  1758. if (!bCalcFromRunCfg || csInfo.Compare(strRet) != 0)
  1759. {
  1760. eErr = pConfigRun->WriteConfigValue("system", "info", strRet.GetData());
  1761. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("device info changed,before[%s],current[%s],write to runcfg:%d"
  1762. , csInfo.GetData(), strRet.GetData(), eErr);
  1763. }
  1764. else
  1765. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("device info: [%s]", strRet.GetData());
  1766. if (!bCalcFromRunCfg)
  1767. {
  1768. ZeroMemory(m_btTermSysInfoSM3, sizeof(m_btTermSysInfoSM3));
  1769. if (!SM3Hash(reinterpret_cast<BYTE*>(const_cast<char*>(strRet.GetData())), strRet.GetLength(), m_btTermSysInfoSM3))
  1770. {
  1771. strErrMsg = "get sm3 hash as fingerprint fail";
  1772. SetAuthErrMsg((const char*)strErrMsg);
  1773. spFunction->SetSysVar("AuthErrMsg", (const char*)strErrMsg, true);
  1774. m_FSM.doWarnMsg(ERROR_ACCESSAUTH_GETSM3HASH, (const char*)strErrMsg);
  1775. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)((const char*)strErrMsg);
  1776. m_iGetTermSysInfo = -1;
  1777. }
  1778. else
  1779. m_iGetTermSysInfo = 1;
  1780. }
  1781. ULONGLONG ullEnd = GetTickCount64();
  1782. if (ullEnd - ullStart > 5000)
  1783. {
  1784. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5201")
  1785. ("获取系统信息耗时过长:%d秒", (ullEnd - ullStart) / 1000);
  1786. LogWarn(Severity_Middle, Error_Unexpect, AccessAuthorization_UserErrorCode_GetTermCostTooLong,
  1787. CSimpleStringA::Format("获取系统信息耗时过长:%d秒", (ullEnd - ullStart) / 1000));
  1788. }
  1789. return;
  1790. }
  1791. #endif // RVC_OS_WIN
  1792. SP_BEGIN_ENTITY_MAP()
  1793. SP_ENTITY(CAccessAuthEntity)
  1794. SP_END_ENTITY_MAP()