How to set Registry Access Rule on a remote machine using c# - c#

I'm trying to set an registry access rule on a remote machine:
using (RegistryKey localMachineKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, serverName))
{
RegistrySecurity rs = new RegistrySecurity();
rs.AddAccessRule(new RegistryAccessRule(userName, RegistryRights.FullControl, AccessControlType.Allow));
using (RegistryKey subKey = localMachineKey.CreateSubKey(registryKey))
{
subKey.SetValue(name, value);
subKey.SetAccessControl(rs);
}
}
this produces the following exception:
System.NotSupportedException: The supplied handle is invalid. This can happen when trying to set an ACL on an anonymous kernel object.
at System.Security.AccessControl.NativeObjectSecurity.Persist(String name, SafeHandle handle, AccessControlSections includeSections, Object exceptionContext)
at System.Security.AccessControl.NativeObjectSecurity.Persist(SafeHandle handle, AccessControlSections includeSections, Object exceptionContext)
at System.Security.AccessControl.RegistrySecurity.Persist(SafeRegistryHandle hKey, String keyName)...
Does anyone know how to make this working?
Thanks!

Using WinRM might be an option.
How to access WinRM in C#
This link suggests that along with a bit more information:
http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/0beee366-ee8d-4052-b1b9-8ad9bf0f8ff0/
Part of the link suggests that it is not possible set this remotely. However, at the bottom, Shaka_01 mentions calling.SetAccessRuleProtection.
RegistryKey rk = RegistryKey.OpenRemoteBaseKey(...);
RegistrySecurity rs = rk.GetAccessControl(AccessControlSections.All);
rs.SetAccessRuleProtection(true, true); //this line you need to set ACL on a remote machines registry key.

Related

C# Access Remote Registry with Windows 10 not work

I use this code to get the installed .NET Version on a remote machine. With Windows 7 it works perfect but with Windows 10 the following exception throws
System.Security.SecurityException: Requested registry access is not allowed.
The user with i connect, is in the Administrators Group
The Service "RemoteRegistry" is set to Startup type "Manual"
Code example
using (RegistryKey remoteHklm = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, hostName))
{
using (RegistryKey serviceKey = remoteHklm.OpenSubKey(#"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full", true))
{
if (serviceKey != null)
{
version = serviceKey.GetValue("Version").ToString();
}
else
{
version = "error on get version from registry";
}
}
}
You have with Windows 10 no write Access to this registry key. Change the second OpenSubKey parameter to false, you can check in Registry Editor the permission of the key.
using (RegistryKey serviceKey = remoteHklm.OpenSubKey(#"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full", false))

Remote Registry Reads Not Working

I've searched and found a lot of good information on remote registry reads but nothing seems to address my problem. I've never had to ask for help before but I'm at a loss as to why I can't get my code to work. I have a mapped drive, on the same domain, so credentials are not the issue. I'm not getting access denied. My code is pretty much straight from the Microsoft examples. It should be pretty easy.
This code works with no problems:
string keyname = #"SOFTWARE\Microsoft\Windows\CurrentVersion";
RegistryKey rk = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "COMPUTER.opr.domain.org");
RegistryKey registryKey = rk.OpenSubKey(keyname);
string mykey = (string)registryKey.GetValue("DevicePath");
Console.WriteLine(mykey);
However, if I simply change the key as follows, it now fails with a null exception
string keyname = #"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update";
RegistryKey rk = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "COMPUTER.opr.domain.org");
RegistryKey registryKey = rk.OpenSubKey(keyname);
string mykey = (string)registryKey.GetValue("RebootRequired");
Console.WriteLine(mykey);
The key RebootRequired is present on the remote machine. And permissions don't seem to be an issue either. This is also my first post so I hope I did not violate any rules.
Thoughts?
Thanks,
Rob

Modify an existing registry key value in c#

I want to modify a data in registry path SOFTWARE\Wow6432Node\Program\SubProgram using C# code in windows 7. I am able to read the value but I can't write into Registry.
Here is the code:
RegistryKey SUBKEY;
RegistryKey TAWKAY = RegistryKey.OpenRemoteBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, "");
string subkey = "SOFTWARE\\Wow6432Node\\Program\\SubProgram ";
if (TAWKAY.OpenSubKey(subkey) != null) // Get values from Registry
{
TAWKAY = RegistryKey.OpenRemoteBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, "");
SUBKEY = TAWKAY.OpenSubKey(subkey); // subkey opens
SUBKEY = TAWKAY.OpenSubKey(subkey,true); // subkey not open shows error Requested registry access is not allowed
SUBKEY.SetValue("Some name", "1234567890");
Console.WriteLine(SUBKEY.GetValue("Some name").ToString());
}
else
{
Console.WriteLine("Cannot open registry");
}
Console.Read();
If I set OpenSubKey(subkey, true), it shows an error message Requested registry access is not allowed
Is there any permission needed to write into registry?
Please help me to solve the issue
Wow6432Node is not a real path in the registry. It is an alias for 32 bit keys in 64 bit OS.
You must use RegistryView.Registry32 in order to specify you want to work with 32 bits.
RegistryKey reg32key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
RegistryKey reg_32bit_AppKey = reg32key.OpenSubKey(#"SOFTWARE\Program\SubProgram");
if (reg_32bit_AppKey != null)
{
// Here you can work with "SOFTWARE\\Wow6432Node\\Program\\SubProgram "
}
Modifying/deleting/adding keys in HKLM requires administrator rights.
In that case you want to do that you will need to change your applications manifest requestedExecutionLevel value to requireAdministrator
It is better to use "Reg" command inorder to perform any operation on registry.
Even though if you want to access the registry of remote machine you don't nedd credentials of that machine, having the machine name is sufficient.
For more information about "REG" command refer to the following link
http://technet.microsoft.com/en-us/library/cc732643(v=ws.10).aspx

Issue in accessing the registry programmatically

I have a issue reading a registry value programmatically using C#.
I looked into many sites and help but could not find any helpful.
I am able to access and read registry when I run VS in eleveated mode, but face issue when I run VS with out elevated mode.
Initially I started with the below code
byte[] val = (byte[])Registry.GetValue("HKEY_LOCAL_MACHINE\\Software\\MyServices\\Identity\\ASPNET_SETREG", "ValueName", 0);
This worked fine with elevated mode, but fails in non elevated mode.
Placed the attribute on top of the function
[RegistryPermissionAttribute(SecurityAction.Demand,Unrestricted=true)]
This did not help. Then Tried
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.AllFlags)]
Still did not work.
Now I Tried the below code...
RegistryKey key = Registry.LocalMachine;
RegistrySecurity rs = new RegistrySecurity();
rs = key.GetAccessControl();
string user = "DomainName\\Username";
rs.AddAccessRule(new RegistryAccessRule(user,
RegistryRights.ReadKey,
InheritanceFlags.None,
PropagationFlags.None,
AccessControlType.Allow));
key.SetAccessControl(rs);//Exception: "Attempted to perform an unauthorized operation."}
//RegistryKey key2 = key.OpenSubKey("Software\\MyServices\\Identity\\ASPNET_SETREG");
//RegistryKey key2 = key.OpenSubKey("Software\\MyServices\\Identity\\ASPNET_SETREG", false);
//RegistryKey key2 = key.OpenSubKey("Software\\MyServices\\Identity\\ASPNET_SETREG", RegistryKeyPermissionCheck.ReadSubTree);
RegistryKey key2 = key.OpenSubKey("Software\\MyServices\\Identity\\ASPNET_SETREG", RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadPermissions);
Commenting SetAccessControl and use any of the OpenSubkey option, I get Exception: "Requested registry access is not allowed."
I am badly stuckup and unable to proceed.
private RegistryKey keyR = Registry.CurrentUser.OpenSubKey("Software\\YourKey",true);
private RegistryKey keyW = Registry.CurrentUser.CreateSubKey("Software\\YourKey");
public string version
{
get { return keyR.GetValue("VERSION", "", RegistryValueOptions.DoNotExpandEnvironmentNames).ToString(); }
set { keyW.SetValue("VERSION", value, RegistryValueKind.String); }
}
I am using windows registry in this way. No problem...
The windows registry is basically a structured file system, and has permissions for keys and values.
You do not have the permissions set correctly on ...\MyServices\ or deeper keys - you have no permission to access those from your unprivileged process.
Either:
Those keys should be readable by anybody, so you should change the permissions to make them readable by everybody. Or -
Those keys were intentionally restricted for a good reason, and so they should not be readable by everybody, in which case your program should always run elevated.

Programmatically adding Write permissions to files in WPF

In my WPF MVVM application,I have a XML file to modify.
It is successfully working In Visual Studio.
But It showing error, while running the installed application.
How can i set the Permissions Through code..
me used this code ,
// current security settings.
FileSecurity fSecurity = File.GetAccessControl(FilePath);
// Add the FileSystemAccessRule to the security settings.
string rr = WindowsIdentity.GetCurrent().Name;
fSecurity.AddAccessRule(new FileSystemAccessRule(WindowsIdentity.GetCurrent().Name,
FileSystemRights.FullControl, AccessControlType.Allow));
// Set the new access settings.
File.SetAccessControl(FilePath, fSecurity);
Still cant solve the Problem...,
Thanks in advance..
see the exception...
System.UnauthorizedAccessException: Attempted to perform an
unauthorized operation. at
System.Security.AccessControl.Win32.SetSecurityInfo(ResourceType type,
String name, SafeHandle handle, SecurityInfos securityInformation,
SecurityIdentifier owner, SecurityIdentifier group, GenericAcl sacl,
GenericAcl dacl) at
System.Security.AccessControl.NativeObjectSecurity.Persist(String
name, SafeHandle handle, AccessControlSections includeSections, Object
exceptionContext) at
System.Security.AccessControl.NativeObjectSecurity.Persist(String
name, AccessControlSections includeSections, Object exceptionContext)
at System.Security.AccessControl.NativeObjectSecurity.Persist(String
name, AccessControlSections includeSections) at
System.Security.AccessControl.FileSystemSecurity.Persist(String
fullPath) at System.IO.File.SetAccessControl(String path,
FileSecurity fileSecurity)
To set permissions mostly it requires power user rights(assuming your are running windows 7).
To verify above, launch the Visual studio as "Run as Administrator" and debug the your code.
What is exact exception message?
Here is working example: It sets full permissions for user group EveryOne
private static void WriteAcl ( string filename )
{
//Set security for EveryOne Group
SecurityIdentifier sid =new SecurityIdentifier(WellKnownSidType.WorldSid, null);
IdentityReference userIdentity =sid.Translate (typeof(NTAccount));
var AccessRule_AllowEveryOne = new FileSystemAccessRule ( userIdentity, FileSystemRights.FullControl, AccessControlType.Allow );
var securityDescriptor = new FileSecurity ();
securityDescriptor.SetAccessRule ( AccessRule_AllowEveryOne );
File.SetAccessControl ( filename, securityDescriptor );
}
This code works only if User Account Settings are set to Never notify. Looks its turned on at your computer?
A workaround is to launch your application as power user using Application Manifest.
http://msdn.microsoft.com/en-us/library/bb756929.aspx

Categories