From b99cfc38fcf4fbf5c87e23f93a02d1d6a6d931ca Mon Sep 17 00:00:00 2001 From: Iain Patterson Date: Sat, 8 Oct 2011 11:02:51 +0100 Subject: [PATCH] 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. --- nssm.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/nssm.cpp b/nssm.cpp index 2933dea..4203c61 100644 --- a/nssm.cpp +++ b/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)); -- 2.20.1