Browse Source

Check for administrator privileges.

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.
Iain Patterson 12 years ago
parent
commit
b99cfc38fc
1 changed files with 24 additions and 0 deletions
  1. 24 0
      nssm.cpp

+ 24 - 0
nssm.cpp

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