The class is not configured to support Elevated activation - c#

When I try to load a COM visible C#.net assembly from a Delphi application, "The class is not configured to support Elevated activation" error pops up on windows server 2012.
Is there a way to configure it to support elevated activation programmatically ?
Currently to avoid, privilege level is set to "Run as administrator".

That's the CO_E_ELEVATION_DISABLED error. It may happen if the class is not properly registered for elevation in the registry. You can find how to register it in MSDN:
The COM Elevation Moniker
The COM class must also be annotated as LUA-Enabled. This requires the following registry entry:
HKEY_LOCAL_MACHINE\Software\Classes\CLSID
{CLSID}
Elevation
Enabled = 1
If this entry is missing, then the activation returns the error CO_E_ELEVATION_DISABLED.
Note that these entries must exist in the HKEY_LOCAL_MACHINE hive, not the HKEY_CURRENT_USER or HKEY_USERS hive. This prevents users from elevating COM classes that they did not also have the privileges to register.
More info is in this blog post:
Local elevation points in Windows and Delphi

Related

Setting Registry from windows service does not work

I am setting or reading reg key from a windows services which runs as local system.
But when I read or set the values in the Registry Editor they are not the same as when i read and set them from the windows services.
If I execute the following command in powershell from the windows services or when i am logged in as a user the results differ as well. Why? Is there a different LocalMachine for a LocalSystem account?
$DefaultUserName = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name "DefaultUserName").DefaultUserName
Write-Host $DefaultUserName
I am using the following c# lines to execute the powershell script from the windows service:
var process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = #"C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe";
process.StartInfo.Arguments = "\"&'" + cacheFile + "'\"";
process.StartInfo.Verb = "runas";
process.Start();
You need to be careful of bitness. On 64-bit Windows, 32-bit applications run using the 'Windows on Windows' subsystem, which by default uses different filesystem paths and registry paths. You are executing powershell from the SysWOW64 folder, which means you are executing the 32-bit version, which will use the 32-bit registry hive.
If you open up regedit, the 32-bit hive for your registry key is: Computer\HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows NT\CurrentVersion\Winlogon. I suspect you are getting/setting this value.
Please refer to How to access a 64Bit Registry key using 32Bit Powershell without Redirection to WOW6432Node for strategies you can take, including using the Sysnative rather than SysWOW64 version of powershell.
If you need to support 32-bit and 64-bit operating systems, you will need to make sure you are using the appropriate technique.
This answer has beautiful explanation of Windows built in accounts :
The difference between the 'Local System' account and the 'Network Service' account?
A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user
Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)
Also can you try running the service as SYSTEM?

Detecting elevated privileges on Windows Server 2008 or higher

I have an C#, .Net 4.6.1 Windows Forms Application running on Windows Server Platforms (2008 or higher) which requires to be "Run as Administrator". Elevated privileges are required because the application changes User Access Rights on various folders (underneath the IIS Default Web Site Root if that matters).
I have no luck in detecting if the application has been "Run as Administrator". If I start the application normally (that is not as Administrator) the following code
var isAdmin = WindowsIdentity.GetCurrent().Owner.IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid);
returns true but the code which changes some User Access Rights on a Directory fails with a Insufficient Privileges Error.
If I run the application as administrator the above check also returns true, but the changing of User Access rights works just fine.
Other attempts I have made without success:
Using the GetTokenInformation method inside the advapi32.dll as suggested here
Adding a manifest file to the application where I set the requestedExecutionLevel to requireAdministrator
Thanks in advance for any help.
The following must work (I hope so; I have a Windows client and it's working with me).
var Identity = WindowsIdentity.GetCurrent();
var Principal = new WindowsPrincipal(Identity);
bool IsAdmin = Principal.IsInRole(WindowsBuiltInRole.Administrator);
Try to change the permissions of a known folder and if there is an exception then you know the program has not been run as administrator.

Loss of admin privileges when Java program calls C# program to write to %ProgramData%

The scenario:
I have a Java based installer.
The Java based installer calls a C# program, whose job is to create a shortcut.
The shortcut location depends on if the installer is running as administrator or as a regular user. When running as admin, I'm trying to create a shortcut to "%ALLUSERSPROFILE%\Desktop", else I write to "%USERPROFILE%\Desktop".
My impression is that the issue seems to be a loss of administrative privilege when my Java program calls my C# shortcut maker program.
Notes:
I run my Java based installer as administrator (right click, run as administrator).
I'm able to verify the installer is running with administrator privileged because I can read registry keys that require administrative privilege.
I'm calling my C# program via 'Process process = Runtime.getRuntime().exec(command);'
When running the command manually through an administrative command prompt, the command works fine. (When outputting to "%ALLUSERSPROFILE%\Desktop")
When running the the same command manually, from a normal command prompt, I get System.UnauthorizedAccessException. (Which is to be expected). The program crashes in a similar was that it does when run from the installer.
The Exception:
Unhandled Exception: System.UnauthorizedAccessException: Access is
denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) at
IWshRuntimeLibrary.IWshShortcut.Save()
Any thoughts on what I'm missing? The installer needs to be flexible to run as both a normal user and as an administrator. How can I ensure this behavior?
Update 1
I attached a debugger to the C# program at runtime. It is throwing a:
DirectoryNoFoundException was unhandled
The system cannot find the path specified. (Exception from HRESULT: 0x80070003)
I added "mkdir" commands before my shortcutmaker commands. The mkdir commands, just ensure that the directories exist before trying to write to them.
Rebuilt the installer, ran it and when trying to mkdir "%ALLUSERSPROFILE%\Desktop", java throws an exception of
java.io.IOException: Cannot run program "mkdir": CreateProcess error=2, The system cannot find the file specified
java.io.IOException: Cannot run program "mkdir": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
At this point, it looks like my process isn't getting admin access
Process process = Runtime.getRuntime().exec(command);
I'm going to see if I can find anything else.
Update 2
The following gave me some info that I tried: Enterprise Logging not translating environment variables in XML Trace Listener fileName specification
It suggested that %ALLUSERSPROFILE% was not getting translated.
Instead of %ALLUSERSPROFILE%, I got the environment variable values via:
String allUsersProfile = System.getenv("ALLUSERSPROFILE");
String userProfile = System.getenv("USERPROFILE");
I was then able to supply the actual values to the C# program. But I'm still having issues.
From a admin console I can navigate to "c:\ProgramData\Start Menu", but if I run "explorer" with administrative priviledges, I can navigate to "c:\ProgramData" but not see anything past that... Through some looking, I found out that "c:\ProgramData\Start Menu" is a protected operating system file. So I turned on the setting to see it. So now I can see it, but not go into it.
Using system internals, I elevated an explorer.exe to "system" access and still can't go into the folder (System internal elevation reference: http://verbalprocessor.com/2007/12/05/running-a-cmd-prompt-as-local-system/)
I right clicked on the folder and checked out the security tab. It looks like even my "System" user has limited access. I find this a bit baffling, that I can run the command from an admin command prompt that will write the shortcut to the desktop, but going through this other process I cannot... I also find the access to be a bit inconsistent.

Stop/Start service in code in Windows 7

I am trying to write a app and service which monitor a given set of services and a) makes sure they are running and b) based on certain criteria, restart them as needed.
I keep running into an access denied error.
If I simply iterate through the processes on the system, find the one I want like so:
foreach (ServiceController sc in ServiceController.GetServices())
{
if(sc.ServiceName == "MyServiceName")
{
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 60));
sc.Start();
}
}
I get:
InnerException: System.InvalidOperationException
Message="Cannot open My Service service on computer '.'."
Source="System.ServiceProcess"
StackTrace:
at System.ServiceProcess.ServiceController.GetServiceHandle(Int32 desiredAccess)
at System.ServiceProcess.ServiceController.Stop()
at lib.ListServices() in D:\lib.cs:line 552
at lib.Init() in D:\lib.cs:line 56
InnerException: System.ComponentModel.Win32Exception
Message="Access is denied"
ErrorCode=-2147467259
NativeErrorCode=5
InnerException:
I have tried to impersonate a user, I have tried to do the same code from another service which is running as a system service. Neither of which have actually been able to affect the service. If its started, I cannot stop it. If its stopped, I cannot start it. I know this is all related to permissions I'm just not finding a mechanism that actually lets me control the service.
Any assistance would be greatly appreciated.
Diagnoses:
UAC is indeed the problem. Your application requires elevated user rights. That is why the "run as administrator" works outside of the IDE.
Some sites suggest disabling UAC. As this is not a possibility in my environment, I decided to request elevated user right via code. Wikipedia provided the help I needed. The "Requesting elevation" section provides the solution.
The solution in short:
Edit your application manifest file to reflect your requirement.
1.1. Right click your project
1.2. Click "Properties"
1.3. Select "Application" tab - default page
1.4. Click "View UAC Settings" - This button opens the application manifest file (app.manifest)
1.5. Look for the "UAC Manifest Options" section
1.6. Remove or comment the current entry - {requestedExecutionLevel level="asInvoker" uiAccess="false"}
1.7. Change to {requestedExecutionLevel level="requireAdministrator" uiAccess="false"}. MS provides your 3 options as part of the section comment.
I think this is UAC fault...
Try to run the exe with right click and "Run as Administrator".
If that helps, you might want to add a Manifest file to your executable project with level="requireAdministrator".
Could it be the .net security policy that is preventing your app from controlling the service?
According to MSDN, your assembly needs full trust for this to work.
You have to set the application to run as administrator. If you look under the files properties menu. On the compatibility tab, there is a Privilige Level option, to let the program run as administrator. It worked with my own system trays in windows 7.

Window Service In C# (ServiceProcessInsaller) -- Error 5: Access is Denied

I am using Visual Studio 2008 and .NetFramework 3.5.
I developed one windows service application in c# using FileSystemWatcher. The main goal of this project is watch an Folder and need to write the modification status in a text file (FolderWatchLog.txt). That text file appeared on another folder.
In ServiceInstaller I specified the StartType=Manual and in ServiceProcessInstaller I specified Account=LocalSystem property.
The issue is, in my pc (Microsoft Windows XP Professional Version 2002 Service Pack 2), I have 2 users. 1 user has ADMIN permission and the 2nd user has LIMITED permission. I developed this applicaion in ADMIN power user and installed (installutil FolderWath.exe). I can start or stop perfectly. But if I logged in the 2nd user (LIMITED permission user), then I CAN'T start or stop the service. I got the error message Could not start the FolderWatch service on LocalComputer. Error 5: Access is Denied. So, I changed the ServiceProcessInstaller Account property. But at that time I got another error in both ADMIN & LIMITED permission users. That error message was FolderWatchLog.txt Access is Denied.
My requirement is this FolderWatch service need to has full access permission for all type of users.

Categories

Resources