mod_AccessAuth.cpp 55 KB

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