LenPayne
LenPayne

Reputation: 105

Why does my ASP.NET application need Administrator rights to read from the registry?

I've looked at a couple of StackOverflow threads now. This comes closest.

I'm stuck using VS2005, and .NET 2.0. The server is Win2008. Not R2.

I'm building a C# ASP.NET web application that reads information from a database that's modified by a VB6 application. The database configuration settings are stored in the registry.

I'm using the Registry.GetValue() function and it's returning a null value.

If I make the Application Pool run as Administrator, the code returns the expected value. With any other user, the ToString throws a System.NullReferenceException. I have tried the following:

  1. Making the AppPool use and assigning Full Control to the following users does not work:
    1. NT AUTHORITY\NETWORK SERVICE
    2. NT AUTHORITY\SYSTEM
    3. NT AUTHORITY\LOCAL SERVICE
    4. A custom user in the Administrators group.
  2. I cannot apply permissions to IIS APPPOOL\DefaultAppPool because the user doesn't seem to exist. This is a documented fault of Server 2008.
  3. If I make the AppPool use the Administrator account, the system works.

Attached is the relevant code:

string root = "HKEY_CURRENT_USER";
string keyName = @"Software\Some\Key\Somewhere\";
string valueName = "someValue";
string fullKey = root + @"\" + keyName;
object keyValue;
try
{
    keyValue = Registry.GetValue(fullKey, valueName, "Value not found.");
    string val = keyValue.ToString();
    return val;
}
catch (Exception ex)
{
    return ex.GetType().ToString();
}

Unless it's running as Administrator, the above code always returns a System.NullReferenceException when running keyValue.ToString(). It never throws the System.Security.SecurityException.

I'm not eager to make my web app require Admin access.

Upvotes: 2

Views: 1602

Answers (1)

to StackOverflow
to StackOverflow

Reputation: 124696

You are searching under the key for the current user. Clearly the data exists under the key for the Administrator but not for the other users.

For the service accounts that don't have a profile, HKEY_CURRENT_USER resolves to HKEY_USERS.Default.

So to make it work with service accounts, you need to add the value to

HKEY_USERS\.Default\Software\Some\Key\Somewhere\

To make it work for the custom user in the Administrators group, you need to add it to

HKEY_USERS\<sid>\Software\Some\Key\Somewhere\

where is the SID of the custom user.

This isn't related to needing Admin access, you're just looking in the wrong place!

If the data isn't user-specific, try putting it in:

HKEY_LOCAL_MACHINE\Software\Some\Key\Somewhere\

then all the users will normally be able to read the same value.

Upvotes: 2

Related Questions