How can I debug an application as a service account (f.e. network service) in Visual Studio?

226 Views Asked by At

Windows has different built-in standard service accounts, f.e. the NetworkService account. This SO post provides different answers on how to debug code as a different user than the current one when debugging in Visual Studio, but these answers show solutions for different local user accounts / admin accounts that request passwords to run code (these built-in accounts have no passwords). Is there a way to run and debug code from Visual Studio as one of these built-in service accounts?


My use case: I want to debug a service (and tests) that runs in production as the NetworkService account. This answer explains how to run an application as a NetworkService by using PsExec. Can I somehow start the service or tests with PsExec and then attach Visual Studio to the process and debug it?

1

There are 1 best solutions below

0
On BEST ANSWER

Turns out this is actually pretty easy and straight forward:


1. Execute the application with the desired service account to have a running process that the Visual Studio debugger can attach itself to

This can just be done by registering as a service, and either entering the service account credentials in the Service app, by right clicking on the service name -> Properties and setting the account in the Log on tab, or via PowerShell, like it is described in this SO answer.

Another way is to use PsExec as described in this answer. After downloading PsExec, run the following command inside a shell to open a cmd as a service account, f.e. for the network service account:

psexec -i -u "nt authority\network service" cmd.exe 

Run whoami in the cmd to ensure that it is getting executed as the desired account. Now navigate to the executable that should be debugged, and launch it from this cmd.


Note: I added a sleep at the beginning of my app to ensure that it does not execute any code until I connected with a debugger to it (C++ example):

while (!IsDebuggerPresent())
{
  std::this_thread::sleep_for(std::chrono::seconds(5));
}

2. Attach the Visual Studio debugger to the running process

Open Visual Studio as Administrator, click on Debug -> Attach to Process to open the Attach to Process window. Once the window is open, make sure to click the Show processes for all users checkbox when searching for the process, since it is getting executed under a different user account. Then search for the process that has been started in the previous step and click on Attach. It should now be possible to debug the app.

enter image description here