Change system registry values on vb.net - vb.net

I want to change my computer's system registry value via vb.net
Dim regKey As RegistryKey
regKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Ole", True)
regKey.SetValue("EnableDCOM", "Y")
regKey.Close()
I've tried the above, however it gives no error but it simply doesn't change the value...

I hardly use VB, but I believe the below is the correct approach.
Dim autoshell = My.Computer.Registry.LocalMachine.OpenSubKey("Software\Microsoft\Windows NT\CurrentVersion\Winlogon", True)
'' Set the value to 0
autoshell.SetValue("autorestartshell", 0)
autoshell.Close()
If you experience errors, you need to check that:
You have permissions to read/write to the registry.
The subkey you are trying to change actually exists.
You should also consult the MSDN VB Documentation.

Related

IBM AppScan Security PathTraversal issue in File.Copy method in VB.Net

I ran IBM AppScan tool on a VB.Net source.I am getting one security issue in File.Copy method under Path Traversal category.
Issue Detail -
Vulnerability Type - PathTraversal
This API accepts a directory, a filename, or both. If user supplied data is used to create the file path, the path can be manipulated to point to directories and files which should not be allowed access or which may contain malicious data or code.
How can i fix this issue?
Imports System.Web.Security.AntiXss
Private Function ProcessFile() As Boolean
Dim drive As String = String.Empty
Dim folder As String = String.Empty
Dim filename As String = String.Empty
Dim sourcePath As String = String.Empty
Dim destinationPath As String = String.Empty
drive = AntiXssEncoder.XmlEncode(String.Format("{0}", System.Configuration.ConfigurationManager.AppSettings("Drive").ToString()))
folder = AntiXssEncoder.XmlEncode(String.Format("{0}", System.Configuration.ConfigurationManager.AppSettings("Folder").ToString()))
filename = AntiXssEncoder.XmlEncode(String.Format("{0}", System.Configuration.ConfigurationManager.AppSettings("File").ToString()))
sourcePath = Path.Combine(drive, folder, filename)
destinationPath = Path.Combine(drive, folder, "text2.txt")
Try
If sourcePath.IndexOfAny(Path.GetInvalidPathChars()) = -1 AndAlso destinationPath.IndexOfAny(Path.GetInvalidPathChars()) = -1 Then
File.Copy(sourcePath, destinationPath, True)
Return True
Else
Return False
End If
Catch ex As Exception
Return False
End Try
End Function
It's probably considering AppSettings to be untrusted user input (I've seen AppScan Source do similar with config on a Java project), so it's complaining that you're making a path with untrusted input that could have separators in.
If any of drive, folder and filename did come from untrusted this would definitely be a problem. Assuming however that your config is only accessible to trusted administrators this is nothing. It's pretty stupid that config is treated as an unchecked source, but then taint tracking tools are pretty stupid in general.
The handling of filenames here is rather wacky. It seems very unlikely that XML-encoding filenames before using them is a good idea; the ToString and Format steps are entirely superfluous; and checking the whole path for ‘invalid’ characters doesn't protect against injection from an individual part anyway. Is this stuff an attempt to work around AppScan? The InvalidPathChars check wouldn't help as it doesn't directly encode/validate and return the tainted value, and the XmlEncode would only help if that function were explicitly marked as a validation/encoding function.
It's sad to make code more broken in an attempt to satisfy a blunt instrument of a static analyser. Could you perhaps add a function to be used as a wrapper on AppSettings values and tell AppScan it is a validation/encoding function, so it doesn't think the values are tainted? Or just ignore/silence the bogus warning?
System.Configuration.ConfigurationManager.AppSettings can be considered as a safe source, you can just exclude the findings so it won't come up again.
On the other hand, this code can be considered as having poor secure coding practice. If you replace "System.Configuration.ConfigurationManager.AppSettings" with something like a web UI input, then the end user has control over the value of "folder" "drive" and "filename", this then becomes a serious path traversal issue.

VB.NET - Edit Windows Registry Value

I'm trying to set my program as the "Default Program" for all Text Files so in order to do this I need to change the (Default) value which is: %SystemRoot%\system32\NOTEPAD.EXE %1 to C:\Program.exe %1 in HKEY_CLASSES_ROOT\txtfile\shell\open\command\
I do this by using this code:
Dim regKey As RegistryKey
regKey = Registry.ClassesRoot.OpenSubKey("txtfile\shell\open\command", True)
regKey.SetValue("(Default)", "C:\Program.exe %1", RegistryValueKind.ExpandString)
regKey.Close()
The problem is that when I do it, it creates another key with the Expand String called "(Default)" rather than editing the "(Default)" key which is already there. How can I EDIT rather than just create?
This is explicitly mentioned in a NOTE in the MSDN article for RegistryKey.SetValue():
A registry key can have one value that is not associated with any name. When this unnamed value is displayed in the registry editor, the string "(Default)" appears instead of a name. To set this unnamed value, specify either null or the empty string ("") for the name.
Fix:
regKey.SetValue("", "C:\Program.exe %1", RegistryValueKind.ExpandString)

Access to the registry key '[KEY_NAME]' is denied

I'm writing a small program in Visual Basic 2008 that flips the values of specific DWORDs in a registry key
The registry key in question is:
'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Render\{91801674-82d9-459a-9358-6e5cf3d81d21}\FxProperties'
The dword I'm manipulating is "{e0a941a0-88a2-4df5-8d6b-dd20bb06e8fb},4"
This is the line of code I wrote to set the DWORD's value is this:
Dim keyString = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Render\{91801674-82d9-459a-9358-6e5cf3d81d21}\FxProperties"
My.Computer.Registry.SetValue(keyString, "{ad75efc0-8f48-4285-bfa8-40fb036cdab2},2", "00000000")
But I get a UnauthorizedAccessException at runtime stating that "Access to the registry key [KEY_NAME] is denied."
I ran the program with Administrator privileges, changed the app's manifest to include:
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
But that didn't work either. So I searched a few forums and tried this:
Dim rkLM As RegistryKey = Registry.LocalMachine
Dim pRegKey As RegistryKey = rkLM.OpenSubKey("\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Render\{91801674-82d9-459a-9358-6e5cf3d81d21}\FxProperties", True)
pRegKey.SetValue("{ad75efc0-8f48-4285-bfa8-40fb036cdab2},2", "00000000")
But that threw a NullReferenceException at me stating "Object reference not set to an instance of an object."
Is there any way I can modify that that key without having to run my program with SYSTEM privileges?
You should probably try with requireAdministrator in your manifest because highestAvailable may not actually be an administrator.
I would also try specifying the data type (in your case I think it is binary):
My.Computer.Registry.SetValue(keyString, _
"{ad75efc0-8f48-4285-bfa8-40fb036cdab2},2", _
"00000000", _
RegistryValueKind.Binary)
However the value you are setting may need to be a byte array (something else you could try)
Thanks Matt, I tried running it with requireAdministrator as well but that didn't help either. Anyway, I found the solution to this and it seems the problem lied with the permissions on the registry key that I was trying to modify.
Full Control access was only given to the TrustedInstaller group, so I granted Full Control to the users in the Administrators group as well.
I started 'regedit' with SYSTEM privileges using Sysinternals' PsExec tool
[psexec -si regedit] and navigated to the key I wished to manipulate using my program and used [Edit -> Permissions] to grant write access to myself.
After doing that, my code worked and this:
Dim keyString = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\" _
+ "MMDevices\Audio\Render\{91801674-82d9-459a-9358-6e5cf3d81d21}\FxProperties"
Dim regKey = "{ad75efc0-8f48-4285-bfa8-40fb036cdab2},2"
My.Computer.Registry.SetValue( _
keyString, regKey, "00000000", RegistryValueKind.DWord)
could successfully flip the value of the DWORD. Although this worked, I would like to know if there's a way to do this without having to manually change permissions on the registry subkey.
I found a similar problem and solution for this in C# given here but I couldn't successfully convert the C# code mentioned there to VB.NET code. Could you help with that?
Here is the vb.net code for the c# link referenced below. You will need to set a reference to System.Security.
Imports System.Security
Imports System.Security.Principal
Imports System.Security.AccessControl
Imports Microsoft.Win32
Private Sub TestMethod(ByVal subkey As String)
' Create access rule giving full control to the Administrator user.
Dim rs As New RegistrySecurity()
rs.AddAccessRule( New RegistryAccessRule( _
"Administrator", _
RegistryRights.FullControl, _
InheritanceFlags.ContainerInherit Or InheritanceFlags.ObjectInherit, _
PropagationFlags.InheritOnly, _
AccessControlType.Allow))
' Get the registry key desired with ChangePermissions Rights.
Dim rk As RegistryKey = Registry.LocalMachine.OpenSubKey( _
subkey, _
RegistryKeyPermissionCheck.ReadWriteSubTree, _
RegistryRights.ChangePermissions Or RegistryRights.ReadKey)
' Apply the new access rule to this Registry Key.
rk.SetAccessControl(rs)
' Get the registry key desired with ChangePermissions Rights.
rk = Registry.LocalMachine.OpenSubKey( _
subkey, _
RegistryKeyPermissionCheck.ReadWriteSubTree, _
RegistryRights.ChangePermissions Or RegistryRights.ReadKey)
' Apply the new access rule to this Registry Key.
rk.SetAccessControl(rs)
' Open the key again with full control.
rk = Registry.LocalMachine.OpenSubKey( _
subkey, _
RegistryKeyPermissionCheck.ReadWriteSubTree, _
RegistryRights.FullControl)
' Set the security's owner to be Administrator.
rs.SetOwner(New NTAccount("Administrator"))
' Set the key with the changed permission so Administrator is now owner.
rk.SetAccessControl(rs)
End Sub
I had this same problem, and setting requireAdministrator didn't help. Then I realized VS2010 never asked me to restart with Administrative rights. I closed and reopened VS2010, ran the program, and then it asked me to start with Administrative privileges. I'm used to changing to requireAdministrator and it asking me to restart at the next time I debug.
So, to clarify, requireAdministrator does help, but may require a manual restart of VS2010 (or just run VS2010 as Administrator).

Surest way to detect if an application has been installed on a Windows PC in a VB.NET app?

I know the default install path of the app and the name of the .exe file, but is there a way to see if it is actually installed?
I've seen suggestions for checking registry entries, but I don't know if this app uses any or if if varies for different users on different pc's.
Many of the registy entries have no default values set. I prefer not to dive too deep and have to rely on a value for the font setting.
I'd like to know if "App_Name" exists. I can't rely on it having a default value because it never does. Since I'm using .GetValueKind, I don't have to worry about "AboutSiteUR" having any value set assuming if it has a type it actually exists. Otherwise, I'm assuming the Try/Catch will trap the IO.IORegistry type error (I'm not sure about that one.).
Dim sDisplay_Reg_Value As String
Dim Everest_Registry As Microsoft.Win32.RegistryKey = _
My.Computer.Registry.CurrentUser.OpenSubKey("Software\Company_Name\App_Name")
Try
sDisplay_Reg_Value = CType(Everest_Registry.GetValueKind("AboutSiteUR"), String)
'If the key does not exist Everest_Registry will contain Nothing, otherwise the returned key will be populated. Try this:
Dim Everest_Registry As Microsoft.Win32.RegistryKey = _
My.Computer.Registry.CurrentUser.OpenSubKey("Software\Microsoft\Internet Explorer")
If Everest_Registry Is Nothing Then
'key does not exist
MsgBox("Key does not exist")
Else
'key is valid, display actual name
MsgBox(Everest_Registry.Name)
End If
Does the application show up in the "Add/Remove programs" control panel? If yes, then there are definitely some registry entries you can look at that would not vary by user.
use regedit.exe to search the subkeys of CLSIDs key, if the application folder appears in any of the subkeys, then this also would be something that doesn't vary by user.
Or your could ask them. I used to work for a company that made software you could buy at Best Buy, etc. In their software, there was a specific registry key that each application created so that all of their apps could find each other.

Storing Connection Strings in Registry?

We decided to use the registry for handling our deployment with connection strings in our VB.net application.
The requirements are:
If the program cannot connect to the server, first check the registry for a connection string. IF not, create the folder and fill in the name, type, and data.
Make sure its encrypted.
I have never edited or created anything in the registry. Where do I start? If anybody has any code samples or links to articles I would really appreciate it.
It looks like this tutorial would be a good source for the problem. I would strongly recommend against storing the connection string in the registry. It adds more work and more dependencies on the current operating environment. Additionally, configuration files are more portable and are better suited for storing property related information. If you use a settings file the supporting admins and your support people will thank you. [Compared to placing the information in the registry.
Totally agree with Steven here, but if you have to do it...here is some info From MSDN (link to all you need to know at the bottom). The following example reads, increments, and then writes a DWORD value to HKCU:
Imports Microsoft.Win32
Dim regVersion As RegistryKey
regVersion =
Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\TestApp\\1.0", True)
If regVersion Is Nothing Then
' Key doesn't exist; create it.
regVersion =
Registry.CurrentUser.CreateSubKey("SOFTWARE\\Microsoft\\TestApp\\1.0")
End If
Dim intVersion As Integer = 0
If (Not regVersion Is Nothing) Then
intVersion = regVersion.GetValue("Version", 0)
intVersion = intVersion + 1
regVersion.SetValue("Version", intVersion)
regVersion.Close()
End If
http://msdn.microsoft.com/en-us/library/aa289494%28VS.71%29.aspx