Windows services 101 (2004)
Upcoming SlideShare
Loading in...5
×
 

Windows services 101 (2004)

on

  • 783 views

 

Statistics

Views

Total Views
783
Views on SlideShare
781
Embed Views
2

Actions

Likes
0
Downloads
4
Comments
0

1 Embed 2

http://www.linkedin.com 2

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Windows services 101 (2004) Windows services 101 (2004) Presentation Transcript

  • Windows Services 101 Vatroslav Mihalj 2004.
  • What is Windows Service?
    • application that conforms to the interface rules of SCM
    • can be started automatically at system boot, by a user through the Services control panel applet, or by an app that uses service functions
    • can execute even when no user is logged on to the system.
    • driver service
      • conforms to the device driver protocols
      • similar to a service app, but it does not interact with the SCM
    • filename extension is .EXE for services and .SYS for driver services
  • Operating Windows Services
    • 3 types of programs use functions provided by SCM, i.e. are neccessary to operate a WS:
      • s ervice program
      • s ervice configuration program
      • s ervice control program
    • s ervice program
      • provides the actual functionality we are looking for (for one or more services)
      • use functions that connect to the SCM and send status information to the SCM
    • s ervice configuration program
      • queries/modifies services DB (install or delete services, query/modify config and security params)
    • s ervice control program
      • sending control requests to SCM (start, stop, pause/continue) - which carries out the request
      • net.exe , sc.exe , VS.NET Server Explorer
  • What is SMC ( Service Control Manager )
    • maintains a database of installed services and driver services ("services" from now on)
      • database includes information on how each service or driver service should be started
    • provides a unified and secure means of controlling them
      • RPC server, so service configuration and service control programs can manipulate services on remote machines
    • enables admins to customize security requirements for each service and thereby control access to the service
  • Service database
    • used by the SCM and programs that add, modify, or configure services
    • HKEY_LOCAL_MACHINESYSTEM
    • CurrentControlSetServices
    • subkey for each installed service
      • name of the subkey is service name
        • specified by CreateService function when service was installed by a service configuration program
    • database includes:
      • service type (own process or shares a process with other services, kernel driver or a file system driver)
      • start type (automatic, manual, disabled)
      • error control level
        • severity of error if svc fails to start, determines action that startup program will take
      • fully qualified path of the executable
      • optional dependency info
        • list of services that SCM must start before it can start the specified service
      • optional account name and password
        • no account specified: executes in context of LocalSystem account
      • for driver svc, optional driver object name, used by the I/O system to load the device driver
    • after successful boot, system saves a clone of the database in the last-known-good (LKG) configuration
      • If an auto-start service with a SERVICE_ERROR_CRITICAL error control level fails to start, the SCM reboots the machine using the LKG configuration
  • Stopping the service
    • with the Services control panel utility
    • ControlService function
      • SERVICE_CONTROL_STOP request to the service through SCM
      • if other running services are dependent on this one, SCM doesn't forward stop request
        • instead, it returns ERROR_DEPENDENT_SERVICES_RUNNING
        • you need to enumerate and stop dependent services
  • "Common" apps as services
    • no need to recode all apps as services
    • Windows 2000/2003 Resource Kit tools: srvany.exe , instsrv.exe
    • NO INTERACTION!
    • instsrv ServiceAnyApp <path> srvany.exe
    • instsrv ServiceAnyApp <path> srvany.exe
    • -a MYDOMAINauser -p My1Password
    • ( instsrv MyService Remove )
    • Some Registry keys need to be added:
      • Open HKLM SYSTEMCurrentControlSetServices < service name >
      • a dd k ey
        • K ey Name: &quot; Parameters &quot;
        • Class : <leave blank>
      • Select the Parameters key , Add Value
        • Value Name: Application
        • Data Type : REG_SZ
        • String : <path><application.ext>
        • optional &quot;AppParameters&quot; and &quot;AppDirectory&quot; (REG_SZ)
  • srvany / instsrv info
    • MS:
    • http://support.microsoft.com/default.aspx?scid=kb;en-us;137890
    • info & help (in German), will create .BAT and .REG file with neccessary params:
    • http://www.rz.uni-freiburg.de
    • /pc/sys/srvany/index.php
  • Service programs
    • when service control program requests the service to run, SCM starts the service:
      • sends start request to control dispatcher
        • CD - special function executed by a separate thread which needs to initialize the service structures
        • does not return until there is an error or all of the services in the process have terminated
        • when all svcs in a process have terminated, SCM sends a control request to dispatcher thread to shut down
      • control dispatcher creates a new thread to execute ServiceMain
      • ServiceMain - starting place for the job the service needs to do
  •  
  • Starting a service
    • Perform initialization (if <1 sec can be done within ServiceMain )
    • init time (&quot;pending&quot; state) <=30s total!
      • use SetServiceStatus function , with SERVICE_START_PENDING
      • as init continues, service should make additional calls to SetServiceStatus to report progress
    • init complete: call SetServiceStatus , with SERVICE_RUNNING
  • Service Control Handler
    • invoked by the control dispatcher when the service process receives a control request from a service control program
    • whenever SCH invoked, service must call SetServiceStatus to report status to SCM, regardless of whether the status changed
    • service control program can send control requests using ControlService
    • control handler must return within 30 sec, or SCM will return an error
      • lengthy processing: create a secondary thread to perform processing, then return
    • service name != display name (in the Service control panel)
  • System s hutdown
    • by default, after received SERVICE_CONTROL_SHUTDOWN, ~20 sec to perform cleanup task s
    • after this expires, shutdown proceeds regardless of whether service shutdown is complete
    • need more time to clean up?
      • send STOP_PENDING status messages, along with a wait hint
        • so service controller knows how long to wait before reporting that svc shutdown is complete
      • there is a limit to how long the service controller will wait
        • To change this time limit, modify WaitToKillServiceTimeout in HKLMSYSTEMCurrentControlSetControl
  • Service User Accounts
    • LocalService Account
      • minimum privileges on the local computer, anonymous credentials on the network
      • does not have a password
    • NetworkService Account
      • minimum privileges on the local computer and acts as the computer on the network
      • does not have a password
      • remote token contains SIDs for the Everyone and Authenticated Users groups
    • LocalSystem Account
      • extensive privileges on the local computer, acts as the computer on the network
      • does not have a password
      • inherits the security context of the SCM
  • Interactive Services
    • each service has an associated “ window station ” and “ desktop ”
    • only one window station, Winsta0 can be an interactive
    • by default, window station the service uses is not interactive, so the service cannot display a user interface
    • interactive service
      • running in the context of the LocalSystem account and has SERVICE_INTERACTIVE_PROCESS attribute
        • can be set by choosing Properties in Service control panel and checking “Allow service to interact with desktop”
    • dangerous practice!!!!
      • never open dialogs for services running on a server-nobody will answer this dialog
    • better solution: separate GUI application running within the context of the user session, IPC communication
      • for hazarders: to display a msg box from a service, even if not running as LocalSystem or not configured to run interactively - call MessageBox using MB_SERVICE_NOTIFICATION
        • “ displays a message box on the current active desktop, even if there is no user logged on to the computer.”
  • Worker threads
    • start worker threads from the main thread and leave the main thread free to answer the requests
    • use Events to notify the main thread when worker thread starts and finishes
    • job processing functions in worker threads can be started by firing custom message which are handled by their message handlers
    • when starting, SCM needs a certain amout of time to query status and stuff
      • if an error occurs or the service can’t connect to a server, don’t stop it immediately after it starts (i.e. exits start pending state) - let the main thread sleep for a while (1 sec is enough)
        • otherwise, an error will occur because SCM might not detect that thread was started and immediately stopped and will write an error in Event Log saying that the thread did not enter the desired (&quot;started&quot;) state - i.e. it didn't detect it because it was too “quick”
    • when creating/opening a custom log file, beware - the service starts in %windir%system32 by default
    • don’t set service control level too high and startup type to auto unless you're absolutly sure – system might get block while booting
    • using Unicode is a good thing to consider
      • but do not insist if it’s not neccessary
  • .NET
    • System.ServiceProcess namespace
    • inherit from ServiceBase class to implement a service
      • registers the service and answers to start and stop requests
    • ServiceController class is used to implement a service control program
      • sends requests to services
      • ServiceProcessInstaller and ServiceInstaller classes install and configure service programs
    • good sample: www.wrox.com , &quot; Professional C# &quot; code samples, ISBN 1861007043
  • WMI
    • service status can be obtained and controlled through WMI
      • Win32_BaseService , Win32_Service
    • Restart any automatic service that is stopped:
    • Set colListOfServices = GetObject(&quot;winmgmts:&quot;).ExecQuery
    • (&quot;Select * from Win32_Service Where
    • State = 'Stopped' and StartMode = 'Automatic'&quot;)
    • For Each strService in colListOfServices
    • strService.StartService()
    • Next
  •  
  • Debugging a Service
    • debug the service by attach to process
    • or call DebugBreak to invoke JIT dbg
    • or specify a debugger to use when starting a program
    • specifying a debugger to use when starting a program:
      • create key Image File Execution Option in HKLMSOFTWAREMicrosoftWindows NTCurrentVersion create a subkey with the same name as your service
      • to this subkey, add a value of type REG_SZ, named Debugger
      • use full path to debugger as string value
      • In the Services control panel applet, select your service, click Startup and check Allow Service to Interact with Desktop
    • to keep it simple:
      • develop (or use) a robust general-purpose service framework
      • develop your code as a normal (or better, console) application, keeping in mid that it will be added on top of the service framework
      • when you’re sure that your code is OK, put it in a separate working thread, so that service framework and the job are separated
        • don’t use worker function threads, but create a class for the thread (CWinThread base class)
  • Event Log
    • service write to Application
    • SCM writes to System
    • to enter a message to the event log, it is not enought just to call a particular function
      • messages are not entered as “normal” records – they need to be compiled by the message compiler
  • Message compiler
    • input: < message_file.mc >), messages which are to be written to Event Log
    • processed by message compiler ( mc.exe )
      • output: compiled messages (bin file)
    • needed because messages (each with an ID) can be in different languages
    • usually a message DLL is created from the output and registered as an even source
      • if you move or delete this DLL, Even Log will not be able to find and display the strings
    • MessageId =0x1
    • Severity =Error
    • Facility =Runtime
    • SymbolicName =MSG_BAD_COMMAND
    • Language =English
    • All your base are belong to us.
    • Language =Japanese
    • 正しくないコマンド選択がされました。
    • .
    • runtime messages can be included in Event Log records ( %1 within message string)
    • MessageID =1
    • Severity =Informational
    • Facility =Application
    • SymbolicName =CNTS_MSG_SERVICE_STARTED
    • Language =English
    • &quot;%1&quot; started successfully.
    • .
  • Useful links & books
    • Platform SDK docs (MSDN)
    • www.naughter.com - CNTService framework
    • Jeffrey Richter : &quot; Programming Server-Side Applications for Microsoft Windows 2000 “
    • links to dev. sites at www. mscommunity .net FAQ/Tips page 