views:

308

answers:

3

I've inherited a hoary old piece of code (by hoary, I mean warty with lots of undocumented bug fixes than WTF-y) and there's one part that's giving me a bit of trouble. Here's how it connects to the remote registry to get the add/remove programs key:

try
            {

                remoteKey = RegistryKey.OpenRemoteBaseKey(
                    RegistryHive.LocalMachine, addr.Value).OpenSubKey(
                    "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall");
                return 1;
            }
            catch (IOException e)
            {
                IOException myexception = e;
                //Console.WriteLine("{0}: {1}: {2}",
                //    e.GetType().Name, e.Message, addr.Value);
                return 2;
            }
            catch (UnauthorizedAccessException e)
            {
                UnauthorizedAccessException myexception = e;
                //Console.WriteLine("{0}: {1}: {2}",
                //    e.GetType().Name, e.Message, addr.Value);
                return 3;
            }
            catch (System.Security.SecurityException e)
            {
                System.Security.SecurityException myexception = e;
                //Console.WriteLine("{0}: {1}: {2}",
                //    e.GetType().Name, e.Message, addr.Value);
                return 4;
            }

Now, I have two problems:

  • I know why the IOException - if it's a non-Windows machine it'll throw that. The difference between UnauthorizedAccessException and SecurityException I'm not so clear on. Anyone got any ideas?

  • This entire bit of code was designed before anyone had thought you might not use your local logon for everything. I can't work out how you do authentication for remotely connecting to the registry, anyway, and this code looks like it's only used in one case, when it can't get this information from WMI.

Any help with either would be great.

+1  A: 

You probably have to use impersonation to change the credentials of the thread that calls the remote registry methods. See here (linky) for some information on MSDN. Basically, your thread has a security context that is used to make managed and unmanaged calls.

Garo Yeriazarian
+1  A: 

According to MSDN, UnauthorizedAccessException is not thrown by OpenSubKey. So I think it's not needed.

John
A: 

John's pointer to MSDN answered what UnauthorizedAccessException is for - it only appears when you try to access a key remotely, using OpenRemoteBaseKey.

We're a little wary about changing the security context on the computer - I've found a reference here about using WMI (which we're already using for the vast majority of the heavy lifting) to access the registry, so I might try that instead.

Merus