1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032 |
- #include "stdafx.h"
- #include "SpBase.h"
- #include "mod_AccessAuth.h"
- #include "RVCComm.h"
- #include "access_basefun.h"
- #include <fileutil.h>
- #include <cmath>
- #include "Event.h"
- #include "comm.h"
- #include "TokenKeeper_client_g.h"
- using namespace TokenKeeper;
- #include "PinPad_client_g.h"
- using namespace PinPad;
- #ifdef RVC_OS_WIN
- #include "WMIDeviceQuery.h"
- #include <WinCrypt.h>
- #include <Strsafe.h>
- #include "DeviceBaseClass.h"
- #include "MyBase64.h"
- #else
- #include "CommEntityRestful.hpp"
- #include "DeviceBaseClass.h"
- #include <iniutil.h>
- #endif
- #define KEY_SIZE 16
- #define BUF_SIZE 256
- extern int HexBuf2StrBuf(PBYTE hexBuf, char** strBuf, DWORD len);
- extern int StrBuf2HexBuf(LPCTSTR strBuf, PBYTE* hexBuf);
- struct InitializerInitMKTask : ITaskSp
- {
- CAccessAuthFSM* m_fsm;
- CAccessAuthEntity* m_entity;
- InitializerInitMKTask(CAccessAuthFSM* fsm, CAccessAuthEntity* entity) :m_fsm(fsm), m_entity(entity) {}
- void Process()
- {
- CSystemStaticInfo si;
- m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(si);
- #ifdef RVC_OS_WIN
- IHttpFunc* client;
- client = create_http(m_fsm->HttpsLogCallBack);
- CInitlizerMKReq initMKReq;
- CInitlizerMKRet initMKRet;
- bool initFlag = m_entity->SendInitMKReqACS(initMKReq);
- if (!initFlag)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5204")("连接密码键盘异常");
- m_entity->EndInitMK(ERR_ACCESSAUTH_CONNECT_PINPAD, "连接密码键盘异常,请检查");//,待完善细化错误码oiltest
- client->Destory();
- }
- auto tmkpair = m_entity->GenerateTmkToKMC();
- initMKReq.encRandom = tmkpair.first;
- initMKReq.m_url = m_entity->GetInitUrl();
- initMKReq.m_url += "/api/v5/initmk";
- long beg = GetTickCount();
- bool ret = client->Post(initMKReq, initMKRet);
- long end = GetTickCount();
- if (ret) {
- if (initMKRet.m_userCode.compare(ACS_SUCCESS)) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("InitializerInitMKTask")("initmk failed.");
- if (client) client->Destory();
- m_entity->EndInitMK(ERR_INITIALIZER_INIT_EXCEPTION, CSimpleStringA::Format("%s,%s"
- , initMKRet.m_userCode.c_str(), initMKRet.m_errMsg.c_str()));
- return;
- }
- //服务端返回成功再将数据写入AcessAuthourization.ini
- CSmartPointer<IConfigInfo> pConfig;
- auto rc = m_entity->GetFunction()->OpenConfig(Config_Run, pConfig);
- rc = pConfig->WriteConfigValue("TerminalPD", "PrivateKey", m_entity->m_privateKey);
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("write pri key failed.");
- m_entity->EndInitMK(ERR_INITIALIZER_INIT_EXCEPTION, "私钥写入失败,请重新初始化。");
- return;
- }
- if (m_entity->HasPinPad()) {
- if (m_entity->LoadKeysToPinPadACS(tmkpair.second, initMKRet.tpk, initMKRet.edk, initMKRet.keyIndex) == Error_Succeed)
- m_entity->EndInitMK(Error_Succeed, "");
- else
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5204")("连接密码键盘异常");
- m_entity->EndInitMK(ERR_ACCESSAUTH_CONNECT_PINPAD, "密钥加载失败,请检查密码键盘连接。");//,待完善细化错误码oiltest
- }
- }
- else
- m_entity->EndInitMK(Error_Succeed, "");
- }
- else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI("InitializerInitMKTask").setBeginTime(beg).setEndTime(end).
- setResultCode(std::to_string(LONGLONG(initMKRet.m_sysCode)).c_str()).
- setResultMsg(initMKRet.m_errMsg.c_str())("InitializerInitMKTask Connect Failed.");
- m_entity->EndInitMK(ERR_INITIALIZER_INIT_EXCEPTION, CSimpleStringA::Format("初始化服务连接失败。%d", ret).GetData());
- }
- client->Destory();
- #else
- CInitlizerMKReq initMKReq;//oiltest dev module count
- bool initFlag = m_entity->SendInitMKReqACS(initMKReq);
- if (!initFlag)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5204")("连接密码键盘异常");
- m_entity->EndInitMK(ERR_ACCESSAUTH_CONNECT_PINPAD, "连接密码键盘异常,请检查");//,待完善细化错误码oiltest
- }
- auto tmkpair = m_entity->GenerateTmkToKMC();
- struct InstanceReqJson
- {
- string enrolAddr;
- string enrolGPS;
- string installVersion;
- string ip;
- string machineModel;
- string machineType;
- string padDeviceID;
- string site;
- string terminalNo;
- string factory;
- string modal;
- string type;
- string version;
- string terminalCharacter; //终端特征值(fingerPrint + fingerPrintSM)
- string pinPadID;
- string publicKey;
- string user; //操作人
- string password; //密码
- string auth;//预留鉴权
- int loginWay;//1表示错误页发起,需要传入登录密码;0表示用户桌面发起,不需要传入登录密码
- string encRandom; //tmk pk加密的随机密钥
- string tpkKeyCheck; //密钥校验值
- string edkKeyCheck; //密钥校验值
- string keyIndex; //密钥序号
- JSONCONVERT2OBJECT_MEMEBER_REGISTER(enrolAddr, enrolGPS, installVersion, ip, machineModel, machineType,
- padDeviceID, site, terminalNo, factory, modal, type, version, terminalCharacter, pinPadID, publicKey,
- user, password, auth, loginWay, encRandom, tpkKeyCheck, edkKeyCheck, keyIndex)
- } instanceReq;
- instanceReq.enrolAddr = initMKReq.enrolAddr;
- instanceReq.enrolGPS = initMKReq.enrolGPS;
- instanceReq.installVersion = initMKReq.installVersion;
- instanceReq.ip = initMKReq.ip;
- instanceReq.machineModel = initMKReq.machineModel;
- instanceReq.machineType = initMKReq.machineType;
- instanceReq.padDeviceID = initMKReq.padDeviceID;
- instanceReq.site = initMKReq.site;
- instanceReq.terminalNo = initMKReq.terminalNo;
- instanceReq.factory = initMKReq.factory;
- instanceReq.modal = initMKReq.modal;
- instanceReq.type = initMKReq.type;
- instanceReq.version = initMKReq.version;
- instanceReq.terminalCharacter = initMKReq.terminalCharacter;
- instanceReq.pinPadID = initMKReq.pinPadID;
- instanceReq.publicKey = initMKReq.publicKey;
- instanceReq.user = initMKReq.user;
- instanceReq.password = initMKReq.password;
- instanceReq.auth = initMKReq.auth;
- instanceReq.loginWay = initMKReq.loginWay;
- instanceReq.encRandom = tmkpair.first;
- instanceReq.tpkKeyCheck = initMKReq.tpkKeyCheck;
- instanceReq.edkKeyCheck = initMKReq.edkKeyCheck;
- instanceReq.keyIndex = initMKReq.keyIndex;
- struct InstanceAnsJson
- {
- string TMK;
- string TPK;
- string EDK;
- string tpkKeyCheck;
- string edkKeyCheck;
- string keyIndex;
- string reserved;
- JSONCONVERT2OBJECT_MEMEBER_REGISTER(TMK, TPK, EDK, tpkKeyCheck, edkKeyCheck, keyIndex)
- JSONCONVERT2OBJECT_MEMEBER_RENAME_REGISTER("tmk", "tpk", "edk", "tpkKeyCheck", "edkKeyCheck", "keyIndex")
- } instanceAns;
- HttpClientResponseResult result;
- HttpClientRequestConfig config(HttpRequestMethod::POST, m_entity->GetInitUrl().GetData(), &SpGetToken);
- config.SetChildUri("/api/v5/initmk");
- SP::Module::Restful::FulfillRequestJsonBody(&config, instanceReq);
- std::string test;
- test = config.GetRequestUri();
- RestfulClient client = RestfulClient::getInstance();
- config.PreDo();
- client.Do(&config, &result);
- if (result.ResponseOK()) {
- SP::Module::Restful::CommResponseJson responseStatus;
- SP::Module::Restful::GetStatusFromDebranchResponse(result.content, responseStatus);
- if (!responseStatus.IsOperatedOK()) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("update wk failed: %s", responseStatus.errorMsg.c_str());
- m_entity->EndInitMK(ERR_INITIALIZER_INIT_EXCEPTION, responseStatus.errorMsg.c_str());
- }
- else {
- //服务端返回成功再将数据写入AcessAuthourization.ini
- CSmartPointer<IConfigInfo> pConfig;
- auto rc = m_entity->GetFunction()->OpenConfig(Config_Run, pConfig);
- rc = pConfig->WriteConfigValue("TerminalPD", "PrivateKey", m_entity->m_privateKey);
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("write pri key failed.");
- m_entity->EndInitMK(ERR_INITIALIZER_INIT_EXCEPTION, "私钥写入失败,请重新初始化。");
- return;
- }
- if (m_entity->HasPinPad()) {
- const bool testResult = SP::Module::Restful::ExtractDataFromDebranchResponse(result.content, instanceAns);
- if (m_entity->LoadKeysToPinPadACS(tmkpair.second, instanceAns.TPK, instanceAns.EDK, instanceAns.keyIndex) == Error_Succeed) {
- m_entity->EndInitMK(Error_Succeed, "");
- }
- else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5204")("连接密码键盘异常");
- m_entity->EndInitMK(ERR_ACCESSAUTH_CONNECT_PINPAD, "密钥加载失败,请检查密码键盘连接。");//,待完善细化错误码oiltest
- }
- }
- else {
- m_entity->EndInitMK(Error_Succeed, "");
- }
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("post wk failed: %s", result.WhatError().c_str());
- m_entity->EndInitMK(ERR_INITIALIZER_INIT_EXCEPTION, CSimpleStringA::Format("初始化服务连接失败。%s", result.WhatError().c_str()).GetData());
- }
- #endif //RVC_OS_WIN
- }
- };
- #ifdef RVC_OS_WIN
- struct GetTermSysInfoTask : ITaskSp
- {
- CAccessAuthEntity* m_entity;
- GetTermSysInfoTask(CAccessAuthEntity* entity) :m_entity(entity) {}
- void Process()
- {
- m_entity->GetTermSysInfo();
- }
- };
- #endif // RVC_OS_WIN
- typedef struct _REG_TZI_FORMAT
- {
- LONG Bias;
- LONG StandardBias;
- LONG DaylightBias;
- SYSTEMTIME StandardDate;
- SYSTEMTIME DaylightDate;
- } REG_TZI_FORMAT;
- void CAccessAuthSession::Handle_Regist(SpOnewayCallContext<AccessAuthService_Regist_Info>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setAPI(__FUNCTION__)("call Handle_Regist");
- m_pEntity->Regist();
- }
- void CAccessAuthSession::Handle_UpdateWK(SpOnewayCallContext<AccessAuthService_UpdateWK_Info>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setAPI(__FUNCTION__)("call Handle_UpdateWK");
- m_pEntity->UpdateWK();
- }
- void CAccessAuthSession::Handle_InitializeNew(SpReqAnsContext<AccessAuthService_InitializeNew_Req, AccessAuthService_InitializeNew_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- DbgWithLink(LOG_LEVEL_INFO, ctx->link.checkEmpty() ? LOG_TYPE_SYSTEM : LOG_TYPE_USER).setAPI(__FUNCTION__)("Handle_InitializeNew");
- m_pEntity->m_ctx = ctx;
- m_pEntity->m_strUserID = ctx->Req.strUserID.GetData();
- m_pEntity->m_strPassword = ctx->Req.strPassword.GetData();
- m_pEntity->BeginInitMKACS();
- }
- void CAccessAuthSession::Handle_InitDev(SpReqAnsContext<AccessAuthService_InitDev_Req, AccessAuthService_InitDev_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setAPI(__FUNCTION__)("call Handle_InitDev");
- m_pEntity->InitDevice(ctx);
- }
- void CAccessAuthSession::Handle_GetNetMsg(SpReqAnsContext<AccessAuthService_GetNetMsg_Req, AccessAuthService_GetNetMsg_Ans>::Pointer ctx)
- {
- DbgToBeidou(ctx->link, __FUNCTION__)();
- m_pEntity->GetNetMsg(ctx);
- }
- void CAccessAuthEntity::OnStarted()
- {
- //设置时区为北京标准时区
- if (!SetLocalTimeZoneByKeyName("China Standard Time", FALSE))
- {
-
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_SETTIMEZONE,GetOutPutStr("%s%s","设置时区错误","False").c_str());
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5202")(GetOutPutStr("%s%s", "设置时区错误", "False").c_str());
- }
- m_FSM.Init(this);
- CSimpleStringA strErrMsg;
- CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
- memset(&m_info,0, sizeof(CSystemStaticInfo));
- auto rc = GetFunction()->GetSystemStaticInfo(m_info);
- if (rc != Error_Succeed)
- {
- strErrMsg = "GetSystemStaticInfo fail";
- SetAuthErrMsg((const char*)strErrMsg);
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_GET_SYSTEM_STATIC_INFO,
- GetOutPutStr("%s%08X", "获取系统静态信息错误", rc).c_str(), strErrMsg.GetData());
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)(GetOutPutStr("%s%08X", "获取系统静态信息错误", rc).c_str());
- }
- #ifdef RVC_OS_WIN
- spFunction->RegistSysVarEvent("NetState", this);
- CSmartPointer<GetTermSysInfoTask> getTermSysInfoTask = new GetTermSysInfoTask(this);
- GetFunction()->PostThreadPoolTask(getTermSysInfoTask.GetRawPointer());
- #endif // RVC_OS_WIN
- }
- void CAccessAuthEntity::OnPreStart(CAutoArray<CSimpleStringA> strArgs,CSmartPointer<ITransactionContext> pTransactionContext)
- {
- ErrorCodeEnum Error = Error_Succeed;
- pTransactionContext->SendAnswer(Error) ;
- }
- void CAccessAuthEntity::OnPreClose(EntityCloseCauseEnum eCloseCause,CSmartPointer<ITransactionContext> pTransactionContext)
- {
- #ifdef RVC_OS_WIN
- GetFunction()->UnregistSysVarEvent("NetState");
- #endif // RVC_OS_WIN
- m_FSM.PostExitEvent();
- pTransactionContext->SendAnswer(Error_Succeed);
- }
- void CAccessAuthEntity::OnSysVarEvent(const char *pszKey, const char *pszValue,const char *pszOldValue,const char *pszEntityName)
- {
- }
- // 开始准入
- ErrorCodeEnum CAccessAuthEntity::Regist()
- {
- m_FSM.PostEventFIFO(new FSMEvent(CAccessAuthFSM::Event_StartRegist));
- return Error_Succeed;
- }
- string CAccessAuthEntity::ByteArrayToHexStr(BYTE *pBuf, int nBufLen)
- {
- char szBuf[1024];
- memset(szBuf, 0, sizeof(szBuf));
- for(int i=0; i<nBufLen; i++)
- {
- BYTE b1 = (pBuf[i] >> 4) & 0x0F;
- BYTE b2 = pBuf[i] & 0x0F;
-
- if (b1 <= 9)
- szBuf[i*2] = '0' + b1;
- else
- szBuf[i*2] = 'A' + b1 - 10;
- if (b2 <= 9)
- szBuf[i*2+1] = '0' + b2;
- else
- szBuf[i*2+1] = 'A' + b2 - 10;
- }
- return szBuf;
- }
- // 生成临时SM2密钥对
- DWORD CAccessAuthEntity::CreateSM2KeyPair(CBlob &pubKey, CBlob &priKey)
- {
- int nPubKeyLen = 256;
- int nPriKeyLen = 256;
- pubKey.Alloc(nPubKeyLen);
- priKey.Alloc(nPriKeyLen);
-
- if (!::CreateSM2KeyPair((BYTE*)(pubKey.m_pData), &nPubKeyLen, (BYTE*)(priKey.m_pData), &nPriKeyLen))
- {
- SetAuthErrMsg("创建SM2密钥对失败");
- CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
-
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_CREATE_RSA_KEY_PAIR,
- GetOutPutStr("%s%s","CreateRsaKeyPair","False").c_str(), true, "创建SM2密钥对失败");
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("创建SM2密钥对失败");
- return ERR_ACCESSAUTH_CREATE_RSA_KEY_PAIR;
- }
- pubKey.Resize(nPubKeyLen);
- priKey.Resize(nPriKeyLen);
- return Error_Succeed;
- }
- // 保存到令牌管理实体中
- DWORD CAccessAuthEntity::SaveSM2KeyPair(const CBlob &pubKey, const CBlob &priKey)
- {
- LOG_FUNCTION();
- CSimpleStringA strErrMsg;
- CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
- TokenService_ClientBase *pTokenServiceClient = new TokenService_ClientBase(this);
- DWORD rc = pTokenServiceClient->Connect();
- if (rc != Error_Succeed)
- {
- strErrMsg = "连接令牌管理实体失败";
- SetAuthErrMsg((const char *)strErrMsg);
- rc = ERR_ACCESSAUTH_CONNECT_TOKEN_SERVICE;
- m_FSM.doWarnMsg(rc,
- "连接令牌管理实体失败", true);
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5206")
- (GetOutPutStr("%s%08X%s%s", "Connect", rc, "strErrMsg", strErrMsg).c_str());
- pTokenServiceClient->SafeDelete();
- }
- else
- {
- TokenService_SetKeyPair_Req req;
- req.pub_key = pubKey;
- req.pri_key = priKey;
- TokenService_SetKeyPair_Ans ans;
- rc = pTokenServiceClient->SetKeyPair(req, ans, 3000);
- pTokenServiceClient->GetFunction()->CloseSession();
- if (rc != Error_Succeed)
- {
- strErrMsg = "保存密钥对失败";
- SetAuthErrMsg((const char *)strErrMsg);
- rc = ERR_ACCESSAUTH_FROM_TOKEN_SERVICE_SET_KEYS;
- m_FSM.doWarnMsg(rc,
- "保存密钥对失败", true);
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5207")
- (GetOutPutStr("%s%08X%s%s", "SetKeyPair", rc, "strErrMsg", (const char*)strErrMsg).c_str());
- }
- }
-
- return rc;
- }
- ErrorCodeEnum CAccessAuthEntity::SaveTokenAndSharedSK(const CBlob &token, const CBlob &sharedSK)
- {
- LOG_FUNCTION();
- CSimpleStringA strErrMsg;
- CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
- TokenService_ClientBase *pTokenServiceClient = new TokenService_ClientBase(this);
- ErrorCodeEnum rc = pTokenServiceClient->Connect();
- if (rc != Error_Succeed)
- {
- strErrMsg = "连接令牌管理实体失败";
- SetAuthErrMsg((const char *)strErrMsg);
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_CONNECT_TOKEN_SERVICE,
- GetOutPutStr("%s%08X%s%s", "Connect", rc,"strErrMsg", (const char*)strErrMsg).c_str());
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)(GetOutPutStr("%s%08X%s%s", "Connect", rc, "strErrMsg", (const char*)strErrMsg).c_str());
- pTokenServiceClient->SafeDelete();
- }
- else
- {
- TokenService_SetToken_Req req = {};
- req.token = token;
- TokenService_SetToken_Ans ans;
- rc = pTokenServiceClient->SetToken(req, ans, 5000);
- if (rc == Error_Succeed)
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI("SetToken")
- ("save token succ, token: [%s]", ByteArrayToHexStr((BYTE*)token.m_pData, token.m_iLength).c_str());
- else
- {
- strErrMsg = "保存令牌失败";
- SetAuthErrMsg((const char *)strErrMsg);
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_FROM_TOKEN_SERVICE_SET_TOKEN,
- GetOutPutStr("%s%08X%s%s", "SetToken", rc,"strErrMsg", strErrMsg).c_str());
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)(GetOutPutStr("%s%08X%s%s", "SetToken", rc, "strErrMsg", strErrMsg).c_str());
- }
- TokenService_SetSharedSK_Req req2 = {};
- req2.ssk = sharedSK;
- TokenService_SetSharedSK_Ans ans2 = {};
- rc = pTokenServiceClient->SetSharedSK(req2, ans2, 5000);
- if (rc != Error_Succeed)
- {
- strErrMsg = "保存会话密钥失败";
- SetAuthErrMsg((const char *)strErrMsg);
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_FROM_TOKEN_SERVICE_SET_SHAREKEY,
- GetOutPutStr("%s%08X%s%s", "SetSharedSK", rc,"strErrMsg", (const char*)strErrMsg).c_str());
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)(GetOutPutStr("%s%08X%s%s", "SetSharedSK", rc, "strErrMsg", (const char*)strErrMsg).c_str());
- }
- pTokenServiceClient->GetFunction()->CloseSession();
- }
- return rc;
- }
- bool CAccessAuthEntity::HasPinPad()
- {
- CSimpleStringA strErrMsg;
- CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
- //oilyang@20210514
- if (!IsMachineTypeConfigurePinPad(m_info.strMachineType))
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("MachineType[%s], not exist pinpad", m_info.strMachineType);
- return false;
- }
- else if (stricmp(m_info.strMachineType, "RVC.PAD") == 0) // Pad机型
- {
- // 根据PinPad实体状态确定是否连接密码键盘
- bool bPinPadExist = false;
- auto pPinPadClient = new PinPadService_ClientBase(this);
- if (pPinPadClient->Connect() != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5204")("连接密码键盘异常");
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_CONNECT_PINPAD,
- GetOutPutStr("%s%s", "连接pinpad错误", "False").c_str());
- pPinPadClient->SafeDelete();
- }
- else
- {
- PinPadService_GetDevInfo_Req req = {};
- PinPadService_GetDevInfo_Ans ans = {};
- #ifdef RVC_OS_WIN
- auto rc = pPinPadClient->GetDevInfo(req, ans, 3000);
- #else
- auto rc = (*pPinPadClient)(EntityResource::getLink().upgradeLink())->GetDevInfo(req, ans, 3000);
- #endif // RVC_OS_WIN
- if (rc != Error_Succeed)
- {
- strErrMsg = "PinPad::GetDevInfo() fail";
- SetAuthErrMsg((const char *)strErrMsg);
-
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_FROM_PINPAD,
- GetOutPutStr("%s%08X%s", "来自pinpad的错误", rc, strErrMsg.GetData()).c_str());
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5205")
- (GetOutPutStr("%s%08X%s", "来自pinpad的错误", rc, strErrMsg.GetData()).c_str());
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("PinPad::GetDevInfo() return state: %d", ans.state);
- bPinPadExist = ans.state != DEVICE_STATUS_NOT_READY;
- }
- pPinPadClient->GetFunction()->CloseSession();
- }
- pPinPadClient = NULL;
- return bPinPadExist;
- }
- else
- {
- // 其它VTM机型,全部有内置密码键盘
- return true;
- }
- }
- // 1:3des only; 2: sm4 only; 3: both 3des and sm4
- // 由当前已初始化的密钥文件决定,兼容旧版本终端
- int CAccessAuthEntity::GetPinPadCapability()
- {
- LOG_FUNCTION();
- int nCapability = 0;
- if (!IsMachineTypeConfigurePinPad(m_info.strMachineType))
- return nCapability;
- PinPadService_ClientBase *pPinPad = new PinPadService_ClientBase(this);
- auto rc = pPinPad->Connect();
- if (rc == Error_Succeed)
- {
- PinPadService_QueryFunc_Req req;
- PinPadService_QueryFunc_Ans ans;
- rc = pPinPad->QueryFunc(req, ans, 3000);
- if (rc == Error_Succeed)
- {
- nCapability = ans.encryptkey;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("QueryFunc from pinpad succ, nCapability[%d]", nCapability);
- }
- else if (rc != Error_DevNotAvailable)
- {
- SetAuthErrMsg("从PinPad获取主密钥类型失败");
- CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_FROM_PINPAD,
- GetOutPutStr("%s%s%s%s", "QueryFunc", "False", "AuthErrMsg", "从PinPad获取主密钥类型失败").c_str());
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5205")
- (GetOutPutStr("%s%s%s%s", "QueryFunc", "False", "AuthErrMsg", "从PinPad获取主密钥类型失败").c_str());
- }
- pPinPad->GetFunction()->CloseSession();
- }
- else
- {
- SetAuthErrMsg("连接PinPad实体失败");
- CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
-
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_CONNECT_PINPAD,
- GetOutPutStr("%s%08X%s%s", "Connect", rc,"AuthErrMsg", "连接PinPad实体失败").c_str());
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)(GetOutPutStr("%s%08X%s%s", "Connect", rc, "AuthErrMsg", "连接PinPad实体失败").c_str());
- pPinPad->SafeDelete();
- }
- return nCapability;
- }
- void CAccessAuthEntity::printPasswdError(const string& strErrMsg){
- //string strErrMsg = "密钥集丢失,请重新初始化密钥!";
- SetAuthErrMsg(strErrMsg.c_str());
- GetFunction()->SetSysVar("AuthErrMsg", strErrMsg.c_str(), true);
- m_FSM.doWarnMsg( ERROR_ACCESSAUTH_OPENCRYPTCONTEXT, strErrMsg.c_str(),true, strErrMsg);
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA520C")("密钥集丢失(私钥为空)");
- }
- int Char2Int(char * ch) {
- int num = 0;
- for (int i = 0;i < strlen(ch);i++) {
- num += ((int)(ch[i] - '0')) * pow((float)10, (float)(strlen(ch) - i - 1));
- }
- return num;
- }
- bool CAccessAuthEntity::SaveAuthKey(BYTE *pKey)
- {
- memset(m_AuthSessionKey, 0, 140);
- CSimpleStringA runInfoPath, iniPath;
- auto rc = GetFunction()->GetPath("runinfo", runInfoPath);
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("GetPath runinfo error=%d.", rc);
- return false;
- }
- char privateKey[BUF_SIZE] = { 0 };
- #ifdef RVC_OS_WIN
- iniPath = runInfoPath + "\\runcfg\\AccessAuthorization.ini";
- GetPrivateProfileString("TerminalPD", "PrivateKey", "", privateKey, BUF_SIZE, iniPath.GetData());
- #else
- iniPath = runInfoPath + SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR "AccessAuthorization.ini";
- char* tmp = inifile_read_str(iniPath.GetData(), "TerminalPD", "PrivateKey", "");
- strcpy(privateKey, tmp);
- delete tmp;
- #endif // RVC_OS_WIN
- if (strlen(privateKey) <= 0) {
- #ifdef RVC_OS_WIN
- iniPath = runInfoPath + "\\runcfg\\Initializer.ini";
- GetPrivateProfileString("TerminalPD", "PrivateKey", "", privateKey, BUF_SIZE, iniPath.GetData());
- #else
- iniPath = runInfoPath + SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR "Initializer.ini";
- char* tmp2 = inifile_read_str(iniPath.GetData(), "TerminalPD", "PrivateKey", "");
- strcpy(privateKey, tmp2);
- delete tmp2;
- #endif // RVC_OS_WIN
- if (strlen(privateKey) <= 0)
- {
- printPasswdError("密钥集丢失(私钥为空),请重置秘钥进行初始化");
- return false;
- }
- }
- int decodedPrivateKeyLen;
- #ifdef RVC_OS_WIN
- char* pDecodedPrivateKey = MyBase64::Hex2Str(privateKey, decodedPrivateKeyLen);
- #else
- char* pDecodedPrivateKey = Hex2Str(privateKey, decodedPrivateKeyLen);
- #endif // RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("privateKey len:%d, decodedPrivateKeyLen=%d", strlen(privateKey), decodedPrivateKeyLen);
- char pDecryptPrivateKey[BUF_SIZE] = { 0 };
- int decryprtLen = BUF_SIZE;
- if (!DecWithSM4_ECB("s5da69gnh4!963@6s5da69gnh4!963@6", (BYTE*)pDecodedPrivateKey, decodedPrivateKeyLen, (BYTE*)pDecryptPrivateKey, &decryprtLen)) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("DecWithSM4_ECB decrypt privateKey error. SM4解密私钥失败");
- printPasswdError("终端初始化未完成,请重置秘钥进行初始化");
- delete[] pDecodedPrivateKey;
- return false;
- }
- delete[] pDecodedPrivateKey;
- char pPlainKey[KEY_SIZE];
- int plainKeyLen = KEY_SIZE;
- char pKeyLen[4] = { 0 };
- memcpy(pKeyLen, pKey, 4);
- int kenLen = Char2Int(pKeyLen);
- #ifdef RVC_OS_WIN
- char* pEncodeKey = MyBase64::Str2Hex((char*)pKey,kenLen + 4);
- #else
- char* pEncodeKey = Str2Hex((char*)pKey, kenLen + 4);
- #endif
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("kenLen=%d", kenLen);
- delete pEncodeKey;
- char* key = new char[kenLen + 1];
- memset(key, 0, kenLen + 1);
- memcpy(key, pKey + 4, kenLen);
- if (!DecWithSM2PriKey((BYTE*)key, kenLen, (BYTE*)pPlainKey, &plainKeyLen, (BYTE*)pDecryptPrivateKey, decryprtLen)) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("使用私钥解密失败!");
- printPasswdError("终端初始化未完成,请重置秘钥进行初始化");
- return false;
- }
- if (plainKeyLen != KEY_SIZE) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI("SaveAuthVerAndKey")("私钥解密后的会话密钥长度不等于16!");
- }
- memcpy(m_AuthSessionKey, pPlainKey, KEY_SIZE);
- return true;
- }
- static BYTE* ConvertHexStrToBytes(const char *pszStr)
- {
- if (pszStr == NULL || strlen(pszStr) == 0)
- return NULL;
- int nLen = strlen(pszStr) / 2;
- BYTE *pRet = (BYTE*)malloc(nLen);
- memset(pRet, 0, nLen);
- for (int i = 0; i < nLen; i++)
- {
- int nTmp(0);
- if (sscanf(&pszStr[i * 2], "%2X", &nTmp) != 1)
- {
- free(pRet);
- return NULL;
- }
- pRet[i] = (BYTE)nTmp;
- }
- return pRet;
- }
- // 使用准入会话密钥加密
- ErrorCodeEnum CAccessAuthEntity::EncryptDataWithSessionKey(const CBlob &raw, CBlob &enc)
- {
- LOG_FUNCTION();
- //这里不需要delete,由CBlob析构函数去执行
- BYTE* pEncData = new BYTE[1024];
- int pEncDataSize = 1024;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("pEncDataSize=%d", pEncDataSize);
- #ifdef RVC_OS_WIN
- char* pPlainInfo = MyBase64::Str2Hex((char*)raw.m_pData, raw.m_iLength);
- #else
- char* pPlainInfo = Str2Hex((char*)raw.m_pData, raw.m_iLength);
- #endif
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("raw Length=%d", raw.m_iLength);
- delete[] pPlainInfo;
-
- char sessionKey[KEY_SIZE] = { 0 };
- memcpy(sessionKey,m_AuthSessionKey,KEY_SIZE);
- #ifdef RVC_OS_WIN
- char* tmpKey = MyBase64::Str2Hex((char*)m_AuthSessionKey, KEY_SIZE);
- #else
- char* tmpKey = Str2Hex((char*)m_AuthSessionKey, KEY_SIZE);
- #endif // RVC_OS_WIN
- delete[] tmpKey;
- if (!EncWithSM4_ECB((BYTE*)sessionKey, (BYTE*)(raw.m_pData), raw.m_iLength, pEncData, &pEncDataSize)) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("会话密钥加密准入信息失败!");
- return Error_Unexpect;
- }
-
- enc.Attach(pEncData,pEncDataSize);
- #ifdef RVC_OS_WIN
- char* tmp = MyBase64::Str2Hex((char*)pEncData, pEncDataSize);
- #else
- char* tmp = Str2Hex((char*)pEncData, pEncDataSize);
- #endif // RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("pEncData size:%d", pEncDataSize);
- delete[] tmp;
- #ifdef RVC_OS_WIN
- tmp = MyBase64::Str2Hex((char*)enc.m_pData, enc.m_iLength);
- #else
- tmp = Str2Hex((char*)enc.m_pData, enc.m_iLength);
- #endif // RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("EncWithSM4_ECB data size:%d", enc.m_iLength);
- delete[] tmp;
- return Error_Succeed;
- }
- static char* ConvertBytesToHexStr(BYTE *pBuf, int nLen)
- {
- char *pRet = (char*)malloc(nLen * 2 + 1);
- memset(pRet, 0, nLen * 2 + 1);
- char *p = pRet;
- for (int i = 0; i < nLen; i++)
- {
- BYTE b = pBuf[i];
- BYTE l = (b >> 4) & 0x0F;
- if (l >= 10)
- *p = l - 10 + 'A';
- else
- *p = l + '0';
- p++;
- BYTE r = b & 0x0F;
- if (r >= 10)
- *p = r - 10 + 'A';
- else
- *p = r + '0';
- p++;
- }
- return pRet;
- }
- bool CAccessAuthEntity::GetTerminalFingerPrint(BYTE *pBuf, int &nBufLen)
- {
- #ifdef RVC_OS_LINUX
- char szTmp[1024] = {};
- string strTmp;
- int nTmpBufLen = 1024;
- CSimpleStringA strErrMsg;
- CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
- CSimpleStringA strRet;
- CSimpleStringA runInfoPath;
- auto rc = GetFunction()->GetPath("runinfo", runInfoPath);
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("GetPath runinfo error=%d.", rc);
- return false;
- }
- runInfoPath += SPLIT_SLASH_STR "runcfg";
- if (!get_cpu_id_by_system(strTmp, runInfoPath.GetData()))
- {
- strErrMsg = CSimpleStringA::Format("查询CPU ID失败,请重启机器并重新初始化");
- SetAuthErrMsg((const char*)strErrMsg);
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_GET_TERMINAL_FINGERPRINT,
- GetOutPutStr("%s%s", "Processor", "False").c_str());
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5203")
- (GetOutPutStr("%s%s", "Processor", "False").c_str());
- return false;
- }
- strRet = strTmp.c_str();
- strTmp.clear();
- if (!get_board_serial_by_system(strTmp, runInfoPath.GetData()))
- {
- strErrMsg = CSimpleStringA::Format("查询主板序列号失败, 请重启机器并重新初始化");
- SetAuthErrMsg((const char*)strErrMsg);
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_GET_TERMINAL_FINGERPRINT,
- GetOutPutStr("%s%s", "BaseBoard", "False").c_str());
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5203")
- (GetOutPutStr("%s%s", "BaseBoard", "False").c_str());
- return false;
- }
- strRet += "|";
- strRet += strTmp.c_str();
- vector<string> disk;
- int errCode = 0;
- if (!get_disk_serial_by_system(disk, errCode, runInfoPath.GetData()))
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("get_disk_serial_by_system errCode:%d", errCode);
- strErrMsg = CSimpleStringA::Format("查询磁盘序列号失败, 请重启机器并重新初始化");
- SetAuthErrMsg((const char*)strErrMsg);
- m_FSM.doWarnMsg(ERR_INITIALIZER_GET_DISKDRIVE_ID,
- GetOutPutStr("%s%s", "DiskDrive", "False").c_str());
- return false;
- }
- strRet += "|";
- strTmp = "";
- vector<string>::iterator it = disk.begin();
- while (it != disk.end()) {
- strTmp += *it;
- it++;
- }
- strRet += strTmp.c_str();
- BYTE m_btTermSysInfoSM3[32] = { 0 };
- if (!SM3Hash(reinterpret_cast<BYTE*>(const_cast<char*>(strRet.GetData())), strRet.GetLength(), m_btTermSysInfoSM3))
- {
- strErrMsg = "get sm3 hash as fingerprint fail";
- SetAuthErrMsg((const char*)strErrMsg);
- spFunction->SetSysVar("AuthErrMsg", (const char*)strErrMsg, true);
- m_FSM.doWarnMsg(ERROR_ACCESSAUTH_GETSM3HASH, (const char*)strErrMsg);
- return false;
- }
- #endif // RVC_OS_LINUX
- if (nBufLen < 32)
- {
- m_FSM.doWarnMsg(ERROR_ACCESSAUTH_GETSM3HASH, "buf len is too small fail");
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("buf len is too small fail");
- return false;
- }
- #ifdef RVC_OS_WIN
- while (1)
- {
- if (m_iGetTermSysInfo == -1)
- return false;
- else if (m_iGetTermSysInfo == 1)
- break;
- else if (m_iGetTermSysInfo == 0)
- Sleep(1000);//oiltmp@20220917 之前的逻辑是不跳出去,现在要加么?暂时不加,连调用系统接口都有问题,让其他逻辑处理
- }
- #endif // RVC_OS_WIN
- nBufLen = 32;
- memcpy(pBuf, m_btTermSysInfoSM3, nBufLen);
- char *pszSM3 = ConvertBytesToHexStr(m_btTermSysInfoSM3, nBufLen);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("fringerprint: [%s]", pszSM3);
- free(pszSM3);
- return true;
- }
- #ifdef RVC_OS_WIN
- #define RSAPUBKEY_BITLEN 1024
- struct PublicKeyBlob
- {
- PUBLICKEYSTRUC publickeystruc;
- RSAPUBKEY rsapubkey;
- BYTE modulus[RSAPUBKEY_BITLEN / 8];
- };
- #endif // RVC_OS_WIN
- // 生成SM2密钥对,并导出公钥
- bool CAccessAuthEntity::GetTerminalPublicKey(BYTE* pBuf, int& nBufLen)
- {
- CSimpleStringA runInfoPath, iniPath;
- auto rc = GetFunction()->GetPath("runinfo", runInfoPath);
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")
- ("GetPath runinfo error=%d.", rc);
- return false;
- }
- char publicKey[BUF_SIZE] = { 0 };
- #ifdef RVC_OS_WIN
- iniPath = runInfoPath + "\\runcfg\\AccessAuthorization.ini";
- GetPrivateProfileString("TerminalPD", "PublicKey", "", publicKey, BUF_SIZE, iniPath.GetData());
- #else
- iniPath = runInfoPath + SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR "AccessAuthorization.ini";
- char* tmp = inifile_read_str(iniPath.GetData(), "TerminalPD", "PublicKey", "");
- strcpy(publicKey, tmp);
- delete tmp;
- #endif // RVC_OS_WIN
- if (strlen(publicKey) <= 0) {
- #ifdef RVC_OS_WIN
- iniPath = runInfoPath + "\\runcfg\\Initializer.ini";
- GetPrivateProfileString("TerminalPD", "PublicKey", "", publicKey, BUF_SIZE, iniPath.GetData());
- #else
- iniPath = runInfoPath + SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR "Initializer.ini";
- char* tmp2 = inifile_read_str(iniPath.GetData(), "TerminalPD", "PublicKey", "");
- strcpy(publicKey, tmp2);
- delete tmp2;
- #endif // RVC_OS_WIN
- if (strlen(publicKey) <= 0)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("读取公钥失败,公钥长度小于等于零!");
- if (!ExistsFileA(iniPath))
- printPasswdError("密钥集丢失(公钥为空),请重置秘钥进行初始化");
- return false;
- }
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("publickey=%s,%d", publicKey, strlen(publicKey));
- #ifdef RVC_OS_WIN
- char* pDecodedPublickey = MyBase64::Hex2Str(publicKey, nBufLen);
- #else
- char* pDecodedPublickey = Hex2Str(publicKey, nBufLen);
- #endif // RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("pDecodedPublickey len=%d", nBufLen);
- memcpy(pBuf, pDecodedPublickey, nBufLen);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("pBuf[0]=%02X,nBufLen=%d", pBuf[0], nBufLen);
- delete[] pDecodedPublickey;
- return true;
- }
- // 生成RSA密钥对,并导出公钥
- bool CAccessAuthEntity::GetTerminalPublicKey(BYTE* pBuf, int& nBufLen, string& pubkey)
- {
- LOG_FUNCTION();
- CSimpleString runInfoPath;
- auto rc = GetFunction()->GetPath("runinfo", runInfoPath);
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("GetPath runinfo error=%d.", rc);
- return false;
- }
- #ifdef RVC_OS_WIN
- runInfoPath += "\\runcfg\\";
- DWORD dwAttr = GetFileAttributes(runInfoPath.GetData());
- if (dwAttr == 0xFFFFFFFF) //目录不存在则创建
- {
- if (!CreateDirectory(runInfoPath.GetData(), NULL))
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("Create %s dir failed!", runInfoPath.GetData());
- }
- }
- #else
- runInfoPath += SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR;
- if (!dir_is_exist(runInfoPath.GetData()))
- {
- if (dir_create(runInfoPath.GetData()) != 0)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("Create %s dir failed!", runInfoPath.GetData());
- }
- }
- #endif // RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("Dir=%s", runInfoPath.GetData());
- CSmartPointer<IConfigInfo> pConfig;
- rc = GetFunction()->OpenConfig(Config_Run, pConfig);
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("OpenConfig Config_Run error=%d.", rc);
- return false;
- }
- CSimpleString publicKey;
- rc = pConfig->ReadConfigValue("TerminalPD", "PublicKey", publicKey);
- if (rc != Error_Succeed || publicKey.IsNullOrEmpty()) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("ReadConfig publicKey error=%d or publicKey is NULL.", rc);
- }
- BYTE btPublicKey[BUF_SIZE] = { 0 }, btPrivateKey[BUF_SIZE] = { 0 };
- int iPublicKeyLen = sizeof(btPublicKey);
- int iPrivateKeyLen = sizeof(btPrivateKey);
- if (!::CreateSM2KeyPair(btPublicKey, &iPublicKeyLen, btPrivateKey, &iPrivateKeyLen)) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("Create SM2 key pair error.");
- return false;
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("iPublicKeyLen=%d,iPrivateKeyLen=%d", iPublicKeyLen, iPrivateKeyLen);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("[btPublicKey=%s]", (char*)btPublicKey);
- #ifdef RVC_OS_WIN
- char* pEncode = MyBase64::Str2Hex((char*)btPublicKey, iPublicKeyLen);
- #else
- char* pEncode = Str2Hex((char*)btPublicKey, iPublicKeyLen);
- #endif // RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("pEncode=%s,%d", pEncode, strlen(pEncode));
- /*rc = pConfig->WriteConfigValue("TerminalPD", "PublicKey", pEncode);
- assert(rc == Error_Succeed);*/
- m_publicKey = pEncode;
- pubkey = pEncode;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("write public key success.");
- BYTE pCryptPrivateKey[BUF_SIZE] = { 0 };
- int cryptPrivateKeyLen = BUF_SIZE;
- if (!EncWithSM4_ECB("s5da69gnh4!963@6s5da69gnh4!963@6", btPrivateKey, iPrivateKeyLen, pCryptPrivateKey, &cryptPrivateKeyLen)) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("sm4 crypt privateKey error.");
- /*rc = pConfig->WriteConfigValue("TerminalPD", "PublicKey", "");*/
- m_publicKey = "";
- delete[] pEncode;
- return false;
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("sm4 encrypt pri key success.");
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("cryptPrivateKeyLen=%d", cryptPrivateKeyLen);
- #ifdef RVC_OS_WIN
- char* pEncodedCryptPrivateKey = MyBase64::Str2Hex((char*)pCryptPrivateKey, cryptPrivateKeyLen);
- #else
- char* pEncodedCryptPrivateKey = Str2Hex((char*)pCryptPrivateKey, cryptPrivateKeyLen);
- #endif // RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("encode pri key success.");
- m_privateKey = pEncodedCryptPrivateKey;
- /*rc = pConfig->WriteConfigValue("TerminalPD", "PrivateKey", pEncodedCryptPrivateKey);
- if (rc != Error_Succeed) {
- rc = pConfig->WriteConfigValue("TerminalPD", "PublicKey", "");
- delete[] pEncodedCryptPrivateKey;
- return false;
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("write pri key success.");*/
- publicKey = pEncode;
- delete[] pEncode;
- delete[] pEncodedCryptPrivateKey;
- #ifdef RVC_OS_WIN
- char* pDecode = MyBase64::Hex2Str(publicKey.GetData(), nBufLen);
- #else
- char* pDecode = Hex2Str(publicKey.GetData(), nBufLen);
- #endif // RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("pDecode=[%s],len=%d", pDecode, nBufLen);
- memcpy(pBuf, pDecode, nBufLen);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetTerminalPublicKey")("pBuf[0]=%02X,nBufLen=%d", pBuf[0], nBufLen);
- return true;
- }
- //oilyang@20210510 嵌入"bool CAccessAuthEntity::HasPinPad()"的逻辑
- // 返回1:只有PinPadID;2:只有DeviceID;3:两者都有;0:没有;-1表示失败
- int CAccessAuthEntity::GetPinPadIDAndDeviceID(CSimpleStringA &strPinPadID, CSimpleStringA &strDeviceID, bool& bHasPinPad)
- {
- bHasPinPad = false;
- m_bNewSMFWB = false;
- CSimpleStringA strErrMsg;
- CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
- //oilyang@20210514
- if (!IsMachineTypeConfigurePinPad(m_info.strMachineType))
- return 0;
- int nRet = -1;
- auto pPinPadClient = new PinPadService_ClientBase(this);
- bool bPinPadID = false;
- bool bDeviceID = false;
- bool bVendor = false;
- bool bBluetooth = false;
- CSimpleStringA strVendor;
- CSimpleStringA strBluetoothID;
- CSimpleStringA strPID;
- CSimpleStringA strMID;
- bHasPinPad = true;
- auto rc = 0;
- if ((rc = pPinPadClient->Connect()) == Error_Succeed)
- {
- PinPadService_GetDevInfo_Req req = {};
- PinPadService_GetDevInfo_Ans ans = {};
- rc = pPinPadClient->GetDevInfo(req, ans, 3000);
- if (rc == Error_Succeed)
- {
- if (ans.state == DEVICE_STATUS_NORMAL)
- {
- nRet = 0;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("pinpad model: %s", (const char*)ans.model);
- // CM = V2.0#PM = V1.0#MID = 75500001#PID = 12345678#FWID = V1234567#Vendor = nantian
- // 密码键盘ID,PID,8到16字节; 设备ID,MID,8到16字节; 固件版本号,FWID,8字节
- CSimpleStringA str = ans.model;
- if (!str.IsNullOrEmpty())
- {
- auto arr = str.Split('#');
- if (arr.GetCount() > 0)
- {
- for (int i = 0; i < arr.GetCount(); i++)
- {
- auto arr2 = arr[i].Split('=');
- if (arr2.GetCount() != 2)
- continue;
- //if (arr2[0] == "PID")
- if (!strnicmp((LPCTSTR)arr2[0], "PID", strlen("PID")))
- {
- strPID = arr2[1];
- if (!strPID.IsNullOrEmpty())
- bPinPadID = true;
- }
- //else if (arr2[0] == "MID")
- else if (!strnicmp((LPCTSTR)arr2[0], "MID", strlen("MID")))
- {
- strMID = arr2[1];
- if (!strMID.IsNullOrEmpty())
- bDeviceID = true;
- }
- //else if (arr2[0] == "Vendor")
- else if (!strnicmp((LPCTSTR)arr2[0], "Vendor", strlen("Vendor")))
- {
- strVendor = arr2[1];
- if (!strVendor.IsNullOrEmpty())
- bVendor = true;
- }
- else if (!strnicmp((LPCTSTR)arr2[0], "FWBID", strlen("FWBID")))
- {
- strBluetoothID = arr2[1];
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("strBluetoothID=%s", strBluetoothID);
- if (!strBluetoothID.IsNullOrEmpty())
- bBluetooth = true;
- }
- #ifdef RVC_OS_WIN
- else if (!strnicmp((LPCTSTR)arr2[0], "PM", strlen("PM")))
- {
- CSimpleStringA strPM = arr2[1];
- if (!strPM.IsNullOrEmpty() && strPM.Compare("V3.0", true) == 0)
- m_bNewSMFWB = true;
- }
- #endif // RVC_OS_WIN
- }
- }
- }
- }
- else
- {
- if (m_info.strMachineType.IsStartWith("RVC.PAD", true))
- bHasPinPad = false;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("pinpad not exist, state: %d", ans.state);
- return nRet; //此时nRet = -1, pinpad调用失败
- }
- }
- else
- {
- if (m_info.strMachineType.IsStartWith("RVC.PAD", true))
- bHasPinPad = false;
- strErrMsg = "调用PinPad实体的GetDevInfo方法失败";
- SetAuthErrMsg((const char*)strErrMsg);
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_FROM_PINPAD,
- GetOutPutStr("%s%08X%s%s", "GetDevInfo", rc, "strErrMsg", (const char*)strErrMsg).c_str());
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5205")
- (GetOutPutStr("%s%08X%s%s", "GetDevInfo", rc, "strErrMsg", (const char*)strErrMsg).c_str());
-
- return nRet; //此时nRet = -1, pinpad调用失败
- }
- pPinPadClient->GetFunction()->CloseSession();
- }
- else
- {
- if (m_info.strMachineType.IsStartWith("RVC.PAD", true))
- bHasPinPad = false;
- strErrMsg = "连接PinPad实体失败";
- SetAuthErrMsg((const char*)strErrMsg);
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_CONNECT_PINPAD,
- GetOutPutStr("%s%08X%s%s", "Connect", rc, "strErrMsg", "连接PinPad实体失败").c_str());
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5204")("连接密码键盘异常");
- pPinPadClient->SafeDelete();
- return nRet; //此时nRet = -1, pinpad调用失败
- }
- pPinPadClient = NULL;
- if (bPinPadID)
- {
- if (bVendor)
- strPinPadID = strVendor + "_" + strPID;
- else
- strPinPadID = strPID;
- nRet += 1;
- }
- if (bDeviceID)
- {
- if (bVendor)
- strDeviceID = strVendor + "_" + strMID;
- else
- strDeviceID = strMID;
- if (bBluetooth)
- strDeviceID = strDeviceID + "_" + strBluetoothID;
- nRet += 2;
- }
- else if (bBluetooth)
- {
- strDeviceID = strDeviceID + "_" + strBluetoothID;
- nRet += 2;
- }
- return nRet;
- }
- wstring CAccessAuthEntity::ANSIToUnicode(const string& str)
- {
- int len = 0;
- len = str.length();
- int unicodeLen = ::MultiByteToWideChar(CP_ACP,
- 0,
- str.c_str(),
- -1,
- NULL,
- 0);
- wchar_t * pUnicode;
- pUnicode = new wchar_t[unicodeLen+1];
- memset(pUnicode,0,(unicodeLen+1)*sizeof(wchar_t));
- ::MultiByteToWideChar( CP_ACP,
- 0,
- str.c_str(),
- -1,
- (LPWSTR)pUnicode,
- unicodeLen);
- wstring rt;
- rt = (wchar_t*)pUnicode;
- delete pUnicode;
- return rt;
- }
- //China Standard Time
- BOOL CAccessAuthEntity::SetLocalTimeZoneByKeyName(const TCHAR* szTimeZoneKeyName, BOOL isDaylightSavingTime)
- {
- #ifdef RVC_OS_WIN
- HKEY hKey;
- LONG ErrorCode;
- TCHAR szSubKey[256];
- TCHAR szStandardName[32];
- TCHAR szDaylightName[32];
- REG_TZI_FORMAT regTZI;
- DWORD dwByteLen;
- // 检测入口参数
- if ((szTimeZoneKeyName == NULL) || (strlen(szTimeZoneKeyName) == 0))
- {
- // 时区标识符不能为空
- return FALSE;
- }
- StringCchCopy(szSubKey, 256, TEXT("Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\"));
- StringCchCat(szSubKey, 256, szTimeZoneKeyName);
- ErrorCode = RegOpenKeyEx(HKEY_LOCAL_MACHINE, szSubKey, 0, KEY_QUERY_VALUE, &hKey);
- if (ErrorCode != ERROR_SUCCESS)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("RegOpenKeyEx Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\China Standard Time fail");
- return FALSE;
- }
- // 标准名
- dwByteLen = sizeof(szStandardName);
- ErrorCode = RegQueryValueEx(hKey, TEXT("Std"), NULL, NULL, reinterpret_cast<LPBYTE>(&szStandardName), &dwByteLen);
- if (ErrorCode != ERROR_SUCCESS)
- {
- RegCloseKey(hKey);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("RegQueryValueEx Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\China Standard Time\\Std fail");
- return FALSE;
- }
- // 夏时制名
- dwByteLen = sizeof(szDaylightName);
- ErrorCode = RegQueryValueEx(hKey, TEXT("Dlt"), NULL, NULL, reinterpret_cast<LPBYTE>(&szDaylightName), &dwByteLen);
- if (ErrorCode != ERROR_SUCCESS)
- {
- RegCloseKey(hKey);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("RegQueryValueEx Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\China Standard Time\\Dlt fail");
- return FALSE;
- }
- // 时区信息
- dwByteLen = sizeof(regTZI);
- ErrorCode = RegQueryValueEx(hKey, TEXT("TZI"), NULL, NULL, reinterpret_cast<LPBYTE>(®TZI), &dwByteLen);
- RegCloseKey(hKey);
- if ((ErrorCode != ERROR_SUCCESS) || (dwByteLen > sizeof(regTZI)))
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("RegQueryValueEx Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\China Standard Time\\TZI fail");
- return FALSE;
- }
- // 开启权限
- HANDLE hToken;
- TOKEN_PRIVILEGES tkp;
- BOOL isOK;
- if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("OpenProcessToken Standard Time\\Dlt fail");
- return FALSE;
- }
- LookupPrivilegeValue(NULL, SE_TIME_ZONE_NAME, &tkp.Privileges[0].Luid);
- tkp.PrivilegeCount = 1;
- tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
- AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
- if (GetLastError() != ERROR_SUCCESS)
- {
- CloseHandle(hToken);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("AdjustTokenPrivileges fail");
- return FALSE;
- }
- // 设置新时区
- DYNAMIC_TIME_ZONE_INFORMATION tzi;
- tzi.Bias = regTZI.Bias;
- tzi.StandardDate = regTZI.StandardDate;
- tzi.StandardBias = regTZI.StandardBias;
- tzi.DaylightDate = regTZI.DaylightDate;
- tzi.DaylightBias = regTZI.DaylightBias;
- tzi.DynamicDaylightTimeDisabled = !isDaylightSavingTime;
- wcscpy(tzi.StandardName, ANSIToUnicode(szStandardName).c_str());
- wcscpy(tzi.DaylightName, ANSIToUnicode(szDaylightName).c_str());
- wcscpy(tzi.TimeZoneKeyName, ANSIToUnicode(szTimeZoneKeyName).c_str());
- isOK = SetDynamicTimeZoneInformation(&tzi); // 设置动态时区
- if (!isOK)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("SetDynamicTimeZoneInformation fail");
- }
- // 关闭权限
- tkp.Privileges[0].Attributes = 0;
- AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
- CloseHandle(hToken);
- return isOK;
- #else
- //temporarily not relased at linux
- return TRUE;
- #endif // RVC_OS_WIN
- }
- bool CAccessAuthEntity::IsMachineTypeConfigurePinPad(CSimpleStringA strMachineType)
- {
- // PAD单独判定
- if (strMachineType.Compare("RVC.PAD", true) == 0)
- {
- #ifdef RVC_OS_WIN
- //oilyang@20220413 except RVC.PAD without FWB
- CSimpleStringA tmpFWBDevSN("");
- GetFunction()->GetSysVar("FWBDevSN", tmpFWBDevSN);
- if (tmpFWBDevSN.IsNullOrEmpty())
- {
- return false;
- }
- else
- {
- return true;
- }
- #endif // RVC_OS_WIN
- }
- else
- {
- CSmartPointer<IConfigInfo> spConfig;
- ErrorCodeEnum Error = GetFunction()->OpenConfig(Config_CenterSetting, spConfig);
- CSimpleStringA mcType = CSimpleStringA("CoreBootList.") + strMachineType;
- CSimpleStringA loaderConifg("");
- ErrorCodeEnum errCode = spConfig->ReadConfigValue("VtmLoader", mcType.GetData(), loaderConifg);
- if (errCode != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Get VtmLoader config failed!");
- }
- if (string(loaderConifg.GetData()).find("PinPad") != string::npos) //集中配置配了启动pinpad实体
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- }
- void CAccessAuthEntity::UpdateWK()
- {
- m_FSM.UpdateWK();
- }
- void CAccessAuthEntity::BeginInitMKACS()
- {
- LOG_FUNCTION();
- // 1:3des only; 2: sm4 only; 3: both 3des and sm4
- int nCapability = GetPinPadCapability();
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("pinpad capability: %d", nCapability);
- CSmartPointer<IConfigInfo> spConfig;
- ErrorCodeEnum Error = GetFunction()->OpenConfig(Config_CenterSetting, spConfig);
- if (Error_Succeed == Error)
- {
- Error = spConfig->ReadConfigValue("AccessAuthorization", "HostInitUrl", m_strInitUrl);
- if (Error_Succeed != Error)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("get InitUrl from CenterSetting failed");
- return;
- }
- } else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("open InitUrl from CenterSetting.ini failed");
- return;
- }
- CSmartPointer<InitializerInitMKTask> initUpdateWKTask = new InitializerInitMKTask(&this->m_FSM, this);
- GetFunction()->PostThreadPoolTask(initUpdateWKTask.GetRawPointer());
- }
- bool CAccessAuthEntity::SendInitMKReqACS(CInitlizerMKReq& initMKReq)
- {
- LOG_FUNCTION();
- CSmartPointer<IEntityFunction> pFunc = GetFunction();
- #ifdef RVC_OS_LINUX
- if (HasPinPad())
- {
- CSmartPointer<IConfigInfo> pConfig;
- DWORD rc = pFunc->OpenConfig(Config_CenterSetting, pConfig);
- if (rc != Error_Succeed)
- {
- LogWarn(Severity_Middle, (ErrorCodeEnum)rc, ERR_INITIALIZER_READ_WRITE_FILE,
- GetOutPutStr("%s%08X%s%s", "OpenConfig", rc, "File", "Config_CenterSetting").c_str());
- rc = ERR_INITIALIZER_READ_WRITE_FILE;
- return rc;
- }
- CSimpleStringA strSubBankNo, strBranchNo;
- rc = pConfig->ReadConfigValue("Initializer", "SubBankNo", strSubBankNo);
- if (rc == Error_Succeed)
- rc = pConfig->ReadConfigValue("Initializer", "BranchNo", strBranchNo);
- if (rc != Error_Succeed)
- {
- LogWarn(Severity_Low, (ErrorCodeEnum)rc, ERR_INITIALIZER_READ_WRITE_FILE,
- GetOutPutStr("%s%08X%s%s", "ReadConfigValue", rc, "File", "SubBankNo & BranchNo").c_str());
- rc = ERR_INITIALIZER_READ_WRITE_FILE;
- return rc;
- }
- // 1:3des only; 2: sm4 only; 3: both 3des and sm4
- int nCapability = GetPinPadCapability();
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("pinpad capability: %d", nCapability);
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("has no pinpad, not need init MK");
- }
- #endif // RVC_OS_LINUX
- CSimpleStringA strPinPadID = "", strDeviceID = "";
- bool hasPinPad;
- int nRet = GetPinPadIDAndDeviceID(strPinPadID, strDeviceID, hasPinPad);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("GetPinPadIDAndDeviceID ret: %d, PinPadID: %s, DeviceID: %s", nRet, (const char*)strPinPadID, (const char*)strDeviceID);
- if (nRet < 0)
- {
- return false; //具有pinpad的设备调用pinpad失败
- }
- // 从系统获取设备信息和硬件信息
- // 变长结构初始化
- char buf2[512];
- memset(buf2, 0, 512);
- CSystemStaticInfo si;
- pFunc->GetSystemStaticInfo(si);
- initMKReq.enrolGPS = "00000A4500000A4E";//oiltmp
- initMKReq.enrolAddr = si.strEnrolAddr;
- initMKReq.installVersion = si.InstallVersion.ToString();
- #ifdef RVC_OS_WIN
- hostent* ent = gethostbyname(NULL);
- if (ent && ent->h_addr_list[0] != NULL)
- {
- int i = 0;
- for (; ent->h_addr_list[i] != NULL; ++i)
- {
- struct in_addr* in = (struct in_addr*)ent->h_addr_list[i];
- if (in->S_un.S_un_b.s_b1 == 99 || in->S_un.S_un_b.s_b1 == 10)
- break;
- }
- if (ent->h_addr_list[i] == NULL)
- i = 0;
- auto in = (struct in_addr*)ent->h_addr_list[i];
- char xIP[64] = {};
- sprintf(xIP, "%d.%d.%d.%d", in->S_un.S_un_b.s_b1, in->S_un.S_un_b.s_b2, in->S_un.S_un_b.s_b3, in->S_un.S_un_b.s_b4);
- initMKReq.ip = xIP;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("ip:%s", xIP);
- }
- #else
- BYTE xIP[64] = {};
- char ip[32] = { 0 };
- if (getIPFromLinux(ip)) DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Get IP From Linux Error ex.");
- else {
- if (ip2byte(ip, xIP)) DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Ip 2 Byte Error");
- else {
- for (int i = 0; i < 4; i++) {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("ip[%d]=%d", i, xIP[i]);
- }
- char strIP[64];
- memset(strIP, 0, 64);
- sprintf(strIP, "%d.%d.%d.%d", xIP[0], xIP[1], xIP[2], xIP[3]);
- initMKReq.ip = strIP;
- }
- }
- #endif // RVC_OS_WIN
- initMKReq.machineType = si.strMachineType;
- if (nRet == 2 || nRet == 3)
- initMKReq.padDeviceID = strDeviceID;
- initMKReq.site = si.strSite;
- initMKReq.terminalNo = si.strTerminalID;
- BYTE fingerPrint[32] = { 0 };
- int nBufLen = sizeof(fingerPrint);
- if (!GetTerminalFingerPrint(fingerPrint, nBufLen))
- {
- LogWarn(Severity_Middle, Error_Unexpect, ERR_INITIALIZER_GET_TERMINAL_FINGERPRINT,
- GetOutPutStr("%s%s", "GetTerminalFingerPrint", "False").c_str());
- return ERR_INITIALIZER_GET_TERMINAL_FINGERPRINT;
- }
- initMKReq.terminalCharacter = ConvertBytesToHexStr(fingerPrint, nBufLen);
- if (nRet == 1 || nRet == 3)
- initMKReq.pinPadID = strPinPadID;
- BYTE xPublicKey[148];
- nBufLen = sizeof(xPublicKey);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SendInitMKReqACS")("开始获取公钥。。。");
- memset(xPublicKey, 0, nBufLen);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SendInitMKReqACS")("nBufLen=%d", nBufLen);
- if (!GetTerminalPublicKey(xPublicKey, nBufLen, initMKReq.publicKey))
- {
- LogWarn(Severity_Middle, Error_Unexpect, ERR_INITIALIZER_GET_TERMINAL_PUBKEY,
- GetOutPutStr("%s%s", "GetTerminalPublicKey", "False").c_str());
- return ERR_INITIALIZER_GET_TERMINAL_PUBKEY;
- }
- initMKReq.user = m_strUserID.GetData();
- initMKReq.password = m_strPassword.GetData();
- if (!m_strUserID.IsNullOrEmpty() && !m_strPassword.IsNullOrEmpty())
- {
- LogWarn(Severity_Low, Error_Succeed, AccessAuthorization_UserErrorCode_Init_From_ClosePage, "Init by ClosePage.");
- initMKReq.loginWay = 1;
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("no need to call login again as User Desktop have logined.");
- initMKReq.loginWay = 0;
- }
- PinPadService_ClientBase* pPinPad = new PinPadService_ClientBase(this);
- auto errRc = pPinPad->Connect();
- if (errRc == Error_Succeed)
- {
- PinPadService_GetCheckCode_Req req = {};
- PinPadService_GetCheckCode_Ans ans = {};
- req.mSN.Init(1);
- req.wSN.Init(1);
- req.mSN[0] = 1;
- req.wSN[0] = 0;
- errRc = (*pPinPad)(EntityResource::getLink().upgradeLink())->GetCheckCode(req, ans, 10000);
- if (errRc == Error_Succeed)
- {
- initMKReq.tpkKeyCheck = ans.checkcode[0].GetData();
- initMKReq.keyIndex = ans.index[0].GetData();
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Get keyChek && keyIndex failed.");
- }
- pPinPad->GetFunction()->CloseSession();
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("connect to pinpad failed.error code:%d", errRc);
- }
- return true;
- }
- void CAccessAuthEntity::EndInitMK(DWORD rc, const char *pszErrMsg)
- {
- LOG_FUNCTION();
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("EndInitMK:rc:%d,errMsg:%s", rc, pszErrMsg);
- GetFunction()->KillTimer(22);
- m_strLastErrMsg = pszErrMsg;
- if (rc != Error_Succeed)
- {
- LogWarn(Severity_Middle, Error_Unexpect, ERR_INITIALIZER_INIT_MK,
- GetOutPutStr("%s%08X%s%s", "EndInitMK", rc,"pszErrMsg", pszErrMsg).c_str());
- GetFunction()->ShowFatalError(pszErrMsg);
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("初始化成功。。。");
- }
- m_eErrNum = rc;
- bool bSuc = rc == Error_Succeed;
- // 通知UI窗口
- if (m_ctx != NULL) {
- m_ctx->Ans.Errcode = rc;
- m_ctx->Ans.ErrMsg = m_strLastErrMsg;
- m_ctx->Answer(Error_Succeed);
- }
- }
- ErrorCodeEnum CAccessAuthEntity::LoadKeysToPinPadACS(string TMK, string TPK, string EDK, string index)
- {
- LOG_FUNCTION();
- #ifdef RVC_OS_WIN
- if (m_bNewSMFWB && m_FSM.GetDevPubKey().GetLength() <= 0)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("新蓝牙多合一密钥初始化依赖加密通道建立时的设备公钥,不具备,跳过密钥初始化");
- return Error_Succeed;
- }
- #endif // RVC_OS_WIN
- //加载到密码键盘
- PinPadService_ClientBase* pPinPad = new PinPadService_ClientBase(this);
- auto rc = pPinPad->Connect();
- if (rc == Error_Succeed)
- {
- PinPadService_LoadKeysSM_Req req = {};
- req.initializeflag = true;
- if (m_bNewSMFWB)
- {
- //oilyang@20220902 to encrypte tmp using device public key
- req.smflag = 11;
- auto tmkpairDev = GenerateTmkToDevice();
- if (tmkpairDev.first.length() <= 0)
- {
- //oiltest todo 补充错误信息
- return Error_Unexpect;
- }
- else
- req.masterkey = tmkpairDev.first.c_str();
- }
- else
- {
- req.smflag = 1;
- req.masterkey = TMK.c_str();
- }
- req.workingkey1 = TPK.c_str();
- req.workingkey2 = EDK.c_str();
- req.reserved3 = index.c_str();
- if (!req.initializeflag) DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("LoadKeysToPinPadACS")("initializeflag is false");
- PinPadService_LoadKeysSM_Ans ans = {};
- rc = pPinPad->LoadKeysSM(req, ans, 30000);
- if (rc != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("load sm key to pinpad failed.");
- return Error_Unexpect;
- }
- pPinPad->GetFunction()->CloseSession();
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("connect to pinpad failed %x", rc);
- return Error_Unexpect;
- }
- return Error_Succeed;
- }
- DWORD CAccessAuthEntity::InitDevice(SpReqAnsContext<AccessAuthService_InitDev_Req, AccessAuthService_InitDev_Ans>::Pointer& ctx)
- {
- return m_FSM.InitDevice(ctx);
- }
- void CAccessAuthEntity::GetNetMsg(SpReqAnsContext<AccessAuthService_GetNetMsg_Req, AccessAuthService_GetNetMsg_Ans>::Pointer& ctx)
- {
- m_FSM.GetNetMsg(ctx);
- return;
- }
- bool CAccessAuthEntity::GenerateRandomNum()
- {
- LOG_FUNCTION();
- const int MAX_KEY_SIZE = 256;
- //get public key-->send random number --> set working key
- int ret1, ret2, ret3, ret4;
- unsigned int ram[4];
- #ifdef RVC_OS_WIN
- ret1 = rand_s(&ram[0]);
- ret2 = rand_s(&ram[1]);
- ret3 = rand_s(&ram[2]);
- ret4 = rand_s(&ram[3]);
- if ((ret1 != 0) || (ret2 != 0) || (ret3 != 0) || (ret4 != 0))
- return false;
- ZeroMemory(m_btRam, 16);
- #else
- ram[0] = rand();
- ram[1] = rand();
- ram[2] = rand();
- ram[3] = rand();
- memset(m_btRam, 0, 16);
- #endif // RVC_OS_WIN
- for (int i = 0, j = 0; j < 4; ++j)
- {
- m_btRam[i + 0] = ((ram[j] & 0xff000000) >> 24);
- m_btRam[i + 1] = ((ram[j] & 0x00ff0000) >> 16);
- m_btRam[i + 2] = ((ram[j] & 0x0000ff00) >> 8);
- m_btRam[i + 3] = (ram[j] & 0x000000ff);
- i += 4;
- }
- return true;
- }
- pair<string, string> CAccessAuthEntity::GenerateTmkToKMC()
- {
- LOG_FUNCTION();
- if (!GenerateRandomNum())
- return make_pair("", "");
- #ifdef DEVOPS_ON_ST /*DevOps流水线编译,ST环境*/
- CSimpleStringA tmpPubKey = "0445FAF2B721207A39A9F3DEE3B3D89E2EF8924882968D31FC54FDA4F41D3D94AED4DA1B3C38B17193AD2952BD24407B7C01A80E65630A2FAD5073691613EAA814";
- #elif defined(DEVOPS_ON_UAT)/*DevOps流水线编译,UAT环境*/
- CSimpleStringA tmpPubKey = "040AEC50A1FC9C5E9B1162FE4520C9E18E6F471A3F6DB77B147F0A464B5BFD0EDBE08AE8377C458CA204456E7A86568AAA9240F1C843E47988A6A197B232539DC8";
- #elif defined(DEVOPS_ON_PRD)/*DevOps流水线编译,PRD环境*/
- CSimpleStringA tmpPubKey = "04E0A4FDA2484A1A0FAB0844F59110AEB7A08D314B5E451E816FC0E78CBA383B461474E1167B86FC48D704CB482DD5164A73AB9E019CCE26EE382B89C394B5ACE1";
- #elif defined(DEVOPS_ON_DEV)/*DevOps流水线编译,Dev环境*/
- CSimpleStringA tmpPubKey = "0445FAF2B721207A39A9F3DEE3B3D89E2EF8924882968D31FC54FDA4F41D3D94AED4DA1B3C38B17193AD2952BD24407B7C01A80E65630A2FAD5073691613EAA814";
- #else/*本地编译等非DevOps环境编译的版本*/
- CSimpleStringA tmpPubKey = "0445FAF2B721207A39A9F3DEE3B3D89E2EF8924882968D31FC54FDA4F41D3D94AED4DA1B3C38B17193AD2952BD24407B7C01A80E65630A2FAD5073691613EAA814";
- #endif
- return EncryptedByPubKey(tmpPubKey);
- }
- pair<string, string> CAccessAuthEntity::GenerateTmkToDevice()
- {
- if (m_FSM.GetDevPubKey().GetLength() <= 0)
- return make_pair("", "");
- return EncryptedByPubKey(m_FSM.GetDevPubKey(), true);
- }
- pair<string, string> CAccessAuthEntity::EncryptedByPubKey(CSimpleStringA pubKey, bool bNeed04Head)
- {
- LOG_FUNCTION();
- if (pubKey.GetLength() <= 0)
- return make_pair("", "");
- PCHAR strRam = new CHAR[512];
- #ifdef RVC_OS_WIN
- ZeroMemory(strRam, 512);
- #else
- memset(strRam, 0, 512);
- #endif // RVC_OS_WIN
- memcpy(strRam, &(m_btRam[0]), 16);
- HexBuf2StrBuf((PBYTE)m_btRam, &strRam, 16);
- const int MAX_KEY_SIZE = 256;
- char random_enc_bypbk[MAX_KEY_SIZE];
- #ifdef RVC_OS_WIN
- ZeroMemory(random_enc_bypbk, MAX_KEY_SIZE);
- #else
- memset(random_enc_bypbk, 0, MAX_KEY_SIZE);
- #endif // RVC_OS_WIN
- //公钥加密随机数
- int outMsgLen = MAX_KEY_SIZE;
- PBYTE pxxKey = new BYTE[256];
- PBYTE pOldPubKey = new BYTE[256];
- #ifdef RVC_OS_WIN
- ZeroMemory(pxxKey, 256);
- ZeroMemory(pOldPubKey, 256);
- #else
- memset(pOldPubKey, 0, 256);
- memset(pxxKey, 0, 256);
- #endif // RVC_OS_WIN
- int size = StrBuf2HexBuf(pubKey.GetData(), &pOldPubKey);
- if (bNeed04Head)
- {
- pxxKey[0] = 0x04;
- memcpy(pxxKey + 1, pOldPubKey, size);
- }
- else
- memcpy(pxxKey, pOldPubKey, 65);
- int retSM2 = EncWithSM2PubKey((unsigned char*)m_btRam, 16, (unsigned char*)random_enc_bypbk, &outMsgLen, (unsigned char*)pxxKey, 65);
- if (!retSM2 || outMsgLen != 113)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("EncWithSM2PubKey failed outMsgLen:%d.", outMsgLen);
- return make_pair("", "");
- }
- PBYTE tmp_enc_bypbk = new BYTE[112];
- #ifdef RVC_OS_WIN
- ZeroMemory(tmp_enc_bypbk, 112);
- #else
- memset(tmp_enc_bypbk, 0, 112);
- #endif // RVC_OS_WIN
- //tmp_enc_bypbk[0] = 0x04;
- if (bNeed04Head)
- {
- memcpy(tmp_enc_bypbk, &(random_enc_bypbk[1]), 112);
- }
- else
- {
- memcpy(tmp_enc_bypbk, &(random_enc_bypbk[1]), 64);
- memcpy(tmp_enc_bypbk + 64, &(random_enc_bypbk[97]), 16);
- memcpy(tmp_enc_bypbk + 80, &(random_enc_bypbk[65]), 32);
- }
- PCHAR pBlock = new CHAR[512];
- #ifdef RVC_OS_WIN
- ZeroMemory(pBlock, 512);
- #else
- memset(pBlock, 0, 512);
- #endif // RVC_OS_WIN
- BYTE tmpRandomEnc[512];
- memset(tmpRandomEnc, 0, 512);
- memcpy(tmpRandomEnc, &(tmp_enc_bypbk[0]), outMsgLen - 1);
- size = HexBuf2StrBuf((PBYTE)tmpRandomEnc, &pBlock, 112);
- return make_pair(pBlock, strRam);
- }
- #ifdef RVC_OS_WIN
- void CAccessAuthEntity::GetTermSysInfo()
- {
- //oilyang@20231008 to get system info from runcfg first
- //no matter calculating from runcfg succeed or not,we also get system info from system api for update runcfg
- bool bCalcFromRunCfg = false;
- CSimpleString csInfo, strErrMsg, strRet;
- CSmartPointer<IConfigInfo> pConfigRun;
- ErrorCodeEnum eErr = GetFunction()->OpenConfig(Config_Run, pConfigRun);
- if (eErr == Error_Succeed && pConfigRun->ReadConfigValue("system", "info", csInfo) == Error_Succeed && !csInfo.IsNullOrEmpty()) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("read device info from runcfg: [%s]", csInfo.GetData());
- ZeroMemory(m_btTermSysInfoSM3, sizeof(m_btTermSysInfoSM3));
- if (!SM3Hash(reinterpret_cast<BYTE*>(const_cast<char*>(csInfo.GetData())), csInfo.GetLength(), m_btTermSysInfoSM3))
- {
- strErrMsg = "get sm3 hash as fingerprint fail";
- SetAuthErrMsg((const char*)strErrMsg);
- this->GetFunction()->SetSysVar("AuthErrMsg", (const char*)strErrMsg, true);
- m_FSM.doWarnMsg(ERROR_ACCESSAUTH_GETSM3HASH, (const char*)strErrMsg);
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI("GetTerminalFingerPrint")((const char*)strErrMsg);
- m_iGetTermSysInfo = -1;
- }
- else
- {
- m_iGetTermSysInfo = 1;
- bCalcFromRunCfg = true;
- }
- }
- else
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetTermSysInfo, OpenConfig Config_Run error=%d.", eErr);
- ULONGLONG ullStart = GetTickCount64();
- char szTmp[1024] = {};
- int nTmpBufLen = 1024;
- CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
- if (!QueryWMIDevice(Processor, "ProcessorId", szTmp, &nTmpBufLen))
- {
- strErrMsg = CSimpleStringA::Format("查询 cpu id 失败: %d, 请尝试重启应用", GetLastError());
- SetAuthErrMsg((const char*)strErrMsg);
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_GET_TERMINAL_FINGERPRINT,
- GetOutPutStr("%s%s%s%d", "QueryWMIDevice", "False", "Processor", GetLastError()).c_str(), true, strErrMsg.GetData());
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5203")
- (GetOutPutStr("%s%s%s%d", "QueryWMIDevice", "False", "Processor", GetLastError()).c_str());
- if (!bCalcFromRunCfg)
- m_iGetTermSysInfo = -1;
- return;
- }
- strRet = szTmp;
- nTmpBufLen = 1024;
- memset(szTmp, 0, sizeof(szTmp));
- if (!QueryWMIDevice(BaseBoard, "SerialNumber", szTmp, &nTmpBufLen))
- {
- strErrMsg = CSimpleStringA::Format("查询 baseboard sn 失败: %d, 请尝试重启应用", GetLastError());
- SetAuthErrMsg((const char*)strErrMsg);
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_GET_TERMINAL_FINGERPRINT,
- GetOutPutStr("%s%s%s%d", "QueryWMIDevice", "False", "BaseBoard", GetLastError()).c_str(), true, strErrMsg.GetData());
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5203")
- (GetOutPutStr("%s%s%s%d", "QueryWMIDevice", "False", "BaseBoard", GetLastError()).c_str());
- if (!bCalcFromRunCfg)\
- m_iGetTermSysInfo = -1;
- return;
- }
- strRet += "|";
- strRet += szTmp;
- nTmpBufLen = 1024;
- memset(szTmp, 0, sizeof(szTmp));
- if (!QueryWMIDevice(DiskDrive, "SerialNumber", szTmp, &nTmpBufLen))
- {
- strErrMsg = CSimpleStringA::Format("查询 harddisk sn 失败: %d, 请尝试重启应用", GetLastError());
- SetAuthErrMsg((const char*)strErrMsg);
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_GET_TERMINAL_FINGERPRINT,
- GetOutPutStr("%s%s%s%d", "QueryWMIDevice", "False", "DiskDrive", GetLastError()).c_str(), true, strErrMsg.GetData());
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)(GetOutPutStr("%s%s%s%d", "QueryWMIDevice", "False", "DiskDrive", GetLastError()).c_str());
- if (!bCalcFromRunCfg)
- m_iGetTermSysInfo = -1;
- return;
- }
- strRet += "|";
- strRet += szTmp;
- if (!bCalcFromRunCfg || csInfo.Compare(strRet) != 0)
- {
- eErr = pConfigRun->WriteConfigValue("system", "info", strRet.GetData());
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("device info changed,before[%s],current[%s],write to runcfg:%d"
- , csInfo.GetData(), strRet.GetData(), eErr);
- }
- else
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("device info: [%s]", strRet.GetData());
-
- if (!bCalcFromRunCfg)
- {
- ZeroMemory(m_btTermSysInfoSM3, sizeof(m_btTermSysInfoSM3));
- if (!SM3Hash(reinterpret_cast<BYTE*>(const_cast<char*>(strRet.GetData())), strRet.GetLength(), m_btTermSysInfoSM3))
- {
- strErrMsg = "get sm3 hash as fingerprint fail";
- SetAuthErrMsg((const char*)strErrMsg);
- spFunction->SetSysVar("AuthErrMsg", (const char*)strErrMsg, true);
- m_FSM.doWarnMsg(ERROR_ACCESSAUTH_GETSM3HASH, (const char*)strErrMsg);
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)((const char*)strErrMsg);
- m_iGetTermSysInfo = -1;
- }
- else
- m_iGetTermSysInfo = 1;
- }
- ULONGLONG ullEnd = GetTickCount64();
- if (ullEnd - ullStart > 5000)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5201")
- ("获取系统信息耗时过长:%d秒", (ullEnd - ullStart) / 1000);
- LogWarn(Severity_Middle, Error_Unexpect, AccessAuthorization_UserErrorCode_GetTermCostTooLong,
- CSimpleStringA::Format("获取系统信息耗时过长:%d秒", (ullEnd - ullStart) / 1000));
- }
- return;
- }
- #endif // RVC_OS_WIN
- SP_BEGIN_ENTITY_MAP()
- SP_ENTITY(CAccessAuthEntity)
- SP_END_ENTITY_MAP()
|