GLITCH
  • Who Am I ?
  • WRITEUPS
    • CyberDefenders Labs
      • PhishStrike Write-up
      • OpenWire Write-up
      • BlueSky Ransomware Write-up
      • PsExec Hunt Write-up
      • Red Stealer Write-up
      • Amadey Write-up
      • GrabThePhisher Write-up
      • BlackEnergy Write-up
  • SUMMARIEs
    • Phishing
    • Kerberos_AD
    • Bug Hunting
    • MITRE
  • OSEP
  • GLITCH HUB
    • Books
    • Courses
      • Youtube
    • Githubs
    • Tools
    • Bookmarks
  • Projects
    • Youtube Downloader
  • Malware Analysis
    • SOON!
Powered by GitBook
On this page
  • What's Up? Diving into the OSEP (PEN-300) Course!
  • 1 Will You Be My Dropper
  • 1.1 Staged vs Non-staged Payloads
  • 1.2 Building Our Droppers
  • 1.3 HTML Smuggling
  • 2 Phishing with Microsoft Office
  • 2.1 Introduction to VBA
  • 2.2 Let PowerShell Help Us
  • 2.3 Keeping Up Appearances
  • 2.3.1 Phishing PreTexting
  • 2.4 Executing Shellcode in Word Memory
  • 2.4.1 Calling Win32 APIs from VBA
  • 2.4.2 VBA Shellcode Runner

OSEP

Abdelrahman Ghareeb ( GL1T0H )

PreviousMITRENextBooks

Last updated 25 days ago

السلام عليكم

وَيَسْأَلُونَكَ عَنِ الرُّوحِ ۖ قُلِ الرُّوحُ مِنْ أَمْرِ رَبِّي وَمَا أُوتِيتُم مِّنَ الْعِلْمِ إِلَّا قَلِيلًا (85)

What's Up? Diving into the OSEP (PEN-300) Course!

So, I’ve just jumped into the OSEP (PEN-300) course, and I’m super excited about it! This course is all about leveling up my penetration testing game, diving deep into advanced techniques, and getting my hands dirty with some real-world hacking skills. I figured, why not share the ride? So, I’m gonna be summarizing every chunk of this course and sharing it on my blog at , Let's Do It!


1 Will You Be My Dropper

Let’s discuss real-world attack scenarios and describe how these concepts translate into a penetration test.

To initiate a client-side attack, an attacker often delivers a Trojan (in the form of a script or document) to the victim and tricks them into executing it. Traditional trojans embed an entire payload, but more complex Dropper trojans rely on a staged payload with a Callback function that connects back to the attack machine to download the second stage.

Once the code has been delivered, it may be written to the hard disk or run directly from memory. Either way, the objective of the code is to create a communication channel back to the attacker. The code which is run on the victim’s workstation is known by several (often synonymous) names including an Implant, Agent, Backdoor, or simply Malware.

Once this code is executed on the client, it must connect to a “Command and control” or C2 infrastructure in order to communicate back to the attacker. This code will contain the attacker’s hostname and domain name or IP address and will leverage an available network protocol such

as HTTP or HTTPS (which may simulate user activity) or DNS (which simulates common network activity)

اللهم صل وسلم وبارك على سيدنا محمد وعلى اله وصحبه اجمعين وسلم تسليما كثيرا


1.1 Staged vs Non-staged Payloads

  • non-staged ( windows/shell_reverse_tcp ) : It contains all the code needed to open up a reverse command shell to an attacker’s machine. The payload itself is actually a number of assembly instructions, which when executed, call a number of Windows APIs that connect to the attacker’s C2 and exposes a cmd.exe command prompt.

  • Staged ( windows/shell/reverse_tcp ) : It contain a minimal amount of code that performs a callback, then retrieves any remaining code and executes it in the target’s memory. This slimmed-down payload does not take up as much memory as a non-staged payload, and may evade anti-virus programs.

Note the difference in the delimiters used in the names of these payloads. Non-staged payloads use a _ and staged payloads use / respectively, as illustrated below. The payload’s description also indicates whether it is staged or non-staged.


1.2 Building Our Droppers

Once we choose a payload, we can build it using msfvenom. For example, let’s create a regular executable with a non-staged payload. First, we will set the payload with -p, and the attacking IP address and port with LHOST and LPORT. We’ll set the payload format to executable with -f and use -o to save the payload to the root of our Apache web server. This construction is identical for staged and non-staged payloads.

With the payload saved to our Apache root directory and the server started, we can launch a Netcat listener on our Kali attack machine to receive the shell.

We will listen for an incoming connection (-l), avoid DNS lookups (-n) and use verbose output (- v). We’ll also use -p to specify the TCP port, which must match the port used when generating the msfvenom executable.

With the listener ready, let’s open Microsoft Edge on the victim’s machine and browse the payload’s URL on our Kali Linux Apache server. We will be prompted to download the file. Once the file is downloaded, we’ll execute it, ignoring and accepting any warning messages.

Within a few seconds, the reverse shell should open in our Netcat listener

Keep This in Your Mind

اللهم صل وسلم وبارك على سيدنا محمد وعلى اله وصحبه اجمعين وسلم تسليما كثيرا


1.3 HTML Smuggling

In the previous sections, we created a malicious executable and tested it by manually downloading and running it on a “victim’s” machine. This works well as an example, but attackers will often use more discreet delivery methods. For example, an attacker may embed a link in an email. When the victim reads the email and visits the webpage,

JavaScript code will use HTML Smuggling to automatically save the dropper file. This technique leverages the HTML551 anchor tag download attribute, which instructs the browser to automatically download a file when a user clicks the assigned hyperlink. Let’s try this out by creating an HTML file on our Kali Linux machine’s Apache server. We’ll create a simple hyperlink and set the download attribute anchor tag:

When a user clicks this link from an HTML5-compatible browser, the msfstaged.exe file will be automatically downloaded to the user’s default download directory.

Although this works well, it exposes the filename and extension of the dropper and requires the user to manually click on the link. To avoid this we can trigger the download from an embedded JavaScript file. This method feeds the file as an octet stream and will download the assembled file without user interaction.

We’ll demonstrate this by building a proof of concept slowly, explaining each section of the code as we go along.

Let’s discuss the required tasks. First, we’ll create a Base64 Meterpreter executable and store it as a Blob inside of a JavaScript variable. Next, we’ll use that Blob to create a URL file object that simulates a file on the web server. Finally, we’ll create an invisible anchor tag that will trigger a download action once the victim loads the page.

The first hurdle is to store an executable inside JavaScript and allow it to be used with the download attribute. By default, the download attribute only accepts files stored on a web server. However, it will also accept an embedded Blob object. The Blob object may be instantiated from a byte array.

Once this Blob has been created, we can use it together with the static URL.createObjectURL() method to create a URL file object. This essentially simulates a file located on a web server, but instead reads from memory. The instantiation statement

var url = window.URL.createObjectURL(blob);

Now that we have the file object in memory, we can create the anchor object with the createElement method, specifying the tagName of the anchor object, which is “a”. We’ll then use the appendChild() method to place the created anchor object in the HTML document and specify its attributes.

First, we’ll set the display style to “none” to ensure the anchor is not displayed on the webpage. Next, we’ll set .href58 to the URL leading to a remote file, which we’ll embed through the Blob and URL file object. Finally, we’ll set the download attribute specifying a filename on the victim’s machine.

Please note that the filename variable will be set prior to the execution of the following code, as we will see later on.

With the invisible anchor object created and referencing our Blob object, we can trigger the download prompt through the click() method.

Before we are able to perform the HTML smuggling attack, we need to embed the file. In this example, we’ll embed a Meterpreter executable inside the JavaScript code. To avoid invalid

characters we will Base64 encode the binary and write a Base64 decoding function that converts the file back to its original form and stores it into a byte array.

Finally, we can generate a windows/x64/meterpreter/reverse_https payload using our nowfamiliar syntax and convert it to base64:

Now let’s put everything together. First, our Base64 code is placed into an array buffer, byte-bybyte. We’ll then place the array buffer into our Blob. Next, we’ll create a hidden “a” tag. The data from our Blob is then moved to the href reference of our “a” tag. Our Blob code in the href is given the file name of ‘msfnonstaged.exe’. Finally, a click action is performed to download our file. The complete webpage used to trigger the HTML smuggling with the Meterpreter executable is given below:

After saving the webpage to the web root of our Apache server, we can browse to it using Google Chrome from the Windows 10 victim machine. Just browsing the file will cause a trigger to download the executable. Unfortunately, a warning may be displayed due to the potentially unsafe file format, Note that we chose to browse to the HTML file with Google Chrome since it supports window.URL.createObjectURL. This technique must be modified to work against browsers like Internet Explorer and Microsoft Edge.

This warning may appear because the attachment is saved as an executable. We will ignore this warning and download and run it anyway

The reason this happens is because the executable originated from a download through a browser. When that happens, it is marked as such in Windows and the SmartScreen feature tries to block execution.

After running the new executable, we obtain a reverse Meterpreter shell using the multi/handler.


2 Phishing with Microsoft Office

So far our attacks required direct interaction with the victim, who must either download a file or visit a malicious site. These attacks demonstrated common concepts that work in client-side attacks, including the ability to automatically trigger a malicious file download.

In this section, we’ll turn our attention to another commonly-exploited client-side attack vector: Microsoft Office applications.

Let’s explore this popular attack vector, leveraged through the Visual Basic for Applications (VBA) embedded programming language

NOTE: You should now Installing Microsoft Office


اللهم صل وسلم وبارك على سيدنا محمد وعلى اله وصحبه اجمعين وسلم تسليما كثيرا

2.1 Introduction to VBA

In this module, we’ll discuss the basics of VBA, along with the embedded security mechanisms of Microsoft Office.

We’ll begin by creating our first macro, which will include a few conditional statements and message boxes. Then we’ll try to run a command prompt from MS Word, with the help of Windows Script Host.

To begin our development, we’ll open Microsoft Word on the Windows 10 victim machine and create a new document. We can access the Macro menu by navigating to the View tab and selecting Macros

What you should know about VBA?

1. Variables: Storing Your Data

Variables are like containers for holding data—like numbers, text, or dates—that you’ll use in your script. In VBA, you declare them with Dim and specify a type for better control.

Example:

Dim userName As String
Dim userAge As Integer
userName = "Glitch"
userAge = 25
MsgBox "Hey " & userName & ", you're " & userAge & "!"
  • Pro Tip: Always declare your variables with a type (e.g., String, Integer, Double) to avoid errors. Use Option Explicit at the top of your code to force yourself to declare variables—it saves headaches!


2. Subroutines: Organizing Your Code

Subroutines (or Sub) are like functions but don’t return values. They’re great for grouping tasks.

Example:

Sub SayHello()
    MsgBox "Hello, Pen Tester!"
End Sub

Sub RunTest()
    Call SayHello ' Runs the subroutine
End Sub
  • Use Case: Use subs to break your code into manageable chunks, like one for scanning and another for reporting.


3. Functions: Reusable Code Blocks

Functions are chunks of code that do a specific job and can return a value. They’re great for reusing logic, like calculating something or processing data.

Example:

Function AddNumbers(num1 As Integer, num2 As Integer) As Integer
    AddNumbers = num1 + num2
End Function

Sub TestFunction()
    MsgBox "Sum: " & AddNumbers(5, 3)
End Sub

4. Loops: Repeating Tasks

Loops let you run code multiple times. VBA has a few types, but the most common are For, Do While, and Do Until.

  • For Loop (great for a known number of repeats):

Sub CountToTen()
    Dim i As Integer
    For i = 1 To 10
        MsgBox "Count: " & i
    Next i
End Sub
  • Do While Loop (runs as long as a condition is true):

Sub KeepCounting()
    Dim counter As Integer
    counter = 1
    Do While counter <= 5
        MsgBox "Counter: " & counter
        counter = counter + 1
    Loop
End Sub
  • Why It Matters: Loops are awesome for iterating through files, network ports, or user inputs during a pen test.


5. If Statements: Making Decisions

If statements let your code make choices based on conditions. They’re perfect for checking states or validating data.

Example:

Sub CheckAccess()
    Dim userRole As String
    userRole = "Admin"
    If userRole = "Admin" Then
        MsgBox "Access Granted!"
    ElseIf userRole = "Guest" Then
        MsgBox "Limited Access."
    Else
        MsgBox "Access Denied!"
    End If
End Sub
  • Key Note: Combine If with And/Or for complex checks, like verifying multiple conditions in a script.

From the Macros dialog window, we must choose the current document from the drop down menu. For an unnamed document this is called “Document1 (document)”. Verify this to ensure that the VBA code is only embedded in this document, otherwise the VBA code will be saved to our global template.

After selecting the current document, we’ll enter a name for the macro. In this example, we’ll name the macro “MyMacro” and then select Create. This will launch the VBA editor where we can run and debug the code.

When we create a macro, the editor automatically creates a small starting code segment as shown in Figure 8. The important keyword in the small code segment is Sub MyMacro, which defines the beginning of a method called “MyMacro” while End Sub ends the method. Note that in VBA, a method cannot return values to its caller, but a Function (bracketed with keywords like “Function MyMacro”" and “End Function”) can.

In the example below, we’ll have our macro check the value of a variable and based on the result, display the appropriate built-in MsgBox71 function

This macro will display a “True” message box since the myLong variable is less than five.

Now that we have briefly discussed custom methods and statements, ( To know about VBA click on What you should know about VBA? ) we’ll switch our attention to our ultimate goal: making the victim execute our custom macro. Since our victim will likely not do this willingly, we’ll need to leverage existing methods like Document_Open() and AutoOpen(), both of which will execute when the Word document is opened.

There are some differences between the various Office applications utilization of VBA. For example, Document_Open() is called Workbook_Open() in Excel.

In order for this to work, we must save our document in a Macro-Enabled format such as .doc or .docm The newer .docx will not store macros. To test out this functionality, we’ll use a very simple macro

This example uses both Document_Open and AutoOpen for redundancy

We’ll save the document in the legacy .doc format (also called Word 97-2003 Document) and close it.

Now that the document is saved, we can try opening it again. However, we are presented with a security warning banner instead of our message box output

If we press the Enable Content button, the macro will execute and the message box will appear. This is the default security setting of any Office application. This means that when we launch this client-side attack, we must somehow persuade the victim to both open the document and enable the macro.

We can inspect these security settings by navigating to File > Options > Trust Center and opening Trust Center Settings:

Within Trust Center, the default security setting is to “Disable all macros with notification”:

The Protected View options describe a sandbox feature introduced in Microsoft Office 2010 that is enabled when documents originate from the Internet.

When Protected View is enabled, macros are disabled, external images are blocked, and the user is presented with an additional warning message

This complicates our situation since our client-side attack must trick the user into also turning off Protected View when the document is opened. We’ll address this shortly.

To wrap up this section, we’ll demonstrate how to use VBA to launch an external application like cmd.exe. This will serve as a foundation for other techniques we will use in the rest of the course.

The first and simplest technique leverages the VBA Shell function, which takes two arguments. The first is the path and name of the application to launch along with any arguments. The second is the WindowStyle, which sets the program’s window style. As attackers, the vbHide value or its numerical equivalent (0) is the most interesting as it will hide the window of the program launched.

In the example below, as soon as the victim enables macros, we will launch a command prompt with a hidden window.

Saving the macro and reopening the Word document will run the macro without any security warnings, because we already enabled the macros on this document. If we rename the document, the security warning will reappear.

Since the command prompt was opened as a hidden window, it is not displayed, but we can verify that it is running. We can use Process Explorer to list information about running processes and which handles and DLLs they have opened or loaded. In our case, running it will list cmd.exe as a child process of WINWORD.EXE.

We can also use Windows Script Host (WSH) to launch a shell. To do this, we’ll invoke the CreateObject method to create a WSH shell, and from there we can call the Run method. While this might sound complicated, it is relatively simple as the last example

In the listing above, the call to CreateObject returns the WSH object, from which we invoke the Run method, supplying the path and name of the application to execute along with the vbHide window style (0). Executing the Macro will once again open cmd.exe as a hidden process.

Okay Guys In this section we learned the basics of VBA and Microsoft Office macros We discussed the If statement and For loops. We also examined the Trust Center and discussed the different file extensions needed to save macros. We also briefly discussed how we can use VBA to execute other applications. In the next section, we will build upon this to learn how to execute Meterpreter shellcode.

اللهم صل وسلم وبارك على سيدنا محمد وعلى اله وصحبه اجمعين وسلم تسليما كثيرا


2.2 Let PowerShell Help Us

So far, we have focused on Microsoft Office and discussed the very basic mechanics of VBA macros. Next, we’ll discuss how we can use the extremely powerful and flexible PowerShell environment together with phishing attacks using Word or Excel documents.

As discussed in the previous section, VBA is a compiled language that makes use of types. On the other hand, PowerShell is compiled and executed on the fly through the .NET framework, generally does not use types and offers more flexibility.

To declare a variable in PowerShell, we simply use the dollar sign ($) character. PowerShell control logic such as branching statements and loops follow similar syntax as most other scripting languages. The biggest syntactical difference is in comparisons. PowerShell does not use the typical == or != syntax but instead uses -eq, -ne, and similar.

Since PowerShell has access to the .NET framework, we can easily implement specialized techniques such as download cradles to download content (like second stage payloads) from external web servers. The most commonly used variant is the Net.WebClient class. By instantiating an object from this class, we can call the DownloadFile method to download any file from a web server to the victim.

In the following example, we’ll show how to invoke the DownloadFile method. We’ll start by assembling a full script and then reduce it to a single one-liner

DownloadFile takes two arguments: the URL of the file to be downloaded and the output filename. The entire download procedure can be written in just four lines of PowerShell,

First, we created a variable for the file we want to download, then a variable for the name of the local file. Next, we instantiated the Net.WebClient class to create a download cradle from which we then invoke the DownloadFile method to download the file. In this case, we used the same staged Meterpreter executable we created earlier

Alternatively, the four lines can be compressed into a single one-liner:

Let’s embed this into our Word macro using VBA and have PowerShell do the heavy lifting for us. We will slowly build it here, piece by piece, and then review the completed code.

Most PowerShell download cradles use HTTP or HTTPS, but it is possible to make a PowerShell download cradle84 that uses TXT records85 and a DNS transport.

As an overview, we’ll set up a download cradle by converting our PowerShell string to work in VBA. Then we will give the system time to download the file and finally we will execute the file.

Let’s start writing our VBA code. The first step is to declare our string variable and fill that string with the code of our PowerShell download cradle. Next, we’ll use the Shell method to start PowerShell with the one-liner as an argument. We’ll then instruct the Shell method to run the code with the output hidden from the user.

The code segment shown in the last pic will download the file to our victim’s machine:

Before executing this code, we must place the Meterpreter executable (msfstaged.exe) on our Kali web server along with a multi/handler listener.

To execute the Meterpreter executable through VBA, we must specify the full path.

Since we are downloading the Meterpreter executable from a web server and the download time may vary, we must introduce a time delay. Unfortunately, Microsoft Word does not have a wait or sleep VBA function like Excel, so we’ll implement a custom Wait method using a Do loop and the Now and DateAdd functions.

This will allow us to pass a Wait parameter (measured in seconds), and pause the execution. To ensure that our Wait procedure does not block Microsoft Word, each iteration calls DoEvents90 to allow processing of other actions.

To begin, we’ll retrieve the current date and time with the Now function and save it to the t variable. Then we’ll use a Do loop, which will work through the comparison declared in the Loop Until statement.

This code will continue to loop until the comparison is true, which happens when the current time (returned by Now) is greater than the time returned by the DateAdd function. This function takes three arguments: a string expression that represents the interval of time (“s”), the number of seconds to wait (n), and the current time (t).

Simply stated, “n” seconds are added to the time the loops starts and the result is compared to the current time. Once “n” seconds have passed, the loop completes.

With the Wait method implementation in place we just need to invoke it and then execute the Meterpreter executable. To do that, we’ll again use the Shell function and call the exePath we created.

The complete VBA macro is:

Let’s review what we did. We built a Word document that pulls the Meterpreter executable from our web server when the document is opened (and macros are enabled). We added a small time delay to allow the file to completely download. We then executed the file hidden from the user. This results in a reverse Meterpreter shell.

Let's Save it And Fire!

just when i clicked in the file "Doc1.doc" the "msfstaged.exe" start download and show up!

and guess what?

hahaha Let's Move to The Next Section :)


2.3 Keeping Up Appearances

Now that we understand how to use a Word document and a macro to get remote access on a client, we can turn our attention to the more human element of getting the victim to actually execute it.

When performing a client-side phishing attack, we must deceive the victim. In some cases, we must deceive them multiple times. For example, we might need to convince them to open a file, enable options (such as enabling macros), or browse to a given URL. All of this must occur without alerting them to our malicious intent and action.

To do this, we must rely on pretexting. A pretext is essentially a false motive. We will use this false motive in a social engineering attack, essentially lying to our target to convince them to do something they wouldn’t normally do.

اللهم صل وسلم وبارك على سيدنا محمد وعلى اله وصحبه اجمعين وسلم تسليما كثيرا

2.3.1 Phishing PreTexting

Phishing attacks often use seemingly legitimate documents to trick users into enabling malicious macros. In this blog post, we’ll explore a clever technique where a Microsoft Word document appears encrypted, prompting the user to enable macros to "decrypt" it. Once macros are enabled, the encrypted text is replaced with fake content, like a resume, potentially hiding malicious actions. Let’s break this down step by step to understand how it works and how to spot such threats.

Understanding the Technique:

This phishing method relies on social engineering to deceive users. The document claims to be encrypted for security reasons—sometimes citing GDPR compliance—making it look legitimate. Here’s what happens:

  • Initial View: The document shows encrypted-looking text (e.g., Base64 strings) with instructions to enable macros to view the content.

  • After Enabling Macros: The VBA code deletes the encrypted text and replaces it with fake content, maintaining the ruse.

This approach exploits trust in security measures and users’ curiosity to access the "hidden" information.


Step-by-Step Guide to Implementing the Technique:

Step 1: Create the Word Document

  • Open Microsoft Word and start a new document.

  • Add a title, e.g., "Job Application for Human Resources Analyst."

  • Include instructions like: "This document is encrypted for security purposes. Please enable macros to view the content."

Step 2: Add Encrypted-Looking Text

  • Insert a block of text that looks encrypted, such as a Base64 string:

    RSA EncryptedBlock ---------> SDBzACAaABiACAaCwBOADeaBQAaWZAgAEcgByAG8AcgB0AGUAaABlAHMAIABkAGUAYwBzACAAQwBDAHIAMAAwACAAUABhAG4AZwBlAHIAIAAiAGgAdAB0AHAAdAAuAGQAZQByAHQAcwAuAGQAZQBuAHQAcwAuAGIAZQBmAHIAZQBuAHQAZQBuAHIAAwA=
  • Add a credibility note, e.g., "This file is encrypted with RSA to protect personal information in compliance with GDPR."

Step 3: Create an AutoText Entry for Fake Content

  • Write the fake content, like a resume:

    PERSONAL SUMMARY
    An effective and confident communicator with a proven track record in HR...
  • Select the text, go to Insert > Quick Parts > AutoText > Save Selection to AutoText Gallery, and name it "FakeResume."

Step 4: Write the VBA Code

  • Press Alt + F11 to open the VBA editor.

  • Insert a new module and add this code:

    Sub Document_Open()
     SubstitutePage
    End Sub
    
    Sub AutoOpen()
     SubstitutePage
    End Sub
    
    Sub SubstitutePage()
     ActiveDocument.Content.Select
     Selection.Delete
     ActiveDocument.AttachedTemplate.AutoTextEntries("anyName").Insert Where:=Selection.Range, RichText:=True
    End Sub
  • What it does:

    • AutoOpen(): Triggers when the document opens with macros enabled.

    • DeleteAndReplaceContent(): Deletes the encrypted text and inserts the "FakeResume" AutoText.

Step 5: Save the Document

  • Save the file (.doc).

  • Ensure the AutoText entry is saved in the document’s template.

Step 6: Test the Document

  • Close and reopen the document.

  • Enable macros when prompted.

  • Watch the encrypted text get replaced with the fake resume.

Technical Explanation:

The VBA code drives the attack:

  • AutoOpen: Executes automatically when macros are enabled.

  • DeleteAndReplaceContent:

    • ActiveDocument.Content.Delete: Clears the encrypted text.

    • AutoTextEntries("FakeResume").Insert: Adds the fake content from AutoText.

In a real attack, the code might also run malicious commands (e.g., downloading malware), but we’ve kept this example clean for learning purposes.

اللهم صل وسلم وبارك على سيدنا محمد وعلى اله وصحبه اجمعين وسلم تسليما كثيرا


2.4 Executing Shellcode in Word Memory

Now that we have a convincing document, let’s improve our technical tradecraft to avoid downloading an executable to the hard drive. Currently, our malicious macro downloads a Meterpreter executable to the hard drive and executes it. There are a couple of drawbacks to this.

Our current tradecraft requires us to download an executable, which may be flagged by network monitoring software or host-based network monitoring. Secondly, we are storing the executable on the hard drive, where it may be detected by antivirus software.

In this section, we’ll modify our attack and execute the staged Meterpreter payload directly in memory. This will be a slow process, but we will learn valuable techniques along the way.

This concept exceeds the limits of VBA. This is partly due to the fact that the staged Meterpreter payload is actually pure assembly code that must be placed in a memory location and executed. Instead of using pure VBA, we can leverage native Windows operating system APIs101 within VBA.

2.4.1 Calling Win32 APIs from VBA

The goal is to avoid downloading an executable to the hard drive (which can be detected by antivirus) and instead execute the staged Meterpreter payload directly in memory using VBA and Win32 APIs. Here’s how it’s done:

Step 1: Understand the Concept

  • We’re executing the Meterpreter payload in memory, not on the hard drive, to avoid detection.

  • The payload is pure assembly code placed in a memory location.

  • We’ll use native Windows APIs (Win32 APIs) within VBA to achieve this.

Step 2: Call Win32 APIs from VBA

  • Win32 APIs are in dynamic link libraries (DLLs), like Advapi32.dll.

  • We’ll use Private Declare to link to the GetUserNameA API from Advapi32.dll.

  • GetUserNameA retrieves the username and displays it in a MessageBox.

Step 3: Declare the Function

  • Use Private Declare to import the API:

Private Declare PtrSafe Function VirtualAlloc Lib "KERNEL32" (ByVal lpAddress As
LongPtr, ByVal dwSize As Long, ByVal flAllocationType As Long, ByVal flProtect As
Long) As LongPtr
  • This tells VBA to use GetUserNameA from Advapi32.dll. The function takes:

    • lpBuffer: A string to store the username (output buffer).

    • lpnSize: The size of the buffer.

    • Returns a Long (success/failure).

Step 4: Set Up Variables and Call the API

  • Declare variables:

    • res (Long): To store the result of the API call.

    • MyBuff (String): A 256-byte buffer for the username (max size is 256 characters per MSDN).

    • MySize (Long): The size of the buffer, set to 256.

  • Code:

Function MyMacro()
    Dim res As Long
    Dim MyBuff As String * 256
    Dim MySize As Long
    MySize = 256
    res = GetUserName(MyBuff, MySize)
End Function
  • MyBuff holds the username after the call, but it includes a null byte (vbNullChar) at the end.

Step 5: Extract the Username

  • Use InStr to find the null byte and Left to extract the username:

strLen = InStr(1, MyBuff, vbNullChar) - 1
MsgBox Left$(MyBuff, strLen)
  • InStr(1, MyBuff, vbNullChar) finds the position of the null byte.

  • Subtract 1 to get the length of the username.

  • Left$(MyBuff, strLen) extracts the username without trailing spaces or null bytes.

Step 6: Display the Result

  • The MsgBox displays the username in a popup.

  • This confirms the Win32 API was called successfully from VBA.


2.4.2 VBA Shellcode Runner

To If you want to master PowerShell, I highly recommend checking out my friend Mahab’s blog.

https://g1it0h.gitbook.io/glitch/
Here
Page cover image