Windows services 101 (2004)

40
Windows Services Windows Services 101 101 Vatroslav Mihalj Vatroslav Mihalj 2004. 2004.

Transcript of Windows services 101 (2004)

Page 1: Windows services 101 (2004)

Windows Services 101Windows Services 101

Vatroslav MihaljVatroslav Mihalj

2004.2004.

Page 2: Windows services 101 (2004)

What is Windows Service?What is Windows Service?

application that conforms to the application that conforms to the interface rules of SCMinterface rules of SCM

can be started automatically at can be started automatically at system boot, by a user through the system boot, by a user through the Services control panel applet, or by Services control panel applet, or by an app that uses service functionsan app that uses service functions

can execute even when no user is can execute even when no user is logged on to the system.logged on to the system.

Page 3: Windows services 101 (2004)

driver servicedriver service – conforms to the device driver conforms to the device driver

protocolsprotocols– similar to a service app, but it does similar to a service app, but it does

not interact with the SCMnot interact with the SCM filename extension is .EXE for filename extension is .EXE for

services and .SYS for driver services and .SYS for driver servicesservices

Page 4: Windows services 101 (2004)

Operating Windows Operating Windows ServicesServices

3 types of programs use functions 3 types of programs use functions provided by SCM, i.e. are provided by SCM, i.e. are neccessary to operate a WS:neccessary to operate a WS:– sservice programervice program– sservice configuration programervice configuration program– sservice control programervice control program

Page 5: Windows services 101 (2004)

sservice programervice program– provides the actual functionality we are provides the actual functionality we are

looking for (for one or more services)looking for (for one or more services)

– use functions that connect to the SCM and use functions that connect to the SCM and send status information to the SCMsend status information to the SCM

sservice configuration programervice configuration program– queries/modifies services DB (install or queries/modifies services DB (install or

delete services, query/modify config and delete services, query/modify config and security params)security params)

sservice control programervice control program– sending control requests to SCM (start, stop, sending control requests to SCM (start, stop,

pause/continue) - which carries out the pause/continue) - which carries out the requestrequest

– net.exenet.exe, , sc.exesc.exe, VS.NET Server Explorer, VS.NET Server Explorer

Page 6: Windows services 101 (2004)

What is What is SMC (SMC (Service Service Control ManagerControl Manager))

maintains a database of installed services maintains a database of installed services and driver services ("services" from now on)and driver services ("services" from now on)– database includes information on how each database includes information on how each

service or driver service should be startedservice or driver service should be started provides a unified and secure means of provides a unified and secure means of

controlling themcontrolling them– RPC server, so service configuration and service RPC server, so service configuration and service

control programs can manipulate services on control programs can manipulate services on remote machinesremote machines

enables admins to customize security enables admins to customize security requirements for each service and thereby requirements for each service and thereby control access to the servicecontrol access to the service

Page 7: Windows services 101 (2004)

Service databaseService database used by the SCM and used by the SCM and

programs that add, modify, or programs that add, modify, or configure servicesconfigure services

HKEY_LOCAL_MACHINE\SYSTEM\HKEY_LOCAL_MACHINE\SYSTEM\

CurrentControlSet\ServicesCurrentControlSet\Services

subkey for each installed subkey for each installed serviceservice– name of the subkey is service name of the subkey is service

namename» specified by specified by CreateServiceCreateService

function when service was installed function when service was installed by a service configuration programby a service configuration program

Page 8: Windows services 101 (2004)

database includes:database includes:– service type (own process or shares a service type (own process or shares a

process with other services, kernel process with other services, kernel driver or a file system driver)driver or a file system driver)

Page 9: Windows services 101 (2004)

– start type (automatic, manual, disabled)start type (automatic, manual, disabled)– error control level error control level

» severity of error if svc fails to start, severity of error if svc fails to start, determines action that startup program will determines action that startup program will taketake

– fully qualified path of the executablefully qualified path of the executable– optional dependency infooptional dependency info

» list of services that SCM must start before it list of services that SCM must start before it can start the specified servicecan start the specified service

– optional account name and passwordoptional account name and password» no account specified: executes in context of no account specified: executes in context of LocalSystemLocalSystem account account

– for driver svc, optional driver object for driver svc, optional driver object name, used by the I/O system to load name, used by the I/O system to load the device driverthe device driver

Page 10: Windows services 101 (2004)

after successful boot, system after successful boot, system saves a clone of the database in saves a clone of the database in the last-known-good (LKG) the last-known-good (LKG) configurationconfiguration– If an auto-start service with a If an auto-start service with a

SERVICE_ERROR_CRITICAL error SERVICE_ERROR_CRITICAL error control level fails to start, the SCM control level fails to start, the SCM reboots the machine using the LKG reboots the machine using the LKG configurationconfiguration

Page 11: Windows services 101 (2004)

Stopping the serviceStopping the service

with the Services control panel utilitywith the Services control panel utility ControlServiceControlService function function

– SERVICE_CONTROL_STOPSERVICE_CONTROL_STOP request to the request to the service through SCMservice through SCM

– if other running services are dependent if other running services are dependent on this one, SCM doesn't forward stop on this one, SCM doesn't forward stop requestrequest» instead, it returns instead, it returns ERROR_DEPENDENT_SERVICES_RUNNINGERROR_DEPENDENT_SERVICES_RUNNING

» you need to enumerate and stop dependent you need to enumerate and stop dependent servicesservices

Page 12: Windows services 101 (2004)

"Common" apps as "Common" apps as servicesservices

no need to recode all apps as servicesno need to recode all apps as services Windows 2000/2003 Resource Kit Windows 2000/2003 Resource Kit

tools: tools: srvany.exesrvany.exe, , instsrv.exeinstsrv.exe NO INTERACTION!NO INTERACTION!

instsrv ServiceAnyApp instsrv ServiceAnyApp <path>\<path>\srvany.exesrvany.exe

instsrv ServiceAnyApp instsrv ServiceAnyApp <path>\<path>\srvany.exe srvany.exe

-a MYDOMAIN\auser -p My1Password-a MYDOMAIN\auser -p My1Password

((instsrv MyService Removeinstsrv MyService Remove))

Page 13: Windows services 101 (2004)

Some Registry keys need to be Some Registry keys need to be added:added:– Open Open HKLMHKLM\SYSTEM\CurrentControlSet\\SYSTEM\CurrentControlSet\Services\Services\<<service nameservice name>>\\

– aadd dd kkeyey» KKey Name: ey Name: ""ParametersParameters""» Class : <leave Class : <leave blank>blank>

– Select the Parameters keySelect the Parameters key, , Add ValueAdd Value» Value Name: ApplicationValue Name: Application» Data Type : REG_SZData Type : REG_SZ» String : <path>\<application.ext>String : <path>\<application.ext>» optional "AppParameters" and optional "AppParameters" and

"AppDirectory" (REG_SZ)"AppDirectory" (REG_SZ)

Page 14: Windows services 101 (2004)

srvanysrvany//instsrvinstsrv info info

MS:MS:http://support.microsoft.com/http://support.microsoft.com/default.aspx?scid=kb;en-us;137890default.aspx?scid=kb;en-us;137890

info & help (in German), will info & help (in German), will create .BAT and .REG file with create .BAT and .REG file with neccessary params:neccessary params:

http://www.rz.uni-freiburg.dehttp://www.rz.uni-freiburg.de

/pc/sys/srvany/index.php/pc/sys/srvany/index.php

Page 15: Windows services 101 (2004)

Service programsService programs when service control program requests when service control program requests

the service to run, SCM starts the service:the service to run, SCM starts the service:– sends start request to control dispatchersends start request to control dispatcher

» CD - special function executed by a separate thread CD - special function executed by a separate thread which needs to initialize the service structureswhich needs to initialize the service structures

» does not return until there is an error or all of the does not return until there is an error or all of the services in the process have terminatedservices in the process have terminated

» when all svcs in a process have terminated, SCM when all svcs in a process have terminated, SCM sends a control request to dispatcher thread to shut sends a control request to dispatcher thread to shut downdown

– control dispatcher creates a new thread to control dispatcher creates a new thread to execute execute ServiceMainServiceMain

– ServiceMainServiceMain - starting place for the job the - starting place for the job the service needs to doservice needs to do

Page 16: Windows services 101 (2004)
Page 17: Windows services 101 (2004)

Starting a serviceStarting a service Perform initialization (if <1 sec can be Perform initialization (if <1 sec can be

done within done within ServiceMainServiceMain)) init time ("pending" state) <=30s init time ("pending" state) <=30s

total!total!– use use SetServiceStatusSetServiceStatus function function,, with with

SERVICE_START_PENDINGSERVICE_START_PENDING– as init continues, service should make as init continues, service should make

additional calls to additional calls to SetServiceStatusSetServiceStatus to to report progressreport progress

init complete: call init complete: call SetServiceStatusSetServiceStatus, , with SERVICE_RUNNING with SERVICE_RUNNING

Page 18: Windows services 101 (2004)

Service Control HandlerService Control Handler

invoked by the control dispatcher invoked by the control dispatcher when the service process receives when the service process receives a control request from a service a control request from a service control programcontrol program

whenever SCH invoked, service whenever SCH invoked, service must call must call SetServiceStatusSetServiceStatus to to report status to SCM, regardless of report status to SCM, regardless of whether the status changedwhether the status changed

Page 19: Windows services 101 (2004)

service control program can send service control program can send control requests using control requests using ControlService ControlService

control handler must return within control handler must return within 30 sec, or SCM will return an error30 sec, or SCM will return an error– lengthy processing: create a lengthy processing: create a

secondary thread to perform secondary thread to perform processing, then returnprocessing, then return

service name != display name (in service name != display name (in the Service control panel)the Service control panel)

Page 20: Windows services 101 (2004)

System sSystem shutdownhutdown

by default, after by default, after received received SERVICE_CONTROL_SHUTDOWN, SERVICE_CONTROL_SHUTDOWN, ~20 sec to perform cleanup task~20 sec to perform cleanup taskss

after this expires, shutdown after this expires, shutdown proceeds regardless of whether proceeds regardless of whether service shutdown is service shutdown is completecomplete

Page 21: Windows services 101 (2004)

need more time to clean up?need more time to clean up?– send STOP_PENDING status messages, send STOP_PENDING status messages,

along with a wait hintalong with a wait hint» so service controller knows how long to wait so service controller knows how long to wait

before reporting that svc shutdown is before reporting that svc shutdown is completecomplete

– there is a limit to how long the service there is a limit to how long the service controller will waitcontroller will wait» To change this time limit, modify To change this time limit, modify WaitToKillServiceTimeoutWaitToKillServiceTimeout in in HKLM\HKLM\SYSTEM\CurrentControlSet\ControlSYSTEM\CurrentControlSet\Control

Page 22: Windows services 101 (2004)

Service User AccountsService User Accounts

LocalServiceLocalService Account Account– minimum privileges on the local computer, minimum privileges on the local computer,

anonymous credentials on the networkanonymous credentials on the network– does not have a passworddoes not have a password

NetworkServiceNetworkService Account Account– minimum privileges on the local computer minimum privileges on the local computer

and acts as the computer on the networkand acts as the computer on the network– does not have a passworddoes not have a password– remote token contains SIDs for the remote token contains SIDs for the EveryoneEveryone

and and Authenticated UsersAuthenticated Users groups groups

Page 23: Windows services 101 (2004)

LocalSystemLocalSystem Account Account– extensive privileges on the local extensive privileges on the local

computer, acts as the computer on computer, acts as the computer on the networkthe network

– does not have a passworddoes not have a password– inherits the security context of the inherits the security context of the

SCMSCM

Page 24: Windows services 101 (2004)

Interactive ServicesInteractive Services

each service has an associated each service has an associated ““window stationwindow station”” and and ““desktopdesktop””

only one window station, only one window station, Winsta0Winsta0 can be an interactivecan be an interactive

by default, window station the by default, window station the service uses is not interactive, so service uses is not interactive, so the service cannot display a user the service cannot display a user interfaceinterface

Page 25: Windows services 101 (2004)

interactive serviceinteractive service– running in the context of the running in the context of the LocalSystemLocalSystem account and has account and has SERVICE_INTERACTIVE_PROCESSSERVICE_INTERACTIVE_PROCESS attribute attribute» can be set by choosing Properties in can be set by choosing Properties in

Service control panel and checking “Allow Service control panel and checking “Allow service to interact with desktop”service to interact with desktop”

Page 26: Windows services 101 (2004)

dangerous practice!!!!dangerous practice!!!!– never open dialogs for services running never open dialogs for services running

on a server-nobody will answer this dialogon a server-nobody will answer this dialog better solution: separate GUI better solution: separate GUI

application running within the context application running within the context of the user session, IPC of the user session, IPC communicationcommunication– for hazarders: to display a msg box from for hazarders: to display a msg box from

a service, even if not running as a service, even if not running as LocalSystemLocalSystem or not configured to run or not configured to run interactively - call interactively - call MessageBoxMessageBox using using MB_SERVICE_NOTIFICATIONMB_SERVICE_NOTIFICATION» ““displays a message box on the current displays a message box on the current

active desktop, even if there is no user logged active desktop, even if there is no user logged on to the computer.”on to the computer.”

Page 27: Windows services 101 (2004)

Worker threadsWorker threads

start worker threads from the main start worker threads from the main thread and leave the main thread thread and leave the main thread free to answer the requestsfree to answer the requests

use use EventsEvents to notify the main to notify the main thread when worker thread starts thread when worker thread starts and finishesand finishes

job processing functions in worker job processing functions in worker threads can be started by firing threads can be started by firing custom message which are handled custom message which are handled by their message handlersby their message handlers

Page 28: Windows services 101 (2004)

when starting, SCM needs a certain when starting, SCM needs a certain amout of time to query status and amout of time to query status and stuffstuff– if an error occurs or the service can’t if an error occurs or the service can’t

connect to a server, don’t stop it connect to a server, don’t stop it immediately after it starts (i.e. exits immediately after it starts (i.e. exits start pending state) - let the main thread start pending state) - let the main thread sleep for a while (1 sec is enough)sleep for a while (1 sec is enough)» otherwise, an error will occur because SCM otherwise, an error will occur because SCM

might not detect that thread was started and might not detect that thread was started and immediately stopped and will write an error immediately stopped and will write an error in Event Log saying that the thread did not in Event Log saying that the thread did not enter the desired ("started") state - i.e. it enter the desired ("started") state - i.e. it didn't detect it because it was too “quick”didn't detect it because it was too “quick”

Page 29: Windows services 101 (2004)

when creating/opening a custom when creating/opening a custom log file, beware - the service starts log file, beware - the service starts in in %windir%\system32\%windir%\system32\ by default by default

don’t set service control level too don’t set service control level too high and startup type to auto high and startup type to auto unless you're absolutly sure – unless you're absolutly sure – system might get block while system might get block while bootingbooting

using Unicode is a good thing to using Unicode is a good thing to consider consider – but do not insist if it’s not neccessarybut do not insist if it’s not neccessary

Page 30: Windows services 101 (2004)

.NET.NET System.ServiceProcessSystem.ServiceProcess namespace namespace inherit from inherit from ServiceBaseServiceBase class to implement class to implement

a servicea service– registers the service and answers to start and stop registers the service and answers to start and stop

requestsrequests ServiceControllerServiceController class is used to class is used to

implement a service control programimplement a service control program– sends requests to servicessends requests to services– ServiceProcessInstallerServiceProcessInstaller and and ServiceInstallerServiceInstaller

classes install and configure service programsclasses install and configure service programs good sample: good sample: www.wrox.comwww.wrox.com, ", "Professional Professional

C#C#" code samples, ISBN 1861007043" code samples, ISBN 1861007043

Page 31: Windows services 101 (2004)

WMIWMI

service status can be obtained and controlled service status can be obtained and controlled through WMIthrough WMI– Win32_BaseServiceWin32_BaseService, , Win32_ServiceWin32_Service

Restart any automatic service that is stopped:Restart any automatic service that is stopped:Set colListOfServices = Set colListOfServices = GetObject("winmgmts:").ExecQueryGetObject("winmgmts:").ExecQuery

("Select * from Win32_Service Where("Select * from Win32_Service WhereState = 'Stopped' and StartMode = State = 'Stopped' and StartMode = 'Automatic'")'Automatic'")

For Each strService in colListOfServicesFor Each strService in colListOfServices strService.StartService()strService.StartService()NextNext

Page 32: Windows services 101 (2004)
Page 33: Windows services 101 (2004)

Debugging a ServiceDebugging a Service

debug the service by attach to debug the service by attach to processprocess

or call or call DebugBreakDebugBreak to invoke JIT to invoke JIT dbgdbg

or specify a debugger to use when or specify a debugger to use when starting a programstarting a program

Page 34: Windows services 101 (2004)

specifying a debugger to use when specifying a debugger to use when starting a program:starting a program:– create key create key Image File Execution Image File Execution OptionOption in in HKLM\SOFTWARE\Microsoft\HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersionWindows NT\CurrentVersion create create a subkey with the same name as your a subkey with the same name as your service service

– to this subkey, add a value of type to this subkey, add a value of type REG_SZ, named REG_SZ, named DebuggerDebugger

– use full path to debugger as string use full path to debugger as string valuevalue

– In the Services control panel applet, In the Services control panel applet, select your service, click select your service, click StartupStartup and and check check Allow Service to Interact Allow Service to Interact with Desktopwith Desktop

Page 35: Windows services 101 (2004)

to keep it simple:to keep it simple:– develop (or use) a robust general-develop (or use) a robust general-

purpose service frameworkpurpose service framework– develop your code as a normal (or develop your code as a normal (or

better, console) application, keeping better, console) application, keeping in mid that it will be added on top of in mid that it will be added on top of the service frameworkthe service framework

– when you’re sure that your code is when you’re sure that your code is OK, put it in a separate working OK, put it in a separate working thread, so that service framework and thread, so that service framework and the job are separatedthe job are separated» don’t use worker function threads, but don’t use worker function threads, but

create a class for the thread (CWinThread create a class for the thread (CWinThread base class)base class)

Page 36: Windows services 101 (2004)

Event LogEvent Log

service write to service write to ApplicationApplication SCM writes to SCM writes to SystemSystem to enter a message to the event to enter a message to the event

log, it is not enought just to call a log, it is not enought just to call a particular functionparticular function– messages are not entered as messages are not entered as

“normal” records – they need to be “normal” records – they need to be compiled by the message compilercompiled by the message compiler

Page 37: Windows services 101 (2004)

Message compilerMessage compiler input: <input: <message_file.mcmessage_file.mc>), messages >), messages

which are to be written to Event Logwhich are to be written to Event Log processed by message compiler (processed by message compiler (mc.exemc.exe))

– output: compiled messages (bin file)output: compiled messages (bin file) needed because messages (each with an needed because messages (each with an

ID) can be in different languagesID) can be in different languages usually a message DLL is created from usually a message DLL is created from

the output and registered as an even the output and registered as an even sourcesource– if you move or delete this DLL, Even Log will if you move or delete this DLL, Even Log will

not be able to find and display the stringsnot be able to find and display the strings

Page 38: Windows services 101 (2004)

MessageIdMessageId=0x1 =0x1

SeveritySeverity=Error =Error

FacilityFacility=Runtime =Runtime

SymbolicNameSymbolicName=MSG_BAD_COMMAND =MSG_BAD_COMMAND

LanguageLanguage=English=English

All your base are belong to us. All your base are belong to us.

LanguageLanguage=Japanese=Japanese

正しくないコマンド選択がされました。 正しくないコマンド選択がされました。..

Page 39: Windows services 101 (2004)

runtime messages can be included runtime messages can be included in Event Log records (in Event Log records (%1%1 within within message string)message string)

MessageIDMessageID=1=1

SeveritySeverity=Informational=Informational

FacilityFacility=Application=Application

SymbolicNameSymbolicName=CNTS_MSG_SERVICE_STARTED=CNTS_MSG_SERVICE_STARTED

LanguageLanguage=English=English

"%1" started successfully."%1" started successfully.

..

Page 40: Windows services 101 (2004)

Useful links & booksUseful links & books

Platform SDK docs (MSDN)Platform SDK docs (MSDN) www.naughter.com - CNTService www.naughter.com - CNTService

frameworkframework Jeffrey RichterJeffrey Richter: ": "Programming Programming

Server-Side Applications for Server-Side Applications for Microsoft Windows 2000Microsoft Windows 2000““

links to dev. sites at links to dev. sites at www.www.mscommunitymscommunity.net.net FAQ/Tips page FAQ/Tips page