Writing a Windows Service

Author

Pavel Yosifovich
25+ years as Software developer, trainer, consultant, author, and speaker. Co-author of “Windows Internals”. Author of “Windows Kernel Programming”, “Windows 10 System Programming, as well as System and kernel programming courses and “Windows Internals” series.

Introduction: Writing a Windows Service

Hi, and welcome to this video on writing a Windows service. In the previous video, we explored what Windows services are and how to use related tools. Now, we’ll go through writing a minimal Windows service that can be started and stopped, then gradually add more functionality.

Writing a Windows Service

Setting Up the Project

  1. Create a Console Application:
    • Open Visual Studio and start a new project.
    • Choose a console application and name it, e.g., SimpleSVC.
  2. Turning a Console Application into a Service:
    • Include the necessary Windows APIs.
    • Use StartServiceControlDispatcher to register services in the process.

Defining the Service Table

Create an array with entries for the service names and their corresponding main functions:

  • Service Name: Define a global variable for reuse.
  • Service Entry Function: Define the main function for the service, which will be called by the Service Control Manager (SCM).

Main Service Function and Control Handler

  1. Service Main Function: This function is invoked by StartServiceControlDispatcher. It registers a control handler, which receives commands (e.g., stop, pause).
  2. Control Handler:
    • Use RegisterServiceCtrlHandler to register a function (e.g., SimpleHandler) that handles service commands.
    • Implement a status reporting system using SetServiceStatus to communicate the service’s current state.
  3. Service Initialization:
    • Set the service status to SERVICE_START_PENDING during initialization.
    • Once initialized, set the status to SERVICE_RUNNING.
Windows master developer badge 1

$1,478

$1182 or $120 X 10 payments

Windows Master Developer

Takes you from a “generic” C programmer to a master Windows programmer in user mode and kernel mode.

Testing the Basic Service

  1. Compile the Code: Ensure the code compiles without errors.
  2. Register and Start the Service: Use tools like SC or PowerShell to create and start the service.
  3. Verify Service Functionality: Check if the service starts and stops as expected in the Services applet or Task Manager.

Adding the Logging Functionality

  1. Create a Mailslot for Logging: Mail slots provide a simple way for client applications to send messages to the service.
  2. Open a Log File: Use a file to store log messages from the mail slot. Ensure it has exclusive access to avoid conflicts.
  3. Define the Log Message Structure: Create a structure to hold log levels (e.g., critical, warning, info) and the message text.

Implementing Mail Slot Listening

  1. Mailslot Initialization: Use CreateMailslot to create a mail slot that accepts messages from clients.
  2. Listening for Messages: Use ReadFile to retrieve messages from the mail slot and write them to the log file.
  3. Timestamp Logging: Record the date and time of each log entry for easier tracking.
Windows Internal master badge

$1300

$1040 or $104 X 10 payments

Windows Internals Master

Broadens and deepens your understanding of the inner workings of Windows.

Setting Up a Client Application

  1. Create a Client Application: This application will connect to the mail slot and send log messages to the service.
  2. Format Messages: Structure the messages with process and thread IDs to differentiate log sources.
  3. Sending Messages: Open the mail slot and use WriteFile to send messages to the service.

Addressing Security and Permissions

  1. Mailslot Security: Configure the security descriptor to allow non-admin users to send messages to the mailslot.
  2. File Sharing: Adjust file sharing settings to allow reading of the log file even when the service is running.

Troubleshooting and Testing

  1. Handle Access Errors: Address any “Access Denied” errors by setting appropriate permissions.
  2. Verify Logging: Check that the log file records messages as expected and allows concurrent access.
  3. Test Service Restart and Shutdown: Ensure the service stops and restarts cleanly, releasing resources like file handles and the mailslot.

Conclusion

This video demonstrated creating a Windows service, making the service provide logging functionality. This setup provides a foundation for more advanced service features. Play around with the code and experiment with extending functionality, like adding a custom API for logging. You can find the code on GitHub.

Gain Insider Knowledge

Subscribe to updates from the TrainSec trainers
blue depth

About the author

Pavel Yosifovich
25+ years as Software developer, trainer, consultant, author, and speaker. Co-author of “Windows Internals”. Author of “Windows Kernel Programming”, “Windows 10 System Programming, as well as System and kernel programming courses and “Windows Internals” series.

Black Friday & Cyber Monday Sale Started!

For a limited time, enjoy 25% off ALL available courses for the next month. Whether you’re looking to sharpen your skills or explore new areas of cybersecurity, now’s the perfect time to invest in your growth.

Use code BFRIDAY24 at checkout to claim your discount.

*Excluding bundles and monthly plans.