mod_AccessAuth.cpp 39 KB

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