在没有管理员权限的情况下从应用程序启动 Windows 服务 (c++)

2021-12-05 00:00:00 windows service c++

我编写了一个 Windows 服务(并且运行良好).现在我有一个单独的应用程序,我想从中启动此服务,但如果没有管理员权限,这似乎是不可能的.

I wrote a windows service (and it runs fine). Now i have a separate app where I want to start this service from, but it seems this is not possible without administrator rights.

用户可以启动/停止服务(例如从托盘或应用程序)的正确解决方案是怎样的

How would a proper solution look like that a user can start/stop the service (e.g. from a tray or application)

恕我直言,应用程序必须始终以管理员权限启动是不好的.

IMHO its bad that the application must always be started with administrator rights.

推荐答案

您只需要更改服务对象的权限,最好在安装的同时更改.

You just need to change the permissions on the service object, preferably at the same time you install it.

wchar_t sddl[] = L"D:"
  L"(A;;CCLCSWRPWPDTLOCRRC;;;SY)"           // default permissions for local system
  L"(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)"   // default permissions for administrators
  L"(A;;CCLCSWLOCRRC;;;AU)"                 // default permissions for authenticated users
  L"(A;;CCLCSWRPWPDTLOCRRC;;;PU)"           // default permissions for power users
  L"(A;;RP;;;IU)"                           // added permission: start service for interactive users
  ;

PSECURITY_DESCRIPTOR sd;

if (!ConvertStringSecurityDescriptorToSecurityDescriptor(sddl, SDDL_REVISION_1, &sd, NULL))
{
   fail();
}

if (!SetServiceObjectSecurity(service, DACL_SECURITY_INFORMATION, sd))
{
   fail();
}

我在这里假设您已经打开了服务句柄.您需要 WRITE_DAC 权限.

I'm assuming here you've already opened the service handle. You need WRITE_DAC permission.

如果您还希望非管理员用户能够停止服务,请添加 WP 权限,即

If you also want non-admin users to be able to stop the service, add the WP right, i.e.,

L"(A;;RPWP;;;IU)"                           
  // added permissions: start service, stop service for interactive users

服务权限的 SDDL 代码可以在 Wayne Martin 的博客条目中找到,非管理员的服务控制管理器安全.

SDDL codes for service rights can be found in Wayne Martin's blog entry, Service Control Manager Security for non-admins.

相关文章