Windows services installation / uninstallation in Windows 10 - c++

I have an application, in C++, which attempts, upon running (at which time, no other relevant process is thought to be running), to install a couple of services.
The workflow is that if the services exist, then they are uninstalled, else they and uninstalled and then re-installed.
I had followed a few tutorials like :
Installing a service
Unfortunately, something seems to go wrong with the installation or the uninstallation.
Upon assuming that the service is not installed, when I proceed to install the services, they get installed, and I then attempt to change the configuration, to delayed-Auto start.
At this stage, although the services are installed, I cannot start them, as I get the error saying services cannot be found.
When I try uninstalling the services, the uninstallation fails, giving an error 1060, saying the services are marked for deletion.
SC_HANDLE schSCManager;
SC_HANDLE schService;
schSCManager = OpenSCManager(
NULL, // local computer
NULL, // ServicesActive database
SC_MANAGER_ALL_ACCESS); // full access rights
if (schSCManager == nullptr)
{
continue;
}
if (bInstall)
{
schService = CreateService(
schSCManager, // SCM database
szServiceName, // name of service
szDisplayName, // service name to display
SERVICE_ALL_ACCESS, // desired access
SERVICE_WIN32_OWN_PROCESS, // service type
SERVICE_DEMAND_START, // start type
SERVICE_ERROR_NORMAL, // error control type
szDirectory, // path to service's binary
NULL, // no load ordering group
NULL, // no tag identifier
NULL, // no dependencies
NULL, // LocalSystem account
NULL); // no password
if (schService == NULL)
{
TraceAdvice(L"CreateService failed (%d)\n", GetLastError());
CloseServiceHandle(schSCManager);
continue;
}
else
{
if (!ChangeServiceConfig(
schService, // handle of service
SERVICE_NO_CHANGE, // service type: no change
SERVICE_CONFIG_DELAYED_AUTO_START_INFO, // service start type
SERVICE_NO_CHANGE, // error control: no change
NULL, // binary path: no change
NULL, // load order group: no change
NULL, // tag ID: no change
NULL, // dependencies: no change
NULL, // account name: no change
NULL, // password: no change
NULL)) // display name: no change
{
TraceAdvice(L"ChangeServiceConfig failed (%d)\n", GetLastError());
}
TraceAdvice(L"Service installed successfully\n");
}
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
/*TraceFatal(_T("Now installing : %s"), szServiceName);
_stprintf_s(szTmp, _T("SC create %s binpath= \"%s%s.exe\" displayName= \"%s\" start= delayed-auto"), szServiceName, szDirectory, szServiceName, szDisplayName);
TraceFatal(_T("Command is : %s"), szTmp);*/
}
else
{
_wsystem(_T("taskkill /F /IM mmc.exe")); // Need to kill any instance of MMC running
_wsystem(_T("taskkill /F /IM procexp.exe"));
schService = OpenService(
schSCManager, // SCM database
szServiceName, // name of service
DELETE); // need delete access
if (schService == NULL)
{
TraceAdvice(L"OpenService failed (%d)\n", GetLastError());
CloseServiceHandle(schSCManager);
continue;
}
DWORD dwBytesNeeded;
SERVICE_STATUS_PROCESS ssp;
if (!QueryServiceStatusEx(
schService,
SC_STATUS_PROCESS_INFO,
(LPBYTE)&ssp,
sizeof(SERVICE_STATUS_PROCESS),
&dwBytesNeeded))
{
printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
}
if (ssp.dwCurrentState == SERVICE_RUNNING)
{
_stprintf_s(szTmp, _T("taskkill /F /IM %s.exe"), szServiceName);
_wsystem(szTmp);
}
// Delete the service.
if (!DeleteService(schService))
{
TraceAdvice(L"DeleteService failed (%d)\n", GetLastError());
}
else TraceAdvice(L"Service deleted successfully\n");
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
}
}
I made sure of all the points, viz.
Task manager was closed
Service console was closed.
All instances of MMC were closed.
Service was stopped
Service was not open in debugger in Visual Studio...
But it does not avail. The service does not get uninstalled till I reboot the system (deleting the registry linked to the service does not work either).
I have checked the parameters I pass on to these functions, and they seem correct.
What else should I be checking for, to ensure a correct installation, or a successful uninstallation?

You need to stop the service first, otherwise it gets stuck in this pending delete state. Forcibly killing the service is not the same thing as stopping it. From the same area of documentation, you need to ControlService(SERVICE_CONTROL_STOP).

Related

How to impersonate a logged on user to read registry key/values under HKEY_CURRENT_USER?

I'm trying to impersonate an already logged on user from a windows service (which is started with a local system account).
My main objective is to be able to read some specific registry key/values under HKEY_CURRENT_USER.
I'm already able to start a new process with the user "identity" but it seems I'm unable to practice impersonation from any thread inside my service.
Here is the code I'm using, all seems to be ok except when I try to open a key which only exist under HKEY_CURRENT_USER for the logged on user:
#include <windows.h>
#include <wil/resource.h>
#include <Wtsapi32.h>
// The *wil* namespace comes from the microsoft wil package: https://github.com/microsoft/wil.
// You can just replace unique_handle by HANDLE and unique_hkey by HKEY to make this sample work.
void Impersonate()
{
DWORD sessionId = WTSGetActiveConsoleSessionId();
// Get the primary user token
wil::unique_handle hUserToken;
if (!WTSQueryUserToken(sessionId, &hUserToken))
return;
// Get the impersonation token
wil::unique_handle hImpersonationToken;
if (!DuplicateToken(
hUserToken.get(), SECURITY_IMPERSONATION_LEVEL::SecurityImpersonation, &hImpersonationToken))
return;
// Impersonate ?
if (!SetThreadToken(NULL, hImpersonationToken.get()))
return;
// Also tried by using ImpersonateLoggedOnUser :
// if (!ImpersonateLoggedOnUser(hUserToken.get()))
// return;
// Not working
// (I just created a 'Fake' key under HKEY_CURRENT_USER for the logged on user)
wil::unique_hkey hKey;
LSTATUS status = RegOpenKeyEx(HKEY_CURRENT_USER, L"Fake", 0, KEY_READ | KEY_WOW64_64KEY, &hKey);
if (ERROR_SUCCESS != status)
{
// Get ERROR_FILE_NOT_FOUND error
}
RevertToSelf();
}
Is it possible (by using impersonation) to read registry values under HKEY_CURRENT_USER ?
And if yes, what is wrong in this code ?

How to drop elevated privileges when i no longer need them

I have an application that needs to register controls when it is Run As Administrator and I would like the application to drop the elevated privileges when they are no longer needed. I have read that this can be done with AdjustTokenPrivileges, (Dropping privileges in C++ on Windows) but I have not found any sample code that will allow me to go from SECURITY_MANDATORY_HIGH_RID to SECURITY_MANDATORY_MEDIUM_RID. My code is written C++ using Visual Studio.
if you want
sample code that will allow me to go from SECURITY_MANDATORY_HIGH_RID
to SECURITY_MANDATORY_MEDIUM_RID.
you need open own process token with TOKEN_ADJUST_DEFAULT (for change integrity level - this is mandatory) and WRITE_OWNER (for change mandatory label in your token security descriptor - otherwise you not be able more open own token with write access more - but this is optional)
call SetTokenInformation with TokenIntegrityLevel let downgrade current integrity level. after this it already can not be raised.
also internally system disable some privileges in token, when we set integrity level below SECURITY_MANDATORY_HIGH_RID. i doubt that this is documented, but from my test, next privileges is disabled and can not be more enabled:
SeTakeOwnershipPrivilege
SeLoadDriverPrivilege
SeBackupPrivilege
SeRestorePrivilege
SeDebugPrivilege
SeImpersonatePrivilege
SeDelegateSessionUserImpersonatePrivilege
but you still will be member of admin group (S-1-5-32-544 Administrators) and this group can not be disabled by AdjustTokenGroups because function cannot disable groups with the SE_GROUP_MANDATORY attribute - but S-1-5-32-544 have this attribute. and change primary process token also not possible already (it possible only after process created (in suspended state) and before it begin executed (resumed) if we have SeAssignPrimaryTokenPrivilege )
so really your application will be in intermediate state after downgrade integrity level to medium - from one side you lost most significant privileges, but access to objects (files, registry keys) primary based not on privileges but group membership and mandatory label - vs integrity level. because Administrators group still will be enabled in your token and most objects not have explicit mandatory label (so medium by default) - your app still be able open/create files/keys which limited applications (admin under uac) can not. however if you downgrade you integrity level to SECURITY_MANDATORY_LOW_RID - you really got limited application, but most legacy code incorrect worked under LowLevel integrity
minimal code for downgrade integrity level:
ULONG SetMediumLevel()
{
HANDLE hToken;
if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_DEFAULT, &hToken))
{
ULONG cbSid = GetSidLengthRequired(1);
TOKEN_MANDATORY_LABEL tml = { { alloca(cbSid)} };
ULONG dwError = NOERROR;
if (!CreateWellKnownSid(WinMediumLabelSid, 0, tml.Label.Sid, &cbSid) ||
!SetTokenInformation(hToken, TokenIntegrityLevel, &tml, sizeof(tml)))
{
dwError = GetLastError();
}
CloseHandle(hToken);
return dwError;
}
return GetLastError();
}
but here exist thin point - token itself have security descriptor with explicit label. and high integrity process have High Mandatory Label with SYSTEM_MANDATORY_LABEL_NO_WRITE_UP access policy. this mean that we no more can open our process token with write access (TOKEN_ADJUST_* ) (with read access can). this can create problems if app in some place try open self process token with this access (some bad design code can when need query own process token properties instead TOKEN_QUERY access ask TOKEN_ALL_ACCESS and fail in this point). for prevent this potential issue we can change mandatory label of our token security descriptor before downgrade it integrity:
ULONG SetMediumLevel()
{
HANDLE hToken;
if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_DEFAULT|WRITE_OWNER, &hToken))
{
ULONG cbSid = GetSidLengthRequired(1);
TOKEN_MANDATORY_LABEL tml = { { alloca(cbSid)} };
ULONG dwError = NOERROR;
if (CreateWellKnownSid(WinMediumLabelSid, 0, tml.Label.Sid, &cbSid))
{
SECURITY_DESCRIPTOR sd;
ULONG cbAcl = sizeof(ACL) + FIELD_OFFSET(SYSTEM_MANDATORY_LABEL_ACE, SidStart) + cbSid;
PACL Sacl = (PACL)alloca(cbAcl);
if (!InitializeAcl(Sacl, cbAcl, ACL_REVISION) ||
!AddMandatoryAce(Sacl, ACL_REVISION, 0, SYSTEM_MANDATORY_LABEL_NO_WRITE_UP, tml.Label.Sid) ||
!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION) ||
!SetSecurityDescriptorSacl(&sd, TRUE, Sacl, FALSE) ||
!SetKernelObjectSecurity(hToken, LABEL_SECURITY_INFORMATION, &sd) ||
!SetTokenInformation(hToken, TokenIntegrityLevel, &tml, sizeof(tml)))
{
dwError = GetLastError();
}
}
CloseHandle(hToken);
return dwError;
}
return GetLastError();
}

Can't query, run or stop a Windows Service

I have created my first Windows service following this instruction. I can start or stop my service from the Service panel in Manage-> My computer without problem.
The service account is "LocalSystem" so, I think, I'm ok with privileges.
Now I want to communicate with my service from another app, but first of all I want to stop or start my service.
Following this example I Write this code:
SC_HANDLE schSCManager;
SC_HANDLE schService;
LPCWSTR szSvcName = _T("MyNewService");
// Get a handle to the SCM database.
schSCManager = OpenSCManager(
NULL, // local computer
NULL, // ServicesActive database
SC_MANAGER_ALL_ACCESS); // full access rights
if (NULL == schSCManager)
{
printf("OpenSCManager failed (%d)\n", GetLastError());
return;
}
// Get a handle to the service.
schService = OpenService(
schSCManager, // SCM database
szSvcName, // name of service
SERVICE_CHANGE_CONFIG); // need change config access
if (schService == NULL)
{
printf("OpenService failed (%d)\n", GetLastError());
CloseServiceHandle(schSCManager);
return;
}
//OK until now
// Check the status in case the service is not stopped.
SERVICE_STATUS_PROCESS ssStatus;
DWORD dwBytesNeeded;
if (!QueryServiceStatusEx(
schService, // handle to service
SC_STATUS_PROCESS_INFO, // information level
(LPBYTE) &ssStatus, // address of structure
sizeof(SERVICE_STATUS_PROCESS), // size of structure
&dwBytesNeeded ) ) // size needed if buffer is too small
{
//printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
CString str;
str.Format(_T("QueryServiceStatusEx failed (%d)\n"), GetLastError()); //ERROR 5: ERROR_ACCESS_DENIED
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return;
}
// Check if the service is already running. It would be possible
// to stop the service here, but for simplicity this example just returns.
if(ssStatus.dwCurrentState != SERVICE_STOPPED && ssStatus.dwCurrentState != SERVICE_STOP_PENDING)
{
printf("Cannot start the service because it is already running\n");
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return;
}
In any case I get the error number 5, that is "ERROR_ACCESS_DENIED: The handle does not have the SERVICE_QUERY_STATUS access right", but I'm not sure where is the problem. The service has LocalSystem account option that means all privileges and I'm the admin of my computer.. what's wrong?
I also tried with ControlService trying to start or stop the service but I get the same error about rights
BOOL success = ::ControlService(schService, SERVICE_CONTROL_STOP, &ss);
I'm on Visual Studio 2013 Update 2.
Thank you
You seem to be a little bit confused about terms "privileges" and "access rights". You are quite right that the LocalSystem account is really a privileged one, at least for actions on the local computer. However, even a privileged user must know how to take advantage if her privileges (how things work).
When an application wants to work with an object (e.g. a service), it has to declare its intention to the Windows kernel (done via OpenSCManager and OpenService in your code). The application identifies the object (e.g. by service name) and also informs the kernel what sorts of things it plans to do with it. These "sorts of things" are called "access rights" and the kenrel decides whether the application is privileged enough to obtain the access rights it is requesting. In your code, you are requesting all access rights (SC_MANAGER_ALL_ACCESS) for the SC manager and an access right to change configuration of your service (SERVICE_CHANGE_CONFIG). Then, you attempt to query status of your service, but you did not declare this intention to the kernel when requesting access to the service (the OpenService call). That's why you get the "access denied" error.
Here is a list of access rights defined for services and SC manager(s): https://msdn.microsoft.com/en-us/library/windows/desktop/ms685981(v=vs.85).aspx. The document also contains information about which access rights you need to perform which actions.
To open a service, you need only the SC_MANAGER_CONNECT access right to its SC manager. To query service status, the SERVICE-QUERY_STATUS access right is required. To stop the service, request the SERVICE_STOP right.
So, the short version is: specify SERVICE_STOP | SERVICE_QUERY_STATUS desired access mask when calling OpenService, and optionally SC_MANAGER_CONNECT in the OpenSCManager call.
Problem
Your example program does not have the correct privileges to stop/start your service. It does not matter what privileges your service has.
Solution
Try running your example program as administrator by right-clicking on the exe file and selecting "Run as administrator".
If you need to elevate your process programmatically then have a look at this article.
UINT GetServiceStatus(LPCTSTR ServiceName)
{
SC_HANDLE schService;
SC_HANDLE schSCManager;
DWORD ErrorCode;
SERVICE_STATUS ssStatus;
UINT return_value;
schSCManager = OpenSCManager(
NULL, // machine (NULL == local)
NULL, // database (NULL == default)
SC_MANAGER_ALL_ACCESS // access required
);
if (!schSCManager)
return -1;
schService = OpenService(schSCManager, ServiceName, SERVICE_ALL_ACCESS);
if (!schService)
{
ErrorCode = GetLastError();
CloseServiceHandle(schSCManager);
if (ErrorCode == ERROR_SERVICE_DOES_NOT_EXIST)
return -2;
else
return -1;
}
QueryServiceStatus(schService, &ssStatus);
if (ssStatus.dwCurrentState == SERVICE_RUNNING)
return_value = 1;
else
return_value = 0;
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return return_value;
}

CryptAcquireContext failing with ERROR_FILE_NOT_FOUND (2L) when user not logged on Windows 8.1

I am having a hard time migrating a C++ CryptoAPI-based application that currently runs on Windows Server 2008 to Windows 8.1. The scenario is:
This application is eventually triggered by WatchDog.exe, which in its turn is triggered when the computer is started by Windows' Task Scheduler.
Task Scheduler uses the following rules to start the WatchDog.exe:
A Administrator User Account;
Run Whether user is logged on or not;
UNCHECKED: Do not store password. The task will only have access to
local resources;
Run with Highest Privileges;
Configure for Win 8.1;
Triggered at system startup.
The server sits there, nobody logged, until in a given scenario WatchDog.exe starts the application. Application log confirms that the owner of the process (GetUserName) is the very same user Task Scheduler used to trigger WatchDog.exe.
It turns out that this application works fine in Windows Server 2008, but in windows 8.1 a call to CryptAcquireContext fails with return code ERROR_FILE_NOT_FOUND (2L). The odd thing is that the application will NOT fail if, when started, the user is physically logged onthe machine, although it was not the user who started the application manually.
I took a look at the documentation and found:
"The profile of the user is not loaded and cannot be found. This
happens when the application impersonates a user, for example, the
IUSR_ComputerName account."
I had never heard of impersonification, so I made a research and found the APIs LogonUser, ImpersonateLoggedOnUser and RevertToSelf. I then updated the application in this way:
...
HANDLE hToken;
if (! LogonUser(L"admin", L".", L"XXXXXXXX", LOGON32_LOGON_BATCH, LOGON32_PROVIDER_DEFAULT, &hToken))
{
logger->log (_T("Error logging on."));
}
else
{
logger->log (PMLOG_LEVEL_TRACE, _T("Logged on."));
if (! ImpersonateLoggedOnUser(hToken))
{
logger->log (_T("Error impersonating."));
}
else
{
logger->log (_T("Impersonated."));
err = XXXXXXXXX(); // calls function which will execute CryptAcquireContext
if (! RevertToSelf())
{
logger->log (_T("Error reverting."));
}
else
{
logger->log (_T("Reverted."));
}
}
}
...
Excerpt with the call to CryptAcquireContext:
...
//---------------------------------------------------------------
// Get the handle to the default provider.
if(! CryptAcquireContext(&hCryptProv, cryptContainerName, MS_ENHANCED_PROV, PROV_RSA_FULL, 0))
{
DWORD e = GetLastError();
_stprintf_s (logMsg, 1000, _T("Error %ld acquiring cryptographic provider."), e);
cRSALogger->log (logMsg);
return ERR_CCRYPT_NO_KEY_CONTAINER;
}
cRSALogger->log (_T("Cryptographic provider acquired."));
...
As the result, I got the log:
...
[2015/01/08 20:53:25-TRACE] Logged on.
[2015/01/08 20:53:25-TRACE] Impersonated.
...
[2015/01/08 20:53:26-ERROR] Error 2 acquiring cryptographic provider.
...
[2015/01/08 20:53:26-TRACE] Reverted.
...
That seems to show that impersonation is working properly, but still I get Error 2 (ERROR_FILE_NOT_FOUND) on CryptAcquireContext.
Summary:
On Windows Server 2008, the very same application runs properly even
without the calls to LogonUser/Impersonate/Revert.
On Windows 8.1, the application, with or without the calls to
LogonUser/Impersonate/Revert, will only work properly if the user is logged on (which is not acceptable).
Any thoughts where I can run to in order to get this working on windows 8.1?
Thank in advance,
Dan

How do I detect that my application is running as service or in an interactive session?

I'm writing an application that is able to run as a service or standalone but I want to detect if the application was executed as a service or in a normal user session.
If this is a C++ application, somewhere in your startup code you have to call StartServiceCtrlDispatcher. If it fails and GetLastError() returns ERROR_FAILED_SERVICE_CONTROLLER_CONNECT, the app has not been started as a service.
Another option would be to use System.Environment.UserInteractive
http://msdn.microsoft.com/en-us/library/system.environment.userinteractive.aspx
Update: To make up for posting a .NET answer to a C++ topic, I provide a C implementation based on the .NET implementation.
BOOL IsUserInteractive()
{
BOOL bIsUserInteractive = TRUE;
HWINSTA hWinStation = GetProcessWindowStation();
if (hWinStation != NULL)
{
USEROBJECTFLAGS uof = {0};
if (GetUserObjectInformation(hWinStation, UOI_FLAGS, &uof, sizeof(USEROBJECTFLAGS), NULL) && ((uof.dwFlags & WSF_VISIBLE) == 0))
{
bIsUserInteractive = FALSE;
}
}
return bIsUserInteractive;
}
I think you can query the process token for membership in the Interactive group.
From http://support.microsoft.com/kb/243330:
SID: S-1-5-4
Name: Interactive
Description: A group that includes all users that have logged on interactively. Membership is controlled by the operating system.
Call GetTokenInformation with TokenGroups to get the groups associated with the account under which the process is running, then iterate over the sids looking for the Interactive sid.
I found a nice chunk of code at http://marc.info/?l=openssl-dev&m=104401851331452&w=2
I think you can base your detection on the fact that services are running with SessionID 0 and user accounts do have other values (like 1).
bServiceMode = false;
SessionID=-1;
Size=0;
hToken = NULL;
(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
GetLastError();
if (!GetTokenInformation(hToken, TokenSessionId, &SessionID, sizeof(SessionID), &Size) || !Size)
return FALSE;
if(SessionID==0)
bServiceMode = true;
All of the above methods are unreliable. Session Id is not necessarily 0 (at least not in previous Windows versions), Window Station is only WinSta0 if "If the service is running in the LocalSystem account and is interacting with the desktop".
See KB171890 for more details.
One method for detecting if a process is running as service is following:
Please note: Only services installed in services database will be detected with this method, but not child processes started by a service process that are not registered in the database. In this case, it would not also be a system service. *1.
bool IsRunningAsService(unsigned int Pid) {
bool Result = false;
SC_HANDLE hScm = OpenSCManager(
0,
SERVICES_ACTIVE_DATABASE,
SC_MANAGER_ENUMERATE_SERVICE
);
if (hScm == 0) {
return Result;
}
DWORD ServicesBufferRequired = 0;
DWORD ResumeHandle = 0;
DWORD ServicesBufferSize = 0;
DWORD ServicesCount = 0;
ENUM_SERVICE_STATUS_PROCESS* ServicesBuffer = 0;
EnumServicesStatusEx(hScm, SC_ENUM_PROCESS_INFO, SERVICE_WIN32,
SERVICE_ACTIVE, 0, 0, &ServicesBufferRequired, &ServicesCount, &ResumeHandle, 0);
// Todo: Error handling (GetLastError() results are currently bogus?)
ServicesBuffer = (ENUM_SERVICE_STATUS_PROCESS*) new
char[ServicesBufferRequired];
ServicesBufferSize = ServicesBufferRequired;
EnumServicesStatusEx(hScm, SC_ENUM_PROCESS_INFO, SERVICE_WIN32,
SERVICE_ACTIVE, (LPBYTE) ServicesBuffer, ServicesBufferSize,
&ServicesBufferRequired, &ServicesCount, &ResumeHandle, 0);
ENUM_SERVICE_STATUS_PROCESS* ServicesBufferPtr = ServicesBuffer;
while (ServicesCount--) {
if (ServicesBufferPtr->ServiceStatusProcess.dwProcessId == Pid) {
Result = true;
break;
}
ServicesBufferPtr++;
}
delete [] ServicesBuffer;
CloseServiceHandle(hScm);
return Result;
}
Please note, the code above should contain additional error handling, especially it should be called in a loop until EnumServicesStatusEx returns nonzero. But unfortunetaly as I found out, GetLastError() always returns 1 (ERROR_INVALID_FUNCTION) even if the buffer is correctly filled with data.
*1: Testing if a process was started by a service: In this case you could use a combination of other solutions. One could test, if the process has a parent (grandparent...) process that is a registered as a service. You could use CreateToolhelp32Snapshot API for this purpose. However if the parent process is already killed, things getting difficult. I'm sure there are any undocumented settings which can determine whether a process is running as a service apart from the usual suspects like SessionId = 0, WindowStation = 0, WSF_VISIBLE, No Interactive Group membership...
There is a simple way to detect whether the application is started as a service. When you create a service with CreateService, pass in lpBinaryPathName parameter some additional argument, say -s which would indicate that your application is started as a service. Then in the application you can check for this argument. It can also possibly help when debugging, because you can test your service functionality without actually running as a service. If StartServiceCtrlDispatcher fails with ERROR_FAILED_SERVICE_CONTROLLER_CONNECT, you can set a flag indicating the program is running as a console application simulating a service mode, so you can skip service related API calls using this flag.
Process in normal user session always has a window station called WinSta0.
wchar_t buffer[256] = {0};
DWORD length = 0;
GetUserObjectInformation(GetProcessWindowStation(), UOI_NAME, buffer, 256, &length);
if (!lstricmp(buffer, "WinSta0")) {
// normal user session
} else {
// service session
}