Check for administrator privileges.
authorIain Patterson <me@iain.cx>
Sat, 8 Oct 2011 10:02:51 +0000 (11:02 +0100)
committerIain Patterson <me@iain.cx>
Tue, 11 Oct 2011 10:05:22 +0000 (11:05 +0100)
If nssm is run without an administrator token it will fail to install or
remove services.  Check for the token and bomb out early rather than
waste the user's time filling in the form only to find the service can't
be managed.

nssm.cpp

index 2933dea..4203c61 100644 (file)
--- a/nssm.cpp
+++ b/nssm.cpp
@@ -27,10 +27,34 @@ int usage(int ret) {
   return(ret);\r
 }\r
 \r
+int check_admin(char *action) {\r
+  /* Lifted from MSDN examples */\r
+  PSID AdministratorsGroup;\r
+  SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;\r
+  BOOL ok = AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdministratorsGroup);\r
+  if (ok) {\r
+    if (! CheckTokenMembership(0, AdministratorsGroup, &ok)) ok = 0;\r
+    FreeSid(AdministratorsGroup);\r
+\r
+    if (ok) return 0;\r
+\r
+    fprintf(stderr, "Administator access is needed to %s a service.\n", action);\r
+    return 1;\r
+  }\r
+\r
+  /* Can't tell if we are admin or not; later operations may fail */\r
+  return 0;\r
+}\r
+\r
 int main(int argc, char **argv) {\r
   /* Require an argument since users may try to run nssm directly */\r
   if (argc == 1) exit(usage(1));\r
 \r
+  /* Elevate */\r
+  if (str_equiv(argv[1], "install") || str_equiv(argv[1], "remove")) {\r
+    if (check_admin(argv[1])) exit(100);\r
+  }\r
+\r
   /* Valid commands are install or remove */\r
   if (str_equiv(argv[1], "install")) {\r
     exit(pre_install_service(argc - 2, argv + 2));\r