News:

MASM32 SDK Description, downloads and other helpful links
MASM32.com New Forum Link
masmforum WebSite

Detect USB device insertion

Started by Magnum, May 02, 2010, 03:14:07 AM

Previous topic - Next topic

Magnum

Has anyone come up with some code to detect the insertion of a USB drive?

I found some C++ code, but it's too complicated for me to convert to asm and
it also requires an external msvcr71.dll file.

I disassembled it with IDA, but the source is rather large.

Andy
Have a great day,
                         Andy

hutch--

Without having had the time to bother to do stuff like this myself, have a look at the API DeviceIOcontrol, it may be able to do what you need.
Download site for MASM32      New MASM Forum
https://masm32.com          https://masm32.com/board/index.php

clive

Depends at what level you want to detect this. To catch it under all circumstances I'd use a system driver as a filter (UpperFilter/LowerFilter) attached to the USB or drive stack, I've written a couple of these, but they are not for the faint of heart.
It could be a random act of randomness. Those happen a lot as well.

dioxin

Magnum,
   depends on the job you're trying to do but the following may help.

1) When the USB stick is inserted, the autorun.inf file on that stick is usually run. If you're trying to run something off the stick then you could use that instead of having software already running on the PC to monitor stuff.
Personally, I disable the autorun because it's a common way to spread viruses and the like.


2) When a USB stick is inserted all your top level Windows should receive a Windows Message WM_DEVICECHANGE
On receipt of that you can look for a new drive using GetLogicalDriveStrings and see if a USB memory has been added.

Paul.



farrier

Magnum,

This article:

http://www.codeproject.com/KB/system/HwDetect.aspx

helped me to do something similar to what you asked for.  A lot of info--including the drive letter--is included with the info header filled when you receive the WM_DEVICECHANGE, as dioxin noted.

I used this to detect a USB thumb drive insertion for a backup routine, where I couldn't rely on the thumb drive having the same drive letter each day!

hth,

farrier
It is a GOOD day to code!
Some assembly required!
ASM me!
With every mistake, we must surely be learning. (George...Bush)

Magnum

Quote from: farrier on May 02, 2010, 07:48:35 PM
Magnum,

This article:

http://www.codeproject.com/KB/system/HwDetect.aspx

helped me to do something similar to what you asked for.  A lot of info--including the drive letter--is included with the info header filled when you receive the WM_DEVICECHANGE, as dioxin noted.

I used this to detect a USB thumb drive insertion for a backup routine, where I couldn't rely on the thumb drive having the same drive letter each day!

hth,

farrier


I already have that project code but it requires a separate dll.

Have a great day,
                         Andy

farrier

#6
Magnum,

No separate DLL is required.  Within the program you are using to monitor for a USB change, check in your message loop for the WM_DEVICECHANGE message and check for:

wParam == DBT_DEVICEARRIVAL   for  a device insertion

     then, lParam == a pointer to a structure of type DEV_BROADCAST_HDR

Use this to figure out what was plugged in and what the drive letter is ...

Also, in the SDK under the "DBT_DEVICEARRIVAL Event" listing, there is a link to an example: Detecting Media Insertion or Removal


hth,

farrier
It is a GOOD day to code!
Some assembly required!
ASM me!
With every mistake, we must surely be learning. (George...Bush)

joemc

Quote from: dioxin on May 02, 2010, 01:46:04 PM
When the USB stick is inserted, the autorun.inf file on that stick is usually run. If you're trying to run something off the stick then you could use that instead of having software already running on the PC to monitor stuff.
Personally, I disable the autorun because it's a common way to spread viruses and the like.

It is also turned off for USB devices for Win7 and cannot be turned on. msdn
There is software that emulates the behavior here.  Source code is available and it detects USB input, so you may be interested in it.

"Infection Detections of Malware that Spread via AutoRun"  "(Note: The actual method of infection cannot be determined.)" They make graphs for anything.

Magnum

Quote from: farrier on May 03, 2010, 01:52:37 AM
Magnum,

No separate DLL is required.  Within the program you are using to monitor for a USB change, check in your message loop for the WM_DEVICECHANGE message and check for:

wParam == DBT_DEVICEARRIVAL   for  a device insertion

     then, lParam == a pointer to a structure of type DEV_BROADCAST_HDR

Use this to figure out what was plugged in and what the drive letter is ...

Also, in the SDK under the "DBT_DEVICEARRIVAL Event" listing, there is a link to an example: Detecting Media Insertion or Removal

hth,

farrier


Thanks farrier.

Ragdog gave me this, so I think I am closer.



; With USB stick in F: drive...
; ERROR_RESOURCE_DATA_NOT_FOUND
; 1812 (0x714)
;
; from ragdog
;
.386
.model flat, stdcall  ;32 bit memory model
option casemap :none  ;case sensitive

include DlgMain.inc

.code

start:

    invoke GetModuleHandle,NULL
    mov hInstance,eax
    invoke InitCommonControls


invoke DialogBoxParam,hInstance,IDD_DIALOG,NULL,addr DlgProc,NULL
invoke ExitProcess,0

DlgProc proc hWnd:HWND,uMsg:UINT,wParam:WPARAM,lParam:LPARAM

.if uMsg==WM_INITDIALOG

        .elseif    uMsg ==   WM_DEVICECHANGE 
            mov    eax,wParam
            .if    eax == DBT_DEVICEARRIVAL
                   mov  eax,lParam
                   assume eax:ptr _DEV_BROADCAST_HDR
                   mov  eax,[eax].dbch_devicetype
                   assume eax:nothing
                   .if  eax == DBT_DEVTYP_VOLUME
                        mov eax,lParam
                        assume eax:ptr _DEV_BROADCAST_VOLUME
                        mov edx,[eax].dbcv_unitmask
                        ;mov ecx,[eax].dbcv_flags
                        xor ebx,ebx
                        .while ebx<26
                        mov ecx,edx
                        and edx,01h
                        .if edx==1
                            mov cx,word ptr [eax].dbcv_flags
                            .if cx == 00h ;(subst net use)
                            add ebx,65d
                            invoke CheckUsbDisk,ebx
                            .endif
                            .break
                        .else
                            mov edx,ecx
                            shr edx,1
                        .endif
                        inc ebx
                        .endw
                        assume eax:nothing       
                   .endif
            .endif       
 
.elseif uMsg==WM_COMMAND
            .if wParam==9000
       
            .endif
     
.elseif uMsg==WM_CLOSE

invoke EndDialog,hWnd,0
.else
mov eax,FALSE
ret
.endif
mov eax,TRUE
ret

DlgProc endp

CheckUsbDisk        proc uses ebx esi edi disk:dword
    LOCAL   buffer[128]:byte
    LOCAL   hDisk:dword
    LOCAL   notuse:dword
    LOCAL   Query:STORAGE_PROPERTY_QUERY
    LOCAL   DevDesc:STORAGE_DEVICE_DESCRIPTOR

; from .data
;disk3   db '\\.\',0
;mao     db ':',0


   invoke   lstrcpy,addr buffer,offset disk3   ;buffer=\\.\
   invoke   lstrcat,addr buffer,addr   disk    ;buffer=\\.\X
   invoke   lstrcat,addr buffer,offset mao     ;buffer=\\.\X:
   invoke   CreateFile,addr buffer, NULL, NULL,NULL, OPEN_EXISTING, NULL,NULL
   mov      hDisk,eax
   .if eax !=INVALID_HANDLE_VALUE
        mov Query.PropertyId,StorageDeviceProperty   
        mov Query.QueryType,PropertyStandardQuery
        invoke   DeviceIoControl,hDisk,IOCTL_STORAGE_QUERY_PROPERTY,addr Query, sizeof STORAGE_PROPERTY_QUERY,addr DevDesc,sizeof STORAGE_DEVICE_DESCRIPTOR,addr notuse, NULL
        .if eax != NULL
            mov eax,[ DevDesc.BusType]
            .if eax == BusTypeUsb
                invoke  lstrcpy,addr buffer,addr disk  ;buffer=X
                invoke  lstrcat,addr buffer,offset mao ;buffer=X:
                invoke        GetDriveType,addr buffer
                .if eax != DRIVE_REMOVABLE
                invoke  MessageBox,0,addr buffer,addr buffer,MB_OK
                .endif
            .endif       
        .endif     
   .endif     
   invoke   CloseHandle,hDisk
    ret
CheckUsbDisk        endp
end start



And the .inc file.


; dlgmain.inc From ragdog
;
include \masm32\include\windows.inc
include \masm32\include\kernel32.inc
include \masm32\include\user32.inc
include \masm32\include\Comctl32.inc
include \masm32\include\shell32.inc
INCLUDE \masm32\include\gdi32.inc
includelib \masm32\lib\kernel32.lib
includelib \masm32\lib\user32.lib
includelib \masm32\lib\Comctl32.lib
includelib \masm32\lib\shell32.lib
includelib \masm32\lib\gdi32.lib
include \masm32\macros\macros.asm

CTEXT MACRO text:VARARG
       local TxtName
         .data
          TxtName BYTE text,0
         .code
       EXITM <offset TxtName>
ENDM

CTL_CODE MACRO DeviceType:=<0>, Function:=<0>, Method:=<0>, Access:=<0>
        EXITM %(((DeviceType) SHL 16) OR ((Access) SHL 14) OR ((Function) SHL 2) OR (Method))
ENDM

DlgProc PROTO :HWND,:UINT,:WPARAM,:LPARAM
CheckUsbDisk             proto :dword

.const

IDD_DIALOG    equ 1000

DBT_DEVICEARRIVAL  equ 8000h
DBT_DEVTYP_VOLUME  equ 02h

_DEV_BROADCAST_HDR struct
dbch_size       dd ?
dbch_devicetype dd ?
dbch_reserved   dd ?
_DEV_BROADCAST_HDR ends   

_DEV_BROADCAST_VOLUME struct
dbcv_size       dd ?
dbcv_devicetype dd ?
dbcv_reserved   dd ?
dbcv_unitmask   dd ?
dbcv_flags      dw ?
_DEV_BROADCAST_VOLUME ends

DBTF_MEDIA      equ 01h
DBTF_NET        equ 02h ;subst

FILE_ANY_ACCESS              equ 0
METHOD_BUFFERED              equ 0
FILE_DEVICE_MASS_STORAGE     equ 2dh ;from ntddk.inc
IOCTL_STORAGE_BASE           equ FILE_DEVICE_MASS_STORAGE ;from ntddstor.inc
IOCTL_STORAGE_QUERY_PROPERTY equ CTL_CODE(IOCTL_STORAGE_BASE, 500h, METHOD_BUFFERED, FILE_ANY_ACCESS)

BusTypeUsb equ 7

StorageDeviceProperty equ 0
PropertyStandardQuery equ 0

STORAGE_PROPERTY_QUERY struct
PropertyId     dd ?             ;
QueryType      dd ?             ;
AdditionalParameters dd ?       ;
STORAGE_PROPERTY_QUERY ends

STORAGE_DEVICE_DESCRIPTOR struct
Version                 dd ?       
theSize                 dd ?       
DeviceType              db ?       
DeviceTypeModifier      db ?        ; SCSI-2
RemovableMedia          db ?       
CommandQueueing         db ?       
VendorIdOffset          dd ?       
ProductIdOffset         dd ?       
ProductRevisionOffset   dd ?   
SerialNumberOffset      dd ?   
BusType                 dd ?   
RawPropertiesLength     dd ?   
RawDeviceProperties     dd ?   
STORAGE_DEVICE_DESCRIPTOR ends

.data
disk3   db '\\.\',0
mao     db ':',0
.data?
hInstance dd ?

Have a great day,
                         Andy