1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161 |
- #include "stdafx.h"
- #include "SpBase.h"
- #include "mod_AccessAuth.h"
- #include "RVCComm.h"
- #include "comm.h"
- #include "access_basefun.h"
- #include "DeviceBaseClass.h"
- #include <fileutil.h>
- #include <iniutil.h>
- #include <cmath>
- #include "TokenKeeper_client_g.h"
- using namespace TokenKeeper;
- #include "PinPad_client_g.h"
- using namespace PinPad;
- #ifdef RVC_OS_WIN
- #include "WMIDeviceQuery.h"
- #include <Strsafe.h>
- #endif
- #ifdef WITH_CPPRESTSDK
- #include "CommEntityRestful.hpp"
- #else
- #define SAFE_DELETE_HTTPCLIENT(obj) \
- do{if(obj != NULL) { obj->Destory(); obj = NULL; }}while(false)
- #endif
- #define KEY_SIZE 16
- #define BUF_SIZE 256
- /** TODO(gifur): expand the time to 10s*/
- #define DEFUALT_INVOKE_PINPAD_TIMEOUT 3000
- 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);
- CInitlizerMKReq initMKReq(1);//oiltest dev module count
- m_entity->SendInitMKReqACS(initMKReq);
- #ifdef WITH_CPPRESTSDK
- struct MKD_NEW1JSON
- {
- string enrolAddr;
- string enrolGPS;
- string installVersion;
- string ip;
- string machineModel;
- string machineType;
- string padDeviceID;
- string site;
- string terminalNo;
- JSONCONVERT2OBJECT_MEMEBER_REGISTER(enrolAddr, enrolGPS, installVersion, ip, machineModel, machineType, padDeviceID, site, terminalNo)
- };
- struct MKD_REQ2JSON
- {
- string branchNo;
- string kmcData;
- string subBankNo;
- JSONCONVERT2OBJECT_MEMEBER_REGISTER(branchNo, kmcData, subBankNo)
- };
- struct MKD_REQ3JSON
- {
- string factory;
- string modal;
- string type;
- string version;
- JSONCONVERT2OBJECT_MEMEBER_REGISTER(factory, modal, type, version)
- };
- struct MKD_REQ4JSON
- {
- string fingerPrint;
- string fingerPrintSM;
- string pinPadID;
- string publicKey;
- string reserverd;
- JSONCONVERT2OBJECT_MEMEBER_REGISTER(fingerPrint, fingerPrintSM, pinPadID, publicKey, reserverd)
- };
- struct MKD_REQ5JSON
- {
- int isFirstSM;
- int isSM;
- JSONCONVERT2OBJECT_MEMEBER_REGISTER(isFirstSM, isSM)
- };
- struct MKD_SMR2JSON
- {
- string branchNo;
- string kmcData;
- string subBankNo;
- JSONCONVERT2OBJECT_MEMEBER_REGISTER(branchNo, kmcData, subBankNo)
- };
- struct InstanceReqJson
- {
- MKD_NEW1JSON MKD_NEW1;
- MKD_REQ2JSON MKD_REQ2;
- std::vector<MKD_REQ3JSON> MKD_REQ3;
- MKD_REQ4JSON MKD_REQ4;
- MKD_REQ5JSON MKD_REQ5;
- MKD_SMR2JSON MKD_SMR2;
- JSONCONVERT2OBJECT_MEMEBER_REGISTER(MKD_NEW1, MKD_REQ2, MKD_REQ3, MKD_REQ4, MKD_REQ5, MKD_SMR2)
- } instanceReq;
- instanceReq.MKD_NEW1.enrolAddr = initMKReq.MKD_NEW1.enrolAddr;
- instanceReq.MKD_NEW1.enrolGPS = initMKReq.MKD_NEW1.enrolGPS;
- instanceReq.MKD_NEW1.installVersion = initMKReq.MKD_NEW1.installVersion;
- instanceReq.MKD_NEW1.ip = initMKReq.MKD_NEW1.ip;
- instanceReq.MKD_NEW1.machineModel = initMKReq.MKD_NEW1.machineModel;
- instanceReq.MKD_NEW1.machineType = initMKReq.MKD_NEW1.machineType;
- instanceReq.MKD_NEW1.padDeviceID = initMKReq.MKD_NEW1.padDeviceID;
- instanceReq.MKD_NEW1.site = initMKReq.MKD_NEW1.site;
- instanceReq.MKD_NEW1.terminalNo = initMKReq.MKD_NEW1.terminalNo;
- instanceReq.MKD_REQ2.branchNo = initMKReq.MKD_REQ2.branchNo;
- instanceReq.MKD_REQ2.kmcData = initMKReq.MKD_REQ2.kmcData;
- instanceReq.MKD_REQ2.subBankNo = initMKReq.MKD_REQ2.subBankNo;
- for (int i = 0; i < initMKReq.iReq3Count; ++i) {
- MKD_REQ3JSON item;
- item.type = initMKReq.MKD_REQ3[i]->type;
- item.modal = initMKReq.MKD_REQ3[i]->modal;
- item.factory = initMKReq.MKD_REQ3[i]->factory;
- item.version = initMKReq.MKD_REQ3[i]->version;
- instanceReq.MKD_REQ3.push_back(item);
- }
- instanceReq.MKD_REQ4.fingerPrint = initMKReq.MKD_REQ4.fingerPrint;
- instanceReq.MKD_REQ4.fingerPrintSM = initMKReq.MKD_REQ4.fingerPrintSM;
- instanceReq.MKD_REQ4.pinPadID = initMKReq.MKD_REQ4.pinPadID;
- instanceReq.MKD_REQ4.publicKey = initMKReq.MKD_REQ4.publicKey;
- instanceReq.MKD_REQ4.reserverd = initMKReq.MKD_REQ4.reserverd;
- instanceReq.MKD_REQ5.isFirstSM = initMKReq.MKD_REQ5.isFirstSM;
- instanceReq.MKD_REQ5.isSM = initMKReq.MKD_REQ5.isSM;
- instanceReq.MKD_SMR2.branchNo = initMKReq.MKD_SMR2.branchNo;
- instanceReq.MKD_SMR2.subBankNo = initMKReq.MKD_SMR2.subBankNo;
- instanceReq.MKD_SMR2.kmcData = initMKReq.MKD_SMR2.kmcData;
- struct InstanceAnsJson
- {
- string TMK;
- string TPK;
- string EDK;
- string index;
- string reserved;
- JSONCONVERT2OBJECT_MEMEBER_REGISTER(TMK, TPK, EDK, index)
- JSONCONVERT2OBJECT_MEMEBER_RENAME_REGISTER("tmk", "tpk", "edk", "index")
- } instanceAns;
- HttpClientResponseResult result;
- HttpClientRequestConfig config(HttpRequestMethod::POST, m_entity->GetInitUrl().GetData());
- config.SetChildUri("/api/initmk");
- SP::Module::Restful::FulfillRequestJsonBody(&config, instanceReq);
- RestfulClient client = RestfulClient::getInstance();
- config.PreDo();
- client.Do(&config, &result);
- if (result.ResponseOK()) {
- Dbg("InitializerInitMKTask Connect Success.");
- SP::Module::Restful::CommResponseJson responseStatus;
- SP::Module::Restful::GetStatusFromDebranchResponse(result.content, responseStatus);
- if (!responseStatus.IsOperatedOK()) {
- Dbg("update wk failed: %s", responseStatus.errorMsg.c_str());
- m_entity->EndInitMK(ERR_INITIALIZER_INIT_EXCEPTION, responseStatus.errorMsg.c_str());
- }
- else {
- if (m_entity->HasPinPad()) {
- const bool testResult = SP::Module::Restful::ExtractDataFromDebranchResponse(result.content, instanceAns);
- Dbg("ExtractDataFromDebranchResponse returned: %d", testResult);
- if (m_entity->LoadKeysToPinPadACS(instanceAns.TMK, instanceAns.TPK, instanceAns.EDK, instanceAns.index) == Error_Succeed) {
- m_entity->EndInitMK(Error_Succeed, "");
- }
- else {
- m_entity->EndInitMK(ERR_INITIALIZER_INIT_EXCEPTION, "加载秘钥到密码键盘失败");//,待完善细化错误码oiltest
- }
- }
- else {
- m_entity->EndInitMK(Error_Succeed, "");
- }
- }
- }
- else {
- Dbg("post wk failed: %s", result.WhatError().c_str());
- m_entity->EndInitMK(ERR_INITIALIZER_INIT_EXCEPTION, result.WhatError().c_str());
- }
- #else
- IHttpFunc* client;
- client = create_http(m_fsm->HttpsLogCallBack);
- initMKReq.m_bTransCode = false;
- CInitlizerMKRet initMKRet;
- initMKReq.m_url = m_entity->GetInitUrl();
- initMKReq.m_url += "/api/initmk";
- bool ret = client->Post(initMKReq, initMKRet);
- Dbg("code=%d", initMKRet.m_sysCode);
- if (ret) {
- Dbg("InitializerInitMKTask Connect Success.");
- if (initMKRet.m_userCode.compare(ACS_SUCCESS)) {
- Dbg("update wk failed: %s", initMKRet.m_errMsg.c_str());
- std::string errStr("#ACS#");
- errStr += initMKRet.m_errMsg;
- m_entity->EndInitMK(ERR_INITIALIZER_INIT_EXCEPTION, errStr.c_str());
- SAFE_DELETE_HTTPCLIENT(client);
- return;
- }
- if (m_entity->HasPinPad()) {
- if (m_entity->LoadKeysToPinPadACS(initMKRet.data.TMK, initMKRet.data.TPK, initMKRet.data.EDK, initMKRet.data.index) == Error_Succeed)
- m_entity->EndInitMK(Error_Succeed, "");
- else
- m_entity->EndInitMK(ERR_INITIALIZER_INIT_EXCEPTION, "加载秘钥到密码键盘失败");//,待完善细化错误码oiltest
- }
- else
- m_entity->EndInitMK(Error_Succeed, "");
- }
- else {
- Dbg("UpdateWKTask Connect Failed.");
- }
- SAFE_DELETE_HTTPCLIENT(client);
- #endif //WITH_CPPRESTSDK
- }
- };
- 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)
- {
- m_pEntity->Regist();
- }
- void CAccessAuthSession::Handle_Unregist(SpOnewayCallContext<AccessAuthService_Unregist_Info>::Pointer ctx)
- {
- m_pEntity->Unregist(ctx->Info.nReason, ctx->Info.nWay);
- }
- void CAccessAuthSession::Handle_InitDev(SpReqAnsContext<AccessAuthService_InitDev_Req, AccessAuthService_InitDev_Ans>::Pointer ctx)
- {
- m_pEntity->InitDevice(ctx);
- }
- void CAccessAuthSession::Handle_UpdateWK(SpOnewayCallContext<AccessAuthService_UpdateWK_Info>::Pointer ctx)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setAPI("UpdateWK")("call Handle_UpdateWK");
- m_pEntity->UpdateWK();
- }
- void CAccessAuthSession::Handle_SyncTime(SpOnewayCallContext<AccessAuthService_SyncTime_Info>::Pointer ctx)
- {
- m_pEntity->SyncTime();
- }
- void CAccessAuthSession::Handle_InitializeNew(SpReqAnsContext<AccessAuthService_InitializeNew_Req, AccessAuthService_InitializeNew_Ans>::Pointer ctx)
- {
- DbgWithLink(LOG_LEVEL_INFO, ctx->link.checkEmpty() ? LOG_TYPE_SYSTEM : LOG_TYPE_USER).setAPI("StartInitializeNew")("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 CAccessAuthEntity::OnStarted()
- {
- //设置时区为北京标准时区
- if (!SetLocalTimeZoneByKeyName("China Standard Time", FALSE))
- {
-
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_SETTIMEZONE,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 = "HasPinPad()=>GetSystemStaticInfo() fail";
- SetAuthErrMsg((const char*)strErrMsg);
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_GET_SYSTEM_STATIC_INFO,
- GetOutPutStr("%s%08X", "获取系统静态信息错误", rc).c_str(), strErrMsg.GetData());
- }
- }
- void CAccessAuthEntity::OnPreStart(CAutoArray<CSimpleStringA> strArgs,CSmartPointer<ITransactionContext> pTransactionContext)
- {
- ErrorCodeEnum Error = Error_Succeed;
- pTransactionContext->SendAnswer(Error) ;
- }
- void CAccessAuthEntity::OnPreClose(EntityCloseCauseEnum eCloseCause,CSmartPointer<ITransactionContext> pTransactionContext)
- {
- 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;
- }
- // 重新准入
- ErrorCodeEnum CAccessAuthEntity::Reregist()
- {
- //m_FSM.PostEventFIFO(new FSMEvent(CAccessAuthFSM::Event_StartReregist));
- return Error_Succeed;
- }
- // 准入退出
- ErrorCodeEnum CAccessAuthEntity::Unregist(int nReason, int nWay)
- {
- /*FSMEvent *pEvent = new FSMEvent(CAccessAuthFSM::Event_StartUnregist);
- pEvent->param1 = nReason;
- pEvent->param2 = nWay;
- m_FSM.PostEventFIFO(pEvent);*/
- return Error_Succeed;
- }
- DWORD CAccessAuthEntity::SyncTime()
- {
- return m_FSM.SyncTime();
- }
- ErrorCodeEnum CAccessAuthEntity::PushTerminalStage(char cNewStage, DWORD dwNewStageTime, char cOldStage, DWORD dwOldStageTime)
- {
- Dbg("on PushTerminalStage, cNewStage: %c", cNewStage);
- /*CAccessAuthFSM::ReportStateEvent *pEvent = new CAccessAuthFSM::ReportStateEvent(cNewStage, dwNewStageTime, cOldStage, dwOldStageTime);
- m_FSM.PostEventFIFO(pEvent);*/
- return Error_Succeed;
- }
- // KMC初始化
- DWORD CAccessAuthEntity::InitKMC()
- {
- return Error_Succeed;
- }
-
- // 获取WK更新请求包
- // @nAlgFlag: 1:3des only; 2: sm4 only; 3: both 3des and sm4
- ErrorCodeEnum CAccessAuthEntity::GetKmcWKUpdateData(char *pBuf, int &nLen, int nAlgFlag)
- {
- return Error_Succeed;
- }
- DWORD CAccessAuthEntity::ParseWKUpdateResult(char *pBuf, int nLen, int nAlgFlag)
- {
- return Error_Succeed;
- }
- CSimpleStringA CAccessAuthEntity::GetKMCLastErrMsg()
- {
- return "";
- }
- ErrorCodeEnum CAccessAuthEntity::ReleaseKMC()
- {
- return Error_Succeed;
- }
- // 加载新WK
- DWORD CAccessAuthEntity::LoadPinPadWK(bool bSM)
- {
- Dbg("load sm key to pinpad...");
- CSimpleString strErrMsg;
- CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
- PinPadService_ClientBase* pPinPad = new PinPadService_ClientBase(this);
- DWORD rc = pPinPad->Connect();
- if (rc == Error_Succeed)
- {
-
- PinPadService_LoadKeysSM_Req req = {};
- req.smflag = 1;
- req.initializeflag = true;
- if (m_bGetKMCKey) {
- Dbg("使用云接口更新KMC密钥");
- req.masterkey = m_TMK.c_str();
- req.workingkey1 = m_TPK.c_str();
- req.workingkey2 = m_EDK.c_str();
- req.reserved3 = m_index.c_str();
- }
- else {
- strErrMsg = "更新KMC密钥失败";
- SetAuthErrMsg((const char*)strErrMsg);
- spFunction->SetSysVar("AuthErrMsg", (const char*)strErrMsg, false);
- LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_GET_KMC_NULL,
- GetOutPutStr("%s%s", "m_bGetKMCKey", "False").c_str());
- rc = ERR_ACCESSAUTH_GET_KMC_NULL;
- return rc;
- }
- if (req.initializeflag) Dbg("initializeflag is true");
- else Dbg("initializeflag is false");
- Dbg("req.smflag=%d", req.smflag);
- Dbg("req.masterkey=%s", req.masterkey.GetData());
- Dbg("req.workingkey1=%s", req.workingkey1.GetData());
- Dbg("req.workingkey2=%s", req.workingkey2.GetData());
- Dbg("req.reserved3=%s", req.reserved3.GetData());
- PinPadService_LoadKeysSM_Ans ans = {};
- rc = pPinPad->LoadKeysSM(req, ans, 30000);
- if (rc == Error_Succeed)
- Dbg("load sm key to pinpad succ");
- else
- {
- strErrMsg = "加载SM密钥到PinPad失败";
- SetAuthErrMsg((const char*)strErrMsg);
- spFunction->SetSysVar("AuthErrMsg", (const char*)strErrMsg, false);
- LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_LOAD_KEYS_TO_PINPAD,
- GetOutPutStr("%s%08x%s%s", "LoadKeysSM", rc, "strErrMsg", strErrMsg.GetData()).c_str());
- rc = ERR_ACCESSAUTH_LOAD_KEYS_TO_PINPAD;
- }
- pPinPad->GetFunction()->CloseSession();
- }
- else
- {
- strErrMsg = "连接PinPad实体失败";
- SetAuthErrMsg((const char*)strErrMsg);
- spFunction->SetSysVar("AuthErrMsg", (const char*)strErrMsg, false);
- LogWarn(Severity_Middle, Error_Unexpect, ERR_ACCESSAUTH_CONNECT_PINPAD,
- GetOutPutStr("%s%08x%s%s", "Connect", rc, "strErrMsg", strErrMsg).c_str());
- rc = ERR_ACCESSAUTH_CONNECT_PINPAD;
- //@test 没连接成功调用此接口释放
- pPinPad->SafeDelete();
- }
-
- return rc;
- }
- DWORD CAccessAuthEntity::LoadKeysToPinPadNew(string TMK, string TPK, string EDK, string index)
- {
- LOG_FUNCTION();
- Dbg("load sm key to pinpad...");
- PinPadService_ClientBase* pPinPad = new PinPadService_ClientBase(this);
- DWORD rc = pPinPad->Connect();
- if (rc == Error_Succeed)
- {
- PinPadService_LoadKeysSM_Req req = {};
- req.initializeflag = true;
- req.smflag = 1;
- Dbg("使用云接口获取的KMC密钥");
- req.masterkey = TMK.c_str();
- req.workingkey1 = TPK.c_str();
- req.workingkey2 = EDK.c_str();
- req.reserved3 = index.c_str();
- if (req.initializeflag) Dbg("initializeflag is true");
- else Dbg("initializeflag is false");
- Dbg("req.smflag=%d", req.smflag);
- Dbg("req.masterkey=%s", req.masterkey.GetData());
- Dbg("req.workingkey1=%s", req.workingkey1.GetData());
- Dbg("req.workingkey2=%s", req.workingkey2.GetData());
- Dbg("req.reserved3=%s", req.reserved3.GetData());
- PinPadService_LoadKeysSM_Ans ans = {};
- rc = pPinPad->LoadKeysSM(req, ans, 30000);
- if (rc == Error_Succeed)
- Dbg("load sm key to pinpad succ");
- else
- {
- SetAuthErrMsg("加载SM密钥到PinPad失败");
- m_FSM.doWarnMsg(ERR_INITIALIZER_LOAD_KEYS_TO_PINPAD,
- GetOutPutStr("%s%08x%s%s", "LoadKeys", rc, "strErrMsg", "加载SM密钥到PinPad失败").c_str());
-
- rc = ERR_INITIALIZER_LOAD_KEYS_TO_PINPAD;
- }
- pPinPad->GetFunction()->CloseSession();
- }
- else
- {
- SetAuthErrMsg("连接PinPad实体失败");
- m_FSM.doWarnMsg(ERR_INITIALIZER_CONNECT_PINPAD,
- GetOutPutStr("%s%08x%s%s", "Connect", rc, "strErrMsg", "连接PinPad实体失败").c_str());
-
- rc = ERR_INITIALIZER_CONNECT_PINPAD;
- pPinPad->SafeDelete();
- }
- return rc;
- }
- // 将16进制字符串转成BYTE数据
- bool CAccessAuthEntity::HexStrToByteArray(const char* pHex, BYTE *pBuf, int *pBufLen)
- {
- int nHexLen = strlen(pHex);
- if (nHexLen %2 != 0)
- {
- Dbg("error hex string length");
- return false;
- }
- if (nHexLen /2 > *pBufLen)
- {
- Dbg("not enough buf length");
- return false;
- }
- for(int i=0; i<nHexLen; i++)
- {
- BYTE b =0;
- char ch1 = pHex[i];
- if (ch1 >='0' && ch1<='9')
- b = ch1 - '0';
- else if (ch1 >='A' && ch1 <='F')
- b = ch1 - 'A' + 10;
- else
- {
- Dbg("invalid hex string");
- return false;
- }
- if (i %2 ==0)
- {
- pBuf[i/2] = b;
- }
- else
- {
- pBuf[i/2] = pBuf[i/2] << 4 | b;
- }
- }
- *pBufLen = nHexLen / 2;
- return true;
- }
- 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;
- }
- // 调用密码键盘加密
- DWORD CAccessAuthEntity::EncryptDataWithPinPad(const CBlob &raw, CBlob &enc)
- {
- #ifdef IGNORE_PINPAD
- enc.Alloc(raw.m_iLength);
- memcpy(enc.m_pData, raw.m_pData, raw.m_iLength);
- return Error_Succeed;
- #else
- CSimpleStringA strErrMsg;
- CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
- PinPadService_EncryptDataSM_Req req = {};
-
- PinPadService_EncryptDataSM_Ans ans = {};
-
- req.data = ByteArrayToHexStr((BYTE*)raw.m_pData, raw.m_iLength).c_str();
- Dbg("begin encrpyt data with pinpad");
- PinPadService_ClientBase *pPinPad = new PinPadService_ClientBase(this);
- DWORD rc = pPinPad->Connect();
- if (rc == Error_Succeed)
- {
- rc = pPinPad->EncryptDataSM(req, ans, 10000);
- if (rc == Error_Succeed)
- Dbg("encrypt data with pinpad succ: [%s]", (const char*)ans.ciphertext);
- else
- {
- strErrMsg = "调用PinPad实体中的EncryptData方法加密数据失败";
- SetAuthErrMsg((const char *)strErrMsg);
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_FROM_PINPAD,
- GetOutPutStr("%s%08x%s%s", "EncryptData", rc, "strErrMsg", strErrMsg).c_str());
- rc = ERR_ACCESSAUTH_FROM_PINPAD;
- }
- pPinPad->GetFunction()->CloseSession();
- }
- else
- {
- strErrMsg = "连接PinPad实体失败";
- SetAuthErrMsg((const char *)strErrMsg);
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_CONNECT_PINPAD,
- GetOutPutStr("%s%08x%s%s", "Connect", rc, "strErrMsg", strErrMsg).c_str());
- rc = ERR_ACCESSAUTH_CONNECT_PINPAD;
- pPinPad->SafeDelete();
- }
-
- if (rc != Error_Succeed)
- return rc;
- BYTE buf[512];
- int nLen = 512;
- memset(buf, 0, 512);
- if (!HexStrToByteArray((const char*)ans.ciphertext, buf, &nLen))
- {
- strErrMsg = "加密数据转化十六进制失败";
- SetAuthErrMsg((const char *)strErrMsg);
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_HEX_TO_BYTE,
- GetOutPutStr("%s%s%s%s", "HexStrToByteArray", "False", "strErrMsg", strErrMsg).c_str());
- return ERR_ACCESSAUTH_HEX_TO_BYTE;
- }
- enc.Alloc(nLen);
- memcpy(enc.m_pData, buf, nLen);
- return Error_Succeed;
- #endif
- }
- // 生成临时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(), "创建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,
- 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, DEFUALT_INVOKE_PINPAD_TIMEOUT);
- pTokenServiceClient->GetFunction()->CloseSession();
- if (rc != Error_Succeed)
- {
- strErrMsg = "保存密钥对失败";
- SetAuthErrMsg((const char *)strErrMsg);
- rc = ERR_ACCESSAUTH_FROM_TOKEN_SERVICE_SET_KEYS;
- m_FSM.doWarnMsg(rc,
- GetOutPutStr("%s%08X%s%s", "SetKeyPair", rc,"strErrMsg", (const char*)strErrMsg).c_str());
- }
- else
- Dbg("set sm2 key pair succ");
- }
-
- 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());
- pTokenServiceClient->SafeDelete();
- }
- else
- {
- TokenService_SetToken_Req req = {};
- req.token = token;
- TokenService_SetToken_Ans ans;
- rc = pTokenServiceClient->SetToken(req, ans, 5000);
- if (rc == Error_Succeed)
- Dbg("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());
- }
- TokenService_SetSharedSK_Req req2 = {};
- req2.ssk = sharedSK;
- TokenService_SetSharedSK_Ans ans2 = {};
- rc = pTokenServiceClient->SetSharedSK(req2, ans2, 5000);
- if (rc == Error_Succeed)
- Dbg("save shared session key succ");
- else
- {
- 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());
- }
- pTokenServiceClient->GetFunction()->CloseSession();
- }
- return rc;
- }
- bool CAccessAuthEntity::HasPinPad()
- {
- CSimpleStringA strErrMsg;
- CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
- //oilyang@20210514
- if (!IsMachineTypeConfigurePinPad(m_info.strMachineType))
- {
- Dbg("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)
- {
- Dbg("connect PinPad fail, assume no pinpad");
- 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 = {};
- auto rc = pPinPadClient->GetDevInfo(req, ans, DEFUALT_INVOKE_PINPAD_TIMEOUT);
- if (rc != Error_Succeed)
- {
- strErrMsg = "PinPad::GetDevInfo() fail";
- SetAuthErrMsg((const char *)strErrMsg);
-
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_FROM_PINPAD,
- GetOutPutStr("%s%08X", "来自pinpad的错误", rc).c_str(), strErrMsg.GetData());
- }
- else
- {
- Dbg("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()
- {
- 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, DEFUALT_INVOKE_PINPAD_TIMEOUT);
- if (rc == Error_Succeed)
- {
- nCapability = ans.reserved1;
- Dbg("QueryFunc from pinpad succ, nCapability[%d]", nCapability);
- }
- else
- {
- 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());
- }
- 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());
- pPinPad->SafeDelete();
- }
- return nCapability;
- }
- void CAccessAuthEntity::printPasswdError(){
- string strErrMsg = "密钥集丢失,请重新初始化密钥!";
- SetAuthErrMsg(strErrMsg.c_str());
- GetFunction()->SetSysVar("AuthErrMsg", strErrMsg.c_str(), true);
- m_FSM.doWarnMsg( ERROR_ACCESSAUTH_OPENCRYPTCONTEXT, strErrMsg.c_str(),true, strErrMsg);
- }
- 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)
- {
- LOG_FUNCTION();
- //m_nAuthVersion = nAuthVer;
- memset(m_AuthSessionKey, 0, 140);
- CSimpleString runInfoPath, iniPath;
- auto rc = GetFunction()->GetPath("runinfo", runInfoPath);
- if (rc != Error_Succeed) {
- Dbg("GetPath runinfo error=%d.", rc);
- return false;
- }
- char privateKey[BUF_SIZE] = { 0 };
- iniPath = runInfoPath + SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR "AccessAuthorization.ini";
- //runInfoPath += SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR "Initializer.ini";
- #ifdef RVC_OS_WIN
- GetPrivateProfileString("TerminalPD", "PrivateKey", "", privateKey, BUF_SIZE, runInfoPath.GetData());
- #else
- Dbg("path ex:%s", iniPath.GetData());
- char* tmp = inifile_read_str(iniPath.GetData(), "TerminalPD", "PrivateKey", "");
- strcpy(privateKey, tmp);
- delete tmp;
- #endif // RVC_OS_WIN
- if (strlen(privateKey) <= 0) {
- 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;
- if (strlen(privateKey) <= 0)
- {
- printPasswdError();
- return false;
- }
- }
- Dbg("privateKey=%s,%d", privateKey, strlen(privateKey));
- int decodedPrivateKeyLen;
- char* pDecodedPrivateKey = Hex2Str(privateKey, decodedPrivateKeyLen);
- Dbg("decodedPrivateKeyLen=%d", decodedPrivateKeyLen);
- char pDecryptPrivateKey[BUF_SIZE] = { 0 };
- int decryprtLen = BUF_SIZE;
- if (!DecWithSM4_ECB("s5da69gnh4!963@6s5da69gnh4!963@6", (BYTE*)pDecodedPrivateKey, decodedPrivateKeyLen, (BYTE*)pDecryptPrivateKey, &decryprtLen)) {
- Dbg("DecWithSM4_ECB decrypt privateKey error.");
- printPasswdError();
- delete[] pDecodedPrivateKey;
- return false;
- }
- delete[] pDecodedPrivateKey;
- //添加调试信息
- char* pEncPriKey = Str2Hex((char*)pDecryptPrivateKey, decryprtLen);
- Dbg("DecWithSM4_ECB succeess.privateKey=%s", pEncPriKey);
- delete pEncPriKey;
- char pPlainKey[KEY_SIZE];
- int plainKeyLen = KEY_SIZE;
- char pKeyLen[4] = { 0 };
- memcpy(pKeyLen, pKey, 4);
- int kenLen = Char2Int(pKeyLen);
- Dbg("kenLen=%d", kenLen);
- char* pEncodeKey = Str2Hex((char*)pKey, kenLen + 4);
- Dbg("pEncodeKey=%s", pEncodeKey);
- 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)) {
- Dbg("使用私钥解密失败!");
- printPasswdError();
- return false;
- }
- Dbg("使用私钥解密成功");
- if (plainKeyLen != KEY_SIZE) {
- Dbg("私钥解密后的会话密钥长度不等于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();
- //assert(m_nAuthVersion ==2);
- //这里不需要delete,由CBlob析构函数去执行
- BYTE* pEncData = new BYTE[1024];
- int pEncDataSize = 1024;
- Dbg("pEncDataSize=%d", pEncDataSize);
- char* pPlainInfo = Str2Hex((char*)raw.m_pData, raw.m_iLength);
- Dbg("raw data=%s,raw.m_iLength=%d", pPlainInfo, raw.m_iLength);
- delete[] pPlainInfo;
-
- //char *sessionKey = Str2Hex((char*)m_AuthSessionKey, KEY_SIZE);
- char sessionKey[KEY_SIZE] = { 0 };
- memcpy(sessionKey,m_AuthSessionKey,KEY_SIZE);
- char* tmpKey = Str2Hex((char*)m_AuthSessionKey, KEY_SIZE);
- Dbg("sessionKey=%s", tmpKey);
- delete[] tmpKey;
- if (!EncWithSM4_ECB((BYTE*)sessionKey, (BYTE*)(raw.m_pData), raw.m_iLength, pEncData, &pEncDataSize)) {
- Dbg("会话密钥加密准入信息失败!");
- return Error_Unexpect;
- }
-
- enc.Attach(pEncData,pEncDataSize);
- char* tmp = Str2Hex((char*)pEncData, pEncDataSize);
- Dbg("pEncData=%s,%d", tmp, pEncDataSize);
- delete[] tmp;
- tmp = Str2Hex((char*)enc.m_pData, enc.m_iLength);
- Dbg("EncWithSM4_ECB data=%s,%d", tmp, enc.m_iLength);
- delete[] tmp;
-
- return Error_Succeed;
- }
- bool CAccessAuthEntity::GetMD5Hash(const char *pStr, BYTE md5[16])
- {
- return false;
- }
- 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)
- {
- char szTmp[1024] = {};
- string strTmp;
- int nTmpBufLen = 1024;
- CSimpleStringA strErrMsg;
- CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
- CSimpleStringA strRet;
- #ifdef RVC_OS_WIN
- if (!QueryWMIDevice(Processor, "ProcessorId", szTmp, &nTmpBufLen))
- #else
- CSimpleStringA runInfoPath;
- auto rc = GetFunction()->GetPath("runinfo", runInfoPath);
- if (rc != Error_Succeed) {
- Dbg("GetPath runinfo error=%d.", rc);
- return false;
- }
- runInfoPath += SPLIT_SLASH_STR "runcfg";
- if (!get_cpu_id_by_system(strTmp, runInfoPath.GetData()))
- #endif // RVC_OS_WIN
- {
- strErrMsg = CSimpleStringA::Format("查询CPU ID失败,请重启机器并重新初始化");
- SetAuthErrMsg((const char *)strErrMsg);
-
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_GET_TERMINAL_FINGERPRINT,
- GetOutPutStr("%s%s", "Processor", "False").c_str());
- return false;
- }
-
- #ifdef RVC_OS_WIN
- strRet = szTmp;
- nTmpBufLen = 1024;
- memset(szTmp, 0, sizeof(szTmp));
- if (!QueryWMIDevice(BaseBoard, "SerialNumber", szTmp, &nTmpBufLen))
- #else
- Dbg("cpu id: %s", strTmp.c_str());
- strRet = strTmp.c_str();
- strTmp.clear();
- if (!get_board_serial_by_system(strTmp, runInfoPath.GetData()))
- #endif // RVC_OS_WIN
- {
- strErrMsg = CSimpleStringA::Format("查询主板序列号失败, 请重启机器并重新初始化");
- SetAuthErrMsg((const char *)strErrMsg);
-
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_GET_TERMINAL_FINGERPRINT,
- GetOutPutStr("%s%s", "BaseBoard", "False").c_str());
- return false;
- }
- strRet += "|";
- #ifdef RVC_OS_WIN
- strRet += szTmp;
- nTmpBufLen = 1024;
- memset(szTmp, 0, sizeof(szTmp));
- if (!QueryWMIDevice(DiskDrive, "SerialNumber", szTmp, &nTmpBufLen))
- #else
- Dbg("baseboard sn: %s", strTmp.c_str());
- strRet += strTmp.c_str();
- vector<string> disk;
- int errCode = 0;
- if (!get_disk_serial_by_system(disk, errCode, runInfoPath.GetData()))
- #endif // RVC_OS_WIN
- {
- Dbg("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 += "|";
- #ifdef RVC_OS_WIN
- strRet += szTmp;
- #else
- strTmp = "";
- vector<string>::iterator it = disk.begin();
- while (it != disk.end()) {
- strTmp += *it;
- it++;
- }
- Dbg("harddisk sn: %s", strTmp.c_str());
- strRet += strTmp.c_str();
- #endif // RVC_OS_WIN
- Dbg("device info: [%s]", (const char*)strRet);
- BYTE sm3[32] = { 0 };
- if(!SM3Hash(reinterpret_cast<BYTE*>(const_cast<char*>(strRet.GetData())),strRet.GetLength(),sm3))
- {
- 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;
- }
- if (nBufLen < 32)
- {
- //Dbg("buf len is too small");
- m_FSM.doWarnMsg(ERROR_ACCESSAUTH_GETSM3HASH, "buf len is too small fail");
- return false;
- }
- nBufLen = 32;
- memcpy(pBuf, sm3, nBufLen);
- char *pszSM3 = ConvertBytesToHexStr(sm3, nBufLen);
- Dbg("fringerprint: [%s]", pszSM3);
- free(pszSM3);
- return true;
- }
- // 生成SM2密钥对,并导出公钥
- bool CAccessAuthEntity::GetTerminalPublicKey(BYTE *pBuf, int &nBufLen)
- {
- CSimpleString runInfoPath, iniPath;
- auto rc = GetFunction()->GetPath("runinfo", runInfoPath);
- if (rc != Error_Succeed) {
- Dbg("GetPath runinfo error=%d.", rc);
- return false;
- }
- iniPath = runInfoPath + SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR "AccessAuthorization.ini";
- //runInfoPath += SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR "Initializer.ini";
- char publicKey[BUF_SIZE] = { 0 };
-
- #ifdef RVC_OS_WIN
- GetPrivateProfileString("TerminalPD", "PublicKey", "", publicKey, BUF_SIZE, runInfoPath.GetData());
- #else
- char* tmp = inifile_read_str(iniPath.GetData(), "TerminalPD", "PublicKey", "");
- strcpy(publicKey, tmp);
- delete tmp;
- #endif // RVC_OS_WIN
- if (strlen(publicKey) <= 0) {
- 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;
- if (strlen(publicKey) <= 0)
- {
- Dbg("读取公钥失败,公钥长度小于等于零!");
- printPasswdError();
- return false;
- }
- }
- Dbg("publickey=%s,%d",publicKey,strlen(publicKey));
-
- char* pDecodedPublickey = Hex2Str(publicKey,nBufLen);
- Dbg("pDecodedPublickey=[%s],len=%d", pDecodedPublickey, nBufLen);
- memcpy(pBuf, pDecodedPublickey, nBufLen);
- Dbg("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) {
- Dbg("GetPath runinfo error=%d.",rc);
- return false;
- }
- runInfoPath += SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR;
- /*if (!boost::filesystem::exists(runInfoPath.GetData())) {
- boost::filesystem::create_directories(runInfoPath.GetData());
- }*/
- #ifdef RVC_OS_WIN
- DWORD dwAttr = GetFileAttributes(runInfoPath.GetData());
- if (dwAttr == 0xFFFFFFFF) //目录不存在则创建
- {
- if (!CreateDirectory(runInfoPath.GetData(), NULL))
- #else
- if(!dir_is_exist(runInfoPath.GetData()))
- {
- if(dir_create(runInfoPath.GetData()) != 0)
- #endif
- {
- Dbg("Create %s dir failed!", runInfoPath.GetData());
- }
- }
- Dbg("Dir=%s", runInfoPath.GetData());
- //CSimpleString runFile = runInfoPath + GetEntityName();
- CSmartPointer<IConfigInfo> pConfig;
- rc = GetFunction()->OpenConfig(Config_Run, pConfig);
- if (rc != Error_Succeed) {
- Dbg("OpenConfig Config_Run error=%d.", rc);
- return false;
- }
- CSimpleString publicKey;
- rc = pConfig->ReadConfigValue("TerminalPD","PublicKey",publicKey);
- if (rc != Error_Succeed || publicKey.IsNullOrEmpty()) {
- Dbg("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)) {
- Dbg("Create SM2 key pair error.");
- return false;
- }
- Dbg("iPublicKeyLen=%d,iPrivateKeyLen=%d", iPublicKeyLen, iPrivateKeyLen);
- Dbg("[btPublicKey=%s]", (char*)btPublicKey);
-
- char* pEncode = Str2Hex((char*)btPublicKey,iPublicKeyLen);
- Dbg("pEncode=%s,%d", pEncode,strlen(pEncode));
- //尝试解码
- /*int pDecodeLen = 0;
- char* pDecode = Hex2Str(pEncode,pDecodeLen);
- Dbg("pDecode=%s", pDecode);
- Dbg("pDecodeLen=%d", pDecodeLen);
- char *ret = Str2Hex(pDecode, pDecodeLen);
- Dbg("ret=%s,%d", ret, strlen(ret));
-
- if (strcmp(ret, pEncode)!=0) {
-
- Dbg("No");
- return false;
- }
- Dbg("Yes");
- delete[] pDecode;
- delete[] ret;*/
- rc = pConfig->WriteConfigValue("TerminalPD", "PublicKey", pEncode);
- assert(rc == Error_Succeed);
- pubkey = pEncode;
- Dbg("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)) {
- Dbg("sm4 crypt privateKey error.");
- rc = pConfig->WriteConfigValue("TerminalPD", "PublicKey", "");
- delete[] pEncode;
- return false;
- }
-
- Dbg("sm4 encrypt pri key success.");
- Dbg("cryptPrivateKeyLen=%d", cryptPrivateKeyLen);
-
- char* pEncodedCryptPrivateKey = Str2Hex((char*)pCryptPrivateKey, cryptPrivateKeyLen);
- Dbg("encode pri key success.");
- rc = pConfig->WriteConfigValue("TerminalPD", "PrivateKey", pEncodedCryptPrivateKey);
- if (rc != Error_Succeed) {
- rc = pConfig->WriteConfigValue("TerminalPD", "PublicKey", "");
- delete[] pEncodedCryptPrivateKey;
- return false;
- }
- Dbg("write pri key success.");
- publicKey = pEncode;
- delete[] pEncode;
- delete[] pEncodedCryptPrivateKey;
- }
- else
- {
- pubkey = publicKey;
- }
- Dbg("PublicKey: %s(%d)", publicKey.GetData(), publicKey.GetLength());
- char *pDecode = Hex2Str(publicKey.GetData(),nBufLen);
-
- memcpy(pBuf, pDecode, nBufLen);
- Dbg("pBuf[0]=%02X,nBufLen=%d", pBuf[0], nBufLen);
- return true;
- }
- DWORD CAccessAuthEntity::InitDevice(SpReqAnsContext<AccessAuthService_InitDev_Req, AccessAuthService_InitDev_Ans>::Pointer &ctx)
- {
- return m_FSM.InitDevice(ctx);
- }
- //oilyang@20210510 嵌入"bool CAccessAuthEntity::HasPinPad()"的逻辑
- // 返回1:只有PinPadID;2:只有DeviceID;3:两者都有;0:没有;-1表示失败
- int CAccessAuthEntity::GetPinPadIDAndDeviceID(CSimpleStringA &strPinPadID, CSimpleStringA &strDeviceID, bool& bHasPinPad)
- {
- bHasPinPad = 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, DEFUALT_INVOKE_PINPAD_TIMEOUT);
- if (rc == Error_Succeed) {
- if (ans.state == DEVICE_STATUS_NORMAL) {
- nRet = 0;
- Dbg("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];
- Dbg("strBluetoothID=%s", strBluetoothID);
- if (!strBluetoothID.IsNullOrEmpty())
- bBluetooth = true;
- }
- }
- }
- }
- }
- else
- {
- if (m_info.strMachineType.IsStartWith("RVC.PAD", true))
- bHasPinPad = false;
- Dbg("pinpad not exist, state: %d", ans.state);
- }
- }
- 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());
- }
- 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());
- pPinPadClient->SafeDelete();
- }
-
- 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;
- }
- bool CAccessAuthEntity::HasCkCodeFlg()
- {
- CSimpleStringA strErrMsg;
- CSmartPointer<IEntityFunction> spFunction = this->GetFunction();
- //oilyang@20210514
- if (!IsMachineTypeConfigurePinPad(m_info.strMachineType))
- {
- Dbg("MachineType is [%s], not exist pinpad entity", m_info.strMachineType);
- return false;
- }
-
- auto pPinPadClient = new PinPadService_ClientBase(this);
- bool bCheckCode = false;
- CSimpleStringA strSpeficiCM;
- if (pPinPadClient->Connect() == Error_Succeed)
- {
- PinPadService_GetDevInfo_Req req = {};
- PinPadService_GetDevInfo_Ans ans = {};
- auto rc = pPinPadClient->GetDevInfo(req, ans, DEFUALT_INVOKE_PINPAD_TIMEOUT);
- if (rc == Error_Succeed)
- {
- if (ans.state == DEVICE_STATUS_NORMAL)
- {
- Dbg("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(!strnicmp((LPCTSTR)arr2[0], "CM", strlen("CM")))
- {
- strSpeficiCM = arr2[1];
- if (strSpeficiCM.GetLength() > 3 && _strnicmp(strSpeficiCM, "V2.0", strlen("V2.0")) == 0)
- {
- //Support checkcode, then operate checkcode routine..
- bCheckCode = true;
- }
- }
- }
- }
- }
- }
- else
- {
- Dbg("pinpad not exist, state: %d", ans.state);
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_FROM_PINPAD,
- GetOutPutStr("%s%d", "密码键盘异常,请检查。ans.state", ans.state).c_str());
- }
- }
- else
- {
- strErrMsg = "调用PinPad实体(GetDevInfo)失败";
- SetAuthErrMsg((const char *)strErrMsg);
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_FROM_PINPAD,
- GetOutPutStr("%s%08X", "GetDevInfo", rc).c_str(), strErrMsg.GetData());
- }
- pPinPadClient->GetFunction()->CloseSession();
- }
- else
- {
- strErrMsg = "连接PinPad实体失败";
- SetAuthErrMsg((const char *)strErrMsg);
-
- m_FSM.doWarnMsg(ERR_ACCESSAUTH_CONNECT_PINPAD,
- GetOutPutStr("%s%s", "连接pinpad错误, strErrMsg", strErrMsg).c_str());
- pPinPadClient->SafeDelete();
- }
-
- pPinPadClient = NULL;
- return bCheckCode? true:false;
- }
- 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)
- {
- Dbg("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);
- Dbg("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);
- Dbg("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)))
- {
- Dbg("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))
- {
- Dbg("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);
- Dbg("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)
- {
- Dbg("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
- }
- int CAccessAuthEntity::ConvertStr2Byte(string input, BYTE* output, int outputLen) {
- if (input.size() > outputLen) return 1;
- for (int i = 0;i < input.size();i++) {
- output[i] = input[i];
- }
- return 0;
- }
- int CAccessAuthEntity::GetOrSetIsFirstSM(int type) {
- CSmartPointer<IConfigInfo> pConfig;
- int isFirst = 0;
- auto rc = GetFunction()->OpenConfig(Config_Run, pConfig);
- if (rc != Error_Succeed) {
- Dbg("OpenConfig Config_Run error=%d.", rc);
- return isFirst;
- }
- CSimpleStringA sIsFirst;
- if (type == 0) {
- return 0;//oilyang@20211208 这个逻辑没有存在的必要了
- rc = pConfig->ReadConfigValue("SM", "IsFirst", sIsFirst);
- if (rc != Error_Succeed || sIsFirst.IsNullOrEmpty()) {
- rc = pConfig->WriteConfigValue("SM", "IsFirst", "Yes");
- if (rc != Error_Succeed) {
- Dbg("WriteConfigValue Config_Run SM IsFirst error.");
- return isFirst;
- }
- isFirst = 1;
- }
- else if (sIsFirst == "Yes") {
- isFirst = 1;
- }
- else
- isFirst = 0;
- return isFirst;
- }
- else {
- rc = pConfig->WriteConfigValue("SM", "IsFirst", "No");
- if (rc != Error_Succeed) {
- Dbg("WriteConfigValue Config_Run SM IsFirst error.");
- return isFirst;
- } else {
- isFirst = 1;
- }
- return isFirst;
- }
- }
- bool CAccessAuthEntity::IsMachineTypeConfigurePinPad(CSimpleStringA strMachineType)
- {
- // 回单打印机、卡库、简化版
- if (strMachineType.IsStartWith("RPM", true) || strMachineType.IsStartWith("RVC.CardStore", true)
- || strMachineType.IsStartWith("RVC.IL", true))
- {
- return false;
- }
- else
- return true;
- }
- 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).setAPI("BeginInitMKACS")("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).setAPI("BeginLoginACS")("get InitUrl=%s from CenterSetting.ini", m_strInitUrl.GetData());
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("BeginLoginACS")("get InitUrl from CenterSetting.ini failed");
- return;
- }
- }
- CSmartPointer<InitializerInitMKTask> initUpdateWKTask = new InitializerInitMKTask(&this->m_FSM, this);
- GetFunction()->PostThreadPoolTask(initUpdateWKTask.GetRawPointer());
- }
- ErrorCodeEnum CAccessAuthEntity::LoadKeysToPinPadACS(string TMK, string TPK, string EDK, string index)
- {
- LOG_FUNCTION();
- //获取私钥
- CSmartPointer<IConfigInfo> pConfigRun;
- auto rc = GetFunction()->OpenConfig(Config_Run, pConfigRun);
- if (rc != Error_Succeed) {
- Dbg("OpenConfig Config_Run error=%d.", rc);
- return Error_Unexpect;
- }
- CSimpleStringA csPrivateKey("");
- pConfigRun->ReadConfigValue("TerminalPD", "PrivateKey", csPrivateKey);
- Dbg("privateKey len:%d", csPrivateKey.GetLength());
- int decodedPrivateKeyLen;
- char* pDecodedPrivateKey = Hex2Str(csPrivateKey.GetData(), decodedPrivateKeyLen);
- Dbg("decodedPrivateKeyLen=%d", decodedPrivateKeyLen);
- char pDecryptPrivateKey[BUF_SIZE] = { 0 };
- int decryprtLen = BUF_SIZE;
- if (!DecWithSM4_ECB("s5da69gnh4!963@6s5da69gnh4!963@6", (BYTE*)pDecodedPrivateKey, decodedPrivateKeyLen, (BYTE*)pDecryptPrivateKey, &decryprtLen)) {
- Dbg("DecWithSM4_ECB decrypt privateKey error.");
- delete[] pDecodedPrivateKey;
- return Error_Unexpect;
- }
- delete[] pDecodedPrivateKey;
- Dbg("DecWithSM4_ECB succeess.len:%d.", decryprtLen);
- char pPlainTMK[BUF_SIZE], pPlainTPK[BUF_SIZE], pPlainEDK[BUF_SIZE];
- memset(pPlainTMK, 0, BUF_SIZE);
- memset(pPlainTPK, 0, BUF_SIZE);
- memset(pPlainEDK, 0, BUF_SIZE);
- int plainKeyLen = BUF_SIZE;
- char* pxx = new char[1024];
- memset(pxx, 0, 1024);
- HexBuf2StrBuf((BYTE*)pDecryptPrivateKey, &pxx, decryprtLen);
- PBYTE pBt = new BYTE[512];
- memset(pBt, 0, 512);
- StrBuf2HexBuf(TMK.c_str(), &pBt);
- if (!DecWithSM2PriKey(pBt, TMK.size() / 2, (BYTE*)pPlainTMK, &plainKeyLen, (BYTE*)pDecryptPrivateKey, decryprtLen)) {
- Dbg("使用私钥解密TMK失败!");
- return Error_Unexpect;
- }
- //char* pEncodeTPK = MyBase64::Str2Hex(TPK.c_str(), TPK.size());
- PBYTE pTPK = new BYTE[512];
- memset(pTPK, 0, 512);
- int len = StrBuf2HexBuf(TPK.c_str(), &pTPK);
- plainKeyLen = BUF_SIZE;
- Dbg("001,len:%d", len);
- if (!DecWithSM2PriKey(pTPK, TPK.size() / 2, (BYTE*)pPlainTPK, &plainKeyLen, (BYTE*)pDecryptPrivateKey, decryprtLen)) {
- Dbg("使用私钥解密TPK失败!");
- //delete[]pEncodeTPK;
- return Error_Unexpect;
- }
- //char* pEncodeEDK = MyBase64::Str2Hex(EDK.c_str(), EDK.size());
- PBYTE pEDK = new BYTE[512];
- memset(pEDK, 0, 512);
- StrBuf2HexBuf(EDK.c_str(), &pEDK);
- plainKeyLen = BUF_SIZE;
- if (!DecWithSM2PriKey(pEDK, EDK.size() / 2, (BYTE*)pPlainEDK, &plainKeyLen, (BYTE*)pDecryptPrivateKey, decryprtLen)) {
- Dbg("使用私钥解密EDK失败!");
- //delete[]pEncodeEDK;
- return Error_Unexpect;
- }
- Dbg("解密秘钥成功");
- //加载到密码键盘
- Dbg("load sm key to pinpad...");
- PinPadService_ClientBase* pPinPad = new PinPadService_ClientBase(this);
- rc = pPinPad->Connect();
- if (rc == Error_Succeed)
- {
- PinPadService_LoadKeysSM_Req req = {};
- req.initializeflag = true;
- req.smflag = 1;
- Dbg("使用云接口获取的KMC密钥");
- req.masterkey = pPlainTMK;
- req.workingkey1 = pPlainTPK;
- req.workingkey2 = pPlainEDK;
- req.reserved3 = index.c_str();
- if (req.initializeflag) Dbg("initializeflag is true");
- else Dbg("initializeflag is false");
- Dbg("req.smflag=%d", req.smflag);
- Dbg("req.masterkey=%s", req.masterkey.GetData());
- Dbg("req.workingkey1=%s", req.workingkey1.GetData());
- Dbg("req.workingkey2=%s", req.workingkey2.GetData());
- Dbg("req.reserved3=%s", req.reserved3.GetData());
- PinPadService_LoadKeysSM_Ans ans = {};
- rc = pPinPad->LoadKeysSM(req, ans, 30000);
- if (rc == Error_Succeed)
- Dbg("load sm key to pinpad succ");
- else
- {
- Dbg("load sm key to pinpad failed.");
- return Error_Unexpect;
- //SetAuthErrMsg("加载SM密钥到PinPad失败");
- //doWarnMsg(ERR_INITIALIZER_LOAD_KEYS_TO_PINPAD,
- // GetOutPutStr("%s%08x%s%s", "LoadKeys", rc, "strErrMsg", "加载SM密钥到PinPad失败").c_str());
- //rc = ERR_INITIALIZER_LOAD_KEYS_TO_PINPAD;
- }
- pPinPad->GetFunction()->CloseSession();
- }
- else
- {
- Dbg("oiltest connect to pinpad failed.");
- return Error_Unexpect;
- }
- return Error_Succeed;
- }
- bool CAccessAuthEntity::SendInitMKReqACS(CInitlizerMKReq& initMKReq)
- {
- LOG_FUNCTION();
- CSmartPointer<IEntityFunction> pFunc = GetFunction();
- //auto pEntity = ((CInitializerEntity*)m_pEntity);
- // 如果有外置PinPad,则需要初始化主密钥
- 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();
- Dbg("pinpad capability: %d", nCapability);
- //gui console中,用户桌面,蓝牙多合一绑定时的初始化会重置kmc密钥,自动初始化不会重置密钥,自动初始化的目的仅用在非国密
- //版本到国密版本的升级无缝切换
- //if (m_bHandWork && !m_afterSMIsFirst) {
- if (false) {//oiltest@20211113
- Dbg("初始化开始重置密钥。。。");
- if (nCapability == 1 || nCapability == 3)
- {
- // support des key
- initMKReq.MKD_REQ2.branchNo = strSubBankNo;
- initMKReq.MKD_REQ2.subBankNo = strBranchNo;
- }
- if (nCapability == 2 || nCapability == 3)
- {
- // support sm key
- initMKReq.MKD_SMR2.branchNo = strSubBankNo;
- initMKReq.MKD_SMR2.subBankNo = strBranchNo;
- }
- }
- }
- else
- {
- Dbg("has no pinpad, not need init MK");
- }
- bool bHasPinPad = false;
- CSimpleStringA strPinPadID = "", strDeviceID = "";
- int nRet = GetPinPadIDAndDeviceID(strPinPadID, strDeviceID, bHasPinPad);
- Dbg("GetPinPadIDAndDeviceID ret: %d, PinPadID: %s, DeviceID: %s", nRet, (const char*)strPinPadID, (const char*)strDeviceID);
- // 从系统获取设备信息和硬件信息
- // 变长结构初始化
- char buf2[512];
- memset(buf2, 0, 512);
- CSystemStaticInfo si;
- pFunc->GetSystemStaticInfo(si);
- initMKReq.MKD_NEW1.terminalNo = si.strTerminalID;
- initMKReq.MKD_NEW1.installVersion = si.InstallVersion.ToString();
- if (nRet == 2 || nRet == 3) {
- initMKReq.MKD_NEW1.padDeviceID = strDeviceID;
- }
- initMKReq.MKD_NEW1.machineType = si.strMachineType;
- initMKReq.MKD_NEW1.site = si.strSite;
- BYTE xIP[64] = {};
- #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];
- 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.MKD_NEW1.ip = xIP;
- Dbg("ip:%s", xIP);
- }
- #else
- char ip[32] = { 0 };
- if (getIPFromLinux(ip)) Dbg("Get IP From Linux Error ex.");
- else {
- if (ip2byte(ip, xIP)) Dbg("Ip 2 Byte Error");
- else {
- for (int i = 0; i < 4; i++) {
- Dbg("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.MKD_NEW1.ip = strIP;
- }
- }
- #endif //RVC_OS_WIN
- initMKReq.MKD_NEW1.enrolGPS = "00000A4500000A4E";//oiltmp
- initMKReq.MKD_NEW1.enrolAddr = si.strEnrolAddr;
- initMKReq.MKD_REQ3[0]->modal = "";
- initMKReq.MKD_REQ3[0]->factory = "";
- initMKReq.MKD_REQ3[0]->type = "";
- initMKReq.MKD_REQ3[0]->version = "";
- 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;
- }
- string xFingerPrint = ConvertBytesToHexStr(fingerPrint, nBufLen);
- initMKReq.MKD_REQ4.fingerPrint = xFingerPrint.substr(0, 32);
- initMKReq.MKD_REQ4.fingerPrintSM = xFingerPrint.substr(32, 64);
- BYTE xPublicKey[148];
- nBufLen = sizeof(xPublicKey);
- Dbg("开始获取公钥。。。");
- memset(xPublicKey, 0, nBufLen);
- Dbg("nBufLen=%d", nBufLen);
- if (!GetTerminalPublicKey(xPublicKey, nBufLen, initMKReq.MKD_REQ4.publicKey))
- {
- LogWarn(Severity_Middle, Error_Unexpect, ERR_INITIALIZER_GET_TERMINAL_PUBKEY,
- GetOutPutStr("%s%s", "GetTerminalPublicKey", "False").c_str());
- return ERR_INITIALIZER_GET_TERMINAL_PUBKEY;
- }
- if (nRet == 1 || nRet == 3)
- //strncpy(req4.PinPadID, (const char*)strPinPadID, sizeof(req4.PinPadID) - 1);
- initMKReq.MKD_REQ4.pinPadID = strPinPadID;
- //国密改造
- initMKReq.MKD_REQ5.isFirstSM = GetOrSetIsFirstSM(0);
- initMKReq.MKD_REQ5.isSM = 1;
- Dbg("rinitMKReq.MKD_REQ5.isFirstSM=%d", initMKReq.MKD_REQ5.isFirstSM);
- return true;
- }
- void CAccessAuthEntity::EndInitMK(DWORD rc, const char *pszErrMsg)
- {
- LOG_FUNCTION();
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("EndInitMK")("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).setAPI("EndInitMK")("初始化成功。。。");
- }
- m_eErrNum = rc;
- bool bSuc = rc == Error_Succeed;
- // 通知UI窗口
- if (m_ctx != NULL) {
- Dbg("success");
- m_ctx->Ans.Errcode = rc;
- m_ctx->Ans.ErrMsg = m_strLastErrMsg;
- m_ctx->Answer(Error_Succeed);
- }
- }
- SP_BEGIN_ENTITY_MAP()
- SP_ENTITY(CAccessAuthEntity)
- SP_END_ENTITY_MAP()
|