Sign in to follow this  
Followers 0
BullGates

Restrict USB Storage usage

5 posts in this topic

#1 ·  Posted (edited)

Well, after some discussions on this topic, I decided to re-code my usb storage protection script. It is designed only for windows XP machines, and it installs and starts itself to a system as a service <<<- please read it again before blaming me for a "like a virus behavior"

I do it this way because I want to be able to update the service on all clients in a simple way, as well as install it.

Some notes about this script:

- it is designed to work as a system service, and watch the current logged on user

- it have 2 modes: online and offline

- if no AD connection is found it checks the registry for the last remembered users with access

- it provides access to usb storage for allowed users by controlling USBSTOR service state

- it may for sure contain bugs, I used the _ReduceMemory() function to keep it "clean"

- on my own version I will encrypt the usernames on the registry so it will be harder to crack - sorry I won't post it here.

- it needs srvany.exe to run the script as a service - you can find it on this forums

- it is deployed with a VB script to check for it's presence in a computer, if absent run once in the machine context startup script

any simpler way of achieving those functionalities is welcome.

Version list:

1.0 initial script without AD testing ;-)

1.01 Rewrite of most of the code

dropped unstable COM code

fixed always on AD connections, using "net user" command for group check (faster, much more stable)

Bug list:

???none at the moment??? :)

ToDo:

Automatic update of the clients when a new version is available - instead of using VBS as I do it know, I have to code some update routines

;
; AutoIt Version: 3.2.6.0
; Author:         Paulo Freire
;
; Script Function:
;   Avoid not allowed users to use usb storage devices
;
; Version 1.01
;
; Thanks to: UglyBob, w0uter, Johny Clelland, the AutoIT Creators
; ------------------------------------------------------------------------------------------
Opt("TrayIconHide", 1)
Opt("RunErrorsFatal", 0)
#include"ServiceControl.au3"
#include <String.au3>
Global Const $STDOUT_CHILD = 2
Global Const $STDERR_CHILD = 4

If @OSVersion <> "WIN_XP" Then Exit
Dim $AllowUser = False
Dim $Offline = True
Dim $UserLoggedIn
Dim $OfflineModeKey = "HKEY_LOCAL_MACHINE\SOFTWARE\UsbAccess"
Dim $USB_Allow_Group = "USBAllowGroup"
Dim $idletime = 300000

FileInstall("srvany.exe", @TempDir & "\", 0)
$servicename = "USBAccess"
$srvanypath = @SystemDir & "\srvany.exe"
Sleep(1000)
If Not FileExists(@SystemDir & "\srvany.exe") Then
    FileCopy(@TempDir & "\srvany.exe", @SystemDir)
EndIf
If Not FileExists(@SystemDir & "\" & @ScriptName) Then
    FileCopy(@ScriptFullPath, @SystemDir & "\")
EndIf

$softkey = RegEnumKey($OfflineModeKey, 1)
If @error = 1 Then RegWrite($OfflineModeKey)

If Not _ServiceExists ("", $servicename) Then
    _CreateService ("", $servicename, "Control USB Access", $srvanypath, "LocalSystem", "")
    RegWrite("HKLM\SYSTEM\CurrentControlSet\Services\" & $servicename & "\Parameters", "Application", "REG_SZ", @SystemDir & "\" & @ScriptName)
    Sleep(5000)
EndIf

If Not _ServiceRunning ("", $servicename) Then
    _StartService ("", $servicename)
    Exit
EndIf

While 1
    GetLoggedInUser()
    CheckAccess()
    If $Offline = False Then
        If $AllowUser = False Then
            ;ConsoleWrite("Online Mode - User not allowed" & @CRLF)
            DisableUSBAccess()
        Else
            ;ConsoleWrite("Online Mode - User Allowed" & @CRLF)
            EnableUSBAccess()
        EndIf
    Else
        ;ConsoleWrite("Offline Mode" & @CRLF)
        $key = RegRead($OfflineModeKey, $UserLoggedIn)

        If @error = -1 Then
            DisableUSBAccess()
            ;ConsoleWrite("Offline Mode - User not allowed" & @CRLF)
        Else
            EnableUSBAccess()
            ;ConsoleWrite("Offline Mode - User allowed" & @CRLF)
        EndIf
    EndIf
    _ReduceMemory()
    Sleep($idletime)
WEnd

Func GetLoggedInUser()
    $UserLoggedIn = RegRead("HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\", "AltDefaultUserName")
EndFunc   ;==>GetLoggedInUser

Func DisableUSBAccess()
    RegDelete($OfflineModeKey & "\" & $UserLoggedIn)
    RegWrite("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\USBSTOR\", "Start", "REG_DWORD", 4)
EndFunc   ;==>DisableUSBAccess

Func EnableUSBAccess()
    RegWrite($OfflineModeKey, $UserLoggedIn, "REG_SZ", "")
    RegWrite("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\USBSTOR\", "Start", "REG_DWORD", 3)
EndFunc   ;==>EnableUSBAccess

Func CheckAccess()
    $cmd = @ComSpec & ' /C net user ' & $UserLoggedIn & " " & " /domain"
    $Result = Run($cmd, @SystemDir, @SW_HIDE, $STDERR_CHILD + $STDOUT_CHILD)

    While 1
        $line = StdoutRead($Result)
        If @error Then ExitLoop

        If StringInStr($line, $USB_Allow_Group) Then
            $AllowUser = True
            ExitLoop
        Else
            $AllowUser = False
        EndIf
    WEnd

    If StderrRead($Result) Then
        $Offline = True
    Else
        $Offline = False
    EndIf
EndFunc   ;==>CheckAccess

; from w0uter
Func _ReduceMemory($i_PID = -1)
    If $i_PID <> -1 Then
        Local $ai_Handle = DllCall("kernel32.dll", 'int', 'OpenProcess', 'int', 0x1f0fff, 'int', False, 'int', $i_PID)
        Local $ai_Return = DllCall("psapi.dll", 'int', 'EmptyWorkingSet', 'long', $ai_Handle[0])
        DllCall('kernel32.dll', 'int', 'CloseHandle', 'int', $ai_Handle[0])
    Else
        Local $ai_Return = DllCall("psapi.dll", 'int', 'EmptyWorkingSet', 'long', -1)
    EndIf

    Return $ai_Return[0]
EndFunc   ;==>_ReduceMemory
Edited by BullGates

[topic="51913"]Restrict USB Storage usage to group membership[/topic] * [topic="48699"]Using nircmd library[/topic] * Some admin notes

Share this post


Link to post
Share on other sites

Hi!

Interesting (also for various tech used).

When I will have some minutes, I will try (test) it.

Thanks.

Share this post


Link to post
Share on other sites

I was using COM on my script, after many many retries to close the active connections to the DC's, without success I'll quit using it!

Anyone knows how to really close ldap connections?

In my environment I'm always getting 3 ldap connections to 3 different DC's and I could never close them!

Today I found a simple and efficient alternative to check for a user membership under XP:

net user username /domain


[topic="51913"]Restrict USB Storage usage to group membership[/topic] * [topic="48699"]Using nircmd library[/topic] * Some admin notes

Share this post


Link to post
Share on other sites

I've updated my script, the main routine was recoded, I'm quite happy now with the stability and for dropping COM. A much more elegant solution might be using the netapi32.dll API "NetUserGetGroups", but I couldn't find a way of porting it to Autoit code (the data structure kills me for now...)


[topic="51913"]Restrict USB Storage usage to group membership[/topic] * [topic="48699"]Using nircmd library[/topic] * Some admin notes

Share this post


Link to post
Share on other sites

Great mod.

This resolves a problem I encountered, thanks!

Comment: You include a script that is not native to AU3 install (at least not the version I have) and must be pulled from this forum.

Question: Your script seems to assume srvany.exe in the System or Temp folder. This requires placing it there before running. Is that correct?

Thanks again!

P.S. - For the moment, I am just using this to 'monitor' a PCs activities. Here's the version of the code I've mad:

CODE
#include <ServiceControl.au3>

#include <String.au3>

;Disable the tray icon

Opt("TrayIconHide", 1)

Opt("RunErrorsFatal", 0)

Global Const $STDOUT_CHILD = 2

Global Const $STDERR_CHILD = 4

If @OSVersion <> "WIN_XP" Then Exit

Dim $AllowUser = False

Dim $Offline = True

Dim $UserLoggedIn

Dim $OfflineModeKey = "HKEY_LOCAL_MACHINE\SOFTWARE\UsbAccess"

Dim $USB_Allow_Group = "USBAllowGroup"

Dim $idletime = 300000

FileInstall("srvany.exe", @TempDir & "\", 0)

$servicename = "USBWatch"

$srvanypath = @SystemDir & "\srvany.exe"

Sleep(1000)

If Not FileExists(@SystemDir & "\srvany.exe") Then

FileCopy(@TempDir & "\srvany.exe", @SystemDir)

EndIf

If Not FileExists(@SystemDir & "\" & @ScriptName) Then

FileCopy(@ScriptFullPath, @SystemDir & "\")

EndIf

If Not _ServiceExists ("", $servicename) Then

_CreateService ("", $servicename, "Monitor USB Drive Insertion/Removal", $srvanypath, "LocalSystem", "")

RegWrite("HKLM\SYSTEM\CurrentControlSet\Services\" & $servicename & "\Parameters", "Application", "REG_SZ", @SystemDir & "\" & @ScriptName)

Sleep(5000)

EndIf

If Not _ServiceRunning ("", $servicename) Then

_StartService ("", $servicename)

Exit

EndIf

$strComputer = "."

$objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\cimv2")

$colEvents = $objWMIService.ExecNotificationQuery _

("Select * From __InstanceOperationEvent Within 5 Where " _

& "TargetInstance isa 'Win32_LogicalDisk' and " _

& "TargetInstance.DriveType = 2" )

$SystemEvent='eventcreate /T Information /ID 999 /L SYSTEM /SO USBWatch /D "USBWatch monitoring utility has started. This utility monitors for insertion/removal of USB drives and reports it to the System event log."'

;MsgBox(1,"Msg",$SystemEvent)

Run(@ComSpec & " /c " & $SystemEvent, "", @SW_HIDE)

While 1

$objEvent = $colEvents.NextEvent

If $objEvent.TargetInstance.DriveType = 2 Then

Select

Case $objEvent.Path_.Class()="__InstanceCreationEvent"

$SystemEvent='eventcreate /T Warning /ID 999 /L SYSTEM /SO USBWatch /D "Drive ' & $objEvent.TargetInstance.DeviceId & 'has been added. Size: ' & ($objEvent.TargetInstance.Size/1024) & 'MB. Volume Name:' & $objEvent.TargetInstance.VolumeName & ' FreeSpace: '& ($objEvent.TargetInstance.FreeSpace/1024) & 'MB."'

;MsgBox(1,"Msg",$SystemEvent)

Run(@ComSpec & " /c " & $SystemEvent, "", @SW_HIDE)

Case $objEvent.Path_.Class()="__InstanceDeletionEvent"

$SystemEvent='eventcreate /T Warning /ID 999 /L SYSTEM /SO USBWatch /D "Drive ' & $objEvent.TargetInstance.DeviceId & ' , Volume Name: ' & $objEvent.TargetInstance.VolumeName & ', has been removed."'

;MsgBox(1,"Msg",$SystemEvent)

Run(@ComSpec & " /c " & $SystemEvent, "", @SW_HIDE)

EndSelect

EndIf

WEnd


Murphy lives here.My website, if you care: HIPAA Information Security Resources

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0