mod_AccessAuth.cpp 40 KB

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