USB_MASS_STORAGE driver crashes after vb script modify USBSTOR key - vbscript

I have this script written by myself.
Basically what I wanted was script that "unlock" the front usb only for specific device.
The situation is such that we have a workstation with registry key USBSTOR\Start set to 4(disable) so the front usb is not available without some additional work of our IT department - this way we control who can access the usb
But the employees must use a camera to take pictures for specific needs and to send them through email clients.So we want to automate the "lock/unlock" phase.
The usb is unlocked when the device of interest is inserted,it stays "unlocked" while the device is in usb and after the device is plugged out,the script "lock" the usb again.
I have decided to use .vbs.The script works as I expected,but after the "lock" phase,the USB_MASS_STORAGE driver get crashed.I must uninstall it and restart the Windows for the driver to be reloaded again and to work properly.After I have run the script several times,the registry value in USBSTOR\Start does not affect the usb,i.e the usb is unlocked even if there is 4.If I change the value from 4 to 3 the driver crashes.
I am looking for some advices.
Here is the code for usbstor.vbs script. I have used a lot of comments,some of them explain a pretty obvious things,but I have decide so.
' Script for access to Front Usb (a.k.a USB MASS STORAGE)
' The usb is locked by default(the value in Registry Key USBSTOR/Start is 4 - disable).It is enabled(the value in Registry Key USBSTOR/Start is 3 - enable) when the device of interest is put into front usb.
' The usb is in "enable" state ,while the device is into it. After it is removed,the Registry Key USBSTOR/Start value is set to 4(disable).
' The device is recognized by hardware id ,which is known in advance by searching USBSTOR,when the device is inserted. This script is for pc,where what we want is access to front usb only for spcecific device(a camera in our case).
' For everything else the usb should be disabled.The script is loaded in RAM and if the while loop condition isn't change to false,we must kill the process within TaskManager
' The CPU time is high > 98 while the script runs.I came to this solution for my problem,but any ideas for improvements or for different logic are highly welcomed.
Option Explicit On
Dim Shell,Start,Hwid,Enum_0,Enum_1,Count,Flag_0,Flag_1,Check_0,Check_1 'Dimension of varables we are going to use in the script.
Set Shell = CreateObject("WScript.Shell") 'Create an object to work with Windows Registry.
'Start = Shell.RegRead("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\USBSTOR\Start") 'Save the value of the registry key into Start variable
Hwid = "USB\Vid_0930&Pid_6545\001D92A866B8B8B1934703FE" 'hardawre id of device of interest.We get it from the registry and the script scan for this id.It is constant string
Count = 1 'Initialize the Count variable with value of 1.We use it as a condition in endless while() loop.It makes script run in real-time,so it can scan uninterupted for changes in the registry
QueryEnum0 ' The subroutines QueryEnum0 and QueryEnum1.The id is either in USBSTOR\Enum\0 or in USBSTOR\Enum\1 .That is for sure.
QueryEnum1 ' Declaration before definition - not exactly explanation.
'The purpose of these two subroutines is: create an object everytime the sub is called ,thus read the value in Enum\0 or in Enum\1 constantly as "scanning"
'Probably not so elegant solution to somebody,but actually it works.
Sub QueryEnum0 ' Enter the sub
Dim Flag_Enum_0,Shell ' Declare local variables.They will be created each time the sub is invoked.
Set Shell = CreateObject("WScript.Shell") 'Create an object to work wirh registry any time the sub is called
On Error Resume Next 'Error handling
Flag_Enum_0 = Shell.RegRead("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\USBSTOR\Enum\0") 'Try to read reg value into Flag_Enum_0. The purpose
On Error GoTo 0
Flag_0 = Flag_Enum_0 'Assign the value to variable Flag_0,outside of sub.The memory for Flag_0 is set once and lasts while the script runs.
End Sub
' Same as QueryEnum0
Sub QueryEnum1
Dim Flag_Enum_1,Shell
Set Shell = CreateObject("WScript.Shell")
On Error Resume Next
Flag_Enum_1 = Shell.RegRead("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\USBSTOR\Enum\1")
On Error GoTo 0
Flag_1 = Flag_Enum_1
End Sub
Do While Count = 1 'Real-time loop,the code within while is running while count is equal to 1. The script is loaded in memory constanlty.
On Error Resume Next
Enum_0 = Shell.RegRead("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\USBSTOR\Enum\0") ' Try to read hardware id if it is in Enum\0
On Error GoTo 0 '
On Error Resume Next
Enum_1 = Shell.RegRead("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\USBSTOR\Enum\1") 'Try to read hardware id if it is in Enum\1
On Error GoTo 0
If StrComp(Hwid,Enum_0) <> 0 And StrComp(Hwid,Enum_1) <> 0 Then 'Check if both reg keys are empty
MsgBox "There is no device in the front usb.Please put the device or see the connection"
ElseIf StrComp(Hwid,Enum_0) = 0 Then 'If the hardware id is in Enum\0,thus assigned to Enum_0
Shell.RegWrite "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\USBSTOR\Start",3 'Enable the usb by "unlock" it
On Error Resume Next
QueryEnum0 'Invoke sub QueryEnum0.If the id we looking for is in Enum\0,we know that it is assigned to Flag_0 also
Check_0 = Flag_0 'Use another variable to copy value from Flag_0.
On Error GoTo 0
If StrComp(Hwid,Check_0) = 0 Then 'Compare the constant Hwid with the value in Check_0,test for id
Msgbox "Check_0 still holds the hardware id" 'Some messages to inform us whats happening
else
MsgBox "Check_0 does not contain the hardware id anymore"
Shell.RegWrite "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\USBSTOR\Start",4 'Disable the front usb
Count = 2 'End the while loop,count is 2,so the condition is false .The loop breaks.
End If
ElseIf StrComp(Hwid,Enum_1) = 0 Then 'If the hardware is in Enum\1....same as above mentioned
Shell.RegWrite "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\USBSTOR\Start",3
On Error Resume Next
QueryEnum1
Check_1 = Flag_1
On Error GoTo 0
If StrComp(Hwid,Check_1) = 0 Then
MsgBox "Check_1 still holds the hardware id"
MsgBox Check_1
else
MsgBox "Check_0 does not contain the hardware id anymore"
Shell.RegWrite "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\USBSTOR\Start",4
Count = 2
End If
End If
Loop
' Useful information for me
'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\USBSTOR -> value name -> Start ,value data = 3(enable) = 4(disable)
'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\USBSTOR\Enum -> value name -> 1 or 0 ,value data we look for is -> USB\Vid_04da&Pid_2372\5&2f621ee5&0&8
' USB\Vid_04da&Pid_2372\5&2f621ee5&0&8 - camera id in our case
' fantom value - USB\Vid_03f0&Pid_032a\000000000Q912WFBSI1c - name: 0 ,type: REG_SZ,in the key Enum.This is another hardware id,which is strange somehow,because I do not have any device
' inserted in my usb.However,I take this value into account,thus use both keys 0 and 1 within Enum to scan for the id I need.

According to the Microsoft documentation the data in the CurrentControlSet Registry tree is used during start up and driver initialization.
Also with Windows 7 and later any changes to HKEY_LOCAL_MACHINE must be made by a utility running as an Administrator. Otherwise the changes will be made to a user clone of HKEY_LOCAL_MACHINE and changes will affect only the user under whose account the utility was run.
See HKLM\SYSTEM\CurrentControlSet\Services Registry Tree which states
"A driver can store global driver-defined data under its key in the
Services tree. Information that is stored under this key is available
to the driver during its initialization."
Everything that I have found thus far concerning additional security for USB storage devices by setting this value indicates that it is done once as a preventive measure. So it would appear that the approach you outlined is not a feasible solution.
There may also be an initial state issue in that the until a USB mass storage device is plugged in, the device driver is not fully initialized hence this data may not have yet been accessed. Readings also seem to imply that it will depend on whether the device has been previously plugged in successfully, creating the necessary Registry data and driver initialization or not.
I think it is pretty safe to say that changing the Registry value on the fly in this way was not design intent for Windows USB drivers.
See also this page of Microsoft Knowledge Base article 103000, CurrentControlSet\Services Subkey Entries for details about the data in this Registry entry. This article says the following about the Start keyword values.
0x3 (Load on demand) Available, regardless of type, but will not be started until the user starts it (for example, by using the Devices icon in Control Panel).
0x4 (disabled) NOT TO BE STARTED UNDER ANY CONDITIONS.
See also the following stackoverflow posts.
C# Disable/Enable USB ports
Enable and Disable USB port
Win32 API function to programmatically enable/disable device

Related

Find MAC address using VB6

I want to find the MAC address of network adopter, I have a working code too but my problem is it only works if IP addres is enabled otherwise it won't get the address is there any solution to find MAC address even if IP Enabled is false
if its possible update me with sample code
Here is my code to find MAC
Dim myWMI As Object, myObj As Object, Itm
Set myWMI = GetObject("winmgmts:\\.\root\cimv2")
Set myObj = myWMI.ExecQuery("SELECT * FROM " & _
"Win32_NetworkAdapterConfiguration " & _
"WHERE IPEnabled = True")
For Each Itm In myObj
Dim macme As String
Dim NewMac As String
macme = Itm.MACAddress
NewMac = Replace(macme, ":", "")
Text1.Text = NewMac
Exit For
Next
Querying the heavyweight WMI service is not the best choice for application programs. It is a convenience feature meant only for admin scripting. The service could be disabled or even uninstalled on older versions of Windows.
Instead you can go directly to the source. The GetAdaptersInfo function is one of the more obvious candidates.
Using this involves more code than can be conveniently inlined here. Look for the many examples of use in VB6 posted with working source code at more programmer-friendly sites that permit uploaded attachments.
No matter how you go about it the value of doing this is questionable anyway. Many integrated network adapters allow users to insert their own MAC Address values anyway. Quite a few PCs today rely on USB network adapters that are not even plugged in all the time and may get swapped around between devices.

Solving "unable to connect to the specified server" error in Diadem DataFileHeaderAccess

I am currently using Diadem to process a large amount of data.
There is a specific treatment that I must do on a large number of files. Therefore, I have a script loading each file one by one to do this every time.
The thing is, after several hours of computation, I get an error : Incorrect instruction or user command. In <DataFileHeaderAccess.VBC> (line:1328, column:5): Unable to conect to the specified server.
By this time, it will have successfully passed the portion of code where it happens several times, and if I launch it back on the file that has issues, it will not fail (not for this file at least).
Even more strange is that nothing is done remotely there, so I have no idea which server it might be talking about. And the file is ot opened elsewhere. Most of the time, it happens when I'm not even in the office.
And finally, I managed to find nothing anywhere regarding this issue, And I'm growing quite desperate to manage to solve it.
So ... Simple question ... "Help ?".
Well, let's develop it a little :
What might be the cause of this issue ?
How can I solve it ?
Here is the portion of code incriminated if it might help :
Function TryLoadGroup(sPath, sFileName, sGroupName, sNewGroupName)
Dim oDataFileHeader, oImportedGroup
Set oDataFileHeader = DataFileHeaderAccess(sPath & sFileName, "TDM", True)
Dim iLoop, bRet
For iLoop = 1 To oDataFileHeader.GroupCount
If oDataFileHeader.GroupNameGet(iLoop) = sGroupName Then
bret = True
End If
Next
oDataFileHeader.Close(False)
If bRet Then
Set oImportedGroup = DatafileLoadSel(sPath & sFileName,"TDM", sGroupName & "/*")
oImportedGroup.Item(1).Name = sNewGroupName
Set TryLoadGroup = oImportedGroup
Else
Set TryLoadGroup = Data.CreateElementList
End If
End Function
Set oDataFileHeader = DataFileHeaderAccess(sPath & sFileName, "TDM", True)
The error message just means that it is not capable to open the file.
There are some things I can think of
The file is corrupt (but this seems not to be true because you can open it)
The file is opened by DIAdem or a group of it is already loaded into DIAdem
DIAdem has run out of memory
Potentially you should put an error handler arround your inner loop
on error goto 0
' call a method
if 0 <> err.number then
LogFileWrite "Unable to insert file '" & filename & "': " & err.description
end if
on error goto 0
This will allow you to go on processing and see the error in the DIAdem Logfile later on.

Return to an already open application when a user tries to open a new instance in vb6

Suppose a user minimize my visual basic application to the taskbar notification icon. Now I want when user open a new instance, the old one should restore.
Generally, the strategy used to create a single-instance application is to add some code to the application initialization that determines whether an instance is already running. If one is, it gets a handle to its main window, passes the focus to it, and silently dies. If one is not, it continues to run and completes the rest of the initialization sequence as usual.
You'll find lots of old VB 6 articles that accomplished this by iterating through all of the top-level windows, looking for one whose caption matches the one you expect. But this is a pretty fragile solution, it doesn't take very much to throw it off.
Same deal with the App.PrevInstance property. This is very simple to use, but also very simple in its implementation. It works based on the name of the executable and looks for a running process whose name is a match. However, this is easily defeated if a user creates and renames a copy of the executable. If this is acceptable for you, you could implement this very easily by querying the App.PrevInstance property. Otherwise, you'll need to use a more robust solution.
One such possibility is to create and register a named mutex when the first instance of your application is starting up. Then, when subsequent instances try to register that same mutex, they will fail, indicating that an instance is already running. You can find instructions on using mutexes in VB 6 in the answers to this question.
A couple of important caveats to using mutexes:
You need to make sure that you call the ReleaseMutex and CloseHandle functions when your application is closed in order to release ownership of and destroy the mutex that you created.
When you are running your program in the VB 6 IDE (e.g., to debug it) and it registers a mutex, the mutex belongs to the IDE and won't be released until you close the IDE and restart it. To prevent this, you can suppress the creation of the mutex when running inside of the IDE/debugger using conditional compilation. If you take this approach, make sure to test your program outside of the debugger to be sure that the mutex-related functionality is working as expected! You should never ship something to customers that you haven't thoroughly tested.
You can find all of the VB 6 declarations for these Windows API functions by using the API Viewer program that comes bundled with your VB 6 installation.
More information about handling multiple instances of a VB 6 application is available here on Karl Peterson's site. There's also a complete example implementation in this article on VB Accelerator—focus specifically at step 2, you don't need the rest of the code.
You can often do this fairly simply using DDE in a degenerate way:
Form1.frm
Option Explicit
'This is Form1. To use as DDE source at design time we set:
' Form1.LinkMode = 1 (Source, i.e. vbLinkSource).
' Form1.LinkTopic = "Form1" (default).
'
'Note we use (hidden) Label1 on this Form as a DDE destination.
Private PrevState As Integer
Private Sub Form_LinkExecute(CmdStr As String, Cancel As Integer)
'Got a "command" so restore Form1 and accept the command.
WindowState = PrevState
Caption = "I am awake!"
Cancel = False
End Sub
Private Sub Form_Load()
PrevState = WindowState
End Sub
Private Sub Form_Resize()
If WindowState <> vbMinimized Then PrevState = WindowState
End Sub
Module1.bas
Option Explicit
Private Sub Main()
Load Form1
'After Form1 is loaded (hidden), try DDE link to possible prior copy.
With Form1.Label1
.LinkTopic = App.EXEName & "|Form1"
On Error Resume Next
.LinkMode = vbLinkManual
If Err.Number = 0 Then
On Error GoTo 0
'Link succeeded. Wake up prior copy via pushback to
'the DDE source, then unload Form1 and terminate.
.LinkExecute "Wake up!"
Unload Form1
Else
On Error GoTo 0
'Link failed, so we're 1st. Show Form1.
Form1.Show vbModal
End If
End With
End Sub

how to get the dsf code below to work?

I wish to send input to multiple emulated mice using dsf(device simulation framework) incuded in the current windows ddk. My code is below the problem is device manager recogizes the device got added but my program (mouse mischief - also microsoft) doesnt create the addtional pointer like its supposed to:
WriteLine "Create first input report to send to the consumer control"
Dim strMessage
strMessage = "Press Enter key to stop looping"
WriteLine strMessage
Do While NOT WScript.StdIn.AtEndOfLine
Dim InputReport1(4)
InputReport1(0) = CByte(0)
InputReport1(1) = CByte(100)
InputReport1(2) = CByte(100)
InputReport1(3) = CByte(0)
InputReport1(4) = CByte(0)
'PromptAndWaitForEnterKey "Queue input reports for processing"
GenericHIDDev.QueueInputReport(InputReport1), 10
'PromptAndWaitForEnterKey "Wait for the device to finish enumerating. Press enter to start processing input reports."
GenericHIDDev.StartProcessing
'WriteLine "You may send additional input reports at this time..."
'PromptAndWaitForEnterKey "Press enter at any time to stop processing input reports and start cleanup."
GenericHIDDev.StopProcessing
Input = WScript.StdIn.Read(1)
Loop
Note: this is the only section i modified of the TestGenericHid sample included with the dsf in the windows ddk(device driver kit). After install of windows ddk go to c:\Program Files\dsf\GenericHid or something similar to access the vbscript file.
Need mousmischief and windows ddk to fully understand whats going on and to correctly answer this. Dont worry all samples are in vbscript and can be redone in vb.net but i dont wish to waste time converting until i get the vbscript to work.
I have since I posted this got it working with multiple mouse and within 2-3 months time will have a nice beta upload of my whole kinectmultipoint project here:
http://kinectmultipoint.codeplex.com
The code above is in a zip file at the address above in the preceding sentence.

Is there any way to tell if the Windows Directory is writeable without actually writing to it to test?

I have some old vb6 code that checks to see if the Windows directory is writeable by WRITING to it then reading a value back.
But... we have a virus scanner that's viewing that as suspicious behavior so I want to check it without touching it.
Any Windows API calls for that? (Ideally for Win 98 and above)
Something to remember here is that the file system is volatile. About the only way I can see this code being used is to first do a check if a folder is writable, and then try to write something you wanted to write. The problem here is that with a volatile file system things might change in between when you make your check and when you try to write. As a consequence, you still have to be able to handle an exception if your write fails. That means the initial check is pretty much wasted. Better to put your effort into writing a better exception handler.
Additionally, for windows 2000 and later the Windows directly should only ever be writable if the user is running as an administrator. For a very long time running as an administrator was common practice, but people are starting to get the hint that this isn't a good idea. Long term, it's not a good idea for your program to do anything that requires running that way.
In fact, starting with Windows Vista, the user doesn't run anything as administrator by default, even when logged in to the administrator account. Instead, they have to manually choose to run the program as administrator or wait a security check to fail the system can prompt them to elevate.
If you have the VB6 code, you should take the time to fix it so that it does NOT need to write to the Windows directory at all because regardless of whether or not you are an administrator - unless you work at Microsoft you should consider that directory off limits.
However, you should consider that on Windows 98, the user will always have the ability to write to the Windows directory. On Windows XP, local administrators will. On Windows Vista and Seven, even administrators will not unless your application has been elevated.
So you can check for whether or not the user is in the built-in role BUILTIN\Administrators using CheckTokenMembership. This will be false for non-admins or non-elevated processes. It does not guarantee you can write to the Windows directory but it will be right most of the time. You can then add error handling logic for when the call actually fails.
But again, you should take the opportunity to fix the code and not use the Windows directory.
For Windows 2000 and above you could use GetNamedSecurityInfo() and AccessCheck(), but I would imagine those are a pain to call from VB.
Here is a function that will do it. I adapted this from some other code kind of quickly so if you use it you need to add error handling, (for instance a directory that doesn't exist just returns False. I have no idea if your anti-virus software is going to like this or not.
Function FolderIsReadOnly(ByVal FolderSpec As String) As Boolean
Dim rst As Long
Dim udtW32FindD As WIN32_FIND_DATA
Dim lngFHandle As Long
Dim strFolder As String 'set to FolderSpec parameter so I can change it
If Len(FolderSpec) = 0 Then
FolderIsReadOnly = False
Exit Function
End If
strFolder = FolderSpec
If Right$(strFolder, 1) <> "\" Then
strFolder = strFolder & "\"
End If
strFolder = strFolder & "*" 'add the wildcard allows finding share roots
lngFHandle = FindFirstFile(strFolder, udtW32FindD)
If lngFHandle <> INVALID_HANDLE_VALUE Then
Call FindClose(lngFHandle)
FolderIsReadOnly = (udtW32FindD.dwFileAttributes And FILE_ATTRIBUTE_READONLY) = FILE_ATTRIBUTE_READONLY
End If
End Function
Function IsPathAccessible(ByVal sPath As String) As Boolean
On Error GoTo ErrHandler
FileSystem.SetAttr sPath, vbNormal
IsPathAccessible = True
Exit Function
ErrHandler:
IsPathAccessible = False
End Function

Resources