الثلاثاء، 11 ديسمبر 2012

Hacking Windows Registry using VB.NET


Introduction

Developers have always found the windows registry to be a suitable place for storing application specific information and configuration settings. Traditionally, the registry has been used for storing configuration information like database connection strings, profiles etc. The popularity of the registry can be attributed to the fact that registry access is faster than file access and also because it is a very secure system-wide data repository. Moreover, configuration files like INI files had their own limitations.
In this article I shall discuss some basics of Windows registry and then explain how basic registryoperations can be done in VB.NET

Basics of Windows Registry

The registry is organized as a hierarchical structure. It has basically five predefined keys under which all data is added or accessed. These keys cannot be renamed or deleted. Given below is a table containing a brief description about them.
Subtree
Definition
HKEY_CURRENT_USERThis contains configuration information of a user who is currently logged on to the system.That is, user profile data is stored here
HKEY_USERSContains all user profiles on the computer. HKEY_CURRENT_USER is actually an alias for a key in the HKEY_USERS sub tree.
HKEY_LOCAL_MACHINEContains configuration information particular to the computer, irrespective of which user is logged on.
HKEY_CLASSES_ROOTContains data that associates file types with programs, and configuration data for COM objects.
HKEY_CURRENT_CONFIGContains information about the hardware profile used by the local computer at system startup.
Each key has many subkeys and may have a value. Given below is a snapshot of the registry as seen through the registry editor (Regedit.exe), which comes along with windows.
Registry Structure
Fig 1: Registry Structure
In the snapshot shown above, each node under My Computer is a key. For example ,HKEY_CURRENT_CONFIG is a key which has two subkeys: Software and System. Fonts is a subkey under software and has values. Each Value contains a name and its associated data. Each value needs to be associated with a particular data type. Given below is a table containing the important data types
Data typesUsed for
REG_SZA fixed-length text string. Boolean (True or False) values and other short text values usually have this data type.
REG_EXPAND_SZA variable-length text string that can include variables that are resolved when an application or service uses the data.
REG_DWORDData represented by a number that is 4 bytes (32 bits) long.
REG_MULTI_SZMultiple text strings formatted as an array of null-terminated strings, and terminated by two null characters.
Referring back to figure 1, there is a value called LogPixels which has data of type REG_DWORD and value 96.

Working with Microsoft.Win32 Namespace

The operations on the registry in .NET can be done using two classes of the Microsoft.Win32NamespaceRegistry class and the RegistryKey class.The Registry class provides baseregistry keys as shared public (read-only) methods: 
ClassesRootThis field reads the Windows registry base key HKEY_CLASSES_ROOT
Currentconfig Reads the Windows registry base key HKEY_CURRENT_CONFIG.
CurrentUserReads the Windows registry base key HKEY_CURRENT_USER
LocalMachineThis field reads the Windows registry base key HKEY_LOCAL_MACHINE.
UsersThis field reads the Windows registry base key HKEY_USERS.
Each of the public methods shown above provides an object of the RegistryKey class whose methods can be used to access subkeys under the corresponding keys. The important members of theRegistryKey class are enlisted below

Public Properties

NameRetrieves the name of the key.
SubKeyCountRetrieves the count of subkeys at the base level, for the current key.
ValueCountRetrieves the count of values in the key.

Public Methods

CloseCloses the key and flushes it to disk if the contents have been modified.
CreateSubKeyCreates a new subkey or opens an existing subkey.
DeleteSubKeyDeletes the specified subkey.
DeleteSubKeyTreeDeletes a subkey and any child subkeys recursively.
DeleteValueDeletes the specified value from this key.
FlushWrites all the attributes of the specified openregistry key into the registry.
GetSubKeyNamesRetrieves an array of strings that contains all the subkey names.
GetValueRetrieves the specified value.
GetValueNamesRetrieves an array of strings that contains all the value names associated with this key.
OpenSubKeyRetrieves a specified subkey, with the writeaccess as specified.
SetValueSets the specified value.

VB.NET and Registry

I shall now come to the practical aspect and see how the registry can be manipulated using VB.NETcode. I have considered three basic operations: Creating a subkey, adding values and deleting a subkey

Creating a Subkey

Dim regKey As RegistryKey
regKey = Registry.LocalMachine.OpenSubKey("SOFTWARE", True)
regKey.CreateSubKey("MyApp")
regKey.Close()
In the code snippet shown above, I have created a subkey under HKLM\Software called MyApp. Note that I passed True as the second parameter to the OpenSubKey method. This boolean value is to indicate whether the key is writable or not. For instance, you can set it to false if you are just reading data from the registry.

Reading and Writing Values

Dim regKey As RegistryKey
Dim ver As Decimal
regKey = Registry.LocalMachine.OpenSubKey("Software\MyApp", True)
regKey.SetValue("AppName", "MyRegApp")
ver = regKey.GetValue("Version", 0.0)
If ver <  1.1 Then
regKey.SetValue("Version", 1.1)
End If
regKey.Close()
In the code snippet shown above, I am creating two values AppName and Version. I am also setting the values to MyRegApp and 1.1 respectively. Note: If you recollect that in the previous sections I had mentioned about data types for registry values like REG_SZ. But nowhere in the above code we mentioned about the data type. This is because .NET runtime interprets the type itself based on what is passed as value and we do not need to pass it explicitly.

Deleting a Subkey

Dim regKey As RegistryKey
regKey = Registry.LocalMachine.OpenSubKey("Software", True)
regKey.DeleteSubKey("MyApp", True)
regKey.Close()
In the code snippet shown above, I am deleting the subkey MyApp and all its values. Note that in the call to DeleteSubkey, I have passed a second Boolean argument of True. This means that an exception is thrown when the key to be deleted is not found

Important

  • To read and write to the registry you need security permissions. If you do not have sufficient permissions, then you will get a SecurityException when you try to access or create keys.
  • The registry is a very sensitive part of the Windows Operating system. So, it is imperative that you take a backup of the registry before attempting to play around with it. A corrupt registry could render the operating system non functional.

Conclusion

This article hopefully has made it easier for beginners to understand the registry and to do simple operations with it. A lot more operations are possible with the Registry and RegistryKey classes but for the sake of simplicity, I have omitted all those here.

الاثنين، 10 ديسمبر 2012

How to repair a SQL Server 2005 Suspect database

Workshare Compare/Deltaview for Microsoft Office
Sometimes when you connect to your database server, you may find it in suspect mode. Your database server won’t allow you to perform any operation on that database until the database is repaired. A database can go in suspect mode for many reasons like improper shutdown of the database server, corruption of the database files etc. To get the exact reason of a database going into suspect mode can be found using the following query, 

DBCC CHECKDB (‘YourDBname’) WITH NO_INFOMSGS, ALL_ERRORMSGS
Output of the above query will give the errors in the database. To repair the database, run the following queries in Query Analyzer,
EXEC sp_resetstatus ‘yourDBname’;
ALTER DATABASE yourDBname SET EMERGENCY
DBCC checkdb(‘yourDBname’)
ALTER DATABASE yourDBname SET SINGLE_USER WITH ROLLBACK IMMEDIATE
DBCC CheckDB (‘yourDBname’, REPAIR_ALLOW_DATA_LOSS)
ALTER DATABASE yourDBname SET MULTI_USER
You should keep one thing in mind while using the above queries that the repair mode used here , REPAIR_ALLOW_DATA_LOSS, is a one way operation i.e. once the database is repaired all the actions performed by these queries can’t be undone. There is no way to go back to the previous state of the database. So as a precautionary step you should take backup of your database before executing above mentioned queries.