Click here to Skip to main content
Click here to Skip to main content

Developing a USB Storage Device Protection Tool with C#

, 4 Jun 2009
Rate this:
Please Sign up or sign in to vote.
USB storage policy management, Registry editing, password protection, and hashing.

Introduction

USB storage devices (flash drives, USB sticks etc.) offer many advantages for us. However, at the same time, they cause security problems because it is easy to copy a lot of files to a tiny USB memory in a few seconds. We might have some secure data on our PC which we do not want other users to copy through the USB. Therefore, we many need to define a USB storage policy to make USB drives write protected or not to be accessed through the system.

Background

Windows XP with SP2 or later Operating Systems provide soft protection of USB ports. This feature can be enabled through the Registry Editor. Under HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\StorageDevicePolicies, there is a DWORD value named WriteProtect. Setting this value to 1 makes USB drives write protected.

We may want to completely disable USB drives. For this, the Start value in the following Registry key needs to be set to 4: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\UsbStor.

The Program

For many users, dealing with Registry keys is a boring job. A utility software developed for this job will be very useful.

Let’s develop our own application having the following functionalities:

  1. Define a USB storage devices access mode (Full Access/ Read Only / Disabled)
  2. Enable / Disable the Registry editor
  3. Provide password protection for configuration

The second functionality is needed because otherwise the configuration can be discarded easily by other people with the help of the Registry Editor (Regedit). And the third functionality, password protection, will prevent configuration change attempts of unauthorized users.

In Visual Studio 2005/2008, create a new Windows Forms Application project. Rename the empty form to frmMain. To make use of the Windows Registry functionality within our C# program, we need to add the following line to the beginning of our code:

using Microsoft.Win32;

Before making any changes in the configuration, it is good to know the current configuration. To achieve that, define the following methods and call them during the Load event of frmMain:

private void frmMain_Load(object sender, EventArgs e)
{
  CheckPasswordStatus();
  USB_getStatus();
  REG_getStatus();
}  

Define the CheckPasswordStatus() method as follows:

private void CheckPasswordStatus()
{
    Program.strPwdFilePath += "\\usbpolicy.pwd";
    if (File.Exists(Program.strPwdFilePath))
    {
        try
        {
             StreamReader fsPwdFile =
                      new StreamReader(
                            new FileStream(
                               Program.strPwdFilePath, 
                               FileMode.Open, FileAccess.Read));
             string pwd = fsPwdFile.ReadToEnd();
             if (String.IsNullOrEmpty(pwd) == false)
             Program.isPwdEnabled = true;
             fsPwdFile.Close();
        }
        catch { }
    }
    else
        Program.isPwdEnabled = false;
}

In this code segment, you can see that there are two global variables, a string named strPwdFilePath, and a boolean variable named isPwdEnabled . These variables are defined in the Program.cs file and are accessible to all the forms in our application. This is because we need to access these variables again in two other forms related to password protection. To learn the status of USB write protection, we need to read the WriteProtect value under the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\StorageDevicePolicies key with the help of the following code defined in the body of the USB_getStatus() method:

RegistryKey key;
try
{
    key = Registry.LocalMachine.OpenSubKey
             ("SYSTEM\\CurrentControlSet\\Control\\StorageDevicePolicies");
    if (System.Convert.ToInt16(key.GetValue("WriteProtect", null)) == 1)
        USB_radio_ReadOnly.Checked = true;
    else
        USB_radio_FullAccess.Checked = true;
}
catch (NullReferenceException )
{
    key = Registry.LocalMachine.OpenSubKey
             ("SYSTEM\\CurrentControlSet\\Control", true);
    key.CreateSubKey("StorageDevicePolicies");
    key.Close();
}
catch( Exception ) {}

As you can see, the code is written in try and catch blocks because the absence of the StorageDevicePolicies key will cause a NullReferenceExcetion. In this case, we need to catch the exception and create the key. We are not done yet. The Start value under the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\UsbStor key also needs to be checked. So, continue with the USB_getStatus() method with the following lines of code:

try
{
    key = Registry.LocalMachine.OpenSubKey
             ("SYSTEM\\CurrentControlSet\\Services\\UsbStor");
    if (System.Convert.ToInt16(key.GetValue("Start", null)) == 4)
    {
       USB_radio_Disabled.Checked = true;
       return;
    }
}
catch ( NullReferenceException )
{
    key = Registry.LocalMachine.OpenSubKey
             ("SYSTEM\\CurrentControlSet\\Services", true);
    key.CreateSubKey("USBSTOR");
    key = Registry.LocalMachine.OpenSubKey
            ("SYSTEM\\CurrentControlSet\\Services\\UsbStor", true);
    key.SetValue("Type", 1, RegistryValueKind.DWord);
    key.SetValue("Start", 3, RegistryValueKind.DWord);
    key.SetValue("ImagePath", "system32\\drivers\\usbstor.sys", 
                 RegistryValueKind.ExpandString);
    key.SetValue("ErrorControl", 1, RegistryValueKind.DWord);
    key.SetValue("DisplayName", "USB Mass Storage Driver",
                 RegistryValueKind.String);
    key.Close();
}

catch( Exception ) {}

To enable write protection, define the following method:

void USB_enableWriteProtect()
{
    RegistryKey key = 
        Registry.LocalMachine.OpenSubKey
            ("SYSTEM\\CurrentControlSet\\Control\\StorageDevicePolicies", true);
    if (key == null)
    {
       Registry.LocalMachine.CreateSubKey
          ("SYSTEM\\CurrentControlSet\\Control\\StorageDevicePolicies",
           RegistryKeyPermissionCheck.ReadWriteSubTree);
       key = Registry.LocalMachine.OpenSubKey
          ("SYSTEM\\CurrentControlSet\\Control\\StorageDevicePolicies", true);
       key.SetValue("WriteProtect", 1, RegistryValueKind.DWord);
    }
    else if (key.GetValue("WriteProtect") != (object)(1))
    {
       key.SetValue("WriteProtect", 1, RegistryValueKind.DWord);
    }
}

To disable write protection, use the following method:

void USB_disableWriteProtect()
{
    RegistryKey key =
        Registry.LocalMachine.OpenSubKey
           ("SYSTEM\\CurrentControlSet\\Control\\StorageDevicePolicies",true);
    if (key != null)
    {
       key.SetValue("WriteProtect", 0, RegistryValueKind.DWord);
    }
    key.Close();
}

To disable USB storage devices (make them not available to use):

void USB_disableAllStorageDevices()
{
    RegistryKey key =
        Registry.LocalMachine.OpenSubKey
           ("SYSTEM\\CurrentControlSet\\Services\\UsbStor",true);
    if (key != null)
    {
       key.SetValue("Start", 4, RegistryValueKind.DWord);
    }
    key.Close();
}

To enable USB storage services:

void USB_enableAllStorageDevices()
{
    RegistryKey key = 
       Registry.LocalMachine.OpenSubKey
          ("SYSTEM\\CurrentControlSet\\Services\\UsbStor", true);
    if (key != null)
    {
       key.SetValue("Start", 3, RegistryValueKind.DWord);
    }
    key.Close();
}

To disable Regedit:

private void REG_DisableRegedit()
{
    RegistryKey key = 
        Registry.CurrentUser.OpenSubKey
           ("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", true);
    key.SetValue("DisableRegistryTools", 1, RegistryValueKind.DWord);
    key.Close();
}

To enable Regedit:

private void REG_EnableRegedit()
{
    RegistryKey key = 
        Registry.CurrentUser.OpenSubKey
           ("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", true);
    key.SetValue("DisableRegistryTools", 0, RegistryValueKind.DWord);
    key.Close();
}

The third functionality of our program is password protection to prevent unauthorized access to configuration. To achieve this, we will design two others forms. In the first form, we define, change, or remove password.

password.jpg

In the second one, we will just do a password confirmation.

pwdcheck.jpg

There are several ways to store the password. Our approach will be to hash the password string first and then store it in a file in the Windows directory.

To hash the password string, we will use the following method:

public static string MD5Hash(string str)
{
    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
    byte[] data = System.Text.Encoding.ASCII.GetBytes( str );
    data = md5.ComputeHash(data);
    string md5Hash = System.Text.Encoding.ASCII.GetString(data);
    return md5Hash;
}

Since this method is used by more than one form, it is good to make it static and define it in a static class in which common methods are defined.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Ozcan ILIKHAN
Engineer
Turkey Turkey
Borned in Malatya, TURKEY. Graduated from Department of Computer Engineering, Eastern Mediterranean University, T.R.N.C
 
Currently, PhD student-Graduate Research Assistant in Computer Sciences Department at UW-Madison.

Comments and Discussions

 
Questioneasy PinmemberMember 1075141815-Apr-14 7:38 
QuestionUsb enabled Automaticly after few day!!! PinmemberPouya474-Dec-13 21:48 
GeneralMy vote of 4 PinmemberMic8-Aug-13 13:52 
Questionspecific drive write protected? PinmemberBikar1112-Jul-13 19:34 
GeneralMy vote of 5 Pinmember Gun Gun Febrianza24-May-13 2:30 
QuestionWhat about Write only? Pinmemberfarhanmirzaaa29-Jan-13 3:02 
QuestionFile damage Pinmemberlailailaihou15-Nov-12 20:38 
QuestionUser rights? Pinmembermr_iq732-Jul-12 3:22 
QuestionDeny execution? Pinmembermr_iq732-Jul-12 3:20 
Questionquestion2 Pinmemberaliprogrammer28-Apr-12 20:52 
Questionquestion Pinmemberaliprogrammer28-Apr-12 20:44 
GeneralMy Vote of 5 PinmemberRaviRanjankr8-Dec-11 4:34 
Generalusb connection Pinmemberparastoo_8121419-Feb-11 1:17 
GeneralMy vote of 5 PinmemberAslam_Iqbal10-Jan-11 8:24 
GeneralMy vote of 4 Pinmemberanirban_sinha30-Dec-10 22:39 
GeneralVery Useful Tool for Me PinmemberSunasara Imdadhusen24-Dec-10 23:05 
GeneralMy vote of 5 PinmemberSunasara Imdadhusen24-Dec-10 23:04 
GeneralUSB_Policy.exe.manifest Pinmemberaditya_ingle10-Sep-10 5:22 
GeneralGod,help, plz!!! Pinmembersmall23-Sep-10 7:31 
GeneralRe: God,help, plz!!! PinmemberOzcan ILIKHAN4-Sep-10 13:50 
GeneralRe: God,help, plz!!! Pinmemberaliprogrammer28-Apr-12 21:08 
GeneralMy vote of 5 Pinmemberbirthfuture26-Jul-10 11:32 
Questionwhat the benefit of usbstor.sys Pinmemberzaed19-Jul-10 9:16 
AnswerRe: what the benefit of usbstor.sys PinmemberOzcan ILIKHAN4-Sep-10 13:52 
GeneralNot compatable with windows vista/7 PinmemberCrazyd2279-Feb-10 4:41 
GeneralRe: Not compatable with windows vista/7 PinmemberHassan3D29-Mar-10 2:41 
Question.... Pinmembermanali2426-Aug-09 0:11 
AnswerRe: .... PinmemberAslam_Iqbal10-Jan-11 8:53 
Generalhelp plz. Pinmembermanali2420-Aug-09 20:05 
GeneralRe: help plz. PinmemberOzcan ILIKHAN20-Aug-09 22:13 
GeneralPls. Help Me Pinmemberrikimaruz0917-Jul-09 18:39 
GeneralRe: Pls. Help Me PinmemberOzcan ILIKHAN18-Jul-09 21:13 
Generaldisable usb PinmemberPower-x25-Jun-09 8:15 
GeneralRe: disable usb PinmemberOzcan ILIKHAN26-Jun-09 1:34 
GeneralRe: disable usb Pinmemberstanliritche28-Apr-10 3:48 
Generalregistry access policy PinmemberAlex Cohn9-Jun-09 1:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140709.1 | Last Updated 5 Jun 2009
Article Copyright 2009 by Ozcan ILIKHAN
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid