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.
Related
I'm trying to disable Internet Explorer 11 AutoComplete for usernames and passwords on forms using the Windows Registry in a c# application.
The following code works some times (browser stops asking to save passwords and the checkboxes in AutoComplete Settings is unchecked), and fails at other times (that is, no exceptions but the browser still asks if you want to save passwords, and the checkboxes in AutoComplete settings are checked).
My question:
Is there another key that controls password saving, or is it perhaps failing due to the user's privileges? Or am I assigning the wrong value to the subkeys? Why would it work sometimes and fail silently others?
Another question: If a website is running in compatibility view, which displays webpages as if they were viewed by an earlier version of the browser, does IE11 then use the registry keys from the older versions (eg, HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\AutoComplete?)
// Keys I am manipulating:
// HKCU\Software\Microsoft\Internet Explorer\Main\FormSuggest Passwords
// HKCU\Software\Microsoft\Internet Explorer\Main\FormSuggest PW Ask
// others?
RegistryKey regKey1 = default(RegistryKey);
regKey1 = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Internet Explorer\Main", true);
regKey1.SetValue("FormSuggest Passwords", "no", RegistryValueKind.String);
regKey1.Close(); //are these values ok?
RegistryKey regKey2 = default(RegistryKey);
regKey2 = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Internet Explorer\Main", true);
regKey2.SetValue("FormSuggest PW Ask", "no", RegistryValueKind.String);
regKey2.Close();
Edit:
I have since discovered several other registry items that appear related to Auto Complete, but it is unclear which version of Internet Explorer these apply to. It also seems very difficult to find information about IE 11 registry settings in general.
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\AutoComplete
HKEY_CURRENT_USER\Software\Policies\Microsoft\Internet Explorer\Control Panel\FormSuggest
HKEY_CURRENT_USER\Software\Policies\Microsoft\Internet Explorer\Control Panel\FormSuggest Password
Setting access control for the registry key might help to resolve your problem
example
string user = Environment.UserDomainName + "\\" + Environment.UserName;
RegistrySecurity regSecurity = new RegistrySecurity();
rs.AddAccessRule(new RegistryAccessRule(user,
RegistryRights.ReadKey | RegistryRights.WriteKey,
InheritanceFlags.None,
PropagationFlags.None,
AccessControlType.Allow));
RegistryKey regKey1 = null;
try
{
regKey1 = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Internet Explorer\Main",
RegistryKeyPermissionCheck.Default, rs);
regKey1.SetValue("FormSuggest Passwords", "no",RegistryValueKind.String);
}
catch (Exception ex)
{
Console.WriteLine("\r\nUnable to read key: {0}", ex);
}
These keys are also accessed by Internet Explorer when internet options->autocomplete is loaded:
HKCU\Software\Microsoft\Internet Explorer\DomainSuggestion\Enabled
HKLM\Software\Microsoft\Internet Explorer\DomainSuggestion
HKCU\Software\Microsoft\Internet Explorer\Main\Use FormSuggest
HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\AutoComplete
HKCU\Software\Policies\Microsoft\Windows\CurrentVersion\Explorer\AutoComplete
Seems windows explorer and internet explorer share some autocomplete options.
You can use some registry monitoring tools to see what is being accessed in compatibility view. This is how I found these keys.
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
give the code below, lastuser string returns null, however, if I use regedit to look at this key it has data associated with it. Is LoggedOnSAMuser a restricted key?
public static string lastlogon()
{
string lastuser;
RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI",false);
if (registryKey != null)
{
lastuser = (string) registryKey.GetValue("LastLoggedOnSAMUser");
}
else lastuser = "Unknown User";
return (lastuser);
}
2 possible issues:
You are trying to read the LoggedOnSAMUser key, quite a chance you
meant LastLoggedOnSAMUser.
You might be trying to read a 64-bit registry entry from a 32-bit application. If possible, change your platform target to x64 and retry. If not possible, you might have to use the registry API directly. Hopefully a nudge in the right directon: link
Almost certainly you have a 32 bit process on a 64 bit machine and so are subject to registry redirection. Your 32 bit process, by default, reads from the 32 bit view of the registry. But you want to read from the 64 bit view.
Solve the problem by requesting that you read from the 64 bit view of the registry, by way of the RegistryView enumeration.
This seems to work on Windows 7
RegistryKey thisKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
RegistryKey thisSubkey = thisKey.OpenSubKey(#"SOFTWARE\\fred", false);
_url = (string)thisSubkey.GetValue("_url", "*");
_port = (string)thisSubkey.GetValue("_port", 0);
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
Before you try to answer this with, "Do a quick Google search." I'd like to point out that I have already. Here is the situation, I have the following method that attempts to modify a registry key value. The problem I'm getting is that when executed, it throws an UnauthorizedAccessException even though I've opened the key as writeable. I'm running Visual Studio as administrator and even tried to make a small .exe with a manifest file forcing it to run as admin that will execute the code with no luck. The key already exists, it doesn't try to go into the CreateKey method. Here is the block of code.
Path = "S-1-5-21-1644491937-1078145449-682003330-5490\Software\Microsoft\Windows\CurrentVersion\Policies\System"
Key = "DisableTaskMgr"
NewValue = 1
public OperationResult ModifyKey()
{
OperationResult result = new OperationResult();
if (!Path.IsNullOrEmptyTrim())
{
if (!Key.IsNullOrEmptyTrim())
{
try
{
var key = Microsoft.Win32.Registry.Users.OpenSubKey(Path, true);
if (key != null)
{
key.SetValue(Key, NewValue);
key.Close();
}
else
{
result = CreateKey();
}
}
catch (Exception ex)
{
result.SetFail("Error accessing registry", ex);
}
}
else
{
result.SetFail("Registry key was null");
}
}
else
{
result.SetFail("Registry path was null");
}
return result;
}
Do I have to manually walk down the registry tree setting each OpenSubKey call to writeable? I tried this as well, still threw the same error...
in the var for your key
var key = Microsoft.Win32.Registry.Users.OpenSubKey(Path, true);
change to
var key = Microsoft.Win32.Registry.Users.OpenSubKey(Path, RegistryKeyPermissionCheck.ReadWriteSubTree);
Have you tried setting the accessrule and permissions?
string user = Environment.UserDomainName + "\\" + Environment.UserName;
RegistryAccessRule rule = new RegistryAccessRule(user,
RegistryRights.FullControl,
AccessControlType.Allow);
RegistrySecurity security = new RegistrySecurity();
security.AddAccessRule(rule);
var key = Microsoft.Win32.Registry.Users.OpenSubKey(subKeyPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl);
key.SetAccessControl(security);
One possible issue that I see with your code is that the Path variable is being set to a string that doesn't escape the \ characters. How about something like:
Path = #"S-1-5-21-1644491937-1078145449-682003330-5490\Software\Microsoft\Windows\CurrentVersion\Policies\System";
As a last ditch effort to figure out what was going on, I created a simple service to test this code that will run as the local system account. It's the highest privileges I could think of to try and run the code with. Running the code with these permissions worked.
Special thanks go out to 0_____0 and Charleh for pointing out the anti-virus as well. I checked the logs and it turns out it was trying to quarantine my changes. I guess even it won't stop the System user from making these changes though.
Special thanks go out to Sorceri as well for helping me research this so much.
In conclusion, if you're having intermittent, extremely odd behavior, check your virus scanner and permissions.
I ran into the same problem recently. So I tried a few things and instead of calling key.SetValue(Key, NewValue) simply calling create function solved my problem. That is;
Microsoft.Win32.RegistryKey key1 = Microsoft.Win32.Registry.Users.CreateSubKey(Path);
key1.SetValue(Key, NewValue);
CreateSubKey call doesn't delete the current entry but provided with the ability to write without exception. I hope that helps.
Only set grants to dword. You must to open Registry and at the last folder path, rigth click over it and set Grants, and select All Aplications and check Total Control. I hope to help you.
just Registry.SetValue(sub_key, key, value);
Example:
Registry.SetValue(
#"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run",
"MyApp",
Application.ExecutablePath);