Foro de elhacker.net

Programación => .NET (C#, VB.NET, ASP) => Mensaje iniciado por: **Aincrad** en 10 Mayo 2019, 16:08 pm



Título: Funcion calloc() en vb.net?
Publicado por: **Aincrad** en 10 Mayo 2019, 16:08 pm
Hola, bueno como dice el titulo, no encuentro como declarar esa funcion en vb.net. espero que me puedan ayudar gracias de antemano, la necesito para este code :

Código
  1. <DllImport("msvcrt.dll", EntryPoint:="memcpy", CallingConvention:=CallingConvention.Cdecl)> _
  2.    Public Shared Sub CopyMemory(ByVal dest As IntPtr, ByVal src As IntPtr, ByVal count As Integer)
  3.    End Sub
  4.  
  5.  
  6.  
  7.    Private Function GetMutexString() As String
  8.  
  9.        Dim lpMutexStr As String = calloc(64, 1)
  10.        Dim s() As Byte = {&H98, &H9B, &H99, &H9D, &HC3, &H15, &H6F, &H6F, &H2D, &HD3, &HEA, &HAE, &H13, &HFF, &H7A, &HBE, &H63, &H36, &HFC, &H63, &HF3, &H74, &H32, &H74, &H71, &H72, &H4E, &H2, &H81, &H1E, &H19, &H20, &H44, &HDF, &H81, &HD7, &H15, &H92, &H93, &H1A, &HE7}
  11.        Dim Sizes As Integer = Marshal.SizeOf(s(0)) * s.Length
  12.        Dim pnt1 As IntPtr = Marshal.AllocHGlobal(Sizes)
  13.        Dim m As UInteger = 0
  14.        Do While m < Len(s)
  15.            Dim c As Byte = s(m)
  16.            c -= &HE8
  17.            c = ((c >> &H5) Or (c << &H3))
  18.            c = -c
  19.            c += &H51
  20.            c = Not c
  21.            c -= &H93
  22.            c = ((c >> &H3) Or (c << &H5))
  23.            c += &H14
  24.            c = c Xor &H14
  25.            c = ((c >> &H1) Or (c << &H7))
  26.            c = c Xor &HD3
  27.            c += m
  28.            c = Not c
  29.            c = ((c >> &H5) Or (c << &H3))
  30.            c -= &H2B
  31.            s(m) = c
  32.            m += 1
  33.        Loop
  34.  
  35.        CopyMemory(lpMutexStr, pnt1, Len(s))
  36.        Return lpMutexStr
  37.    End Function

Intento pasar este code de Anti-Debug a VB.NET .

Código
  1. #include <stdio.h>
  2. #include <windows.h>
  3. #include <tchar.h>
  4. #include <psapi.h>
  5.  
  6. typedef enum { ThreadHideFromDebugger = 0x11 } THREADINFOCLASS;
  7.  
  8. typedef NTSTATUS(WINAPI *NtQueryInformationThread_t)(HANDLE, THREADINFOCLASS, PVOID, ULONG, PULONG);
  9. typedef NTSTATUS(WINAPI *NtSetInformationThread_t)(HANDLE, THREADINFOCLASS, PVOID, ULONG);
  10.  
  11. VOID ThreadMain(LPVOID p);
  12. LPSTR GetMutexString();
  13.  
  14. VOID WINAPI init_antidbg(PVOID DllHandle, DWORD Reason, PVOID Reserved)
  15. {
  16.    //Deobfuscate our mutex and lock it so our child doesnt execute this TLS callback.
  17.    unsigned char s[] =
  18.    {
  19.  
  20.        0x9d, 0x3, 0x3c, 0xec, 0xf0, 0x8b, 0xb5, 0x5,
  21.        0xe2, 0x2a, 0x87, 0x5, 0x64, 0xe4, 0xf8, 0xe7,
  22.        0x64, 0x29, 0xd2, 0x6, 0xad, 0x29, 0x9a, 0xe0,
  23.        0xea, 0xf9, 0x2, 0x7d, 0x31, 0x72, 0xf7, 0x33,
  24.        0x13, 0x83, 0xb, 0x8f, 0xae, 0x2c, 0xa7, 0x2a,
  25.        0x95
  26.    };
  27.  
  28.    for (unsigned int m = 0; m < sizeof(s); ++m)
  29.    {
  30.        unsigned char c = s[m];
  31.        c = (c >> 0x7) | (c << 0x1);
  32.        c ^= m;
  33.        c = (c >> 0x5) | (c << 0x3);
  34.        c += 0xa9;
  35.        c = ~c;
  36.        c += 0xd6;
  37.        c = -c;
  38.        c += m;
  39.        c = ~c;
  40.        c = (c >> 0x5) | (c << 0x3);
  41.        c -= m;
  42.        c = ~c;
  43.        c += m;
  44.        c ^= m;
  45.        c += m;
  46.        s[m] = c;
  47.    }
  48.  
  49.    HANDLE hMutex = CreateMutexA(NULL, TRUE, s);
  50.  
  51.    // We don't want to empty the working set of our child process, it's not neccessary as it has a debugger attached already.
  52.    if (GetLastError() == ERROR_ALREADY_EXISTS)
  53.    {
  54.        return;
  55.    }
  56.  
  57.    /*
  58.         CODE DESCRIPTION:
  59.         The following code is reponsible for preventing the debugger to attach on parent process at runtime.
  60.     */
  61.    SIZE_T min, max;
  62.    SYSTEM_INFO si = { 0 };
  63.  
  64.    GetSystemInfo(&amp;si);
  65.  
  66.    K32EmptyWorkingSet(GetCurrentProcess());
  67.  
  68.    void *p = NULL;
  69.    while (p = VirtualAllocEx(GetCurrentProcess(), NULL, si.dwPageSize, MEM_COMMIT | MEM_RESERVE, PAGE_NOACCESS))
  70.    {
  71.        if (p == NULL)
  72.            break;
  73.    }
  74.    /*
  75.         DESCRIPTION END
  76.     */
  77.  
  78.  
  79.    /*
  80.         CODE DESCRIPTION:
  81.         The following code is responsible for handling the application launch inside a debbuger and invoking a crash.
  82.     */
  83.    NtQueryInformationThread_t fnNtQueryInformationThread = NULL;
  84.    NtSetInformationThread_t fnNtSetInformationThread = NULL;
  85.  
  86.    DWORD dwThreadId = 0;
  87.    HANDLE hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadMain, NULL, 0, 0, &amp;dwThreadId);
  88.  
  89.    HMODULE hDLL = LoadLibrary("ntdll.dll");
  90.    if (!hDLL) return -1;
  91.  
  92.    fnNtQueryInformationThread = (NtQueryInformationThread_t)GetProcAddress(hDLL, "NtQueryInformationThread");
  93.    fnNtSetInformationThread = (NtSetInformationThread_t)GetProcAddress(hDLL, "NtSetInformationThread");
  94.  
  95.    if (!fnNtQueryInformationThread || !fnNtSetInformationThread)
  96.        return -1;
  97.  
  98.    ULONG lHideThread = 1, lRet = 0;
  99.  
  100.    fnNtSetInformationThread(hThread, ThreadHideFromDebugger, &amp;lHideThread, sizeof(lHideThread));
  101.    fnNtQueryInformationThread(hThread, ThreadHideFromDebugger, &amp;lHideThread, sizeof(lHideThread), &amp;lRet);
  102.    /*
  103.         DESCRIPTION END
  104.     */
  105. }
  106.  
  107.  
  108. // Usually what happens is that person who does the analysis doesn't have a breakpoint set for TLS.
  109. // (It's not set ON by default in x64dbg)
  110. #pragma comment(linker, "/INCLUDE:__tls_used") // We want to include TLS Data Directory structure in our program
  111. #pragma data_seg(push)
  112. #pragma data_seg(".CRT$XLAA")
  113. EXTERN_C PIMAGE_TLS_CALLBACK p_tls_callback1 = init_antidbg; // This will execute before entry point and main function.
  114. #pragma data_seg(pop)
  115.  
  116.  
  117. int main(int argc, char *argv[])
  118. {
  119.    // Beging by deobfuscating our mutex.
  120.    HANDLE hMutex = CreateMutexA(NULL, TRUE, GetMutexString());
  121.  
  122.    if (GetLastError() == ERROR_ALREADY_EXISTS) {
  123.        // We are a spawn, run normally
  124.        printf("[+] Normal execution.\n");
  125.        getchar();
  126.        return 0;
  127.    }
  128.    else {
  129.        // We are the first instance
  130.        TCHAR szFilePath[MAX_PATH] = { 0 };
  131.        GetModuleFileName(NULL, szFilePath, MAX_PATH);
  132.  
  133.        PROCESS_INFORMATION pi = { 0 };
  134.        STARTUPINFO si = { 0 };
  135.        si.cb = sizeof(STARTUPINFO);
  136.  
  137.        // Create child process
  138.        CreateProcess(szFilePath, NULL, NULL, NULL, FALSE, DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS | CREATE_NEW_CONSOLE, 0, NULL, &amp;si, &amp;pi);
  139.        if (pi.hProcess != NULL) {
  140.            printf("[+] Spawning child process and attaching as a debugger.\n");
  141.  
  142.            // Debug event
  143.            DEBUG_EVENT de = { 0 };
  144.            while (1)
  145.            {
  146.                WaitForDebugEvent(&amp;de, INFINITE);
  147.                // We only care about when the process terminates
  148.                if (de.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
  149.                    break;
  150.                // Otherwise ignore all other events
  151.                ContinueDebugEvent(pi.dwProcessId, pi.dwThreadId, DBG_CONTINUE);
  152.            }
  153.        }
  154.  
  155.        CloseHandle(pi.hProcess);
  156.        CloseHandle(hMutex);
  157.    }
  158.  
  159.    return 0;
  160. }
  161.  
  162. LPSTR GetMutexString()
  163. {
  164.    LPSTR lpMutexStr = calloc(64, 1);
  165.    unsigned char s[] =
  166.    {
  167.  
  168.        0x98, 0x9b, 0x99, 0x9d, 0xc3, 0x15, 0x6f, 0x6f,
  169.        0x2d, 0xd3, 0xea, 0xae, 0x13, 0xff, 0x7a, 0xbe,
  170.        0x63, 0x36, 0xfc, 0x63, 0xf3, 0x74, 0x32, 0x74,
  171.        0x71, 0x72, 0x4e, 0x2, 0x81, 0x1e, 0x19, 0x20,
  172.        0x44, 0xdf, 0x81, 0xd7, 0x15, 0x92, 0x93, 0x1a,
  173.        0xe7
  174.    };
  175.  
  176.    for (unsigned int m = 0; m < sizeof(s); ++m)
  177.    {
  178.        unsigned char c = s[m];
  179.        c -= 0xe8;
  180.        c = (c >> 0x5) | (c << 0x3);
  181.        c = -c;
  182.        c += 0x51;
  183.        c = ~c;
  184.        c -= 0x93;
  185.        c = (c >> 0x3) | (c << 0x5);
  186.        c += 0x14;
  187.        c ^= 0x14;
  188.        c = (c >> 0x1) | (c << 0x7);
  189.        c ^= 0xd3;
  190.        c += m;
  191.        c = ~c;
  192.        c = (c >> 0x5) | (c << 0x3);
  193.        c -= 0x2b;
  194.        s[m] = c;
  195.    }
  196.    memcpy(lpMutexStr, s, sizeof(s));
  197.    return lpMutexStr;
  198. }
  199.  
  200. VOID ThreadMain(LPVOID p)
  201. {
  202.    while (1)
  203.    {
  204.        if (IsDebuggerPresent())
  205.        {
  206.            __asm { int 3; }
  207.        }
  208.        Sleep(500);
  209.    }
  210.    return 0;
  211. }
  212. }


Título: Re: Funcion calloc() en vb.net?
Publicado por: Eleкtro en 11 Mayo 2019, 01:01 am
Según la documentación de Microsoft, el propósito de la función calloc es asignar un array de tamaño específico, e inicializar todos sus elementos a cero...

Cita de: https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/calloc?view=vs-2019
calloc | Microsoft Docs
Allocates an array in memory with elements initialized to 0.

Por lo tanto, es innecesario reproducir esta función, ya que en .NET no es necesario administrar manualmente la memoria para el propósito que tu quieres llevar a cabo.

De todas formas, un equivalente cercano en VB.NET sería usar el siguiente tipo de declaración, con la obvia diferencia de que esto asignaría el array en la memoria administrada...

Código
  1. Dim chars(63) As Char

Ten en cuenta que referente a la asignación en la memoria no administrada, siempre puedes utilizar la función Marshal.AlllocHGlobal().



El propósito de la función GetMutexString es devolver el nombre de un Mutex de 64 caracteres (lo cual es muy arbitrario, bien podrían ser 10, 20, o 128 caracteres), por lo que perfectamente puedes simplificar todo ese código de C/C++ a una simple declaración de String en lugar de declarar un array de caracteres...

Código
  1. Dim mutexName As String = "Global\Nombre del mutex" ' Global\Name or Local\Name

O si quieres generar un nombre aleatorio de X caracteres, puedes hacerlo así:
Código
  1. Dim mutexName As New StringBuilder()
  2. mutexName.Append("Global\") ' Global\Name or Local\Name
  3.  
  4. For i As Integer = 0 To (16 - 1)
  5.    mutexName.Append(Convert.ToChar(RNG.Next(65, 91))) ' A to Z virtual-keys.
  6. Next
  7.  

Si quieres añadir alguna medida de ofuscación, eso ya sería decisión tuya.



Y ten en cuenta también la existencia de la clase System.Threading.Mutex para crear un mutex mediante código administrado...

Código
  1. Dim mtxACL As New MutexAccessRule(New SecurityIdentifier(WellKnownSidType.WorldSid, Nothing), MutexRights.FullControl, AccessControlType.Allow)
  2. Dim mtxSecurity As New MutexSecurity()
  3. mtxSec.AddAccessRule(mtxACL)
  4.  
  5. Dim mtx As New Mutex(True, mutexName, New Boolean, mtxSec)

Saludos.


Título: Re: Funcion calloc() en vb.net?
Publicado por: **Aincrad** en 11 Mayo 2019, 01:27 am
Gracias por responder, me has ayudado xd.

una Pregunta. hay alguna manera facil de declarar codigo ASM en vb.net?

Por ejemplo en esta funcion :

Código
  1. VOID ThreadMain(LPVOID p)
  2. {
  3.    while (1)
  4.    {
  5.        if (IsDebuggerPresent())
  6.        {
  7.            __asm { int 3; }
  8.        }
  9.        Sleep(500);
  10.    }
  11.    return 0;
  12. }

No encontre como declarar codigo ASM en vb.net, en la parte :

Código
  1. __asm { int 3; }

Bueno al final lo hice asi :

Código
  1. Private Declare Function IsDebuggerPresent Lib "kernel32" () As Integer
  2.  
  3. Private Function IsDebuggerPresentFunc() As Boolean
  4.        If IsDebuggerPresent = 1 Then
  5.            Return True
  6.        End If
  7.        Return False
  8.    End Function


Título: Re: Funcion calloc() en vb.net?
Publicado por: Eleкtro en 11 Mayo 2019, 13:11 pm
Actualiza tus P/Invokes...

Código
  1. Friend NotInheritable Class NativeMethods
  2.  
  3.    Private Sub New()
  4.    End Sub
  5.  
  6.    ''' ----------------------------------------------------------------------------------------------------
  7.    ''' <summary>
  8.    ''' Determines whether the calling process is being debugged by a user-mode debugger.
  9.    ''' </summary>
  10.    ''' ----------------------------------------------------------------------------------------------------
  11.    ''' <remarks>
  12.    ''' <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms680345(v=vs.85).aspx"/>
  13.    ''' </remarks>
  14.    ''' ----------------------------------------------------------------------------------------------------
  15.    ''' <returns>
  16.    ''' If the current process is running in the context of a debugger, the return value is <see langword="True"/>.
  17.    ''' <para></para>
  18.    ''' If the current process is not running in the context of a debugger, the return value is <see langword="False"/>.
  19.    ''' </returns>
  20.    ''' ----------------------------------------------------------------------------------------------------
  21.    <DllImport("Kernel32.dll", SetLastError:=False)>
  22.    Friend Shared Function IsDebuggerPresent(
  23.    ) As <MarshalAs(UnmanagedType.Bool)> Boolean
  24.    End Function
  25.  
  26. End Class

Y recuerda que también puedes utilizar la propiedad System.Diagnostics.Debugger.IsAttached para el debugger de Visual Studio. Aunque me imagino que eso no es lo que buscas...

  • Debugger.IsAttached Property (System.Diagnostics) | Microsoft Docs (https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.debugger.isattached?view=netframework-4.8)



En fin. Te muestro un modo en como lo puedes hacer...

( El siguiente código ha sido extraido de forma gratuita de la librería comercial DevCase for .NET Framework (https://codecanyon.net/item/elektrokit-class-library-for-net/19260282) para desarrolladores de .NET )

DebuggerNotify.vb
Código
  1. #Region " Imports "
  2.  
  3. Imports System
  4. Imports System.Timers
  5.  
  6. #End Region
  7.  
  8. #Region " Usage Examples "
  9.  
  10. ' Public Class Form1
  11. '
  12. '     Private WithEvents DebuggerNotify As DebuggerNotify
  13. '
  14. '     Public Sub New()
  15. '         MyClass.InitializeComponent()
  16. '         Me.DebuggerNotify = New DebuggerNotify()
  17. '     End Sub
  18. '
  19. '     Private Sub DebuggerNotify_StatusChanged(ByVal sender As Object, ByVal e As DebuggerNotifyEventArgs) Handles DebuggerNotify.StatusChanged
  20. '         Dim msg As String = $"Debugger status changed to {NameOf(e.IsAttached)}: {e.IsAttached}"
  21. '         Console.WriteLine(msg)
  22. '     End Sub
  23. '
  24. ' End Class
  25.  
  26. #End Region
  27.  
  28. #Region " DebuggerNotify "
  29.  
  30. Namespace DevCase.Core.Diagnostics.Debug
  31.  
  32.    ''' ----------------------------------------------------------------------------------------------------
  33.    ''' <summary>
  34.    ''' Provides a mechanism to notify when a debugger in user-mode is attached to or detached from the current process.
  35.    ''' </summary>
  36.    ''' ----------------------------------------------------------------------------------------------------
  37.    ''' <example> This is a code example.
  38.    ''' <code>
  39.    ''' Public Class Form1
  40.    '''
  41.    '''     Private WithEvents DebuggerNotify As DebuggerNotify
  42.    '''
  43.    '''     Public Sub New()
  44.    '''         MyClass.InitializeComponent()
  45.    '''         Me.DebuggerNotify = New DebuggerNotify()
  46.    '''     End Sub
  47.    '''
  48.    '''     Private Sub DebuggerNotify_StatusChanged(ByVal sender As Object, ByVal e As DebuggerNotifyEventArgs) Handles DebuggerNotify.StatusChanged
  49.    '''         Dim msg As String = $"Debugger status changed to {NameOf(e.IsAttached)}: {e.IsAttached}"
  50.    '''         Console.WriteLine(msg)
  51.    '''     End Sub
  52.    '''
  53.    ''' End Class
  54.    ''' </code>
  55.    ''' </example>
  56.    ''' ----------------------------------------------------------------------------------------------------
  57.    Public Class DebuggerNotify : Implements IDisposable
  58.  
  59. #Region " Private Fields "
  60.  
  61.        ''' ----------------------------------------------------------------------------------------------------
  62.        ''' <summary>
  63.        ''' A <see cref="Timer"/> that periodically checks for the presence of a debugger attached to the current process.
  64.        ''' </summary>
  65.        ''' ----------------------------------------------------------------------------------------------------
  66.        Private WithEvents DebuggerCheckTimer As Timer
  67.  
  68.        ''' <summary>
  69.        ''' The interval, in milliseconds, to check for the presence of a debugger attached to the current process.
  70.        ''' </summary>
  71.        Protected checkInterval As Integer = 1000 ' ms
  72.  
  73.        ''' ----------------------------------------------------------------------------------------------------
  74.        ''' <summary>
  75.        ''' Flag to keep track of the last result from a call to <see cref="NativeMethods.IsDebuggerPresent()"/>
  76.        ''' </summary>
  77.        ''' ----------------------------------------------------------------------------------------------------
  78.        Protected lastIsDebuggerPresent As Boolean
  79.  
  80. #End Region
  81.  
  82. #Region " Events "
  83.  
  84.        ''' ----------------------------------------------------------------------------------------------------
  85.        ''' <summary>
  86.        ''' Occurs when a debugger is attached to or detached from the current process.
  87.        ''' </summary>
  88.        ''' ----------------------------------------------------------------------------------------------------
  89.        Public Event StatusChanged As EventHandler(Of DebuggerNotifyEventArgs)
  90.  
  91. #End Region
  92.  
  93. #Region " Constructors "
  94.  
  95.        ''' ----------------------------------------------------------------------------------------------------
  96.        ''' <summary>
  97.        ''' Initializes a new instance of the <see cref="DebuggerNotify"/> class.
  98.        ''' </summary>
  99.        ''' ----------------------------------------------------------------------------------------------------
  100.        <DebuggerNonUserCode>
  101.        Public Sub New()
  102.  
  103.            Me.DebuggerCheckTimer = New Timer(Me.checkInterval) With {
  104.                .AutoReset = True
  105.            }
  106.  
  107.            Me.lastIsDebuggerPresent = NativeMethods.IsDebuggerPresent()
  108.            Me.DebuggerCheckTimer.Start()
  109.  
  110.        End Sub
  111.  
  112. #End Region
  113.  
  114. #Region " Event Invocators "
  115.  
  116.        ''' ----------------------------------------------------------------------------------------------------
  117.        ''' <summary>
  118.        ''' Raises the <see cref="DebuggerNotify.StatusChanged"/> event.
  119.        ''' </summary>
  120.        ''' ----------------------------------------------------------------------------------------------------
  121.        ''' <param name="e">
  122.        ''' The <see cref="DebuggerNotifyEventArgs"/> instance containing the event data.
  123.        ''' </param>
  124.        ''' ----------------------------------------------------------------------------------------------------
  125.        <DebuggerStepThrough>
  126.        Protected Overridable Sub OnStatusChanged(ByVal e As DebuggerNotifyEventArgs)
  127.            If (Me.StatusChangedEvent IsNot Nothing) Then
  128.                RaiseEvent StatusChanged(Me, e)
  129.            End If
  130.        End Sub
  131.  
  132. #End Region
  133.  
  134. #Region " Event Handlers "
  135.  
  136.        ''' ----------------------------------------------------------------------------------------------------
  137.        ''' <summary>
  138.        ''' Handles the <see cref="Timer.Elapsed"/> event of the <see cref="DebuggerNotify.DebuggerCheckTimer"/> object.
  139.        ''' </summary>
  140.        ''' ----------------------------------------------------------------------------------------------------
  141.        ''' <param name="sender">
  142.        ''' The source of the event.
  143.        ''' </param>
  144.        '''
  145.        ''' <param name="e">
  146.        ''' The <see cref="ElapsedEventArgs"/> instance containing the event data.
  147.        ''' </param>
  148.        ''' ----------------------------------------------------------------------------------------------------
  149.        Private Sub DebuggerCheckTimer_Elapsed(sender As Object, e As ElapsedEventArgs) Handles DebuggerCheckTimer.Elapsed
  150.  
  151.            Dim isDebuggerPresent As Boolean = NativeMethods.IsDebuggerPresent()
  152.            If (isDebuggerPresent <> Me.lastIsDebuggerPresent) Then
  153.                Me.lastIsDebuggerPresent = isDebuggerPresent
  154.                Me.OnStatusChanged(New DebuggerNotifyEventArgs(isDebuggerPresent))
  155.            End If
  156.  
  157.        End Sub
  158.  
  159. #End Region
  160.  
  161. #Region " IDisposable Implementation "
  162.  
  163.        ''' ----------------------------------------------------------------------------------------------------
  164.        ''' <summary>
  165.        ''' Flag to detect redundant calls.
  166.        ''' </summary>
  167.        ''' ----------------------------------------------------------------------------------------------------
  168.        Private disposedValue As Boolean
  169.  
  170.        ''' ----------------------------------------------------------------------------------------------------
  171.        ''' <summary>
  172.        ''' Releases all the resources used by this instance.
  173.        ''' </summary>
  174.        ''' ----------------------------------------------------------------------------------------------------
  175.        ''' <param name="disposing">
  176.        ''' <see langword="True"/> to release both managed and unmanaged resources;
  177.        ''' <see langword="False"/> to release only unmanaged resources.
  178.        ''' </param>
  179.        ''' ----------------------------------------------------------------------------------------------------
  180.        Protected Overridable Sub Dispose(disposing As Boolean)
  181.            If Not (Me.disposedValue) AndAlso (disposing) Then
  182.                Me.DebuggerCheckTimer?.Dispose()
  183.            End If
  184.            Me.disposedValue = True
  185.        End Sub
  186.  
  187.        ''' ----------------------------------------------------------------------------------------------------
  188.        ''' <summary>
  189.        ''' Releases all the resources used by this instance.
  190.        ''' </summary>
  191.        ''' ----------------------------------------------------------------------------------------------------
  192.        Public Sub Dispose() Implements IDisposable.Dispose
  193.            Me.Dispose(True)
  194.        End Sub
  195.  
  196. #End Region
  197.  
  198.    End Class
  199.  
  200. End Namespace
  201.  
  202. #End Region

DebuggerNotifyEventArgs.vb
Código
  1. #Region " Imports "
  2.  
  3. Imports System
  4.  
  5. #End Region
  6.  
  7. #Region " DebuggerNotifyEventArgs "
  8.  
  9. Namespace DevCase.Core.Diagnostics.Debug
  10.  
  11.    ''' ----------------------------------------------------------------------------------------------------
  12.    ''' <summary>
  13.    ''' Provides the event data for the <see cref="DebuggerNotify.StatusChanged"/> event.
  14.    ''' </summary>
  15.    ''' ----------------------------------------------------------------------------------------------------
  16.    Public NotInheritable Class DebuggerNotifyEventArgs : Inherits EventArgs
  17.  
  18. #Region " Constructors "
  19.  
  20.        ''' ----------------------------------------------------------------------------------------------------
  21.        ''' <summary>
  22.        ''' Gets a value indicating whether a debugger in user-mode is attached to the current process.
  23.        ''' </summary>
  24.        ''' ----------------------------------------------------------------------------------------------------
  25.        Public ReadOnly Property IsAttached As Boolean
  26.  
  27. #End Region
  28.  
  29. #Region " Constructors "
  30.  
  31.        ''' ----------------------------------------------------------------------------------------------------
  32.        ''' <summary>
  33.        ''' Prevents a default instance of the <see cref="DebuggerNotifyEventArgs"/> class from being created.
  34.        ''' </summary>
  35.        ''' ----------------------------------------------------------------------------------------------------
  36.        Private Sub New()
  37.        End Sub
  38.  
  39.        ''' ----------------------------------------------------------------------------------------------------
  40.        ''' <summary>
  41.        ''' Initializes a new instance of the <see cref="DebuggerNotifyEventArgs"/> class.
  42.        ''' </summary>
  43.        ''' ----------------------------------------------------------------------------------------------------
  44.        ''' <param name="isAttached">
  45.        ''' A value indicating whether a debugger in user-mode is attached to the current process.
  46.        ''' </param>
  47.        ''' ----------------------------------------------------------------------------------------------------
  48.        Public Sub New(ByVal isAttached As Boolean)
  49.            Me.IsAttached = isAttached
  50.        End Sub
  51.  
  52. #End Region
  53.  
  54.    End Class
  55.  
  56. End Namespace
  57.  
  58. #End Region

PreventDebuggerContext.vb
Código
  1. #Region " Imports "
  2.  
  3. Imports System
  4.  
  5. #End Region
  6.  
  7. #Region " Usage Examples "
  8.  
  9. ' Using preventDebugger As New PreventDebuggerContext()
  10. '     ' Insert your non-debuggable task here...
  11. '     Do While True
  12. '         Thread.Sleep(1000)
  13. '     Loop
  14. ' End Using
  15.  
  16. #End Region
  17.  
  18. #Region " PreventDebuggerContext "
  19.  
  20. Namespace DevCase.Core.Diagnostics.Debug
  21.  
  22.    ''' ----------------------------------------------------------------------------------------------------
  23.    ''' <summary>
  24.    ''' Prevents a debugger in user-mode from being attached to the current process,
  25.    ''' and immediately terminates the current process after writing a message to the Windows Application event log.
  26.    ''' </summary>
  27.    ''' ----------------------------------------------------------------------------------------------------
  28.    ''' <example> This is a code example.
  29.    ''' <code>
  30.    ''' Using preventDebugger As New PreventDebuggerContext()
  31.    '''     ' Insert your non-debuggable task here...
  32.    '''     Do While True
  33.    '''         Thread.Sleep(1000)
  34.    '''     Loop
  35.    ''' End Using
  36.    ''' </code>
  37.    ''' </example>
  38.    ''' ----------------------------------------------------------------------------------------------------
  39.    Public NotInheritable Class PreventDebuggerContext : Implements IDisposable
  40.  
  41. #Region " Private Fields "
  42.  
  43.        ''' ----------------------------------------------------------------------------------------------------
  44.        ''' <summary>
  45.        ''' The <see cref="DevCase.Core.Diagnostics.Debug.DebuggerNotify"/> instance.
  46.        ''' </summary>
  47.        ''' ----------------------------------------------------------------------------------------------------
  48.        Private WithEvents DebuggerNotify As DebuggerNotify
  49.  
  50. #End Region
  51.  
  52. #Region " Constructors "
  53.  
  54.        ''' ----------------------------------------------------------------------------------------------------
  55.        ''' <summary>
  56.        ''' Initializes a new instance of the <see cref="PreventDebuggerContext"/> class.
  57.        ''' </summary>
  58.        ''' ----------------------------------------------------------------------------------------------------
  59.        Public Sub New()
  60.            Me.DebuggerNotify = New DebuggerNotify()
  61.        End Sub
  62.  
  63. #End Region
  64.  
  65. #Region " Event Handlers "
  66.  
  67.        ''' ----------------------------------------------------------------------------------------------------
  68.        ''' <summary>
  69.        ''' Handles the <see cref="DevCase.Core.Diagnostics.Debug.DebuggerNotify.StatusChanged"/> event of the <see cref="PreventDebuggerContext.DebuggerNotify"/> object.
  70.        ''' </summary>
  71.        ''' ----------------------------------------------------------------------------------------------------
  72.        ''' <param name="sender">
  73.        ''' The source of the event.
  74.        ''' </param>
  75.        '''
  76.        ''' <param name="e">
  77.        ''' The <see cref="DebuggerNotifyEventArgs"/> instance containing the event data.
  78.        ''' </param>
  79.        ''' ----------------------------------------------------------------------------------------------------
  80.        Private Sub DebuggerNotify_StatusChanged(ByVal sender As Object, ByVal e As DebuggerNotifyEventArgs) Handles DebuggerNotify.StatusChanged
  81.  
  82.            If (e.IsAttached) Then
  83.                Environment.FailFast("A debugger was attached to the current process.")
  84.            End If
  85.  
  86.        End Sub
  87.  
  88. #End Region
  89.  
  90. #Region " IDisposable Implementation "
  91.  
  92.        ''' ----------------------------------------------------------------------------------------------------
  93.        ''' <summary>
  94.        ''' Flag to detect redundant calls.
  95.        ''' </summary>
  96.        ''' ----------------------------------------------------------------------------------------------------
  97.        Private disposedValue As Boolean
  98.  
  99.        ''' ----------------------------------------------------------------------------------------------------
  100.        ''' <summary>
  101.        ''' Releases all the resources used by this instance.
  102.        ''' </summary>
  103.        ''' ----------------------------------------------------------------------------------------------------
  104.        ''' <param name="disposing">
  105.        ''' <see langword="True"/> to release both managed and unmanaged resources;
  106.        ''' <see langword="False"/> to release only unmanaged resources.
  107.        ''' </param>
  108.        ''' ----------------------------------------------------------------------------------------------------
  109.        Private Sub Dispose(disposing As Boolean)
  110.            If Not (Me.disposedValue) AndAlso (disposing) Then
  111.                Me.DebuggerNotify?.Dispose()
  112.            End If
  113.            Me.disposedValue = True
  114.        End Sub
  115.  
  116.        ''' ----------------------------------------------------------------------------------------------------
  117.        ''' <summary>
  118.        ''' Releases all the resources used by this instance.
  119.        ''' </summary>
  120.        ''' ----------------------------------------------------------------------------------------------------
  121.        Public Sub Dispose() Implements IDisposable.Dispose
  122.            Me.Dispose(True)
  123.        End Sub
  124.  
  125. #End Region
  126.  
  127.    End Class
  128.  
  129. End Namespace
  130.  
  131. #End Region



Modo de empleo de la clase PreventDebuggerContext:
Código
  1. Using preventDebugger As New PreventDebuggerContext()
  2.  
  3.    ' Insert your non-debuggable task here...
  4.    Do While True
  5.        Thread.Sleep(1000)
  6.    Loop
  7.  
  8. End Using

O simplemente creando una nueva instancia que tenga efecto durante todo el tiempo de vida de la aplicación:
Código
  1. Friend Shared ReadOnly PreventDebugger As New PreventDebuggerContext()

Modo de empleo de la clase DebuggerNotify:
Código
  1. Public Class Form1
  2.  
  3.    Private WithEvents DebuggerNotify As DebuggerNotify
  4.  
  5.    Public Sub New()
  6.        MyClass.InitializeComponent()
  7.        Me.DebuggerNotify = New DebuggerNotify()
  8.    End Sub
  9.  
  10.    Private Sub DebuggerNotify_StatusChanged(ByVal sender As Object, ByVal e As DebuggerNotifyEventArgs) Handles DebuggerNotify.StatusChanged
  11.        Dim msg As String = $"Debugger status changed to {NameOf(e.IsAttached)}: {e.IsAttached}"
  12.        Console.WriteLine(msg)
  13.    End Sub
  14.  
  15. End Class

PD: intenta darle créditos a la librería DevCase for .NET Framework si esto lo publicas por ahí...

Saludos.


Título: Re: Funcion calloc() en vb.net?
Publicado por: **Aincrad** en 15 Mayo 2019, 14:31 pm
Gracias. Funciona perfecto.  ;-)