Enable non-admin users to start or stop Windows services - c++

I wrote my own windows service. I want to start and stop it from a non-admin account too. I know that I can set it manually in system security settings. But, I want to know, is there a way to set it inside my windows services code(like using Security_attribute)? What I want is a code in C++, to include in the windows service's code. It must enable my service to start even from non-admin accounts.

Actually, there are already some ways to meet your needs. You could refer to this link for more information.
Primarily, there are two ways in which to Start / Stop a Windows Service. 1. Directly accessing the service through logon Windows user account. 2. Accessing the service through IIS using Network Service account.
Command line command to start / stop services:
C:/> net start <SERVICE_NAME>
C:/> net stop <SERVICE_NAME>
C# Code to start / stop services:
ServiceController service = new ServiceController(SERVICE_NAME);
//Start the service
if (service.Status == ServiceControllerStatus.Stopped)
{
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10.0));
}
//Stop the service
if (service.Status == ServiceControllerStatus.Running)
{
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10.0));
}
Note 1: When accessing the service through IIS, create a Visual Studio C# ASP.NET Web Application and put the code in there. Deploy the WebService to IIS Root Folder (C:\inetpub\wwwroot) and you're good to go. Access it by the url http:///.
1. Direct Access Method
If the Windows User Account from which either you give the command or run the code is a non-Admin account, then you need to set the privileges to that particular user account so it has the ability to start and stop Windows Services. This is how you do it. Login to an Administrator account on the computer which has the non-Admin account from which you want to Start/Stop the service. Open up the command prompt and give the following command:
C:/>sc sdshow <SERVICE_NAME>
Output of this will be something like this:
D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)
It lists all the permissions each User / Group on this computer has with regards to .
A description of one part of above command is as follows:
D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)
It has the default owner, default group, and it has the Security descriptor control flags (A;;CCLCSWRPWPDTLOCRRC;;;SY):
ace_type - "A": ACCESS_ALLOWED_ACE_TYPE,
ace_flags - n/a,
rights - CCLCSWRPWPDTLOCRRC, please refer to the Access Rights and Access Masks and Directory Services Access Rights
CC: ADS_RIGHT_DS_CREATE_CHILD - Create a child DS object.
LC: ADS_RIGHT_ACTRL_DS_LIST - Enumerate a DS object.
SW: ADS_RIGHT_DS_SELF - Access allowed only after validated rights checks supported by the object are performed. This flag can be used alone to perform all validated rights checks of the object or it can be combined with an identifier of a specific validated right to perform only that check.
RP: ADS_RIGHT_DS_READ_PROP - Read the properties of a DS object.
WP: ADS_RIGHT_DS_WRITE_PROP - Write properties for a DS object.
DT: ADS_RIGHT_DS_DELETE_TREE - Delete a tree of DS objects.
LO: ADS_RIGHT_DS_LIST_OBJECT - List a tree of DS objects.
CR: ADS_RIGHT_DS_CONTROL_ACCESS - Access allowed only after extended rights checks supported by the object are performed. This flag can be used alone to perform all extended rights checks on the object or it can be combined with an identifier of a specific extended right to perform only that check.
RC: READ_CONTROL - The right to read the information in the object's security descriptor, not including the information in the system access control list (SACL). (This is a Standard Access Right, please read more http://msdn.microsoft.com/en-us/library/aa379607(VS.85).aspx)
object_guid - n/a,
inherit_object_guid - n/a,
account_sid - "SY": Local system. The corresponding RID is SECURITY_LOCAL_SYSTEM_RID.
Now what we need to do is to set the appropriate permissions to Start/Stop Windows Services to the groups or users we want. In this case we need the current non-Admin user be able to Start/Stop the service so we are going to set the permissions to that user. To do that, we need the SID of that particular Windows User Account. To obtain it, open up the Registry (Start > regedit) and locate the following registry key.
LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
Under that there is a seperate Key for each an every user account in this computer, and the key name is the SID of each account. SID are usually of the format S-1-5-21-2103278432-2794320136-1883075150-1000. Click on each Key, and you will see on the pane to the right a list of values for each Key. Locate "ProfileImagePath", and by it's value you can find the User Name that SID belongs to. For instance, if the user name of the account is SACH, then the value of "ProfileImagePath" will be something like "C:\Users\Sach". So note down the SID of the user account you want to set the permissions to.
Note2: Here a simple C# code sample which can be used to obtain a list of said Keys and it's values.
//LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList RegistryKey
RegistryKey profileList = Registry.LocalMachine.OpenSubKey(keyName);
//Get a list of SID corresponding to each account on the computer
string[] sidList = profileList.GetSubKeyNames();
foreach (string sid in sidList)
{
//Based on above names, get 'Registry Keys' corresponding to each SID
RegistryKey profile = Registry.LocalMachine.OpenSubKey(Path.Combine(keyName, sid));
//SID
string strSID = sid;
//UserName which is represented by above SID
string strUserName = (string)profile.GetValue("ProfileImagePath");
}
Now that we have the SID of the user account we want to set the permissions to, let's get down to it. Let's assume the SID of the user account is S-1-5-21-2103278432-2794320136-1883075150-1000. Copy the output of the [sc sdshow ] command to a text editor. It will look like this:
D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)
Now, copy the (A;;CCLCSWRPWPDTLOCRRC;;;SY) part of the above text, and paste it just before the S:(AU;... part of the text. Then change that part to look like this: (A;;RPWPCR;;;S-1-5-21-2103278432-2794320136-1883075150-1000)
Then add sc sdset at the front, and enclose the above part with quotes. Your final command should look something like the following:
sc sdset <SERVICE_NAME> "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)(A;;RPWPCR;;;S-1-5-21-2103278432-2794320136-1883075150-1000)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)"
Now execute this in your command prompt, and it should give the output as follows if successful:
[SC] SetServiceObjectSecurity SUCCESS
Now we're good to go! Your non-Admin user account has been granted permissions to Start/Stop your service! Try loggin in to the user account and Start/Stop the service and it should let you do that.
2. Access through IIS Method
In this case, we need to grant the permission to the IIS user "Network Services" instead of the logon Windows user account. The procedure is the same, only the parameters of the command will be changed. Since we set the permission to "Network Services", replace SID with the string "NS" in the final sdset command we used previously. The final command should look something like this:
sc sdset <SERVICE_NAME> "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)(A;;RPWPCR;;;NS)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)"
Execute it in the command prompt from an Admin user account, and voila! You have the permission to Start / Stop the service from any user account (irrespective of whether it ia an Admin account or not) using a WebMethod. Refer to Note1 to find out how to do so.

Related

Is there a way to pass credentials programmatically for using google documentAI without reading from a disk?

I am trying to run the demo code given in pdf parsing of GCP document AI. To run the code, exporting google credentials as a command line works fine. The problem comes when the code needs to run in memory and hence no credential files are allowed to be accessed from disk. Is there a way to pass the credentials in the document ai parsing function?
The sample code of google:
def main(project_id='YOUR_PROJECT_ID',
input_uri='gs://cloud-samples-data/documentai/invoice.pdf'):
"""Process a single document with the Document AI API, including
text extraction and entity extraction."""
client = documentai.DocumentUnderstandingServiceClient()
gcs_source = documentai.types.GcsSource(uri=input_uri)
# mime_type can be application/pdf, image/tiff,
# and image/gif, or application/json
input_config = documentai.types.InputConfig(
gcs_source=gcs_source, mime_type='application/pdf')
# Location can be 'us' or 'eu'
parent = 'projects/{}/locations/us'.format(project_id)
request = documentai.types.ProcessDocumentRequest(
parent=parent,
input_config=input_config)
document = client.process_document(request=request)
# All text extracted from the document
print('Document Text: {}'.format(document.text))
def _get_text(el):
"""Convert text offset indexes into text snippets.
"""
response = ''
# If a text segment spans several lines, it will
# be stored in different text segments.
for segment in el.text_anchor.text_segments:
start_index = segment.start_index
end_index = segment.end_index
response += document.text[start_index:end_index]
return response
for entity in document.entities:
print('Entity type: {}'.format(entity.type))
print('Text: {}'.format(_get_text(entity)))
print('Mention text: {}\n'.format(entity.mention_text))
When you run your workloads on GCP, you don't need to have a service account key file. You MUSTN'T!!
Why? 2 reasons:
It's useless because all GCP products have, at least, a default service account. And most of time, you can customize it. You can have a look on Cloud Function identity in your case.
Service account key file is a file. It means a lot: you can copy it, send it by email, commit it in Git repository... many persons can have access to it and you loose the management of this secret. And because it's a secret, you have to store it securely, you have to rotate it regularly (at least every 90 days, Google recommendation),... It's nighmare! When you can, don't use service account key file!
What the libraries are doing?
There are looking if GOOGLE_APPLICATION_CREDENTIALS env var exists.
There are looking into the "well know" location (when you perform a gcloud auth application-default login to allow the local application to use your credential to access to Google Resources, a file is created in a "standard location" on your computer)
If not, check if the metadata server exists (only on GCP). This server provides the authentication information to the libraries.
else raise an error.
So, simply use the correct service account in your function and provide it the correct role to achieve what you want to do.

How to retrieve the display name that represents a specified Account Rights constant?

I am trying to work out which Win32 API function is appropriate for retrieving the display name of an Account Rights (User Rights) constant name.
I am aware the LookupPrivilegeDisplayName function exists to retrieve the display name that represents a specified Privilege, but not the Account Rights.
For example, the SeDenyInteractiveLogonRight constant (Account Rights) is mapped to the display name Deny log on locally, which you can see in the Local Group Policy editor (gpedit) in Windows.
See information on Account Rights Constants, which I am trying to fetch the display names for these 10 constants.
https://learn.microsoft.com/en-au/windows/desktop/SecAuthZ/account-rights-constants
I have searched in MSDN and Googled without success. Anyone who knows the appropriate function that can do the job please tell me. Thanks.

AWS RDS Super Privileges

We have AWS RDS instance. We would like to track database user login details like the last login. For this, we have written a stored procedure and we would like to call that procedure on the event init_connect. But we are not able to set the trigger. I am using below command to set it up.
SET GLOBAL init_connect="CALL track.log_trigger()"
and I am getting below error.
Error Code: 1227. Access denied; you need (at least one of) the SUPER
privilege(s) for this operation.
But when I try to set the super to user it again gives an error.
grant super on *.* to user1;
Error Code: 1045. Access denied for user 'root'#'%' (using password:
YES) so unable to use it by normal user, by root user and unable to
set SET GLOBAL init_connect.
Any help is appreciated.

Find files accessible outside of my organization

In the Drive.Files.List I can, using the 'q' parameter, get all files a user can read/write or own. I would like to be able to use regular expression in the query value. For example set q to be "not '.+#my-org.com' in writers".
Is such a query already supported?
Do I have another way (except invoking Drive.Permissions.List for each and every file in my Drive) to get this information from?
Seems the only account level drive API is part of the report API - activities list. This API (and admin console - audit - drive) section is only supported in the unlimited license. Still haven't found the proper API get the drive state (list all files metadata in the account, permissions etc.) seems that the state can only be inferred from analyzing the relevant activity events assuming the activity is not being evicted after a predefined period of time.
My conclusion, at the moment, is that there is no "root" directory at the account level. "root" is only with respect to the logged in user.
I would be more than happy to be proved wrong.
Uri

In windows - API - How to get/use the current users privileges( or single sign on)

I am using vc++. I am trying to create a "front end" which will create a task and put that in " Window's native Scheduler". The task's action is invoking a backup app. Every task needs some privileges to execute the given program. I need to assign administrator privileges to this task. I can assure that the front end can be run by admin only. Now I want to use assign the current user's(admin) privileges to the task. Upto the dig I did in internet/msdn , the api provides below two options( 3rd option is my assumption)
1) Provide account name,password for that task.
2) Use flag "TASK_FLAG_RUN_ONLY_IF_LOGGED_ON", and give the administrator "account name", and password as NULL.
3)Single Sign on
Now the constraints:
1->It is not a good idea to make the client to type the admin account name and password frequently
2->Admin Account name is not always the same(in XP it is possible to change it). So I can't provide a default admin account name.
3-> I don't know how to achieve it. The "single sign on" is something like once you logged in as admin, then the applications can get the current(logged in) user's privileges.
Searching MSDN for this is like "searching a needle in hay stack". Somebody, please shed a light on the solution.
Maybe LocalSystem Account
http://msdn.microsoft.com/en-us/library/ms684190(VS.85).aspx