mod_AccessAuth.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372
  1. #include "stdafx.h"
  2. #include "SpBase.h"
  3. #include "mod_AccessAuth.h"
  4. #include "RVCComm.h"
  5. #include "comm.h"
  6. #include "DeviceBaseClass.h"
  7. #include <fileutil.h>
  8. #include <iniutil.h>
  9. #include <cmath>
  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 <Strsafe.h>
  17. #endif
  18. #define KEY_SIZE 16
  19. #define BUF_SIZE 256
  20. typedef struct _REG_TZI_FORMAT
  21. {
  22. LONG Bias;
  23. LONG StandardBias;
  24. LONG DaylightBias;
  25. SYSTEMTIME StandardDate;
  26. SYSTEMTIME DaylightDate;
  27. } REG_TZI_FORMAT;
  28. void CAccessAuthSession::Handle_Regist(SpOnewayCallContext<AccessAuthService_Regist_Info>::Pointer ctx)
  29. {
  30. m_pEntity->Regist();
  31. }
  32. void CAccessAuthSession::Handle_Unregist(SpOnewayCallContext<AccessAuthService_Unregist_Info>::Pointer ctx)
  33. {
  34. m_pEntity->Unregist(ctx->Info.nReason, ctx->Info.nWay);
  35. }
  36. void CAccessAuthSession::Handle_Reregist(SpOnewayCallContext<AccessAuthService_Reregist_Info>::Pointer ctx)
  37. {
  38. m_pEntity->Reregist();
  39. }
  40. void CAccessAuthSession::Handle_PushTerminalStage(SpOnewayCallContext<AccessAuthService_PushTerminalStage_Info>::Pointer ctx)
  41. {
  42. m_pEntity->PushTerminalStage(ctx->Info.cNewStage, ctx->Info.dwNewStageTime, ctx->Info.cOldStage, ctx->Info.dwOldStageTime);
  43. }
  44. void CAccessAuthSession::Handle_InitDev(SpReqAnsContext<AccessAuthService_InitDev_Req, AccessAuthService_InitDev_Ans>::Pointer ctx)
  45. {
  46. m_pEntity->InitDevice(ctx);
  47. }
  48. void CAccessAuthSession::Handle_SyncTime(SpOnewayCallContext<AccessAuthService_SyncTime_Info>::Pointer ctx)
  49. {
  50. m_pEntity->SyncTime();
  51. }
  52. void CAccessAuthEntity::OnStarted()
  53. {
  54. //设置时区为北京标准时区
  55. if (!SetLocalTimeZoneByKeyName("China Standard Time", FALSE))
  56. {
  57. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_SETTIMEZONE,GetOutPutStr("%s%s","SetLocalTimeZoneByKeyName","False").c_str());
  58. }
  59. m_FSM.Init(this);
  60. }
  61. void CAccessAuthEntity::OnPreStart(CAutoArray<CSimpleStringA> strArgs,CSmartPointer<ITransactionContext> pTransactionContext)
  62. {
  63. ErrorCodeEnum Error = Error_Succeed;
  64. pTransactionContext->SendAnswer(Error) ;
  65. }
  66. void CAccessAuthEntity::OnPreClose(EntityCloseCauseEnum eCloseCause,CSmartPointer<ITransactionContext> pTransactionContext)
  67. {
  68. m_FSM.PostExitEvent();
  69. pTransactionContext->SendAnswer(Error_Succeed);
  70. }
  71. void CAccessAuthEntity::OnSysVarEvent(const char *pszKey, const char *pszValue,const char *pszOldValue,const char *pszEntityName)
  72. {
  73. }
  74. // 开始准入
  75. ErrorCodeEnum CAccessAuthEntity::Regist()
  76. {
  77. m_FSM.PostEventFIFO(new FSMEvent(CAccessAuthFSM::Event_StartRegist));
  78. return Error_Succeed;
  79. }
  80. // 重新准入
  81. ErrorCodeEnum CAccessAuthEntity::Reregist()
  82. {
  83. m_FSM.PostEventFIFO(new FSMEvent(CAccessAuthFSM::Event_StartReregist));
  84. return Error_Succeed;
  85. }
  86. // 准入退出
  87. ErrorCodeEnum CAccessAuthEntity::Unregist(int nReason, int nWay)
  88. {
  89. FSMEvent *pEvent = new FSMEvent(CAccessAuthFSM::Event_StartUnregist);
  90. pEvent->param1 = nReason;
  91. pEvent->param2 = nWay;
  92. m_FSM.PostEventFIFO(pEvent);
  93. return Error_Succeed;
  94. }
  95. DWORD CAccessAuthEntity::SyncTime()
  96. {
  97. return m_FSM.SyncTime();
  98. }
  99. ErrorCodeEnum CAccessAuthEntity::PushTerminalStage(char cNewStage, DWORD dwNewStageTime, char cOldStage, DWORD dwOldStageTime)
  100. {
  101. Dbg("on PushTerminalStage, cNewStage: %c", cNewStage);
  102. CAccessAuthFSM::ReportStateEvent *pEvent = new CAccessAuthFSM::ReportStateEvent(cNewStage, dwNewStageTime, cOldStage, dwOldStageTime);
  103. m_FSM.PostEventFIFO(pEvent);
  104. return Error_Succeed;
  105. }
  106. // KMC初始化
  107. DWORD CAccessAuthEntity::InitKMC()
  108. {
  109. return Error_Succeed;
  110. }
  111. // 获取WK更新请求包
  112. // @nAlgFlag: 1:3des only; 2: sm4 only; 3: both 3des and sm4
  113. ErrorCodeEnum CAccessAuthEntity::GetKmcWKUpdateData(char *pBuf, int &nLen, int nAlgFlag)
  114. {
  115. return Error_Succeed;
  116. }
  117. DWORD CAccessAuthEntity::ParseWKUpdateResult(char *pBuf, int nLen, int nAlgFlag)
  118. {
  119. return Error_Succeed;
  120. }
  121. CSimpleStringA CAccessAuthEntity::GetKMCLastErrMsg()
  122. {
  123. return "";
  124. }
  125. ErrorCodeEnum CAccessAuthEntity::ReleaseKMC()
  126. {
  127. return Error_Succeed;
  128. }
  129. // 加载新WK
  130. DWORD CAccessAuthEntity::LoadPinPadWK(bool bSM)
  131. {
  132. Dbg("load sm key to pinpad...");
  133. CSimpleString strErrMsg;
  134. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  135. PinPadService_ClientBase* pPinPad = new PinPadService_ClientBase(this);
  136. DWORD rc = pPinPad->Connect();
  137. if (rc == Error_Succeed)
  138. {
  139. PinPadService_LoadKeysSM_Req req = {};
  140. req.smflag = 1;
  141. req.initializeflag = true;
  142. if (m_bGetKMCKey) {
  143. Dbg("使用云接口更新KMC密钥");
  144. req.masterkey = m_TMK.c_str();
  145. req.workingkey1 = m_TPK.c_str();
  146. req.workingkey2 = m_EDK.c_str();
  147. req.reserved3 = m_index.c_str();
  148. }
  149. else {
  150. strErrMsg = "更新KMC密钥失败";
  151. SetAuthErrMsg((const char*)strErrMsg);
  152. spFunction->SetSysVar("AuthErrMsg", (const char*)strErrMsg, true);
  153. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_GET_KMC_NULL,
  154. GetOutPutStr("%s%s", "m_bGetKMCKey", "False").c_str());
  155. rc = ERR_ACCESSAUTH_GET_KMC_NULL;
  156. return rc;
  157. }
  158. if (req.initializeflag) Dbg("initializeflag is true");
  159. else Dbg("initializeflag is false");
  160. Dbg("req.smflag=%d", req.smflag);
  161. Dbg("req.masterkey=%s", req.masterkey.GetData());
  162. Dbg("req.workingkey1=%s", req.workingkey1.GetData());
  163. Dbg("req.workingkey2=%s", req.workingkey2.GetData());
  164. Dbg("req.reserved3=%s", req.reserved3.GetData());
  165. PinPadService_LoadKeysSM_Ans ans = {};
  166. rc = pPinPad->LoadKeysSM(req, ans, 30000);
  167. if (rc == Error_Succeed)
  168. Dbg("load sm key to pinpad succ");
  169. else
  170. {
  171. strErrMsg = "加载SM密钥到PinPad失败";
  172. SetAuthErrMsg((const char*)strErrMsg);
  173. spFunction->SetSysVar("AuthErrMsg", (const char*)strErrMsg, true);
  174. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_LOAD_KEYS_TO_PINPAD,
  175. GetOutPutStr("%s%08x%s%s", "LoadKeysSM", rc, "strErrMsg", strErrMsg).c_str());
  176. rc = ERR_ACCESSAUTH_LOAD_KEYS_TO_PINPAD;
  177. }
  178. pPinPad->GetFunction()->CloseSession();
  179. }
  180. else
  181. {
  182. strErrMsg = "连接PinPad实体失败";
  183. SetAuthErrMsg((const char*)strErrMsg);
  184. spFunction->SetSysVar("AuthErrMsg", (const char*)strErrMsg, true);
  185. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_CONNECT_PINPAD,
  186. GetOutPutStr("%s%08x%s%s", "Connect", rc, "strErrMsg", strErrMsg).c_str());
  187. rc = ERR_ACCESSAUTH_CONNECT_PINPAD;
  188. //@test 没连接成功调用此接口释放
  189. pPinPad->SafeDelete();
  190. }
  191. return rc;
  192. }
  193. // 将16进制字符串转成BYTE数据
  194. bool CAccessAuthEntity::HexStrToByteArray(const char* pHex, BYTE *pBuf, int *pBufLen)
  195. {
  196. int nHexLen = strlen(pHex);
  197. if (nHexLen %2 != 0)
  198. {
  199. Dbg("error hex string length");
  200. return false;
  201. }
  202. if (nHexLen /2 > *pBufLen)
  203. {
  204. Dbg("not enough buf length");
  205. return false;
  206. }
  207. for(int i=0; i<nHexLen; i++)
  208. {
  209. BYTE b =0;
  210. char ch1 = pHex[i];
  211. if (ch1 >='0' && ch1<='9')
  212. b = ch1 - '0';
  213. else if (ch1 >='A' && ch1 <='F')
  214. b = ch1 - 'A' + 10;
  215. else
  216. {
  217. Dbg("invalid hex string");
  218. return false;
  219. }
  220. if (i %2 ==0)
  221. {
  222. pBuf[i/2] = b;
  223. }
  224. else
  225. {
  226. pBuf[i/2] = pBuf[i/2] << 4 | b;
  227. }
  228. }
  229. *pBufLen = nHexLen / 2;
  230. return true;
  231. }
  232. string CAccessAuthEntity::ByteArrayToHexStr(BYTE *pBuf, int nBufLen)
  233. {
  234. char szBuf[1024];
  235. memset(szBuf, 0, sizeof(szBuf));
  236. for(int i=0; i<nBufLen; i++)
  237. {
  238. BYTE b1 = (pBuf[i] >> 4) & 0x0F;
  239. BYTE b2 = pBuf[i] & 0x0F;
  240. if (b1 <= 9)
  241. szBuf[i*2] = '0' + b1;
  242. else
  243. szBuf[i*2] = 'A' + b1 - 10;
  244. if (b2 <= 9)
  245. szBuf[i*2+1] = '0' + b2;
  246. else
  247. szBuf[i*2+1] = 'A' + b2 - 10;
  248. }
  249. return szBuf;
  250. }
  251. // 调用密码键盘加密
  252. DWORD CAccessAuthEntity::EncryptDataWithPinPad(const CBlob &raw, CBlob &enc)
  253. {
  254. #ifdef IGNORE_PINPAD
  255. enc.Alloc(raw.m_iLength);
  256. memcpy(enc.m_pData, raw.m_pData, raw.m_iLength);
  257. return Error_Succeed;
  258. #else
  259. CSimpleStringA strErrMsg;
  260. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  261. PinPadService_EncryptDataSM_Req req = {};
  262. PinPadService_EncryptDataSM_Ans ans = {};
  263. req.data = ByteArrayToHexStr((BYTE*)raw.m_pData, raw.m_iLength).c_str();
  264. Dbg("begin encrpyt data with pinpad");
  265. PinPadService_ClientBase *pPinPad = new PinPadService_ClientBase(this);
  266. DWORD rc = pPinPad->Connect();
  267. if (rc == Error_Succeed)
  268. {
  269. rc = pPinPad->EncryptDataSM(req, ans, 10000);
  270. if (rc == Error_Succeed)
  271. Dbg("encrypt data with pinpad succ: [%s]", (const char*)ans.ciphertext);
  272. else
  273. {
  274. strErrMsg = "调用PinPad实体中的EncryptData方法加密数据失败";
  275. SetAuthErrMsg((const char *)strErrMsg);
  276. spFunction->SetSysVar("AuthErrMsg", (const char *)strErrMsg, true);
  277. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_FROM_PINPAD,
  278. GetOutPutStr("%s%08x%s%s", "EncryptData", rc, "strErrMsg", strErrMsg).c_str());
  279. rc = ERR_ACCESSAUTH_FROM_PINPAD;
  280. }
  281. pPinPad->GetFunction()->CloseSession();
  282. }
  283. else
  284. {
  285. strErrMsg = "连接PinPad实体失败";
  286. SetAuthErrMsg((const char *)strErrMsg);
  287. spFunction->SetSysVar("AuthErrMsg", (const char *)strErrMsg, true);
  288. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_CONNECT_PINPAD,
  289. GetOutPutStr("%s%08x%s%s", "Connect", rc, "strErrMsg", strErrMsg).c_str());
  290. rc = ERR_ACCESSAUTH_CONNECT_PINPAD;
  291. pPinPad->SafeDelete();
  292. }
  293. if (rc != Error_Succeed)
  294. return rc;
  295. BYTE buf[512];
  296. int nLen = 512;
  297. memset(buf, 0, 512);
  298. if (!HexStrToByteArray((const char*)ans.ciphertext, buf, &nLen))
  299. {
  300. strErrMsg = "加密数据转化十六进制失败";
  301. SetAuthErrMsg((const char *)strErrMsg);
  302. spFunction->SetSysVar("AuthErrMsg", (const char *)strErrMsg, true);
  303. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_HEX_TO_BYTE,
  304. GetOutPutStr("%s%s%s%s", "HexStrToByteArray", "False", "strErrMsg", strErrMsg).c_str());
  305. return ERR_ACCESSAUTH_HEX_TO_BYTE;
  306. }
  307. enc.Alloc(nLen);
  308. memcpy(enc.m_pData, buf, nLen);
  309. return Error_Succeed;
  310. #endif
  311. }
  312. // 生成临时SM2密钥对
  313. DWORD CAccessAuthEntity::CreateSM2KeyPair(CBlob &pubKey, CBlob &priKey)
  314. {
  315. int nPubKeyLen = 256;
  316. int nPriKeyLen = 256;
  317. pubKey.Alloc(nPubKeyLen);
  318. priKey.Alloc(nPriKeyLen);
  319. if (!::CreateSM2KeyPair((BYTE*)pubKey.m_pData, &nPubKeyLen, (BYTE*)priKey.m_pData, &nPriKeyLen))
  320. {
  321. SetAuthErrMsg("创建SM2密钥对失败");
  322. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  323. spFunction->SetSysVar("AuthErrMsg", "创建SM2密钥对失败", true);
  324. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_CREATE_RSA_KEY_PAIR,
  325. GetOutPutStr("%s%s","CreateRsaKeyPair","False").c_str());
  326. return ERR_ACCESSAUTH_CREATE_RSA_KEY_PAIR;
  327. }
  328. pubKey.Resize(nPubKeyLen);
  329. priKey.Resize(nPriKeyLen);
  330. return Error_Succeed;
  331. }
  332. // 保存到令牌管理实体中
  333. DWORD CAccessAuthEntity::SaveSM2KeyPair(const CBlob &pubKey, const CBlob &priKey)
  334. {
  335. CSimpleStringA strErrMsg;
  336. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  337. TokenService_ClientBase *pTokenServiceClient = new TokenService_ClientBase(this);
  338. DWORD rc = pTokenServiceClient->Connect();
  339. if (rc != Error_Succeed)
  340. {
  341. strErrMsg = "连接令牌管理实体失败";
  342. SetAuthErrMsg((const char *)strErrMsg);
  343. spFunction->SetSysVar("AuthErrMsg", (const char *)strErrMsg, true);
  344. rc = ERR_ACCESSAUTH_CONNECT_TOKEN_SERVICE;
  345. LogWarn(Severity_Middle, Error_Unexpect, rc,
  346. GetOutPutStr("%s%08X%s%s", "Connect", rc,"strErrMsg", strErrMsg).c_str());
  347. pTokenServiceClient->SafeDelete();
  348. }
  349. else
  350. {
  351. TokenService_SetKeyPair_Req req;
  352. req.pub_key = pubKey;
  353. req.pri_key = priKey;
  354. TokenService_SetKeyPair_Ans ans;
  355. rc = pTokenServiceClient->SetKeyPair(req, ans, 3000);
  356. pTokenServiceClient->GetFunction()->CloseSession();
  357. if (rc != Error_Succeed)
  358. {
  359. strErrMsg = "保存密钥对失败";
  360. SetAuthErrMsg((const char *)strErrMsg);
  361. spFunction->SetSysVar("AuthErrMsg", (const char *)strErrMsg, true);
  362. rc = ERR_ACCESSAUTH_FROM_TOKEN_SERVICE_SET_KEYS;
  363. LogWarn(Severity_Middle, Error_Unexpect, rc,
  364. GetOutPutStr("%s%08X%s%s", "SetKeyPair", rc,"strErrMsg", (const char*)strErrMsg).c_str());
  365. }
  366. else
  367. Dbg("set sm2 key pair succ");
  368. }
  369. return rc;
  370. }
  371. ErrorCodeEnum CAccessAuthEntity::SaveTokenAndSharedSK(const CBlob &token, const CBlob &sharedSK)
  372. {
  373. CSimpleStringA strErrMsg;
  374. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  375. TokenService_ClientBase *pTokenServiceClient = new TokenService_ClientBase(this);
  376. ErrorCodeEnum rc = pTokenServiceClient->Connect();
  377. if (rc != Error_Succeed)
  378. {
  379. strErrMsg = "连接令牌管理实体失败";
  380. SetAuthErrMsg((const char *)strErrMsg);
  381. spFunction->SetSysVar("AuthErrMsg", (const char *)strErrMsg, true);
  382. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_CONNECT_TOKEN_SERVICE,
  383. GetOutPutStr("%s%08X%s%s", "Connect", rc,"strErrMsg", (const char*)strErrMsg).c_str());
  384. pTokenServiceClient->SafeDelete();
  385. }
  386. else
  387. {
  388. TokenService_SetToken_Req req = {};
  389. req.token = token;
  390. TokenService_SetToken_Ans ans;
  391. rc = pTokenServiceClient->SetToken(req, ans, 5000);
  392. if (rc == Error_Succeed)
  393. Dbg("save token succ, token: [%s]", ByteArrayToHexStr((BYTE*)token.m_pData, token.m_iLength).c_str());
  394. else
  395. {
  396. strErrMsg = "保存令牌失败";
  397. SetAuthErrMsg((const char *)strErrMsg);
  398. spFunction->SetSysVar("AuthErrMsg", (const char *)strErrMsg, true);
  399. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_FROM_TOKEN_SERVICE_SET_TOKEN,
  400. GetOutPutStr("%s%08X%s%s", "SetToken", rc,"strErrMsg", strErrMsg).c_str());
  401. }
  402. TokenService_SetSharedSK_Req req2 = {};
  403. req2.ssk = sharedSK;
  404. TokenService_SetSharedSK_Ans ans2 = {};
  405. rc = pTokenServiceClient->SetSharedSK(req2, ans2, 5000);
  406. if (rc == Error_Succeed)
  407. Dbg("save shared session key succ");
  408. else
  409. {
  410. strErrMsg = "保存会话密钥失败";
  411. SetAuthErrMsg((const char *)strErrMsg);
  412. spFunction->SetSysVar("AuthErrMsg", (const char *)strErrMsg, true);
  413. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_FROM_TOKEN_SERVICE_SET_SHAREKEY,
  414. GetOutPutStr("%s%08X%s%s", "SetSharedSK", rc,"strErrMsg", (const char*)strErrMsg).c_str());
  415. }
  416. pTokenServiceClient->GetFunction()->CloseSession();
  417. }
  418. return rc;
  419. }
  420. bool CAccessAuthEntity::HasPinPad()
  421. {
  422. CSimpleStringA strErrMsg;
  423. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  424. CSystemStaticInfo info;
  425. auto rc = GetFunction()->GetSystemStaticInfo(info);
  426. if (rc != Error_Succeed)
  427. {
  428. strErrMsg = "HasPinPad()=>GetSystemStaticInfo() fail";
  429. SetAuthErrMsg((const char *)strErrMsg);
  430. spFunction->SetSysVar("AuthErrMsg", (const char *)strErrMsg, true);
  431. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_GET_SYSTEM_STATIC_INFO,
  432. GetOutPutStr("%s%08X", "GetSystemStaticInfo", rc).c_str());
  433. return true;
  434. }
  435. if (info.strMachineType.IsStartWith("RPM", true) || info.strMachineType.IsStartWith("RVC.CardStore", true) || info.strMachineType.IsStartWith("RVC.IL", true)) // 回单打印机、简化版
  436. {
  437. Dbg("MachineType[%s], not exist pinpad", info.strMachineType);
  438. return false;
  439. }
  440. else if (stricmp(info.strMachineType, "RVC.PAD") == 0) // Pad机型
  441. {
  442. // 根据PinPad实体状态确定是否连接密码键盘
  443. bool bPinPadExist = false;
  444. auto pPinPadClient = new PinPadService_ClientBase(this);
  445. if (pPinPadClient->Connect() != Error_Succeed)
  446. {
  447. Dbg("connect PinPad fail, assume no pinpad");
  448. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_CONNECT_PINPAD,
  449. GetOutPutStr("%s%s", "Connect", "False").c_str());
  450. pPinPadClient->SafeDelete();
  451. pPinPadClient = NULL;
  452. }
  453. else
  454. {
  455. PinPadService_GetDevInfo_Req req = {};
  456. PinPadService_GetDevInfo_Ans ans = {};
  457. auto rc = pPinPadClient->GetDevInfo(req, ans, 3000);
  458. if (rc != Error_Succeed)
  459. {
  460. strErrMsg = "PinPad::GetDevInfo() fail";
  461. SetAuthErrMsg((const char *)strErrMsg);
  462. spFunction->SetSysVar("AuthErrMsg", (const char *)strErrMsg, true);
  463. //LogError(Severity_Middle, rc, ERROR_ACCESSAUTH_GETPINPADINFO, (const char *)strErrMsg);
  464. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_FROM_PINPAD,
  465. GetOutPutStr("%s%08X", "GetDevInfo", rc).c_str());
  466. }
  467. else
  468. {
  469. Dbg("PinPad::GetDevInfo() return state: %d", ans.state);
  470. bPinPadExist = ans.state != DEVICE_STATUS_NOT_READY;
  471. }
  472. pPinPadClient->GetFunction()->CloseSession();
  473. }
  474. return bPinPadExist;
  475. }
  476. else
  477. {
  478. // 其它VTM机型,全部有内置密码键盘
  479. return true;
  480. }
  481. }
  482. // 1:3des only; 2: sm4 only; 3: both 3des and sm4
  483. // 由当前已初始化的密钥文件决定,兼容旧版本终端
  484. int CAccessAuthEntity::GetPinPadCapability()
  485. {
  486. int nCapability = 0;
  487. PinPadService_ClientBase *pPinPad = new PinPadService_ClientBase(this);
  488. auto rc = pPinPad->Connect();
  489. if (rc == Error_Succeed)
  490. {
  491. PinPadService_QueryFunc_Req req;
  492. PinPadService_QueryFunc_Ans ans;
  493. rc = pPinPad->QueryFunc(req,ans,3000);
  494. if (rc == Error_Succeed)
  495. {
  496. nCapability = ans.reserved1;
  497. Dbg("QueryFunc from pinpad succ, nCapability[%d]", nCapability);
  498. }
  499. else
  500. {
  501. SetAuthErrMsg("从PinPad获取主密钥类型失败");
  502. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  503. spFunction->SetSysVar("AuthErrMsg", "从PinPad获取主密钥类型失败", true);
  504. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_FROM_PINPAD,
  505. GetOutPutStr("%s%s%s%s", "QueryFunc", "False", "AuthErrMsg", "从PinPad获取主密钥类型失败").c_str());
  506. }
  507. pPinPad->GetFunction()->CloseSession();
  508. }
  509. else
  510. {
  511. SetAuthErrMsg("连接PinPad实体失败");
  512. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  513. spFunction->SetSysVar("AuthErrMsg", "连接PinPad实体失败", true);
  514. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_CONNECT_PINPAD,
  515. GetOutPutStr("%s%08X%s%s", "Connect", rc,"AuthErrMsg", "连接PinPad实体失败").c_str());
  516. pPinPad->SafeDelete();
  517. }
  518. return nCapability;
  519. }
  520. void CAccessAuthEntity::printPasswdError(){
  521. string strErrMsg = "密钥集丢失,请重新初始化密钥!";
  522. SetAuthErrMsg(strErrMsg.c_str());
  523. GetFunction()->SetSysVar("AuthErrMsg", strErrMsg.c_str(), true);
  524. LogError(Severity_Low, Error_Unexpect, ERROR_ACCESSAUTH_OPENCRYPTCONTEXT, strErrMsg.c_str());
  525. }
  526. int Char2Int(char * ch) {
  527. int num = 0;
  528. for (int i = 0;i < strlen(ch);i++) {
  529. num += ((int)(ch[i] - '0')) * pow((float)10, (float)(strlen(ch) - i - 1));
  530. }
  531. return num;
  532. }
  533. bool CAccessAuthEntity::SaveAuthVerAndKey(int nAuthVer, BYTE *pKey)
  534. {
  535. LOG_FUNCTION();
  536. m_nAuthVersion = nAuthVer;
  537. memset(m_AuthSessionKey, 0, 140);
  538. if (m_nAuthVersion == 2)
  539. {
  540. CSimpleString runInfoPath;
  541. auto rc = GetFunction()->GetPath("runinfo", runInfoPath);
  542. if (rc != Error_Succeed) {
  543. Dbg("GetPath runinfo error=%d.", rc);
  544. return false;
  545. }
  546. char privateKey[BUF_SIZE] = { 0 };
  547. runInfoPath += SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR "Initializer.ini";
  548. #ifdef RVC_OS_WIN
  549. GetPrivateProfileString("TerminalPD", "PrivateKey", "", privateKey, BUF_SIZE, runInfoPath.GetData());
  550. #else
  551. Dbg("path ex:%s", runInfoPath.GetData());
  552. char* tmp = inifile_read_str(runInfoPath.GetData(),"TerminalPD", "PrivateKey", "");
  553. strcpy(privateKey, tmp);
  554. delete tmp;
  555. #endif // RVC_OS_WIN
  556. if (strlen(privateKey) <= 0) {
  557. printPasswdError();
  558. return false;
  559. }
  560. Dbg("privateKey=%s,%d", privateKey, strlen(privateKey));
  561. int decodedPrivateKeyLen;
  562. char* pDecodedPrivateKey = Hex2Str(privateKey, decodedPrivateKeyLen);
  563. Dbg("decodedPrivateKeyLen=%d", decodedPrivateKeyLen);
  564. char pDecryptPrivateKey[BUF_SIZE] = { 0 };
  565. int decryprtLen = BUF_SIZE;
  566. if (!DecWithSM4_ECB("s5da69gnh4!963@6s5da69gnh4!963@6", (BYTE*)pDecodedPrivateKey, decodedPrivateKeyLen, (BYTE*)pDecryptPrivateKey, &decryprtLen)) {
  567. Dbg("DecWithSM4_ECB decrypt privateKey error.");
  568. printPasswdError();
  569. delete[] pDecodedPrivateKey;
  570. return false;
  571. }
  572. delete[] pDecodedPrivateKey;
  573. //添加调试信息
  574. char * pEncPriKey = Str2Hex((char*)pDecryptPrivateKey, decryprtLen);
  575. Dbg("DecWithSM4_ECB succeess.privateKey=%s", pEncPriKey);
  576. delete pEncPriKey;
  577. char pPlainKey[KEY_SIZE];
  578. int plainKeyLen = KEY_SIZE;
  579. char pKeyLen[4] = { 0 };
  580. memcpy(pKeyLen, pKey, 4);
  581. int kenLen = Char2Int(pKeyLen);
  582. Dbg("kenLen=%d", kenLen);
  583. char* pEncodeKey = Str2Hex((char*)pKey,kenLen + 4);
  584. Dbg("pEncodeKey=%s", pEncodeKey);
  585. delete pEncodeKey;
  586. char* key = new char[kenLen + 1];
  587. memset(key, 0, kenLen + 1);
  588. memcpy(key, pKey + 4, kenLen);
  589. if (!DecWithSM2PriKey((BYTE*)key, kenLen, (BYTE*)pPlainKey, &plainKeyLen, (BYTE*)pDecryptPrivateKey, decryprtLen)) {
  590. Dbg("使用私钥解密失败!");
  591. printPasswdError();
  592. return false;
  593. }
  594. Dbg("使用私钥解密成功。。。");
  595. if (plainKeyLen != KEY_SIZE) {
  596. Dbg("私钥解密后的会话密钥长度不等于16!");
  597. }
  598. memcpy(m_AuthSessionKey, pPlainKey, KEY_SIZE);
  599. }
  600. return true;
  601. }
  602. static BYTE* ConvertHexStrToBytes(const char *pszStr)
  603. {
  604. if (pszStr == NULL || strlen(pszStr) == 0)
  605. return NULL;
  606. int nLen = strlen(pszStr) / 2;
  607. BYTE *pRet = (BYTE*)malloc(nLen);
  608. memset(pRet, 0, nLen);
  609. for (int i = 0; i < nLen; i++)
  610. {
  611. int nTmp(0);
  612. if (sscanf(&pszStr[i * 2], "%2X", &nTmp) != 1)
  613. {
  614. free(pRet);
  615. return NULL;
  616. }
  617. pRet[i] = (BYTE)nTmp;
  618. }
  619. return pRet;
  620. }
  621. // 使用准入会话密钥加密
  622. ErrorCodeEnum CAccessAuthEntity::EncryptDataWithSessionKey(const CBlob &raw, CBlob &enc)
  623. {
  624. LOG_FUNCTION();
  625. assert(m_nAuthVersion ==2);
  626. //这里不需要delete,由CBlob析构函数去执行
  627. BYTE* pEncData = new BYTE[1024];
  628. int pEncDataSize = 1024;
  629. Dbg("pEncDataSize=%d", pEncDataSize);
  630. char* pPlainInfo = Str2Hex((char*)raw.m_pData, raw.m_iLength);
  631. Dbg("raw data=%s,raw.m_iLength=%d", pPlainInfo, raw.m_iLength);
  632. delete[] pPlainInfo;
  633. //char *sessionKey = Str2Hex((char*)m_AuthSessionKey, KEY_SIZE);
  634. char sessionKey[KEY_SIZE] = { 0 };
  635. memcpy(sessionKey,m_AuthSessionKey,KEY_SIZE);
  636. char* tmpKey = Str2Hex((char*)m_AuthSessionKey, KEY_SIZE);
  637. Dbg("sessionKey=%s", tmpKey);
  638. delete[] tmpKey;
  639. if (!EncWithSM4_ECB((BYTE*)sessionKey, (BYTE*)(raw.m_pData), raw.m_iLength, pEncData, &pEncDataSize)) {
  640. Dbg("会话密钥加密准入信息失败!");
  641. return Error_Unexpect;
  642. }
  643. enc.Attach(pEncData,pEncDataSize);
  644. char* tmp = Str2Hex((char*)pEncData, pEncDataSize);
  645. Dbg("pEncData=%s,%d", tmp, pEncDataSize);
  646. delete[] tmp;
  647. tmp = Str2Hex((char*)enc.m_pData, enc.m_iLength);
  648. Dbg("EncWithSM4_ECB data=%s,%d", tmp, enc.m_iLength);
  649. delete[] tmp;
  650. return Error_Succeed;
  651. }
  652. bool CAccessAuthEntity::GetMD5Hash(const char *pStr, BYTE md5[16])
  653. {
  654. return false;
  655. }
  656. static char* ConvertBytesToHexStr(BYTE *pBuf, int nLen)
  657. {
  658. char *pRet = (char*)malloc(nLen * 2 + 1);
  659. memset(pRet, 0, nLen * 2 + 1);
  660. char *p = pRet;
  661. for (int i = 0; i < nLen; i++)
  662. {
  663. BYTE b = pBuf[i];
  664. BYTE l = (b >> 4) & 0x0F;
  665. if (l >= 10)
  666. *p = l - 10 + 'A';
  667. else
  668. *p = l + '0';
  669. p++;
  670. BYTE r = b & 0x0F;
  671. if (r >= 10)
  672. *p = r - 10 + 'A';
  673. else
  674. *p = r + '0';
  675. p++;
  676. }
  677. return pRet;
  678. }
  679. bool CAccessAuthEntity::GetTerminalFingerPrint(BYTE *pBuf, int &nBufLen)
  680. {
  681. char szTmp[1024] = {};
  682. string strTmp;
  683. int nTmpBufLen = 1024;
  684. CSimpleStringA strErrMsg;
  685. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  686. CSimpleStringA strRet;
  687. #ifdef RVC_OS_WIN
  688. if (!QueryWMIDevice(Processor, "ProcessorId", szTmp, &nTmpBufLen))
  689. #else
  690. if (!get_cpu_id_by_system(strTmp))
  691. #endif // RVC_OS_WIN
  692. {
  693. strErrMsg = CSimpleStringA::Format("查询CPU ID失败,请重启机器并重新初始化");
  694. SetAuthErrMsg((const char *)strErrMsg);
  695. spFunction->SetSysVar("AuthErrMsg", (const char *)strErrMsg, true);
  696. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_GET_TERMINAL_FINGERPRINT,
  697. GetOutPutStr("%s%s", "Processor", "False").c_str());
  698. return false;
  699. }
  700. #ifdef RVC_OS_WIN
  701. strRet = szTmp;
  702. nTmpBufLen = 1024;
  703. memset(szTmp, 0, sizeof(szTmp));
  704. if (!QueryWMIDevice(BaseBoard, "SerialNumber", szTmp, &nTmpBufLen))
  705. #else
  706. Dbg("cpu id: %s", strTmp.c_str());
  707. strRet = strTmp.c_str();
  708. strTmp.clear();
  709. if (!get_board_serial_by_system(strTmp))
  710. #endif // RVC_OS_WIN
  711. {
  712. strErrMsg = CSimpleStringA::Format("查询主板序列号失败, 请重启机器并重新初始化");
  713. SetAuthErrMsg((const char *)strErrMsg);
  714. spFunction->SetSysVar("AuthErrMsg", (const char *)strErrMsg, true);
  715. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_GET_TERMINAL_FINGERPRINT,
  716. GetOutPutStr("%s%s", "BaseBoard", "False").c_str());
  717. return false;
  718. }
  719. strRet += "|";
  720. #ifdef RVC_OS_WIN
  721. strRet += szTmp;
  722. nTmpBufLen = 1024;
  723. memset(szTmp, 0, sizeof(szTmp));
  724. if (!QueryWMIDevice(DiskDrive, "SerialNumber", szTmp, &nTmpBufLen))
  725. #else
  726. Dbg("baseboard sn: %s", strTmp.c_str());
  727. strRet += strTmp.c_str();
  728. vector<string> disk;
  729. if (!get_disk_serial_by_system(disk))
  730. #endif // RVC_OS_WIN
  731. {
  732. strErrMsg = CSimpleStringA::Format("查询磁盘序列号失败, 请重启机器并重新初始化");
  733. SetAuthErrMsg((const char*)strErrMsg);
  734. spFunction->SetSysVar("AuthErrMsg", (const char*)strErrMsg, true);
  735. LogWarn(Severity_Middle, Error_Unexpect, ERR_INITIALIZER_GET_DISKDRIVE_ID,
  736. GetOutPutStr("%s%s", "DiskDrive", "False").c_str());
  737. return false;
  738. }
  739. strRet += "|";
  740. #ifdef RVC_OS_WIN
  741. strRet += szTmp;
  742. #else
  743. strTmp = "";
  744. vector<string>::iterator it = disk.begin();
  745. while (it != disk.end()) {
  746. strTmp += *it;
  747. it++;
  748. }
  749. Dbg("harddisk sn: %s", strTmp.c_str());
  750. strRet += strTmp.c_str();
  751. #endif // RVC_OS_WIN
  752. Dbg("device info: [%s]", (const char*)strRet);
  753. BYTE sm3[32] = { 0 };
  754. if(!SM3Hash(reinterpret_cast<BYTE*>(const_cast<char*>(strRet.GetData())),strRet.GetLength(),sm3))
  755. {
  756. strErrMsg = "get sm3 hash as fingerprint fail";
  757. SetAuthErrMsg((const char *)strErrMsg);
  758. spFunction->SetSysVar("AuthErrMsg", (const char *)strErrMsg, true);
  759. LogError(Severity_Low, Error_Unexpect, ERROR_ACCESSAUTH_GETSM3HASH, (const char *)strErrMsg);
  760. return false;
  761. }
  762. if (nBufLen < 32)
  763. {
  764. LogError(Severity_Low, Error_Unexpect, ERROR_ACCESSAUTH_GETSM3HASH, "buf len is too small fail");
  765. return false;
  766. }
  767. nBufLen = 32;
  768. memcpy(pBuf, sm3, nBufLen);
  769. char *pszSM3 = ConvertBytesToHexStr(sm3, nBufLen);
  770. Dbg("fringerprint: [%s]", pszSM3);
  771. free(pszSM3);
  772. return true;
  773. }
  774. // 生成SM2密钥对,并导出公钥
  775. bool CAccessAuthEntity::GetTerminalPublicKey(BYTE *pBuf, int &nBufLen)
  776. {
  777. CSimpleString runInfoPath;
  778. auto rc = GetFunction()->GetPath("runinfo", runInfoPath);
  779. if (rc != Error_Succeed) {
  780. Dbg("GetPath runinfo error=%d.", rc);
  781. return false;
  782. }
  783. runInfoPath += SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR "Initializer.ini";
  784. char publicKey[BUF_SIZE] = { 0 };
  785. #ifdef RVC_OS_WIN
  786. GetPrivateProfileString("TerminalPD", "PublicKey", "", publicKey, BUF_SIZE, runInfoPath.GetData());
  787. #else
  788. char* tmp = inifile_read_str(runInfoPath.GetData(), "TerminalPD", "PublicKey", "");
  789. strcpy(publicKey, tmp);
  790. delete tmp;
  791. #endif // RVC_OS_WIN
  792. if (strlen(publicKey) <= 0) {
  793. Dbg("读取公钥失败,公钥长度小于等于零!");
  794. printPasswdError();
  795. return false;
  796. }
  797. Dbg("publickey=%s,%d",publicKey,strlen(publicKey));
  798. char* pDecodedPublickey = Hex2Str(publicKey,nBufLen);
  799. Dbg("pDecodedPublickey=[%s],len=%d", pDecodedPublickey, nBufLen);
  800. memcpy(pBuf, pDecodedPublickey, nBufLen);
  801. Dbg("pBuf[0]=%02X,nBufLen=%d", pBuf[0], nBufLen);
  802. delete[] pDecodedPublickey;
  803. return true;
  804. }
  805. DWORD CAccessAuthEntity::InitDevice(SpReqAnsContext<AccessAuthService_InitDev_Req, AccessAuthService_InitDev_Ans>::Pointer &ctx)
  806. {
  807. return m_FSM.InitDevice(ctx);
  808. }
  809. // 返回1:只有PinPadID;2:只有DeviceID;3:两者都有;0:没有;-1表示失败
  810. int CAccessAuthEntity::GetPinPadIDAndDeviceID(CSimpleStringA &strPinPadID, CSimpleStringA &strDeviceID)
  811. {
  812. CSimpleStringA strErrMsg;
  813. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  814. CSystemStaticInfo info;
  815. auto rc = GetFunction()->GetSystemStaticInfo(info);
  816. if (rc != Error_Succeed)
  817. {
  818. strErrMsg = "获取系统静态信息(GetPinPadIDAndDeviceID)失败";
  819. SetAuthErrMsg((const char *)strErrMsg);
  820. spFunction->SetSysVar("AuthErrMsg", (const char *)strErrMsg, true);
  821. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_GET_SYSTEM_STATIC_INFO,
  822. GetOutPutStr("%s%08X", "GetSystemStaticInfo", rc).c_str());
  823. return -1;
  824. }
  825. if (info.strMachineType.IsStartWith("RPM", true) || info.strMachineType.IsStartWith("RVC.CardStore", true) || info.strMachineType.IsStartWith("RVC.IL", true)) // 回单打印机、简化版
  826. return 0;
  827. int nRet = -1;
  828. auto pPinPadClient = new PinPadService_ClientBase(this);
  829. bool bPinPadID = false;
  830. bool bDeviceID = false;
  831. bool bVendor = false;
  832. bool bBluetooth = false;
  833. CSimpleStringA strVendor;
  834. CSimpleStringA strBluetoothID;
  835. CSimpleStringA strPID;
  836. CSimpleStringA strMID;
  837. if (pPinPadClient->Connect() == Error_Succeed)
  838. {
  839. PinPadService_GetDevInfo_Req req = {};
  840. PinPadService_GetDevInfo_Ans ans = {};
  841. auto rc = pPinPadClient->GetDevInfo(req, ans, 3000);
  842. if (rc == Error_Succeed)
  843. {
  844. if (ans.state == DEVICE_STATUS_NORMAL)
  845. {
  846. nRet = 0;
  847. Dbg("pinpad model: %s", (const char*)ans.model);
  848. // CM = V2.0#PM = V1.0#MID = 75500001#PID = 12345678#FWID = V1234567#Vendor = nantian
  849. // 密码键盘ID,PID,8到16字节; 设备ID,MID,8到16字节; 固件版本号,FWID,8字节
  850. CSimpleStringA str = ans.model;
  851. if (!str.IsNullOrEmpty())
  852. {
  853. auto arr = str.Split('#');
  854. if (arr.GetCount() > 0)
  855. {
  856. for (int i = 0; i < arr.GetCount(); i++)
  857. {
  858. auto arr2 = arr[i].Split('=');
  859. if (arr2.GetCount() != 2)
  860. continue;
  861. //if (arr2[0] == "PID")
  862. if(!strnicmp((LPCTSTR)arr2[0], "PID", strlen("PID")))
  863. {
  864. strPID = arr2[1];
  865. if (!strPID.IsNullOrEmpty())
  866. bPinPadID = true;
  867. }
  868. //else if (arr2[0] == "MID")
  869. else if(!strnicmp((LPCTSTR)arr2[0], "MID", strlen("MID")))
  870. {
  871. strMID = arr2[1];
  872. if (!strMID.IsNullOrEmpty())
  873. bDeviceID = true;
  874. }
  875. //else if (arr2[0] == "Vendor")
  876. else if(!strnicmp((LPCTSTR)arr2[0], "Vendor", strlen("Vendor")))
  877. {
  878. strVendor = arr2[1];
  879. if (!strVendor.IsNullOrEmpty())
  880. bVendor = true;
  881. }
  882. else if (!strnicmp((LPCTSTR)arr2[0], "FWBID", strlen("FWBID")))
  883. {
  884. strBluetoothID = arr2[1];
  885. Dbg("strBluetoothID=%s", strBluetoothID);
  886. if (!strBluetoothID.IsNullOrEmpty())
  887. bBluetooth = true;
  888. }
  889. }
  890. }
  891. }
  892. }
  893. else
  894. {
  895. Dbg("pinpad not exist, state: %d", ans.state);
  896. }
  897. }
  898. else
  899. {
  900. strErrMsg = "调用PinPad实体的GetDevInfo方法失败";
  901. SetAuthErrMsg((const char *)strErrMsg);
  902. spFunction->SetSysVar("AuthErrMsg", (const char *)strErrMsg, true);
  903. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_FROM_PINPAD,
  904. GetOutPutStr("%s%08X%s%s", "GetDevInfo", rc, "strErrMsg", (const char*)strErrMsg ).c_str());
  905. }
  906. pPinPadClient->GetFunction()->CloseSession();
  907. }
  908. else
  909. {
  910. strErrMsg = "连接PinPad实体失败";
  911. SetAuthErrMsg((const char *)strErrMsg);
  912. spFunction->SetSysVar("AuthErrMsg", (const char *)strErrMsg, true);
  913. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_CONNECT_PINPAD,
  914. GetOutPutStr("%s%08X%s%s", "Connect", rc, "strErrMsg", "连接PinPad实体失败").c_str());
  915. pPinPadClient->SafeDelete();
  916. pPinPadClient = NULL;
  917. }
  918. if (bPinPadID)
  919. {
  920. if (bVendor)
  921. strPinPadID = strVendor + "_" + strPID;
  922. else
  923. strPinPadID = strPID;
  924. nRet += 1;
  925. }
  926. if (bDeviceID)
  927. {
  928. if (bVendor)
  929. strDeviceID = strVendor + "_" + strMID;
  930. else
  931. strDeviceID = strMID;
  932. if (bBluetooth)
  933. strDeviceID = strDeviceID + "_" + strBluetoothID;
  934. nRet += 2;
  935. }
  936. return nRet;
  937. }
  938. bool CAccessAuthEntity::HasCkCodeFlg()
  939. {
  940. CSimpleStringA strErrMsg;
  941. CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
  942. CSystemStaticInfo info;
  943. auto rc = GetFunction()->GetSystemStaticInfo(info);
  944. if (rc != Error_Succeed)
  945. {
  946. strErrMsg = "获取系统静态信息失败";
  947. SetAuthErrMsg((const char *)strErrMsg);
  948. spFunction->SetSysVar("AuthErrMsg", (const char *)strErrMsg, true);
  949. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_GET_SYSTEM_STATIC_INFO,
  950. GetOutPutStr("%s%08X%s%s", "GetSystemStaticInfo", rc, "strErrMsg", (const char*)strErrMsg).c_str());
  951. return false;
  952. }
  953. if (info.strMachineType.IsStartWith("RPM", true) || info.strMachineType.IsStartWith("RVC.CardStore", true) || info.strMachineType.IsStartWith("RVC.IL", true)) // 回单打印机、简化版
  954. {
  955. Dbg("MachineType is [%s], not exist pinpad entity", info.strMachineType);
  956. return false;
  957. }
  958. auto pPinPadClient = new PinPadService_ClientBase(this);
  959. bool bCheckCode = false;
  960. CSimpleStringA strSpeficiCM;
  961. if (pPinPadClient->Connect() == Error_Succeed)
  962. {
  963. PinPadService_GetDevInfo_Req req = {};
  964. PinPadService_GetDevInfo_Ans ans = {};
  965. auto rc = pPinPadClient->GetDevInfo(req, ans, 3000);
  966. if (rc == Error_Succeed)
  967. {
  968. if (ans.state == DEVICE_STATUS_NORMAL)
  969. {
  970. Dbg("pinpad model: %s", (const char*)ans.model);
  971. // CM = V2.0#PM = V1.0#MID = 75500001#PID = 12345678#FWID = V1234567#Vendor = nantian
  972. // 密码键盘ID,PID,8到16字节; 设备ID,MID,8到16字节; 固件版本号,FWID,8字节
  973. CSimpleStringA str = ans.model;
  974. if (!str.IsNullOrEmpty())
  975. {
  976. auto arr = str.Split('#');
  977. if (arr.GetCount() > 0)
  978. {
  979. for (int i = 0; i < arr.GetCount(); i++)
  980. {
  981. auto arr2 = arr[i].Split('=');
  982. if (arr2.GetCount() != 2)
  983. continue;
  984. if(!strnicmp((LPCTSTR)arr2[0], "CM", strlen("CM")))
  985. {
  986. strSpeficiCM = arr2[1];
  987. if (strSpeficiCM.GetLength() > 3 && _strnicmp(strSpeficiCM, "V2.0", strlen("V2.0")) == 0)
  988. {
  989. //Support checkcode, then operate checkcode routine..
  990. bCheckCode = true;
  991. }
  992. }
  993. }
  994. }
  995. }
  996. }
  997. else
  998. {
  999. Dbg("pinpad not exist, state: %d", ans.state);
  1000. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_FROM_PINPAD,
  1001. GetOutPutStr("%s%d", "ans.state", ans.state).c_str());
  1002. }
  1003. }
  1004. else
  1005. {
  1006. strErrMsg = "调用PinPad实体(GetDevInfo)失败";
  1007. SetAuthErrMsg((const char *)strErrMsg);
  1008. spFunction->SetSysVar("AuthErrMsg", (const char *)strErrMsg, true);
  1009. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_FROM_PINPAD,
  1010. GetOutPutStr("%s%08X", "GetDevInfo", rc).c_str());
  1011. }
  1012. pPinPadClient->GetFunction()->CloseSession();
  1013. }
  1014. else
  1015. {
  1016. strErrMsg = "连接PinPad实体失败";
  1017. SetAuthErrMsg((const char *)strErrMsg);
  1018. spFunction->SetSysVar("AuthErrMsg", (const char *)strErrMsg, true);
  1019. LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_CONNECT_PINPAD,
  1020. GetOutPutStr("%s%s", "strErrMsg", strErrMsg).c_str());
  1021. pPinPadClient->SafeDelete();
  1022. pPinPadClient = NULL;
  1023. }
  1024. return bCheckCode? true:false;
  1025. }
  1026. wstring CAccessAuthEntity::ANSIToUnicode(const string& str)
  1027. {
  1028. int len = 0;
  1029. len = str.length();
  1030. int unicodeLen = ::MultiByteToWideChar(CP_ACP,
  1031. 0,
  1032. str.c_str(),
  1033. -1,
  1034. NULL,
  1035. 0);
  1036. wchar_t * pUnicode;
  1037. pUnicode = new wchar_t[unicodeLen+1];
  1038. memset(pUnicode,0,(unicodeLen+1)*sizeof(wchar_t));
  1039. ::MultiByteToWideChar( CP_ACP,
  1040. 0,
  1041. str.c_str(),
  1042. -1,
  1043. (LPWSTR)pUnicode,
  1044. unicodeLen);
  1045. wstring rt;
  1046. rt = (wchar_t*)pUnicode;
  1047. delete pUnicode;
  1048. return rt;
  1049. }
  1050. //China Standard Time
  1051. BOOL CAccessAuthEntity::SetLocalTimeZoneByKeyName(const TCHAR* szTimeZoneKeyName, BOOL isDaylightSavingTime)
  1052. {
  1053. #ifdef RVC_OS_WIN
  1054. HKEY hKey;
  1055. LONG ErrorCode;
  1056. TCHAR szSubKey[256];
  1057. TCHAR szStandardName[32];
  1058. TCHAR szDaylightName[32];
  1059. REG_TZI_FORMAT regTZI;
  1060. DWORD dwByteLen;
  1061. // 检测入口参数
  1062. if ((szTimeZoneKeyName == NULL) || (strlen(szTimeZoneKeyName) == 0))
  1063. {
  1064. // 时区标识符不能为空
  1065. return FALSE;
  1066. }
  1067. StringCchCopy(szSubKey, 256, TEXT("Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\"));
  1068. StringCchCat(szSubKey, 256, szTimeZoneKeyName);
  1069. ErrorCode = RegOpenKeyEx(HKEY_LOCAL_MACHINE, szSubKey, 0, KEY_QUERY_VALUE, &hKey);
  1070. if (ErrorCode != ERROR_SUCCESS)
  1071. {
  1072. Dbg("RegOpenKeyEx Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\China Standard Time fail");
  1073. return FALSE;
  1074. }
  1075. // 标准名
  1076. dwByteLen = sizeof(szStandardName);
  1077. ErrorCode = RegQueryValueEx(hKey, TEXT("Std"), NULL, NULL, reinterpret_cast<LPBYTE>(&szStandardName), &dwByteLen);
  1078. if (ErrorCode != ERROR_SUCCESS)
  1079. {
  1080. RegCloseKey(hKey);
  1081. Dbg("RegQueryValueEx Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\China Standard Time\\Std fail");
  1082. return FALSE;
  1083. }
  1084. // 夏时制名
  1085. dwByteLen = sizeof(szDaylightName);
  1086. ErrorCode = RegQueryValueEx(hKey, TEXT("Dlt"), NULL, NULL, reinterpret_cast<LPBYTE>(&szDaylightName), &dwByteLen);
  1087. if (ErrorCode != ERROR_SUCCESS)
  1088. {
  1089. RegCloseKey(hKey);
  1090. Dbg("RegQueryValueEx Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\China Standard Time\\Dlt fail");
  1091. return FALSE;
  1092. }
  1093. // 时区信息
  1094. dwByteLen = sizeof(regTZI);
  1095. ErrorCode = RegQueryValueEx(hKey, TEXT("TZI"), NULL, NULL, reinterpret_cast<LPBYTE>(&regTZI), &dwByteLen);
  1096. RegCloseKey(hKey);
  1097. if ((ErrorCode != ERROR_SUCCESS) || (dwByteLen > sizeof(regTZI)))
  1098. {
  1099. Dbg("RegQueryValueEx Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\China Standard Time\\TZI fail");
  1100. return FALSE;
  1101. }
  1102. // 开启权限
  1103. HANDLE hToken;
  1104. TOKEN_PRIVILEGES tkp;
  1105. BOOL isOK;
  1106. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &hToken))
  1107. {
  1108. Dbg("OpenProcessToken Standard Time\\Dlt fail");
  1109. return FALSE;
  1110. }
  1111. LookupPrivilegeValue(NULL, SE_TIME_ZONE_NAME, &tkp.Privileges[0].Luid);
  1112. tkp.PrivilegeCount = 1;
  1113. tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1114. AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
  1115. if (GetLastError() != ERROR_SUCCESS)
  1116. {
  1117. CloseHandle(hToken);
  1118. Dbg("AdjustTokenPrivileges fail");
  1119. return FALSE;
  1120. }
  1121. // 设置新时区
  1122. DYNAMIC_TIME_ZONE_INFORMATION tzi;
  1123. tzi.Bias = regTZI.Bias;
  1124. tzi.StandardDate = regTZI.StandardDate;
  1125. tzi.StandardBias = regTZI.StandardBias;
  1126. tzi.DaylightDate = regTZI.DaylightDate;
  1127. tzi.DaylightBias = regTZI.DaylightBias;
  1128. tzi.DynamicDaylightTimeDisabled = !isDaylightSavingTime;
  1129. wcscpy(tzi.StandardName, ANSIToUnicode(szStandardName).c_str());
  1130. wcscpy(tzi.DaylightName, ANSIToUnicode(szDaylightName).c_str());
  1131. wcscpy(tzi.TimeZoneKeyName, ANSIToUnicode(szTimeZoneKeyName).c_str());
  1132. isOK = SetDynamicTimeZoneInformation(&tzi); // 设置动态时区
  1133. if (!isOK)
  1134. {
  1135. Dbg("SetDynamicTimeZoneInformation fail");
  1136. }
  1137. // 关闭权限
  1138. tkp.Privileges[0].Attributes = 0;
  1139. AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
  1140. CloseHandle(hToken);
  1141. return isOK;
  1142. #endif // RVC_OS_WIN
  1143. }
  1144. int CAccessAuthEntity::ConvertStr2Byte(string input, BYTE* output, int outputLen) {
  1145. if (input.size() > outputLen) return 1;
  1146. for (int i = 0;i < input.size();i++) {
  1147. output[i] = input[i];
  1148. }
  1149. return 0;
  1150. }
  1151. int CAccessAuthEntity::GetOrSetIsFirstSM(int type) {
  1152. CSmartPointer<IConfigInfo> pConfig;
  1153. int isFirst = 0;
  1154. auto rc = GetFunction()->OpenConfig(Config_Run, pConfig);
  1155. if (rc != Error_Succeed) {
  1156. Dbg("OpenConfig Config_Run error=%d.", rc);
  1157. return isFirst;
  1158. }
  1159. CSimpleStringA sIsFirst;
  1160. if (type == 0) {
  1161. rc = pConfig->ReadConfigValue("SM", "IsFirst", sIsFirst);
  1162. if (rc != Error_Succeed || sIsFirst.IsNullOrEmpty()) {
  1163. rc = pConfig->WriteConfigValue("SM", "IsFirst", "Yes");
  1164. if (rc != Error_Succeed) {
  1165. Dbg("WriteConfigValue Config_Run SM IsFirst error.");
  1166. return isFirst;
  1167. }
  1168. isFirst = 1;
  1169. }
  1170. else if (sIsFirst == "Yes") {
  1171. isFirst = 1;
  1172. }
  1173. else isFirst = 0;
  1174. return isFirst;
  1175. }
  1176. else {
  1177. rc = pConfig->WriteConfigValue("SM", "IsFirst", "No");
  1178. if (rc != Error_Succeed) {
  1179. Dbg("WriteConfigValue Config_Run SM IsFirst error.");
  1180. return isFirst;
  1181. }
  1182. else {
  1183. isFirst = 1;
  1184. }
  1185. return isFirst;
  1186. }
  1187. }
  1188. SP_BEGIN_ENTITY_MAP()
  1189. SP_ENTITY(CAccessAuthEntity)
  1190. SP_END_ENTITY_MAP()