دسته: هسته اصلی سیستم‌عامل

  • Critical SAP Vulnerability & How to Protect Your Enterprise

    Critical SAP Vulnerability & How to Protect Your Enterprise


    Executive Summary

    CVE-2025-31324 is a critical remote code execution (RCE) vulnerability affecting the SAP NetWeaver Development Server, one of the core components used in enterprise environments for application development and integration. The vulnerability stems from improper validation of uploaded model files via the exposed metadatauploader endpoint. By exploiting this weakness, attackers can upload malicious files—typically crafted as application/octet-stream ZIP/JAR payloads—that the server mistakenly processes as trusted content.

    The risk is significant because SAP systems form the backbone of global business operations, handling finance, supply chain, human resources, and customer data. Successful exploitation enables adversaries to gain unauthenticated remote code execution, which can lead to:

    • Persistent foothold in enterprise networks
    • Theft of sensitive business data and intellectual property
    • Disruption of critical SAP-driven processes
    • Lateral movement toward other high-value assets within the organization

    Given the scale at which SAP is deployed across Fortune 500 companies and government institutions, CVE-2025-31324 poses a high-impact threat that defenders must address with urgency and precision.

    Vulnerability Overview

    • CVE ID: CVE-2025-31324
    • Type: Unauthenticated Arbitrary File Upload → Remote Code Execution (RCE)
    • CVSS Score: 8 (Critical) (based on vector: AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H)
    • Criticality: High – full compromise of SAP systems possible
    • Affected Products: SAP NetWeaver Application Server (Development Server module), versions prior to September 2025 patchset
    • Exploitation: Active since March 2025, widely weaponized after August 2025 exploit release
    • Business Impact: Persistent attacker access, data theft, lateral movement, and potential disruption of mission-critical ERP operations

    Threat Landscape & Exploitation

    Active exploitation began in March–April 2025, with attackers uploading web shells like helper.jsp, cache.jsp, or randomly-named .jsp files to SAP servers . On Linux systems, a stealthy backdoor named Auto-Color was deployed, enabling reverse shells, file manipulation, and evasive operation .

    In August 2025, the exploit script was publicly posted by “Scattered LAPSUS$ Hunters – ShinyHunters,” triggering a new wave of widespread automatic attacks . The script includes identifiable branding and taunts, a valuable signals for defenders.

    Technical Details

    Root Cause:
    The ‘metadatauploader’ endpoint fails to sanitize uploaded binary model files. It trusts client-supplied ‘Content-Type: application/octet-stream’ payloads and parses them as valid SAP model metadata.

    Trigger:

    Observed Payloads: Begin with PK (ZIP header), embedding .properties + compiled bytecode that triggers code execution when parsed.

    Impact: Arbitrary code execution within SAP NetWeaver server context, often leading to full system compromise.

    Exploitation in the Wild

    March–April 2025: First observed exploitation with JSP web shells.

    August 2025: Public exploit tool released by Scattered LAPSUS$ Hunters – ShinyHunters, fueling mass automated attacks.

    Reported Havoc: Over 1,200 exposed SAP NetWeaver Dev servers scanned on Shodan showed exploit attempts. Multiple confirmed intrusions across manufacturing, retail, and telecom sectors. Incidents of data exfiltration and reverse shell deployment confirmed in at least 8 large enterprises.

    Exploitation

    Attack Chain:
    1. Prepare Payload – Attacker builds a ZIP/JAR containing malicious model definitions or classes.
    2. Deliver Payload – Send crafted HTTP POST to /metadatauploader with application/octet-stream.
    3. Upload Accepted – Server writes/loads the malicious file without validation.
    4. Execution – Code is executed when the model is processed by NetWeaver.

    Indicators in PCAP:
    – POST /developmentserver/metadatauploader requests
    – Content-Type: application/octet-stream with PK-prefixed binary content

    Protection

    – Patch: Apply SAP September 2025 security updates immediately.
    – IPS/IDS Detection:
    • Match on POST requests to /metadatauploader containing CONTENTTYPE=MODEL.
    • Detect binary payloads beginning with PK in HTTP body.
    – EDR/XDR: Monitor SAP process spawning unexpected child processes (cmd.exe, powershell, etc).
    – Best Practice: Restrict development server exposure to trusted networks only.

    Indicators of Compromise (IoCs)

    Artifact Details
    1f72bd2643995fab4ecf7150b6367fa1b3fab17afd2abed30a98f075e4913087 Helper.jsp webshell
    794cb0a92f51e1387a6b316b8b5ff83d33a51ecf9bf7cc8e88a619ecb64f1dcf Cache.jsp webshell
    0a866f60537e9decc2d32cbdc7e4dcef9c5929b84f1b26b776d9c2a307c7e36e rrr141.jsp webshell
    4d4f6ea7ebdc0fbf237a7e385885d51434fd2e115d6ea62baa218073729f5249 rrxx1.jsp webshell

     

    Network:
    – URI: /developmentserver/metadatauploader?CONTENTTYPE=MODEL&CLIENT=1
    – Headers: Content-Type: application/octet-stream
    – Binary body beginning with PK

    Files:
    – Unexpected ZIP/JAR in SAP model directories
    – Modified .properties files in upload paths
    Processes:
    – SAP NetWeaver spawning system binaries

    MITRE ATT&CK Mapping

    – T1190 – Exploit Public-Facing Application
    – T1059 – Command Execution
    – T1105 – Ingress Tool Transfer
    – T1071.001 – Application Layer Protocol: Web Protocols

    Patch Verification

    – Confirm SAP NetWeaver patched to September 2025 release.
    – Test with crafted metadatauploader request – patched servers reject binary payloads.

    Conclusion

    CVE-2025-31324 highlights the risks of insecure upload endpoints in enterprise middleware. A single unvalidated file upload can lead to complete SAP system compromise. Given SAP’s role in core business operations, this vulnerability should be treated as high-priority with immediate patching and network monitoring for exploit attempts.

    References

    – SAP Security Advisory (September 2025) – CVE-2025-31324
    – NVD – https://nvd.nist.gov/vuln/detail/CVE-2025-31324
    – MITRE ATT&CK Framework – https://attack.mitre.org/techniques/T1190/

     

    Quick Heal Protection

    All Quick Heal customers are protected from this vulnerability by following signatures:

    • HTTP/CVE-2025-31324!VS.49935
    • HTTP/CVE-2025-31324!SP.49639

     

    Authors:
    Satyarth Prakash
    Vineet Sarote
    Adrip Mukherjee



    Source link

  • Correlation – explained with Python – Useful code


    When you plot two variables, you see data dots scattered across the plane. Their overall tilt and shape tell you how the variables move together. Correlation turns that visual impression into a single number you can report and compare.

    What correlation measures

    Correlation summarises the direction and strength of association between two numeric variables on a scale from −1 to +1.

    • Sign shows direction
      • positive – larger x tends to come with larger y
      • negative – larger x tends to come with smaller y
    • Magnitude shows strength
      • near 0 – weak association
      • near 1 in size – strong association

    Correlation does not prove causation.

    Two methods to measure correlation

    Pearson correlation – distance based

    Pearson asks: how straight is the tilt of the data dots? It uses actual distances from a straight line, so it is excellent for line-like patterns and sensitive to outliers. Use when:

    • you expect a roughly straight relationship
    • units and distances matter
    • residuals look symmetric around a line

    Spearman correlation – rank based

    Spearman converts each variable to ranks (1st, 2nd, 3rd, …) and then computes Pearson on those ranks. It measures monotonic association: do higher x values tend to come with higher y values overall, even if the shape is curved.

    Ranks ignore distances and care only about order, which gives two benefits:

    • robust to outliers and weird units
    • invariant to any monotonic transform (log, sqrt, min-max), since order does not change

    Use when:

    • you expect a consistent up or down trend that may be curved
    • the data are ordinal or have many ties
    • outliers are a concern

    r and p in plain language

    • r is the correlation coefficient. It is your effect size on the −1 to +1 scale.
    • p answers: if there were truly no association, how often would we see an r at least this large in magnitude just by random chance.

    Small p flags statistical signal. It is not a measure of importance. Usually findings, where p is bigger than .05 should be ignored.

    When Pearson and Spearman disagree?

    • Curved but monotonic (for example price vs horsepower with diminishing returns)
      Spearman stays high because order increases consistently. Pearson is smaller because a straight line underfits the curve.

    • Outliers (for example a 10-year-old exotic priced very high)
      Pearson can jump because distances change a lot. Spearman changes less because rank order barely changes.

    https://www.youtube.com/watch?v=IdffxjPdNJY

    Jupyter Notebook in GitHub with code from the video above.

    Enjoy it! 🙂



    Source link

  • NoisyBear Targets Kazakhstan Oil & Gas

    NoisyBear Targets Kazakhstan Oil & Gas


    Contents

    • Introduction
    • Key Targets
      • Industries Affected.
      • Geographical Focus.
    • Infection Chain.
    • Initial Findings
      • Looking into the malicious email.
      • Looking into the decoy-document.
    • Technical Analysis
      • Stage 0 – Malicious ZIP & LNK files.
      • Stage 1 – Malicious BATCH scripts.
      • Stage 2 – Malicious DOWNSHELL loaders.
      • Stage 3 – Malicious DLL implant.
    • Infrastructure and Hunting.
    • Attribution
    • Conclusion
    • Seqrite Protection.
    • IOCs
    • MITRE ATT&CK.

    Authors: Subhajeet Singha & Sathwik Ram Prakki

    Introduction

    Seqrite Labs APT-Team has been tracking and uncovered a supposedly new threat group since April 2025, that we track by the name Noisy Bear as Noisy Bear. This threat group has targeted entities in Central Asia, such as targeting the Oil and Gas or energy sector of Kazakhstan. The campaign is targeted towards employees of KazMunaiGas or KMG where the threat entity delivered a fake document related to KMG IT department, mimicking official internal communication and leveraging themes such as policy updates, internal certification procedures, and salary adjustments.

    In this blog, we will explore the in-depth technical details of the campaign, we encountered during our analysis. We will examine the various stages of this campaign, where infection starts with a phishing email having a ZIP attachment, which contains a malicious LNK downloader along with a decoy, which further downloads a malicious BATCH script, leading to PowerShell loaders, which we dubbed as DOWNSHELL reflectively loading a malicious DLL implant. We will also look into the infrastructure covering the entire campaign.

    Key Targets

    Industries Affected.

    • Energy Sector [Oil and Gas]

    Geographical Focus.

    Infection Chain

    Initial Findings

    Initially, we have been tracking this threat actor since April 2025, and we observed that this threat entity launched a campaign against KazMunaiGas employees in May 2025 using a spear-phishing-oriented method. A compromised business email was used to deliver a malicious ZIP file, which contained a decoy along with a malicious initial infection-based shortcut (.LNK) file known as График зарплат.lnk, which can be translated to Salary Schedule.lnk. The sample initially surfaced on Virus Total in the first half of May 2025.

    Now, let us look into the malicious email and decoy file.

    Looking into the malicious email.

    Initially, looking into the email file’s sender, we found that the threat actor used a compromised business email of an individual working in Finance Department of KazMunaiGas, using the email and an urgent prioritized subject URGENT! Review the updated salary schedule, they emailed it to the employees of KMG.

    Later, upon looking at the contents of the email, it became clear that the message was mostly crafted to look like an internal HR communication related to salary-oriented discussion or decision. The message basically says about reviewing an updated information about lot of things such as work schedules, salaries and incentives related policies and decisions. The TA also instructs the targets of KMG to check for a file known as График.zip translated to Schedule.zip and then to open a file known as График зарплат which translates to Salary Schedule , which is basically the shortcut (LNK) file to be executed to download further stagers.

    Well, last but not the least, the email also mentions to complete the instructions by 15th May 2025 enhancing a sense of urgency. Now, let us go ahead and analyze the decoy file.

    Looking into the decoy-document.

    Looking into the decoy document, we can see that it has an official logo of the targeted entity I.e., KazMunaiGas, along with instructions in both Russian and Kazakh language which instructs the employees through a series of simple steps which is to open the Downloads folder in the browser, extract a ZIP archive named KazMunayGaz_Viewer.zip, and run a file called KazMunayGaz_Viewer, although the file-name is irrelevant, but we believe, this is the exact file dropped from the malicious email. The decoy also mentions users to wait for a console window to appear and specifically advised them not to close or interact with it, to limit suspicion on targets’ ends. Last, not the least, it also mentions the IT-Support team in salutations to make it look completely legitimate, with above artefacts present in the decoy.

    Technical Analysis.

    We have divided the technical analysis into four parts, where initially we will look into the malicious ZIP containing the LNK file, which further downloads the malicious Batch script, and going ahead with downloading the script-based loader followed by the malicious DLL.

    Stage 0 – Malicious ZIP & LNK Files.

    Initially, looking into the ZIP file, we found three files, out of which one of them stands to be the decoy document, which we saw initially, the second one turns out to be README.txt, which once again makes sure that the instructions are present, so that it does not seem suspicious and the later one turns out to be malicious LNK file.

    Now, upon looking into the malicious shortcut(.LNK) file, named as График зарплат , we found that is using powershell.exe LOLBIN to execute a downloader-based behavior.

    It downloads a malicious batch script known as 123.bat, from a remote-server, which is hxxps[://]77[.]239[.]125[.]41[:]8443 and once it is downloaded, it stores the batch script under the path C:\Users\Public, it then executes the batch script using the Start-Process cmdlet from the path.

    Similarly, hunting for similar LNK file, we found another LNK, which belongs to the same campaign, looks slightly different.

    This malicious LNK file, uses a little operand shenanigan to avoid static signature detection, but concatenation of the string literals and further downloading a batch script from the same remote server, saving it to the Public folder, further executing it via cmdlet.

    In, the next section, we will examine the malicious BATCH scripts.

    Stage 1 – Malicious BATCH Scripts.

    Now, looking into the one of the BATCH scripts, I.e., it.bat , we can see that it is downloading PowerShell Loaders, which we have dubbed as DOWNSHELL, from a remote server known as support.ps1 and a.ps1, once they are downloaded, it then sleeps for a total of 11 seconds.

    Now, looking into the second batch script I.e., the 123.bat file, it also does the same which is downloading the PowerShell loaders, followed by a sleep of 10 seconds.

    In the next section, we will move ahead to understanding the working of the DOWNSHELL loaders written in PowerShell.

    Stage 2 – Malicious DOWNSHELL Loaders.

    In, this section we will look into the set of malicious PowerShell scripts, which we have dubbed as DOWNSHELL, the first PowerShell file, also known as support.ps1 is basically a script which is responsible for impairing defense on the target machine and the latter is responsible for performing loader-oriented function.

    Looking into the code, we figured out that the script is basically obfuscating, the target namespace by building “System.Management.Automation” via string concatenation, then enumerates all loaded .NET assemblies in the current AppDomain and filters for the one whose FullName matches that namespace.

    Then, using reflection technique, it resolves the internal type System.Management.Automation.AmsiUtils, which basically retrieves the private static field amsiInitiFailed, so changing or flipping this flag convinces PowerShell that the AMSI has failed to initialize, so the other malicious script belonging to DOWNSHELL family, does not get scanned and executes without any hassle or interruption. Now, let us look into the second PowerShell script.

    Looking into the first part of the code, it looks like a copied version of the famous red-team emulation-based tool known as PowerSploit, the function LookUpFunc basically dynamically retrieves the memory address of any exported function from a specified DLL without using traditional DllImport or Add-Type calls. It performs this by locating the Microsoft.Win32.UnsafeNativeMethods type within the already-loaded System.dll assembly, then extracting and invoking the hidden .NET wrappers for GetModuleHandle and GetProcAddress. By first resolving the base address of the target module ($moduleName) and then passing it along with the target function name ($functionName), it returns a raw function pointer to that API, which is required.

    Then, looking into the second part of the code, the function getDelegateType basically creates a custom .NET delegate on the fly, entirely in memory. It takes the parameter types and returns certain type, builds a new delegate class with those, and gives it an Invoke method so it can be used like a normal function. This lets the entire script wrap the raw function pointers (from LookupFunc) into something PowerShell can call directly, making it easy to run WinAPI functions without having to import them in the usual way, followed by querying the process ID of the explorer.exe process and storing it inside a variable.

    The latter part of the script is followed by a byte array containing the meterpreter reverse_tcpshellcode, which is basically using classical Create-RemoteThread Injection technique using OpenProcess, VirtualAllocEx, WriteProcessMemory & CreateRemoteThread to inject the shellcode inside the target process which is explorer.exe , followed by a message Injected! Check your listener!.

    Well, an interesting part of this script is some part of this is commented, which performs Reflective DLL injection into remote process, which is notepad in this case, using a tool known as PowerSploit , hosted at the remote server, which is downloaded, and the Meterpreter based DLL is being used. Another slight interesting case are the comments in Russian Language. In the next case, we will examine the DLL.

    Stage 3 – Malicious DLL Implant.

    Initially, we did check out the DLL implant, in a PE-analysis tool, and it was confirmed that the DLL implant or shellcode loader is a 64-bit binary.

    Next, moving ahead with the code, we saw that the implant is using Semaphores as a sort of gatekeeper to make sure only one copy of itself runs at a time, in this case the implant uses a named object Local\doSZQmSnP12lu4Pb5FRD. When it starts, it tries to create this semaphore then if it already exists, that means another instance is active. To double-check, it uses WaitForSingleObject on the semaphore and then looks for a specific named event. If the event exists, it knows another instance has already completed its setup. If it doesn’t, it creates the event itself.

    Now, depending on the previous function, which is responsible for checking the number of instances, the next step is it spawns a rundll32.exe process in a suspended manner.

    After creating the process in a suspended state, the implant performs classic thread-context hijacking: it calls GetThreadContext on the primary thread, uses VirtualAllocEx to reserve RWX memory in the target, WriteProcessMemory to drop the shellcode, updates the thread’s RIP to point to that buffer via SetThreadContext, and finally calls ResumeThread so execution continues at the injected shellcode. In this case, the shellcode basically is a reverse shell.

    Infrastructure & Hunting.

    Upon looking into the infrastructure, the threat entity had been using, we found a few slightly interesting details about it.

    Tool-Arsenal

    Along, with the tools, which we saw had been used by the threat actor, we also found that there are more open-source red-team oriented tools, which had been hosted by the threat actor for further usage.

    Pivoting

    Using similar fingerprint, we hunted a similar infrastructure, which belongs to the similar threat actor.

    One of most interesting part, being both the infrastructure is hosted under a sanctioned hosting firm known as Aeza Group LLC.

    Another interesting part is, we also discovered a lot of suspicious web applications being hosted, related to wellness, fitness and health assistance for Russian individuals.

    Attribution.

    Attribution is a very important metric when describing a threat entity. It involved analyzing and correlating various domains, which include Tactics, Techniques and Procedures (TTPs), operational mistakes, rotation and re-use of similar infrastructural artefacts, operational mistakes which could lead to attribution and much more.

    In our ongoing tracking of Noisy Bear, we have a lot of artefacts, such as languages present inside the tooling, usage of sanctioned web-hosting services and similar behavioral artefacts with related to Russian threat entities which have previously targeted similar Central Asian nations, we attribute the threat actor possibly could be of Russian origin.

    Conclusion.

    We have found that a threat entity, dubbed as NoisyBear is targeting Kazakh Energy Sector using company specific lure while heavily depending on PowerShell and open-source post-exploitation tools such as Metasploit, hosting them over a sanctioned web-hosting provider, we can also conclude that the threat actor has been active since the month of April 2025.

    SEQRITE Protection.

    TBD.

    IOCs

    File-Type SHA-256
    Outlook 5168a1e22ee969db7cea0d3e9eb64db4a0c648eee43da8bacf4c7126f58f0386
    ZIP 021b3d53fe113d014a9700488e31a6fb5e16cb02227de5309f6f93affa4515a6
    ZIP f5e7dc5149c453b98d05b73cad7ac1c42b381f72b6f7203546c789f4e750eb26
    LNK a40e7eb0cb176d2278c4ab02c4657f9034573ac83cee4cde38096028f243119c
    LNK 26f009351f4c645ad4df3c1708f74ae2e5f8d22f3b0bbb4568347a2a72651bee
    Batch Script d48aeb6afcc5a3834b3e4ca9e0672b61f9d945dd41046c9aaf782382a6044f97
    Batch Script 1eecfc1c607be3891e955846c7da70b0109db9f9fdf01de45916d3727bff96e0
    PowerShell da98b0cbcd784879ba38503946898d747ade08ace1d4f38d0fb966703e078bbf
    PowerShell 6d6006eb2baa75712bfe867bf5e4f09288a7d860a4623a4176338993b9ddfb4b
    PowerShell fb0f7c35a58a02473f26aabea4f682e2e483db84b606db2eca36aa6c7e7d9cf8
    DLL 1bfe65acbb9e509f80efcfe04b23daf31381e8b95a98112b81c9a080bdd65a2d
    Domains/IPs
    77[.]239[.]125[.]41
    wellfitplan[.]ru
    178[.]159[.]94[.]8

    MITRE ATT&CK

    Tactic Technique ID Name
    Reconnaissance T1589.002 Gather Victim Identity Information: Email Addresses
    Initial Access T1204.002

    T1078.002

    User Execution: Malicious File
    Valid Accounts: Domain Accounts
    Execution T1059.001

    T1059.00

    Command and Scripting Interpreter: PowerShell
    Defense Evasion T1562

    T1027.007

    T1027.013

    T1055.003

    T1620

    T1218.011

    Impair Defenses

    Dynamic API Resolution

    Encrypted/Encoded File

    Thread Execution Hijacking

    Reflective Code Loading

    System Binary Proxy Execution: Rundll32

    Command and Control T1105 Ingress Tool Transfer
    Exfiltration T1567.002 Exfiltration to Cloud Storage

     



    Source link

  • Python – Learn Pandas with SQL Examples – Football Analytics Example – Useful code

    Python – Learn Pandas with SQL Examples – Football Analytics Example – Useful code


    When working with data, you will often move between SQL databases and Pandas DataFrames. SQL is excellent for storing and retrieving data, while Pandas is ideal for analysis inside Python.

    In this article, we show how both can be used together, using a football (soccer) mini-league dataset. We build a small SQLite database in memory, read the data into Pandas, and then solve real analytics questions.

    There are neither pythons or pandas in Bulgaria. Just software.

    • Setup – SQLite and Pandas

    We start by importing the libraries and creating three tables –
    [teams, players, matches]  inside an SQLite in-memory database.

    Now, we have three tables.

    • Loading SQL Data into Pandas


    pd.read_sql  does the magic to load either a table or a custom query directly.

    At this point, the SQL data is ready for analysis with Pandas.

    • SQL vs Pandas – Filtering Rows

    Task: Find forwards (FW) with more than 1200 minutes on the field:

    SQL:

    Pandas:

    As expected, both return the same subset, one written in SQL and the other in Pandas.

    Task: Total goals per team:

    SQL:

    Pandas:

    Both results show which team has scored more goals overall.

    Task: Add the city of each team to the players table.

    SQL:

    Pandas:

    The fun part: calculating points (3 for a win, 1 for a draw) and goal difference. Only with SQL this time.

    This produces a proper football league ranking – teams sorted by points and then goal difference:

    • Quick Pandas Tricks

      • Top scorers with
        nlargest:

    https://www.youtube.com/watch?v=U0lbBaHFAEM

    https://github.com/Vitosh/Python_personal/tree/master/YouTube/041_Python-Learn-Pandas-with-Football-Analytics



    Source link

  • A Deep Dive into the UNC6040 Cyber Attack

    A Deep Dive into the UNC6040 Cyber Attack


    Executive Summary

    In early June 2025, Google’s corporate Salesforce instance (used to store contact data for small‑ and medium‑sized business clients) was compromised through a sophisticated vishing‑extortion campaign orchestrated by the threat‑group tracked as UNC6040 & UNC6240 (online cybercrime collective known as “The Com” linked to “ShinyHunters).”

    The attackers combined three core vectors:

    1. Voice‑phishing (vishing) – Impersonating IT staff in a convincing phone call, persuading a Google employee to approve a malicious application connected to Salesforce, a rapid‑reply extortion scheme demanding Bitcoin payments within 72 hrs.
    2. OAuth app abuse – the deployment of custom Python scripts that emulate Salesforce’s DataLoader, allowing automated bulk exports.
    3. Anonymity layers – Mullvad VPN‑initiated calls followed by TOR‑based data exfiltration, which anonymized the actors’ true location.

    Though Google confirmed that no user passwords were stolen, the breached dataset, included business names, email addresses, phone numbers and related notes. The implications reach far beyond the affected small and medium business customers: while associating compliance, brand integrity, partner security, and regulatory scrutiny of SaaS risk management practices.

    Meanwhile, the Salesloft Drift attack orchestrated by UNC6395 has emerged as one of the most significant cyber incidents in late 2025, which compromised the Salesloft Drift (AI chat-bot/assistant) used for its Salesforce integration. The theft of OAuth token appears to have resulted in running SOQL queries on Salesforce databases that held objects such as cases, accounts, users and opportunities. The attack affected hundreds of Salesforce customers, impacting not just Salesforce users but also other third-party integrations. Salesloft said “Initial findings have shown that the actor’s primary objective was to steal credentials, specifically focusing on sensitive information like AWS access keys, passwords and Snowflake-related access tokens”. Google explicitly warned of the breach’s extensive scope beyond its own systems.

    Primary Tactics & Attack Vectors:

    • Initial Access: Unauthorized OAuth apps installed via trial accounts (using legitimate email domains) and later via compromised accounts from unrelated orgs.
    • Vishing, Social Engineering: Voice phishing calls to employees
    • Exfiltration: Custom Python scripts that replicate DataLoader operations.
      Infrastructure: Initial calls routed via Mullvad VPN IPs; data transfer via TOR exit nodes.
    • Extortion: Requesting immediate Bitcoin payment.

    Threat Attribution

    UNC5537, UNC6040 & UNC6240 likely linked with “Scattered LAPSUS$ Hunters” (“Chos hub”) exhibits similar attack patterns.

    A Telegram channel called “Scattered LAPSUS$ Hunters”, blending the names of ShinyHunters, Scattered Spider and Lapsus$ groups emerged, which researchers describe as a chaotic hub for leaks and threats. The group focuses in exploiting the human element to gain access to company networks. The channel ran public polls where members voted on which victim’s data to fully dump, advertised zero-day exploits and a supposed new ransomware toolkit, touting the collective’s action.

    GOOGLE - SALESFORCE BREACH

    UNC6395 shared the theme of abusing OAuth mechanisms for Salesforce access via compromised 3rd party integration – evolving their tactics against cloud ecosystems. Meanwhile, UNC6040 uses vishing and OAuth abuse to access Salesforce through social engineering. Overlapping TTPs indicate targeting trusted access applications and the name ShinyHunters appears across these incidents. Al the same time, Google tracks this cluster separately as UNC6395, ShinyHunters extortion group initially told BleepingComputer that they were behind the SalesLoft Drift attack.

    Parallel Campaigns

    Similar tactics applied in attacks targeting Adidas, Qantas, Allianz Life, LVMH brands (Louis Vuitton, Dior, Tiffany & Co.), Chanel, AT&T, Santander, Starbucks Singapore, Snowflake breach at Ticketmaster, Cisco, Pandora, Bouygues Telecom, Tokopedia, Homechef, Chatbooks, Portail Orange, Farmers Insurance, TransUnion, UK Legal Aid Agency, Gucci, Salesforce, Fairhaven Homes, Workday, Mazars.fr, Adidas, Air France-KLM, Phantom Wallet, Neiman Marcus, Coca-Cola, ZScaler.

    • Qantas Airways: Employee credentials & sensitive flight/customer records targeted. Attack blended SIM swapping + SaaS compromise.
    • Air France-KLM: Airline loyalty accounts and CRM cloud environment probed.
    • Retailers (generalized set) → Used social engineering and SIM-swap vishing to gain access to IT/helpdesk portals.
    • Okta: Service provider breach led to downstream impact on multiple clients (identity federation exploited).
    • MGM Resorts: Social engineering of IT desk led to ransomware deployment, slot machines & hotel services down for days.
    • Caesars Entertainment: Extortion campaign where ransom was allegedly paid; loyalty program records got leaked.
    • AT&T: Call metadata (500M+ records, including phone numbers, call/SMS logs) stolen and advertised for sale.
    • Ticketmaster (Live Nation): ~560M customer records including event ticketing details, addresses, payment info leaked.
    • Advance Auto Parts: Data set of supply chain and retail customer info stolen.
    • Santander Bank: Customer financial records compromised; reported 30M records affected.
    • LendingTree: Customer PII and loan data exposed.
    • Neiman Marcus: Customer loyalty and credit program data targeted.
    • Los Angeles Unified School District (LAUSD): Student/employee data exfiltrated from Snowflake environment.
    • Pandora, Adidas, LVMH (Louis Vuitton, Chanel, Dior): Retail brand data exposed (customer PII + sales info).
    • ZScaler: UNC6395 compromised Salesforce instance through Salesloft Drift and steals customer data

     

     

    With the attack that involves compromise of the Salesloft Drift AI OAuth token, any data that could potentially be compromised from the databases (that held information on users, accounts, cases, etc,) can be utilized by the attacker in various ways. The stolen data could either be sold to third parties or used to access emails (as reported from a very small number of Google Workspace accounts) launch further credential-reuse attacks on other SaaS accounts.

    Indicators of Compromise:

    UNC6040, UNC6240 UNC6395
    81.17.28.95

    31.133.0.210

    45.138.16.69

    45.90.185.109

    45.141.215.19

    45.90.185.115

    45.90.185.107

    37.114.50.27

    45.90.185.118

    179.43.159.201

    38.135.24.30

    91.199.42.164

    192.159.99.74

    208.68.36.90

    44.215.108.109

    154.41.95.2

    176.65.149.100

    179.43.159.198

    185.130.47.58

    185.207.107.130

    185.220.101.133

    185.220.101.143

    185.220.101.164

    185.220.101.167

    185.220.101.169

    185.220.101.180

    185.220.101.185

    185.220.101.33

    192.42.116.179

    192.42.116.20

    194.15.36.117

    195.47.238.178

    195.47.238.83

    shinycorp@tuta[.]com

    shinygroup@tuta[.]com

    shinyhuntersgroups@tutamail[.]com

    ticket-dior[.]com

    ticket-nike[.]com

    ticket-audemarspiguet[.]com

    Salesforce-Multi-Org-Fetcher/1.0

    Salesforce-CLI/1.0

    python-requests/2.32.4

    Python/3.11 aiohttp/3.12.15

     

    In both the campaigns Google observed TOR exit nodes being used to access compromised Salesforce accounts.

    • Majority of attacks orchestrated by UNC6040 and UNC6240 (ShinyHunters) could be traced to originate from TOR exit nodes hosted either in Netherlands or Poland. These were hosted primarily at Macarne or Private Layer INC.

    • Attackers were found to blend TOR traffic with legitimate OAuth sessions to obscure origin and make detection harder. Attacks orchestrated by UNC6395 could be traced to originate from TOR exit nodes hosted either in Germany or Netherlands. These were hosted primarily at Stiftung Erneuerbare Freiheit.
    • Many suspicious SOQL queries (data exfiltration) and deletion of scheduled jobs were initiated from TOR IP addresses, indicating adversaries were anonymizing data theft operations.

    Similarly, Scattered Spider used TOR exit IPs as a cover for account takeovers and extortion activity.

    • Attackers combined vishing (helpdesk calls) with credential access, then routed subsequent access through Tor.
    • Tor traffic was especially noted when adversaries escalated privileges or accessed sensitive SaaS applications.
    • Europe-heavy nodes with a notable U.S. presence.

    Common Threads Across Both Campaigns

    • TOR IPs as operational cover was consistently used to hide adversary infrastructure.
    • Identity-based intrusions by both groups abused identity trust rather than exploiting zero-days.
    • Overlap with Scattered Spider tradecraft where both campaigns show attackers mixing social engineering or stolen credentials with TOR.
    • TOR exit nodes have different ASNs, but both campaigns leverage NL exit nodes. ASN 58087 (Florian Kolb, DE) overlaps across both the campaigns.

    Threat Landscape

    Threat actors such as UNC6040 (ShinyHunters-affiliated), Scattered Spider (UNC3944), and UNC5537 have targeted organizations in the hospitality, retail, and education sectors in the Americas and Europe.

    Scattered Spider (UNC3944) is known for sophistication and stealth:

    • Reliably uses commercial VPN services to mask origin: Mullvad VPN, ExpressVPN, NordVPN, Ultrasurf, Easy VPN, ZenMate.
    • Employs Tools and TTPs including disabling Antivirus/EDR, lateral movement via ADRecon, credential dumping with Mimikatz/LaZagne, and persistence via RMM and cloud VMs.

    “The Com”, short for The Community, is less a formal hacking group and more a sociopathic cybercriminal subculture:

    • Comprised of 1,000+ members and mostly aged 11–25, they operate across Canada, the U.S., and the U.K.
    • Engages in SIM swapping, cryptocurrency theft, swatting, sextortion, spear-phishing, and even extreme coercion or violence.
    • Intel471 reports that members are recruited via social media/gaming and coerced into crimes ranging from grooming to violent acts; the network has also issued a manual (“The Bible”) detailing techniques such as ATM skimming, IP grabbing, doxxing, extortion, and grooming.
    Source: DHS’s Joint Regional Intelligence Center and the Central California Intelligence Center

    UNC5537 orchestrated a large-scale breach targeting Snowflake customer environments:

    • In April–June 2024, accessed over 160 organizations including AT&T, Ticketmaster/Live Nation, Santander, Advance Auto Parts, LendingTree, Neiman Marcus, and LA Unified School District – via stolen credentials, often from infostealers, and constraints due to lack of MFA.
    • Data stolen included sensitive PII, event tickets, DEA numbers, and call/text metadata (500M+ records in aggregate).
    • Targets were later advertised and extorted through forums.

    DataBreaches.net received screenshots of a Telegram message from ShinyHunters claiming to outpace law enforcement, mocking capabilities of agencies like the NSA and stating: “Even the NSA can’t stop or identify us anymore. The FBI… is irrelevant and incompetent…”. In conversation, “Shiny” asserted that Scattered Spider sources voice calls and share access and hinted at a future “Snowflake 3.0” campaign, promising even greater operations ahead.

    Source: DataBreaches.Net

    Cross-Actor Victim Overlaps

    • Cloud SaaS as a hub: Salesforce (UNC6040), Okta (Scattered Spider), and Snowflake (UNC5537) breaches show pivot via cloud identity/data platforms.
    • Retail & hospitality: Multiple actors target customer/loyalty records
      • Scattered Spider targeted casinos.
      • UNC6040 targeted retailers.
      • UNC5537 targeted luxury brands.
    • Education: UNC6040 and UNC5537 both hit educational institutions, stealing student/faculty data.
    • Financial institutions: Santander (UNC5537) vs smaller fintech/payment targets by The Com/Scattered Spider (SIM swaps).

    Detection & Monitoring Guidance

    Additional indicators and associated detection rules for detecting the threat group is made available through STI and SMAP.

    What we recommend

    • Monitoring Logs
      Continuously scan for LOGIN events from unfamiliar IP ranges (especially Mullvad or TOR exit nodes). Flag any API activity exhibiting a high volume of requests every hour.
    • OAuth App Watch‑list
      Maintain a dynamic registry of approved apps. Trigger alerts on new or anomalous app registrations. Enforce a mandatory admin sign‑off workflow. The below detection rule is an example to detect suspicious signin events with OAuth:2.0:
      `SigninLogs | where ResultType == “0” | where AuthenticationDetails has “OAuth:2.0” | where AppDisplayName startswith “Salesforce” | summarize count() by UserPrincipalName, AppDisplayName, IPAddress | where count_ > 5`
    • Vishing Detection
      Implement caller‑ID verification, deploy voice‑analytics modules that detect key phrases (eg: “please pay”, “this is Google”) and cross‑reference against known threat‑intelligence feeds. Integrate with your call‑center platform to surface suspicious calls in real time.
    • Network Traffic Analysis
      Inspect outbound traffic for TOR exit nodes and VPN tunnels that deviate from corporate baselines. Use DPI to spot unusually large, encrypted payloads.
    • Threat‑Intelligence Feeds
      Subscribe to the latest ATT&CK and IOC updates for UNC6040/ShinyHunters. Monitor public Telegram channels for freshly disclosed IOCs.
    • Zero‑Trust IAM to reduce credential‑compromise impact
      MFA, least‑privilege, RBAC for all Salesforce users.
    • OAuth App Governance to stop rogue app installations
      Manual approval + periodic review
    • IP‑Based Restrictions to limit exfiltration paths
      Allow only corporate VPN IPs; block TOR exits
    • Endpoint Security to stop malicious code execution
      EDR to detect custom Python scripts
    • Call‑Center Hardening to mitigate human‑facing social engineering
      Caller‑ID verification, recorded scripts, staff training
    • Data Loss Prevention to detects anomalous data movements
      DLP on outbound exports (volume limits + alerts)
    • Strategic Initiative: SaaS Posture Management – continuous inventory & policy enforcement for third‑party integrations. Early rogue‑app detection is our key takeaway.
    • Revoke and rotate tokens/credentials: Immediately revoke OAuth tokens tied to Salesloft Drift and reset all exposed API keys.
    • Audit activity logs: Review SOQL queries and job deletions between Aug 8–18, 2025 for suspicious access.
    • Limit OAuth permissions: Enforce least privilege, review app scopes regularly, and tighten approval workflows.
    • Govern tokens: Ensure short-lived tokens, track their use, and revoke unused ones.
    • Secure stored credentials: Move AWS keys, Snowflake tokens, and other secrets out of Salesforce objects into vaults.
    • Enhance monitoring: Use UEBA to detect unusual SaaS behavior and consolidate logs across Salesforce, identity providers, and third-party apps.
    • Restrict integrations: Apply IP/network restrictions and remove untrusted apps until validated.

    Strategic Outlook

    • TTP Evolution – The ShinyHunters group hints at a potential pivot towards ransomware‑as‑a‑service (ShinySP1D3R).
    • Broader Targeting – High‑profile brands (Adidas, Qantas, Chanel, etc.) demonstrate that the same methodology can be scaled.
    • Regulatory Momentum – Expect stricter SaaS risk‑management mandates, amplifying the need for proactive controls.
    • Attribution Difficulty – Continued use of VPN/TOR & compromised third‑party accounts will heighten detection complexity; behavioral analytics will become indispensable.

    Final Note from Our Research Team

    The Google Salesforce breach is a textbook illustration of how modern threat actors blend technical supply‑chain exploitation with fast‑turnover social engineering. For organizations that rely on cloud‑native platforms, we see a critical need to:

    • Revisit SaaS integration policies – treat every third‑party app as a potential attack vector.
    • Strengthen human‑facing security – call‑center hardening and real‑time vishing detection should become a standard part of the security stack.
    • Adopt a data‑centric risk perspective – even smaller datasets can fuel large-scale phishing campaigns.
    • Our threat‑intelligence platform remains actively monitoring the ShinyHunters/Tor‑Mullvad threat chain and will update clients with emerging IOCs and risk indicators. We encourage you to integrate these insights into your defensive posture and to collaborate with our team for a tailored, intelligence‑driven response.

    Conclusion

    The Google internal Salesforce breach orchestrated by UNC6040 (“ShinyHunters”) underscores critical vulnerabilities in modern SaaS environments. The attack demonstrates that even data traditionally considered “low-sensitivity” can be weaponized for targeted phishing and extortion schemes, while also posing significant regulatory, reputational, operational, and financial risks. Organizations must adopt robust Identity & Access Management controls, enforce strict OAuth governance, and integrate comprehensive monitoring to mitigate evolving threats.

    The UNC6395 campaign highlights how third-party OAuth integrations can undermine SaaS security. By abusing trusted tokens, attackers bypassed MFA and exfiltrated sensitive data from hundreds of organizations. This attack reinforces SaaS ecosystems and not just core apps as prime targets. Strong governance over OAuth apps, token lifecycles, and SaaS behaviors is critical to reducing risk. Proactive monitoring, least privilege, and credential hygiene are essential to defending against token-based intrusions like this.

     

    Authors

    Deepak Thomas Philip

    Kartikkumar Jivani

    Sathwik Ram Prakki

    Subhajeet Singha

    Rhishav Kanjilal

    Shayak Tarafdar



    Source link

  • Operation HanKook Phantom: APT37 Spear-Phishing Campaign

    Operation HanKook Phantom: APT37 Spear-Phishing Campaign


    Table of Contents:

    • Introduction
    • Threat Profile
    • Infection Chain
    • Campaign-1
      • Analysis of Decoy:
      • Technical Analysis
      • Fingerprint of ROKRAT’s Malware
    • Campaign-2
      • Analysis of Decoy
      • Technical analysis
      • Detailed analysis of Decoded tony31.dat
    • Conclusion
    • Seqrite Protections
    • MITRE Att&ck:
    • IoCs

    Introduction:

    Seqrite Lab has uncovered a campaign in which threat actors are leveraging the “국가정보연구회 소식지 (52호)” (National Intelligence Research Society Newsletter – Issue 52) as a decoy document to lure victims. The attackers are distributing this legitimate-looking PDF along with a malicious LNK (Windows shortcut) file named as 국가정보연구회 소식지(52호).pdf .LNK is typically appended to the same archive or disguised as a related file. Once the LNK file is executed, it triggers a payload download or command execution, enabling the attacker to compromise the system.

    The primary targets appear to be individuals associated with the National Intelligence Research Association, including academic figures, former government officials, and researchers in the newsletter. The attackers likely aim to steal sensitive information, establish persistence, or conduct espionage.

    Threat Profile:

    Our investigation has identified the involvement of APT-37, also referred to as InkySquid, ScarCruft, Reaper, Group123, TEMP. Reaper, or Ricochet Chollima. This threat actor is a North Korean state-backed cyber espionage group operational since at least 2012. While their primary focus has been on targets within South Korea, their activities have also reached nations such as Japan, Vietnam, and various countries across Asia and the Middle East. APT-37 is particularly known for executing sophisticated spear-phishing attacks.

    Targets below Country:

    • South Korea
    • Japan
    • Vietnam
    • Russia
    • Nepal
    • China
    • India
    • Romania
    • Kuwait
    • Middle East

    APT-37 has been observed targeting North Korea through spear-phishing campaigns using various decoy documents. These include files such as 러시아 전장에 투입된 인민군 장병들에게.hwp” (To North Korean Soldiers Deployed to the Russian Battlefield.hwp), 국가정보와 방첩 원고.lnk” (National Intelligence and Counterintelligence Manuscript.lnk), and the most recent sample, which is analyzed in detail in this report.

    Infection Chain:

    Campaign –1:

    Analysis of Decoy:

    The document “국가정보연구회 소식지 (52호)” (“National Intelligence Research Society Newsletter—Issue 52”) is a monthly or periodic internal newsletter issued by a South Korean research group focused on national intelligence, labour relations, security, and energy issues.

    The document informs members of upcoming seminars, events, research topics, and organizational updates, including financial contributions and reminders. It reflects ongoing academic and policy-oriented discussions about national security, labour, and North-South Korea relations, considering current events and technological developments like AI.

    Threat actors leveraged the decoy document as a delivery mechanism to facilitate targeted attacks, disseminating it to specific authorities as part of a broader spear-phishing campaign. This tactic exploited trust and gained unauthorized access to sensitive systems or information.

    Targeted Government Sectors:

    • National Intelligence Research Association (국가정보연구회)
    • Kwangwoon University
    • Korea University
    • Institute for National Security Strategy
    • Central Labor Economic Research Institute
    • Energy Security and Environment Association
    • Republic of Korea National Salvation Spirit Promotion Association
    • Yangjihoe (Host of Memorial Conference)
    • Korea Integration Strategy.

    Technical Analysis:

    After downloading the LNK file named 국가정보연구회 소식지(52).pdf.lnk and executing it in our test environment, we observed the following chain of execution using Procmon.

    The LNK file contains embedded PowerShell scripts that extract and execute additional payloads at runtime.

    This script searches for .lnk files, opens them in binary mode, reads embedded payload data from them, extracts multiple file contents (including a disguised .pdf and additional payloads), writes them to disk (like aio0.dat, aio1.dat, and aio1+.3.b+la+t).

    This block reads specific binary chunks from offsets in the .lnk file:

    • Offset 0x0000102C: likely fake PDF (decoy)
    • Offset 0x0007EDC1: payload #1 (dat)
    • Offset 0x0015A851: string (commands/script)
    • Offset 0x0015AED2: another payload (aio1+3.b+la+t)

    It stores them as:

    • $pdfPath – saved as .pdf decoy
    • $exePath = dat – possibly loader binary
    • $executePath = aio1+3.b+la+t – final malicious payload

    This executes a batch script (aio03.bat) dropped in the %TEMP% folder.

    As per our analysis, the attack starts with a malicious .lnk file containing hidden payloads at specific binary offsets. When executed, PowerShell scans for such .lnk files, extracts a decoy PDF and three embedded payloads (aio1.dat, aio2.dat, and aio1+3.b+la+t), and saves them in %TEMP%. A batch script (aio03.bat) is then executed to trigger the next stage, where PowerShell reads and decodes a UTF-8 encoded script from aio02.dat and runs it in memory using Invoke-Command. This leads to the execution of aio1.dat, the final payload, completing the multi-stage infection chain.

    This PowerShell script ai02.dat represents the final in-memory execution stage of the malware chain and is a clear example of fileless execution via PowerShell with reflective DLL injection.

    It tries to open the file aio01.dat (previously dropped to %TEMP%) and reads its binary content into $exeFile byte array.

    $k=’5′

    for ($i=0; $i -lt $len; $i++) {

    $newExeFile[$i] = $exeFile[$i] -bxor $k[0]

    }

    The payload is XOR-encrypted with a single-byte key (0x35, which is ASCII ‘5’). This loop decodes the encrypted binary into $newExeFile.

    The aio02.dat file contains a PowerShell script that performs in-memory execution of a final payload (aio01.dat). It reads the XOR-encrypted binary (aio01.dat) from the %TEMP% directory, decrypts it using a single-byte XOR key (0x35), and uses Windows API functions (GlobalAlloc, VirtualProtect, CreateThread, WaitForSingleObject) to allocate memory, make it executable, inject the decoded binary, and execute it—all without dropping another file to disk.

    Detailed Analysis of the Extracted EXE file:

    Fingerprint of ROKRAT’s Malware

    The function is building a host fingerprint string set, containing:

    • Architecture flag (WOW64 or not)
    • Computer name
    • Username
    • Path to malware binary
    • BIOS / Manufacturer info

    Anti VM

    This function often checks whether the system runs in a virtual machine, sandbox, or analysis environment. In our case, it is being used with:

    “C:\\Program Files\\VMware\\VMware Tools\\vmtoolsd.exe”

    The function sub_40EA2C is likely used as an environment or privilege check. It tries to create and delete a randomly named .dat file in the Windows system directory, which typically requires administrative privileges. If this operation succeeds, it suggests the program is running in a real user environment with sufficient permissions. However, if it fails, it may indicate a restricted environment such as a sandbox or virtual machine used for malware analysis.

    Screenshot Capture

    The function sub_40E40B appears to capture a screenshot, process the image in memory, and possibly encode or transmit the image data.

    ROKRAT Commands

    Each command is identified by a single character. Some of the commands take arguments, and they are supplied just after the command ID character. After the correct command is determined, the code parses the statements according to the command type. The following table lists the commands we discovered in ROKRAT, together with their expected arguments and actions:

    Command 1 to 4

    The shellcode is retrieved from the C2 server and executed via CreateThread. Execution status—either “Success” or “Failed”—is logged to a file named r.txt. In parallel, detailed system information from the victim’s machine is gathered and transmitted back to the command-and-control (C&C) server.

     

    Command 5 to 9

    The malware first initializes cloud provider information, which is likely part of setting up communication with the command-and-control (C2) server. It then proceeds to download a PE (Portable Executable) file from the C2 server. The downloaded file is saved with the name KB400928_doc.exe, consistent with the naming convention used in earlier steps. Once the file is saved locally, the malware immediately executes it.

     

    Command C – Exfiltrate Files

    Searches for files in the specified file or directory path based on the provided extensions—either all files, common document types (e.g., doc, xls, ppt, txt, m4a, amr, pdf, hwp), or user-defined extensions. The located files are then uploaded to the C&C server.

    Command E – Run a Command

    Executes the specified command using cmd.exe, allowing remote execution of arbitrary system commands.

     

    Command H – Enumerate Files on Drives

    Gathers file and directory information from available drives by executing the command dir /A /S : >> “%temp%\\_.TMP”, which recursively lists all files and folders and stores the output in a temporary file.

    Command ‘i’ – Mark Data as Ready for Exfiltration

    Collected data is ready to be sent to the command and control (C2) server.

    Command ‘j’ or ‘b’ – Terminate Malware Execution

    Initiates a shutdown procedure, causing the malware to stop all operations and terminate its process.

    C2C connection

    RokRat leverages cloud services like pCloud, Yandex, and Dropbox as command and control (C2) channels. it can exfiltrate stolen data, retrieve additional payloads, and execute remote commands with minimal detection.

     

    Provider Function Obfuscated URL
    Dropbox list_folder hxxps://api.dropboxapi[.]com/2/files/list_folder
    upload hxxps://content.dropboxapi[.]com/2/files/upload
    download hxxps://content.dropboxapi[.]com/2/files/download
    delete hxxps://api.dropboxapi[.]com/2/files/delete
    pCloud listfolder hxxps://api.pcloud[.]com/listfolder?path=%s
    uploadfile hxxps://api.pcloud[.]com/uploadfile?path=%s&filename=%s&nopartial=1
    getfilelink hxxps://api.pcloud[.]com/getfilelink?path=%s&forcedownload=1&skipfilename=1
    deletefile hxxps://api.pcloud[.]com/deletefile?path=%s
    Yandex.Disk list folder (limit) hxxps://cloud-api.yandex[.]net/v1/disk/resources?path=%s&limit=500
    upload hxxps://cloud-api.yandex[.]net/v1/disk/resources/upload?path=%s&overwrite=%s
    download hxxps://cloud-api.yandex[.]net/v1/disk/resources/download?path=%s
    permanently delete hxxps://cloud-api.yandex[.]net/v1/disk/resources?path=%s&permanently=%s

     

    Campaign –2:

    Analysis of Decoy:

    Threat Actors are utilizing this document, which is a statement issued by Kim Yō-jong, the Vice Department Director of the Central Committee of the Workers’ Party of Korea (North Korea), dated July 28, and reported by the Korean Central News Agency (KCNA).

    This statement marks a sharp and formal rejection by North Korea of any reconciliation efforts from South Korea, particularly under the government of President Lee Jae-myung. It strongly criticizes the South’s attempts to improve inter-Korean relations, labelling them as meaningless or hypocritical, and asserts.

    North Korea also expressed no interest in any future dialogue or proposals from South Korea, stating that the country will no longer engage in talks or cooperation.

    The statement concluded by reaffirming North Korea’s hostile stance toward South Korea, emphasizing that the era of national unity is over, and future relations will be based on confrontation, not reconciliation.

    Targeted Government organization:

    • South Korean Government (李在明政府 – Lee Jae-myung administration)
    • Ministry of Unification (統一部)
    • Workers’ Party of Korea (朝鮮労働党中央委員会)
    • Korean Central News Agency (KCNA / 朝鮮中央通信)
    • S.–South Korea Military Alliance (韓米同盟)
    • Asia-Pacific Economic Cooperation (APEC)

    Technical Analysis:

    Upon analysing the second LNK file we found while hunting on Virus Total, we observed the same execution chain as previously seen when running the file.

    The LNK file drops a decoy document named file.doc and creates the following artifacts in the %TEMP% directory. After dropping these files, the LNK file deletes itself from the parent directory to evade detection and hinder forensic analysis.

    As observed in our previous campaign, the same set of files is also being used here. However, this time the files have been renamed—likely to random or arbitrary names—to evade detection or hinder analysis.

    Looking into the Bat file,, which is named tony33.bat,

    This appears to be highly obfuscated and contains PowerShell execution code. After decoding, the content can be seen in the snapshot below.

    The file tony32.dat contains a Base64-encoded PowerShell payload that serves as the core malicious component of the attack. The accompanying .bat/PowerShell loader is designed to read this file from the system’s temporary directory, decode its contents twice—first converting the raw bytes to a UTF-8 string, then Base64-decoding that string back into executable PowerShell code—and finally execute the decoded payload directly in memory. This fileless execution technique allows the attackers to run malicious code without writing the final script to disk, making it harder for traditional security solutions to detect or block the activity.

    Upon analysing and decoding the tony32.dat file, we observed that the file has a Base64 encoded string as below,

    After decoding the string, we have seen that the file is memory injection loader — it reads an XOR-encrypted binary from tony31.dat, decrypts it, and executes it directly in memory using Windows API calls.

    $exePath = $env:temp + ‘\tony31.dat’;

    $exeFile = Get-Content -path $exePath -encoding byte;

    Loads tony31.dat as raw bytes from the system’s Temp folder.

    $xK = ‘7’;

    for($i=0; $i -lt $len; $i++) {

        $newExeFile[$i] = $exeFile[$i] -bxor $xk[0];

    Each byte is XOR-decoded using the key 0x37 (ASCII ‘7’).

    $buffer = $b::GlobalAlloc(0x0040, $byteCount + 0x100);

    $a90234sb::VirtualProtect($buffer, $byteCount + 0x100, 0x40, [ref]$old);

    Allocates a memory buffer with executable permissions.

    • dat = Encrypted malicious executable (XOR with ‘7’)
    • The script decrypts it entirely in memory (no file drop to disk)
    • Uses direct Windows API calls to allocate and execute memory (fileless execution).

    Detailed analysis of Decoded tony31.dat:

    Upon analysis of the extracted Exe, we found that this malware acts as a dropper/launcher, downloading a file named abs.tmp in temp directory, and loading ads or drops a file named abs.tmp, and loads its contents.
    It then executes the payload through PowerShell and deletes the staging file to cover its tracks.

    Data Exfiltration

    Malware doesn’t always force its way into systems — sometimes it operates quietly, collecting sensitive data and disappearing without a trace. In this case, two functions, sub_401360 and sub_4021F0, work in tandem to execute a stealthy data exfiltration routine.

    The first function scans a specific Temp directory on the victim’s machine (C:\Users\<username>\AppData\Local\Temp\{502C2E2E-…}), identifying all non-directory files. Each discovered file path is then passed to the second function, which opens the file, reads its contents into memory, and packages it into a browser-style multipart/form-data HTTP POST request.

    Disguised as a PDF upload, the request includes the victim’s computer name and a timestamp, and is sent to a hardcoded C2 server at:

    hxxp://daily.alltop.asia/blog/article/up2.php

    Once the file is successfully exfiltrated, it is deleted from the local system, effectively erasing evidence and complicating recovery efforts. This “scan → steal → delete” workflow is designed to be covert — the network traffic mimics a legitimate Chrome file upload, complete with a WebKitFormBoundary string and a fake MIME type (application/pdf) to evade basic content filters.

    The stolen files can include cached documents, authentication tokens, downloaded content, or staging files from other malware. To detect such activity, defenders should monitor outbound HTTP POST requests to unfamiliar domains, flag inconsistencies between file extensions and MIME types, and watch for bulk deletions in Temp directories.

    Connects to C2C and tries to download payload.

    The captured packet confirms what the functions sub_4020D0 and sub_401F80 implement: the malware builds an HTTP GET request to its C2 server at daily.alltop.Asia, targeting /blog/article/d2.php?downfname=<filename>&crc32=<value> where the filename is victim-specific (e.g., abs.tmp) and the CRC value is set to zero, then sends it with realistic browser-like headers including a spoofed Chrome User-Agent, Accept, Language, and Keep-Alive to blend in with normal traffic. This request is sent via WinINet, the response (typically a short command or acknowledgment) is optionally stored in a buffer, the code sleeps briefly, and then a second request is issued to /blog/article/del2.php?delfname=<filename> without reading the reply, effectively telling the server to delete the staged file and reduce evidence. Together, these functions implement a lightweight download-and-cleanup beacon pattern that makes use of a legitimate-looking HTTP session to disguise malicious C2 communication

    C2C: hxxp://daily.alltop.asia/blog/article/d2.php?downfname=abs.tmp&crc32=0

     

    After downloading the payload, it tries to save it under a benign filename like `abs.tmp.

    Once the file is created, the program opens it using `CreateFileW`, checks its size, and allocates a buffer—rejecting files larger than 128 MB. It then reads the file’s contents into memory.

    If the file contains data, it calls `sub_402620`, which likely performs validation or DE-obfuscation—such as checking for magic bytes, verifying a checksum, or decrypting the payload.

    Upon successful validation, the program constructs a PowerShell command line. It initializes a `STARTUPINFOA` structure and a zeroed `PROCESS_INFORMATION` structure.

    The command line begins with `”powershell “` and appends an encoded or packed payload extracted from the file using `sub_401280(&CommandLine[11], nSize[1], v15, nSize[1])`. This function likely embeds the payload using techniques like Base64 encoding or inline scripting with `-EncodedCommand`.

    Finally, the program executes the PowerShell command via `CreateProcessA`, waits for 2 seconds (`Sleep(0x7D0)`), and deletes `abs.tmp` using `DeleteFileW` to clean up traces.

    Conclusion:

    The analysis of this campaign highlights how APT37 (ScarCruft/InkySquid) continues to employ highly tailored spear-phishing attacks, leveraging malicious LNK loaders, fileless PowerShell execution, and covert exfiltration mechanisms. The attackers specifically target South Korean government sectors, research institutions, and academics with the objective of intelligence gathering and long-term espionage.

    We have named this campaign Operation HanKook Phantom for two reasons: the term “HanKook” (한국) directly signifies that Korea in Korea, while “Phantom” represents the stealthy and evasive techniques used throughout the infection chain, including in-memory execution, disguised decoys, and hidden data exfiltration routines. This name reflects both the strategic targeting and the clandestine nature of the operation.

    Overall, Operation HanKook Phantom demonstrates the persistent threat posed by North Korean state-sponsored actors, reinforcing the need for proactive monitoring, advanced detection of LNK-based delivery, and vigilance against misuse of cloud services for command-and-control.

    Seqrite Protection:

    • Trojan.49901.GC
    • trojan.49897.GC

    MITRE Att&ck:

    Initial Access T1566.001 Spear phishing Attachment
    Execution T1059.001 Command and Scripting Interpreter: PowerShell
    T1204.001 User Execution: Malicious Link
    T1204.002 User Execution: Malicious File
    Persistence T1574.001 Hijack Execution Flow: DLL
    T1547.001 Boot or Logon Autostart Execution: Registry Run Keys / Startup Folder
    Privilege Escalation T1055.001 Process Injection: Dynamic-link Library Injection
    T1055.009 Process Injection: Proc Memory
    T1053.005 Scheduled Task/Job : Scheduled Task
    Defense Evasion T1140 Deobfuscate/Decode Files or Information
    T1070.004 Indicator Removal : File Deletion
    T1027.009 Obfuscated Files or Information: Embedded Payloads
    T1027.013 Obfuscated Files or Information: Encrypted/Encoded File
    Credential Access T1056.002 Input Capture: Keylogging : GUI Input Capture
    Discovery T1087.001 Account Discovery : Local Account
    T1217 Browser Information Discovery
    T1083 File and Directory Discovery
    T1082 System Information Discovery
    Collection T1123 Audio Capture
    T1005 Data from Local System
    T1113 Screen Capture
    Command and Control T1102.002 Web Service: Bidirectional Communication
    Exfiltration T1041 Exfiltration Over C2 Channel
    Impact T1529 System Shutdown/Reboot

     

    IOCs:

    MD5 File Name
    1aec7b1227060a987d5cb6f17782e76e aio02.dat
    591b2aaf1732c8a656b5c602875cbdd9 aio03.bat
    d035135e190fb6121faa7630e4a45eed aio01.dat
    cc1522fb2121cf4ae57278921a5965da *.Zip
    2dc20d55d248e8a99afbe5edaae5d2fc tony31.dat
    f34fa3d0329642615c17061e252c6afe tony32.dat
    051517b5b685116c2f4f1e6b535eb4cb tony33.bat
    da05d6ab72290ca064916324cbc86bab *.LNK
    443a00feeb3beaea02b2fbcd4302a3c9 북한이탈주민의 성공적인 남한정착을 위한 아카데미 운영.lnk
    f6d72abf9ca654a20bbaf23ea1c10a55 국가정보와 방첩 원고.lnk

    Authors: 

    Dixit Panchal
    Kartik Jivani
    Soumen Burma



    Source link

  • The First AI-Powered Ransomware & How It Works

    The First AI-Powered Ransomware & How It Works


    Introduction

    AI-powered malware has become quite a trend now. We have always been discussing how threat actors could perform attacks by leveraging AI models, and here we have a PoC demonstrating exactly that. Although it has not yet been observed in active attacks, who knows if it isn’t already being weaponized by threat actors to target organizations?

    We are talking about PromptLock, shared by ESET Research. PromptLock is the first known AI-powered ransomware. It leverages Lua scripts generated from hard-coded prompts to enumerate the local filesystem, inspect target files, exfiltrate selected data, and perform encryption. These Lua scripts are cross-platform compatible, functioning on Windows, Linux, and macOS. For file encryption, PromptLock utilizes the SPECK 128-bit encryption algorithm.

    Ransomware itself is already one of the most dangerous categories of malware. When created using AI, it becomes even more concerning. PromptLock leverages large language models (LLMs) to dynamically generate malicious scripts. These AI-generated Lua scripts drive its malicious activity, making them flexible enough to work across Windows, Linux, and macOS.

    Technical Overview:

    The malware is written in Go (Golang) and communicates with a locally hosted LLM through the Ollama API.

    On executing this malware, we will observe it to be making connection to the  locally hosted LLM through the Ollama API.

    It identifies whether the infected machine is a personal computer, server, or industrial controller. Based on this classification, PromptLock decides whether to exfiltrate, encrypt, or destroy data.

    It is not just a sophisticated sample – entire LLM prompts are in the code itself. It uses SPECK 128bit encryption algorithm in ECB mode.

    The encryption key is stored in the key variable as four 32-bit little-endian words: local key = {key[1], key[2], key[3], key[4]}. This gets dynamically generated as shown in the figure:

    It begins infection by scanning the victim’s filesystem and building an inventory of candidate files, writing the results into scan.log.

    It also scans the user’s home directory to identify files containing potentially sensitive or critical information (e.g., PII). The results are stored in target_file_list.log

    Probably, PromptLock first creates scan.log to record discovered files and then narrows this into target.log, which defines the set to encrypt. Samples also generate files like payloads.txt for metadata or staging. Once targets are set, each file is encrypted in 16-byte chunks using SPECK-128 in ECB mode, overwriting contents with ciphertext.

    After encryption, it generates ransom notes dynamically. These notes may include specific details such as a Bitcoin address (1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa) this address is the first bitcoin address ever created and ransom amount. As it is a POC, no real data is present.

    PromptLock’s CLI and scripts rely on:

    • model=gpt-oss:20b
    • com/PeerDB-io/gluabit32
    • com/yuin/gopher-lua
    • com/gopher-lfs

    It also prints several required keys in lowercase (formatted as “key: value”), including:

    • os
    • username
    • Home
    • Hostname
    • Temp
    • Sep
    • cwd

    Implementation guidance:

    – environment variables:
    username: os.getenv(“USERNAME”) or os.getenv(“USER”)
    home: os.getenv(“USERPROFILE”) or os.getenv(“HOME”)
    hostname: os.getenv(“COMPUTERNAME”) or os.getenv(“HOSTNAME”) or io.popen(“hostname”):read(“*l”)
    temp: os.getenv(“TMPDIR”) or os.getenv(“TEMP”) or os.getenv(“TMP”) or “/tmp”
    sep: detect from package.path (if contains “\” then “\” else “/”), default to “/”


    – os: detect from environment and path separator:
    * if os.getenv(“OS”) == “Windows_NT” then “windows”
    * elseif sep == “\” then “windows”  
    * elseif os.getenv(“OSTYPE”) then use that valuevir
    * else “unix”

    – cwd: use io.popen(“pwd”):read(“*l”) or io.popen(“cd”):read(“*l”) depending on OS

    Conclusion:

    It’s high time the industry starts considering such malware cases. If we want to beat AI-powered malware, we will have to incorporate AI-powered solutions. In the last few months, we have been observing a tremendous rise in such cases, although PoCs, they are good enough to be leveraged to perform actual attacks. This clearly signals that defensive strategies must evolve at the same pace as offensive innovations.

    How Does SEQRITE Protect Its Customers?

    • PromptLock
    • PromptLock.49912.GC

    IOCs:

    • ed229f3442f2d45f6fdd4f3a4c552c1c
    • 2fdffdf0b099cc195316a85636e9636d
    • 1854a4427eef0f74d16ad555617775ff
    • 806f552041f211a35e434112a0165568
    • 74eb831b26a21d954261658c72145128
    • ac377e26c24f50b4d9aaa933d788c18c
    • F7cf07f2bf07cfc054ac909d8ae6223d

     

    Authors:

    Shrutirupa Banerjee
    Rayapati Lakshmi Prasanna Sai
    Pranav Pravin Hondrao
    Subhajeet Singha
    Kartikkumar Ishvarbhai Jivani
    Aravind Raj
    Rahul Kumar Mishra

     

     



    Source link

  • WinRAR Directory Traversal & NTFS ADS Vulnerabilities (CVE-2025-6218 & CVE-2025-8088)

    WinRAR Directory Traversal & NTFS ADS Vulnerabilities (CVE-2025-6218 & CVE-2025-8088)


    Executive Summary

    Two high-severity vulnerabilities in WinRAR for Windows — CVE-2025-6218 and CVE-2025-8088 — allow attackers to write files outside the intended extraction directory. CVE-2025-6218 involves traditional path traversal, while CVE-2025-8088 extends the attack using NTFS Alternate Data Streams (ADS). Both flaws can be exploited by delivering a malicious archive to a user and relying on minimal interaction (just extraction).

    Why it matters: These flaws enable reliable persistence and remote code execution (RCE) in enterprise environments. Threat actors, including RomCom and Paper Werewolf (aka GOFFEE), have exploited CVE-2025-8088 in active campaigns.

    Vulnerability Overview

    • CVE-2025-6218
      • Type: Directory Traversal during extraction
      • Affected: WinRAR for Windows 7.11 and earlier (before 7.12 Beta 1)
      • Fixed in12 Beta 1
      • Impact: Files can be dropped outside the target extraction directory, e.g., into Windows Startup.
    • CVE-2025-8088
      • Type: Directory Traversal via NTFS ADS syntax (txt: stream)
      • Affected: WinRAR for Windows 7.12 and earlier
      • Fixed in13.
      • Impact: Attackers can hide payloads in ADS or place them into autorun locations for stealthy persistence.
    • Affected Components: WinRAR for Windows (GUI/CLI), UnRAR/UnRAR.dll, portable UnRAR (Windows builds)

    Technical Details

    CVE-2025-6218 – Directory Traversal in Archive Extraction

    Root Cause: The RARReadHeader / RARProcessFile routines in WinRAR fail to normalize or validate relative path components (‘..\’, ‘../’). Attackers can force file writes outside the extraction directory without canonicalizing and bounding the output path.

    Trigger: Any malicious RAR/ZIP archive containing file entries with traversal sequences in their header metadata.

    ExamplePayloadPath:
    ..\..\..\Users\<username>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\malicious.exe

    Impact: File lands in Startup folder → auto-executes on login under user privileges.

    Variant Notes: This exploit works for both absolute and relative extraction destinations. It does not require overwriting existing files — it can create new ones.

    The vulnerability is exploitable whether the archive entry’s stored path is absolute (full system path) or relative (using traversal sequences).

    Absolute path example:
    C:\Users\<username>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\evil.exe
    When extracted, the file is placed directly in the Startup folder, ignoring the chosen extraction directory.

    Relative path example:
    ..\..\..\Users\<username>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\evil.exe
    The ‘..\’ sequences walk up the directory tree from the extraction location, then down into the Startup folder.

    No Need to Overwrite Existing Files: The flaw allows new files to be created in sensitive locations even if they didn’t exist. This enables persistence without replacing trusted binaries, reducing the chance of triggering integrity alerts. Example: Dropping evil.lnk or malware.exe into Startup ensures auto-run on login.

    CVE-2025-8088 – ADS-Assisted Path Traversal

    Root Cause: Same traversal flaw as CVE-2025-6218, but the extraction code also fails to block NTFS ADS syntax in filenames (‘:’ character followed by stream name).

    NTFS ADS Basics: An NTFS file can have multiple data streams: the main unnamed stream (default content) and any number of named alternate streams (e.g., ‘readme.txt: payload.exe’). Windows Explorer and most file listings don’t show ADS, making them useful for hiding content.

    Example Payload Path:
    ..\..\..\Users\<username>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\readme.txt: malicious.exe

    Impact: The payload of a benign-looking file in the Startup folder is stored in ADS. A loader script may execute it later or side-load it via another process.

    Why It’s Worse: ADS hides the malicious binary from casual inspection and some legacy security tools, delaying detection.

    Observed Exploitation: Threat actors use it for stealth persistence plus staging malware for later execution.

    Attack Chain

    1. Prepare Payload: Attacker embeds malicious executable/script in archive using traversal and/or ADS syntax.
    2. Deliver Archive: Sent via email, instant messaging, or malicious download links.
    3. Victim Extraction: User extracts with vulnerable WinRAR/UnRAR.
    4. Silent Path Escape: Payload lands in Startup or other sensitive locations.
    5. Automatic Execution: Runs on reboot/login with user privileges.

    Exploitation in the Wild

    • RomCom: Used CVE-2025-8088 as a zero-day in spear-phishing starting mid-July 2025, delivering backdoors via autorun locations.
    • Paper Werewolf: Observed exploiting similar traversal flaws against Russian targets.
    • Forecast: Expect copycat campaigns — trivial to weaponize, high persistence rate.

    Protection:

    • Trojan.49857.GC
    • Trojan.49856.GC
    • Romcom.49869.SL
    • Ghanarava.1754899322556336
    • Agent.S37377547
    • Agent.S37377548

    Indicators of Compromise (IoCs):

    SHA-256 Detection Name
    49023b86fde4430faf22b9c39e921541e20224c47fa46ff473f880d5ae5bc1f1 Bat.Trojan.49857.GC
    a25d011e2d8e9288de74d78aba4c9412a0ad8b321253ef1122451d2a3d176efa Lnk.Trojan.49856.GC
    4da20b8b16f006a6a745032165be68c42efef9709c8e133e39d4b6951cca5179 Lnk.Trojan.49856.GC
    8082956ace8b016ae8ce16e4a777fe347c7f80f8a576a6f935f9d636a30204e7 Trojan.Ghanarava.1754899322556336

    Others –

    File/Path Patterns

    • Writes to:
      • %APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup\*.exe
    • Presence of ADS (: in filename):
    • Unexpected files outside the intended extraction folder.

    Process/Behavior

    • exe / UnRAR.exe spawning processes (cmd.exe, powershell.exe) post-extraction.
    • ADS creation events (Sysmon Event ID 15).

    Registry/Autorun

    • Dropped Startup files (no registry needed).
    • Monitor HKCU\Software\Microsoft\Windows\CurrentVersion\Run for related changes.

    MITRE ATT&CK Mapping

    • T1059 – Command and Scripting Interpreter
    • T1204 – User Execution
    • 001 – Registry Run Keys / Startup Folder
    • 004 – NTFS File Attributes (ADS)
    • T1027 – Obfuscated Files or Information

    Patch Verification

    • Confirm version 13 on all endpoints.
    • Validate signatures & checksums of installer.
    • Test with crafted traversal/ADS archives to ensure blocking.

    Conclusion

    CVE-2025-6218 and CVE-2025-8088 show how insufficient path validation and overlooked NTFS features can lead to stealthy persistence and RCE. Exploitation requires minimal user interaction, and both flaws have been used in real-world attacks. Immediate patching, combined with proactive hunting for ADS and Startup modifications, is essential for defense.

    References

    1. RARLAB – Official WinRAR Security Advisory (August 2025)
      https://www.rarlab.com/rar/winrar-security.htm
      (Vendor confirmation of affected versions and fixes)
    2. National Vulnerability Database (NVD) – CVE-2025-6218
      https://nvd.nist.gov/vuln/detail/CVE-2025-6218
      (Technical classification, CVSS score, CWE mapping)
    3. National Vulnerability Database (NVD) – CVE-2025-8088
      https://nvd.nist.gov/vuln/detail/CVE-2025-8088
      (Technical classification, CVSS score, CWE mapping)
    4. Malwarebytes Labs – “WinRAR Zero-Day Exploited in the Wild” (August 2025)
      https://blog.malwarebytes.com/
      (Covers RomCom’s exploitation of CVE-2025-8088)
    5. ESET Research – “APT Campaigns Using WinRAR Vulnerabilities”
      https://www.welivesecurity.com/
      (Threat actor campaigns & IOC context)
    6. Microsoft Defender Threat Intelligence – “Detecting ADS Abuse in Windows”
      https://learn.microsoft.com/en-us/windows/security/threat-protection/
      (Guidance on detecting NTFS ADS creation events)
    7. MITRE ATT&CK – Technique T1547.001 (Startup Folder) & T1564.004 (ADS)
      https://attack.mitre.org/
      (Mapping for persistence & hiding techniques)

     

    Authors:

    Nandini Vimal Seth

    Suvarnjeet Milind Jagtap



    Source link

  • Docker Basics in Excel with VBA


    After building a minimal FastAPI + SQLite CRUD application in Docker, I wanted to show how Excel can connect directly to it.
    With a few lines of VBA, we can turn Excel into a client that talks to the API.

    https://www.youtube.com/watch?v=IwUzp85bEDM

    Here are the main commands used in teh demo:


    • SeedTodos – quickly inserts a few sample todos into the API, so we don’t start from an empty sheet.

    • ListTodosToSheet – pulls all todos into Sheet1. It writes ID, Title, and Completed columns, so you can see the live state.

    • DumpTodosToImmediate – prints the same list into the VBA Immediate Window (Ctrl+G). Handy for quick debugging.

    • ?CreateTodo(“Watch VitoshAcademy”, True) – creates a new todo with a title and completed flag. The ? in the Immediate Window prints the returned ID.

    • UpdateTodoTitle 1, “Watch VitoshAcademy” – updates the title of the todo with ID=1.

    • SetTodoCompleted 1, True – marks the same item as completed.

    • GetTodoById 1 – fetches a single item as raw JSON, displayed in the Immediate Window.

    • DeleteTodo 1 – removes the todo with ID=1.

    • DeleteAllTodos – wipes everything in the list (careful with this one!).

    • ListTodosToSheet – refresh the sheet after changes to confirm results.

    • PushSheetToApi – the powerful one: reads rows from Excel (ID, Title, Completed, Action) and syncs them back to the API. That way you can create, update, or delete tasks directly from the sheet.

    With these simple commands, Excel is no longer just a spreadsheet — it’s a lightweight API client. And because the backend runs in Docker, the setup is reproducible and isolated. This small project connects three different worlds — Docker, Python, and Excel VBA. It is a demonstration that APIs are not only for web developers; even Excel can talk to them easily.

    GitHub code: https://github.com/Vitosh/Python_personal/tree/master/YouTube/040_Docker-Basics-With-Excel



    Source link

  • Docker + Python CRUD API + Excel VBA – All for beginners – Useful code


    import os, sqlite3

    from typing import List, Optional

    from fastapi import FastAPI, HTTPException

    from pydantic import BaseModel

     

    DB_PATH = os.getenv(“DB_PATH”, “/data/app.db”)  

     

    app = FastAPI(title=“Minimal Todo CRUD”, description=“Beginner-friendly, zero frontend.”)

     

    class TodoIn(BaseModel):

        title: str

        completed: bool = False

     

    class TodoUpdate(BaseModel):

        title: Optional[str] = None

        completed: Optional[bool] = None

     

    class TodoOut(TodoIn):

        id: int

     

    def row_to_todo(row) -> TodoOut:

        return TodoOut(id=row[“id”], title=row[“title”], completed=bool(row[“completed”]))

     

    def get_conn():

        conn = sqlite3.connect(DB_PATH)

        conn.row_factory = sqlite3.Row

        return conn

     

    @app.on_event(“startup”)

    def init_db():

        os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)

        conn = get_conn()

        conn.execute(“””

            CREATE TABLE IF NOT EXISTS todos(

                id INTEGER PRIMARY KEY AUTOINCREMENT,

                title TEXT NOT NULL,

                completed INTEGER NOT NULL DEFAULT 0

            )

        “””)

        conn.commit(); conn.close()

     

    @app.post(“/todos”, response_model=TodoOut, status_code=201)

    def create_todo(payload: TodoIn):

        conn = get_conn()

        cur = conn.execute(

            “INSERT INTO todos(title, completed) VALUES(?, ?)”,

            (payload.title, int(payload.completed))

        )

        conn.commit()

        row = conn.execute(“SELECT * FROM todos WHERE id=?”, (cur.lastrowid,)).fetchone()

        conn.close()

        return row_to_todo(row)

     

    @app.get(“/todos”, response_model=List[TodoOut])

    def list_todos():

        conn = get_conn()

        rows = conn.execute(“SELECT * FROM todos ORDER BY id DESC”).fetchall()

        conn.close()

        return [row_to_todo(r) for r in rows]

     

    @app.get(“/todos/{todo_id}”, response_model=TodoOut)

    def get_todo(todo_id: int):

        conn = get_conn()

        row = conn.execute(“SELECT * FROM todos WHERE id=?”, (todo_id,)).fetchone()

        conn.close()

        if not row:

            raise HTTPException(404, “Todo not found”)

        return row_to_todo(row)

     

    @app.patch(“/todos/{todo_id}”, response_model=TodoOut)

    def update_todo(todo_id: int, payload: TodoUpdate):

        data = payload.model_dump(exclude_unset=True)

        if not data:

            return get_todo(todo_id)  # nothing to change

     

        fields, values = [], []

        if “title” in data:

            fields.append(“title=?”); values.append(data[“title”])

        if “completed” in data:

            fields.append(“completed=?”); values.append(int(data[“completed”]))

        if not fields:

            return get_todo(todo_id)

     

        conn = get_conn()

        cur = conn.execute(f“UPDATE todos SET {‘, ‘.join(fields)} WHERE id=?”, (*values, todo_id))

        if cur.rowcount == 0:

            conn.close(); raise HTTPException(404, “Todo not found”)

        conn.commit()

        row = conn.execute(“SELECT * FROM todos WHERE id=?”, (todo_id,)).fetchone()

        conn.close()

        return row_to_todo(row)

     

    @app.delete(“/todos/{todo_id}”, status_code=204)

    def delete_todo(todo_id: int):

        conn = get_conn()

        cur = conn.execute(“DELETE FROM todos WHERE id=?”, (todo_id,))

        conn.commit(); conn.close()

        if cur.rowcount == 0:

            raise HTTPException(404, “Todo not found”)

        return  # 204 No Content



    Source link