Category Archives: Uncategorized

Developing complex Suricata rules with Lua – part 2

In part 1 we showed a Lua program to have Suricata detect PDF documents with obfuscated /JavaScript names. In this second part we provide some tips to streamline the development of such programs.

When it comes to developing Lua programs, Suricata is not the best development environment. The “write code & test”-cycle with Suricata can be quite tedious. One of the reasons is that it takes time. It can take 1 minute or more to start Suricata with the new rule, and have it process a test pcap file. And if there are errors in your Lua script, Suricata will not be of much help to identify and fix these errors.

Inspired by Emerging Threats Lua scripts, we adopted the following development method:

Test the script with a standalone Lua interpreter, and move to Suricata for the final tests.

This is one of the reasons why, in part 1, we put the logic of our test in function PDFCheckName which takes a string as input and is called by the match function. By doing this, we can also call (and test) the function from other functions with a standalone Lua interpreter as shown below:

function Test()
    print()
    print(PDFCheckName("testing !!!", true))
    print()
    print(PDFCheckName("testing /JavaScript and more /J#61vaScript !!!", true))
    print()
    print(PDFCheckName("testing /JavaScript and !!!", true))
    print()
    print(PDFCheckName("testing /J#61vaScript !!!", true))
    print()
end

This Test function calls PDFCheckName with different strings as input. We also added extra print statements to the function (see complete source code below), which are activated by the second argument of function PDFCheckName. This boolean argument, bVerbose, adds verbosity to our function when the argument is true.

We can load the Lua program in a Lua interpreter, and then call function Test. One way to do this is type command “lua -i PDFCheckName.lua”, and then type Test() at the Lua prompt. This can all be scripted in a single command like this:

echo Test() ¦ lua -i PDFCheckName.lua

With the following result:

20170306-142115

This “code & run”-cycle is faster than using Suricata, and can be more verbose. Of course, you can also do this with an IDE like Eclipse.

We also added a function TestFile that reads a file (the PDFs we want to test), and then calls PDFCheckName with the content of the PDF file as the argument:

20170306-142208

This produces the following output:

20170306-142242

Being able to test a PDF file directly is also a big advantage, compared to having to create a PCAP file with a http request downloading the PDF file to test.

Conclusion

By using functions and a standalone Lua interpreter, we can significantly improve the development process of Lua programs for Suricata.

Code

-- 2017/02/20

-- echo Test() | lua53.exe -i test.lua
-- echo TestFile() | lua53.exe -i test.lua javascript.pdf

tBlacklisted = {["/JavaScript"] = true}

function PDFCheckName(sInput, bVerbose)
    if bVerbose then
        print('sInput: ' .. sInput)
    end
    for sMatchedName in sInput:gmatch("/[a-zA-Z0-9_#]+") do
        if bVerbose then
            print('sMatchedName: ' .. sMatchedName)
        end
        if sMatchedName:find("#") then
            local sNormalizedName = sMatchedName:gsub("#[a-fA-F0-9][a-fA-F0-9]", function(hex) return string.char(tonumber(hex:sub(2), 16)) end)
            if bVerbose then
                print('sNormalizedName: ' .. sNormalizedName)
            end
            if tBlacklisted[sNormalizedName] then
                if bVerbose then
                    print('Blacklisted!')
                end
                return 1
            end
        end
    end
    if bVerbose then
        print('Not blacklisted!')
    end
    return 0
end

function init(args)
    return {["http.response_body"] = tostring(true)}
end

function match(args)
    return PDFCheckName(tostring(args["http.response_body"]), false)
end

function Test()
    print()
    print(PDFCheckName("testing !!!", true))
    print()
    print(PDFCheckName("testing /JavaScript and more /J#61vaScript !!!", true))
    print()
    print(PDFCheckName("testing /JavaScript and !!!", true))
    print()
    print(PDFCheckName("testing /J#61vaScript !!!", true))
    print()
end

function TestFile()
    local file = io.open(arg[1])
    print()
    print(PDFCheckName(file:read("*all"), true))
    file:close()
end

Analyzing obfuscated scripts using nothing but a text editor

In this blog post, we will perform an analysis on some obfuscated scripts that we received. These files were already detected by automated scanners but as these are mainly malware droppers, we figured it could be interesting to do some manual analysis to determine where the actual malware is hosted.

The first sample we will investigate is a .wsf file. This type of file is a Windows script file and can contain various scripting languages. In this case, we’re dealing with an obfuscated VBScript.

blog_1-image

Due to the obfuscation, it’s impossible to see on first sight what this script is trying to accomplish. We could run it in a virtual machine and dynamically monitor actions taken by the script such as network connections or processes started, but first we’d like to have an idea of the code.

Some script code structures that are interesting to look for are functions that execute commands, such as:

  • Execute
  • Eval
  • ExecuteGlobal
  • Exec

In the script above, we can identify some “eval” statements and “executeglobal”. When the script is started, it will first run “InItIalIZe()”, followed by “ExecGlOBal()”. Let’s take a look at the contents of the Initialize function.

Initialize

The first statement assigns a large encoded string to a parameter. Not much we can do there. The second statement performs a split on the encoded string using “chr(EvAl(31080/740))”. If you calculate 31080/740 from the top of your head, you get 42. Unsurprisingly, using “chr()”, this is translated to “*”, which is used as the splitting character in the obfuscated string. Don’t panic.

In the next step, a loop runs through all the integers from the string above, translates them to characters and appends them to one large string. This string is then passed as the parameter to the “ExecuteGlobal” command.

ExecuteGlobal

We can piggyback on the deobfuscation that the malicious script is already performing by itself. Instead of letting it execute the deobfuscated code in the “ExecuteGlobal” command, we replace this command by something that will print the parameter to output. For Windows scripting, we can do this using “Wscript.echo”.

blog_2-image

Using a command prompt and the “wscript” command, we can run the modified script. Our printing command shows us the decoded output in a pop-up window, which is too small to contain the entire code:

blog_3-image

Copy pasting the entire text is not feasible either. Luckily, there’s an alternative: “cscript”. Using “csript file.wsf > deobfuscated.txt” we can print the deobfuscated string to a new file.

The result is similar to what we started with. We will follow the same approach again and replace the “execute” with a new printing statement and save the script as .vbs. Alternatively, we could surround the script with a “” and “// <![CDATA[
” tag and specify the scripting language in the “” tag. Then we could save and run the script as .wsf, similarly to the original script.

blog_4-image

Now we get something that is actually readable. Nice! On first sight, we can see the script runs some persistence commands, including: writing the script to startup folders and adding some registry keys. This is interesting but these are not the juicy details we were looking for. We’ve added the persistence code below, along with the relevant parameters.

blog_5-image

What follows is a loop that looks a lot more interesting. We can see that it makes a POST call using host and port parameters that are defined at the start of the script. The user-agent is set using pre-defined parameters as well (client & auth). This might allow the malware authors to determine what version of their malware is trying to communicate back to them. This is also a reason why user-agent string monitoring can be interesting for security analysts. Anomalies such as these can easily be detected.

blog_6-image

Based on the result of this POST call, the script continues its execution through one of three functions. All of them make use of the function “D()”, that is defined a bit further in the code, presumably for deobfuscation of the POST response. The two quotes functions seem to be unused (for now).

blog_7-image

If we want to further analyse this script, we need to have a response from the command and control server. The time to actually run the script has come!

Running the script

When executing the script and sniffing the traffic using Wireshark, we can see the POST call flying by, containing the user-agent set by the script. The response is another encoded string, prefixed with “s0”. We can use Wireshark’s “Export Objects” functionality to extract the response. If we go back to the script, we can see a case statement for this string. Looks like “Func0” will be executed on our newly obtained string! Time to let the script do the deobfuscation by replacing the execution command in “Func0” and pasting the obfuscated C&C response in our script! Note that we snipped most of the obfuscated string for the image below. Don’t forget to quit the loop or it’ll keep on running.

blog_8-image

This final script we receive is not obfuscated at all. Looks like this malware is fingerprinting our computer. Adding an additional “echo” command would show us the information contained in the “ret” parameter. We can give you a small hint: it’s our computer and user name, OS, anti-virus,.. being sent through a POST call to the C&C. We have also observed this call in the traffic capture from before, so we could export the contents through Wireshark as well. There’s a sample of the AV fingerprinting code below.

blog_9-image

Unfortunately, we won’t be able to figure out what the other functions (Func1 & Func2) do, since the command and control server did not send us any other command. Some possible causes could be that it decided our system is not interesting based on the information it received or it might just have been in an information gathering phase. If you want more information on this malware, look for Houdini!

Maldoc: It’s not all VBA these days

Since late 2014 we witness a resurgence of campaigns spamming malicious Office documents with VBA macros. Sometimes however, we also see malicious Office documents exploiting relatively recent vulnerabilities.

In this blog post we look at a malicious MS Office document that uses an exploit instead of VBA.

The sample we received is 65495b359097c8fdce7fe30513b7c637. It exploits vulnerability CVE-2015-2545 which allows remote attackers to execute arbitrary code via a crafted EPS image, aka “Microsoft Office Malformed EPS File Vulnerability”. In this blog post we want to focus on extracting the payload.

A more detailed explanation on the exploit itself can be found here (pdf).

Analysis

The sample we received is a .docx file, with oledump.py we can confirm it doesn’t contain VBA code:

screen-shot-2017-02-06-at-10-51-58

With zipdump.py (remember that the MS Office 2007+ file format uses ZIP as a container) we can see what’s inside the document:

Screen Shot 2017-02-06 at 11.03.02.png

Looking at the extensions, we see that most files are XML files. There’s also a .gif and .eps file. The .eps file is unusual. Let’s check the start of each file to see if the extensions can be trusted:

screen-shot-2017-02-06-at-11-09-46

This confirms the extensions we see: 12 XML files, a GIF file and an EPS files. As we know are exploits for EPS, we took a look at this file first:

screen-shot-2017-02-06-at-11-58-26

The file contains a large amount of lines like above, so let’s get some stats first:

Screen Shot 2017-02-06 at 11.52.35.png

byte-stats.py gives us all kinds of statistics about the content of the file. First of all, it’s a large file for MS Office documents (10MB). And it’s a pure text file (it only contains printable characters (96%) and whitespace (4%)).

There is a large amount of bytes that are hexadecimal characters (66%) and BASE64 characters (93%). Since the hexadecimal character set is a subset of the BASE64 character set, we need more info to determine if the file contains hexadecimal strings or BASE64 strings. But it very likely contains some, as there are parts of the file (buckets) that contain only hexadecimal/BASE64 characters (10240 100%).

base64dump.py is a tool to search for BASE64 strings (and other encodings like hexadecimal). We will use it to search for a payload in the EPS file. Since the file is large, we can expect to have a lot of hits. So let’s set a minimum sequence length of 1000:

screen-shot-2017-02-06-at-12-11-31

There are 4 large sequences of BASE64 characters in the document. But as the start of each sequence (field Encoded) contains only hexadecimal characters, it’s necessary to check for hexadecimal encoding too:

screen-shot-2017-02-06-at-12-14-46

With this output, it’s clear that the EPS file contains 4 large hexadecimal strings.

Near the start of the decoded string 2 and 4, we can see characters MZ: this could indicate a PE file. So let’s check:

Screen Shot 2017-02-06 at 12.19.55.png

This certainly looks like a PE file. Let’s pipe it through pecheck.py (we need to skip the first 8 bytes: UUUUffff):

screen-shot-2017-02-06-at-12-32-10

This tells us that it is definitively a PE file. With more details from pecheck’s output, we can say it’s a 64-bit DLL. It has a small overlay:

screen-shot-2017-02-06-at-12-36-22

Since this overlay is actually just 8 bytes (UUUUffff), it’s not an overlay, but a “sentinel” like at the start of the hexadecimal sequence. So let’s remove this:

screen-shot-2017-02-06-at-13-43-24

We did submit this DLL to VirusTotal: 30ec672cfcde4ea6fd3b5b14d6201c43.

It has some interesting strings:

screen-shot-2017-02-06-at-13-18-04

Like the string of the PDB file: GetDownLoader. And a PowerShell command to download and execute an .exe (the URL is readable).

Also notice that the string “This program can not be run in DOS mode.” appears twice. This is a strong indication that this DLL contains another PE file.

Let’s search for it. By using the –cut operator to search for another instance of string MZ, we can cut-out the embedded PE file:

screen-shot-2017-02-06-at-13-56-17

We also submitted this file to VirusTotal: 2938d6eda6cd941e59df3dd54bf8dad8. It is a 32-bit EXE file.

The hexadecimal string with Id 4 found with base64dump also contains a PE file. It is a 32-bit DLL (ce95faf23621a0a705b796c19d9fec44), containing the same 32-bit EXE as the 64-bit DLL:  2938d6eda6cd941e59df3dd54bf8dad8.

Conclusion

With a steady flow of VBA maldocs for over more than 2 years, one would almost forget that Office maldocs with exploits are found in-the-wild too. If you just look for VBA macros in documents you receive, you will miss these exploits.

In this sample, detecting a payload was not too difficult: we found an unusual file (large .eps file) with long hexadecimal strings that decode to PE-files. It’s not always that easy, especially if we are dealing with binary MS Office files (like .doc).

In this post we focus on a static analysis method to extract the payload. When performing analysis on this file yourself, be aware that this maldoc also contains shellcode (strings 1 and 3 found by base64dump) and an exploit to break out of the sandbox (protected view).

A practical guide to RFID badge copying

During red teaming assignments we are sporadically asked to attempt to gain access to certain physical “flags”. These flags could be the inside of a server room, or the workstation of a member of the management team.

Aside from these red teaming assignments, in most organisations, access badges are often the single factor of security that stands between us and the inside of a building, a server room or an office. There are many different RFID card reading systems on the market. Unfortunately, the security they provide is often lacking. With this blog post we want to demonstrate how easy it is to bypass the card reader security mechanism when it is insufficiently secured.

Specialised hardware is required to clone existing RFID cards, this hardware can easily be obtained and is relatively inexpensive. For this case study, we use the Proxmark3, which is a device developed by Jonathan Westhues that allows sniffing, reading and cloning of RFID (Radio Frequency Identification) tags.

DISCLAIMER: This blog post, and by extent any other blog post written by NVISO LABS, are intended for educational purposes only. It is not intended and should not be used for the illegitimate cloning of RFID badges without prior permission.

proxmark3_pic1

Cloning and abusing the card

Below we’ll provide a step by step example on how to clone an HID global RFID card. Note that the Proxmark3 is able to copy many different types of cards.

We have two types of antennas that we can connect to our Proxmark3: a low frequency one and a high frequency one. The low frequency card, operating at 125kHz and 134kHz, can communicate with e.g. HID Prox II, HITAG, and EM4100 tags. The high frequency card, operating at 13.56Mhz, can communicate with e.g. Mifare Classic/Ultralight and iClass tags.

After starting up the proxmark3 interface, we can run the“hw tune”command to see if any card is detected. Currently the LF antenna is connected to the Proxmark3 and at this point there is no card in the presence of our LF antenna.

proxmark3_pic4

When repeating the “hw tune” command, this time with the card within reach of our antenna, we see a clear difference in voltage in comparison with the previous screenshot. This indicates we are dealing with a low frequency card.

proxmark3_pic5

Our next step is finding the type of card we have. Using the “lf search” command we can scan the card. Before executing this command, make sure the card is already on the antenna. If not, the search command will return errors.

proxmark3_pic6

The proxmark3 confirms we are working with a HID global RFID card and we discover its ID: 07848XXXX (redacted). Now we need to use the according command to clone the card.

Using the Proxmark3 help function for the HID cards, we see we can use the clone function.

proxmark3_pic7

The T55x7 you see in the output above, is a type of card that is extremely versatile and supports multiple encoding formats of the majority of 125 Khz RFID tag transponders. We can thus use this type of card to emulate our HID card.

proxmark3_pic8

After executing the command above, including the HID Prox TAG ID identified in the previous steps, we have successfully cloned our card.

That’s all it takes!  Check the video below for proof.

On a final note, when your office building is protected by such an insecure card reading system, often the only solution to fix this vulnerability is to replace the card reading infrastructure and all access badges. Needless to say this will have a significant impact on your organisation.

The following recommendations can be made to improve the security:

  • Use of encryption to ensure that the ID is not sent in clear text. Think of challenge response authentication;
  • Use of contactless smart cards which have encryption, mutual authentication and message replay protection incorporated.

Additionally, it is known that attackers try to covertly copy your RFID cards, for example during a trip on the metro. You can try using an RFID protected sleeve/wallet, but research has shown that not all of them are effective at preventing covert copying. Be sure to test yours out and share your findings!

A 30-minute sweep of Industrial Control Systems in Belgium

TLDR; We found several ICS systems in Belgium that were exposed to the internet without requiring any authentication. Screenshots below.

Update 19/12: We’ve also had some coverage in the media about this research. ‘De Standaard‘ did an article about it and so did ‘Datanews’ (in Dutch and in French).

Industrial Control Systems (ICS) is the general term for electronic control systems used in industrial production. The term encompasses everything from supervisory control and data acquisition (SCADA) to Programmable Logic Controllers (PLC) – often found in industrial and critical infrastructures.

These systems were once state-of-the-art controllers for heavy industry, but nowadays they are included in many HVAC (Heating, Ventilation and Air Conditioning), home automation and even industrial livestock feeding systems. These systems are installed in many corporations – big and small – but also at home.

ICS Security

ICS Security has been a big issue since Stuxnet[1]. Stuxnet was one of the first – and very advanced – malware specifically targeting ICS appliances. Since then, we’ve seen a steady flow of ICS targeted malware, simple and advanced alike[2]. One of the reasons ICS is being heavily targeted, is because of the criticality of the appliances that it controls, but also because most ICS systems have not been designed for security. To make matters worse, many ICS installations are poorly incorporated into existing networks. Today, still many ICS appliances are connected to the internet without any proper authentication. This means that actors with bad intentions could gain access to these critical systems with little to no effort.

Since NVISO is a Belgian company (and thus most of our clients are Belgian or have a Belgian office), we decided to take a quick peek into the security of Belgian ICS systems.

“How many of those systems would we be able to find in Belgium with little effort”, we thought…

Shodan

In comes Shodan[3]. Shodan is the first search engine for internet-connected devices. It allows you to easily search throughout the internet for specific appliances and protocols. We only used Shodan in throughout this research and have only used simple search syntax.

ics-10

30 minutes later

Using our knowledge about ICS systems (some vendors, some protocols), we started investigating the Belgian internet-space. The results were worrisome. Within only 30 minutes, we managed to find at least 9 instances of Belgian ICS systems that were connected to the open internet, without requiring authentication. We found heating systems, ventilation systems, building control systems, delivery acceptance systems, home automation systems, camera systems and even an automatic feeding system of a farm.

Next to these ICS systems, we also found a big volume of Belgian Point-of-Sale (PoS) systems. Luckily, almost no Belgian PoS is equipped with a card reader – and thus no credit card details would be retrieved upon compromise – but there’s still a risk here concerning customer’s data. Next to that it could be used as an entry point into the corporate network. Probably not a good idea to have those directly connected to the internet.

All the ICS systems that we found using Shodan, used a VNC server for remote access. TCP/5900 was in open state and authentication was disabled. We have stopped seen these horrible things in corporate environments, but apparently they still exist in the ICS world…

Remediation

If your ICS system needs to be remotely controlled, we would recommend to use a secure connection towards it (VPN, white listing IP’s, etc.) and enforcing a decent authentication (long and complex password/passphrase, no anonymous login). Since many ICS systems still don’t give you decent authentication out-of-the-box, make sure to put it behind a managed network and enforce decent authentication (and logging!), e.g. by using a jump server.

We will contact all identified companies with our findings and will offer them help with any potential remediation. In Belgium, this sort of ‘notification’ is still in a gray zone, legally speaking. Luckily, the Centre for Cybersecurity Belgium (CCB) is looking into proposing a ‘responsible disclosure’ law[4].

Raise Awareness

With this 30-minute research, we wanted to raise awareness about the criticality of ICS and other internet-attached systems and their lack of security. While companies are slowly but steadily investing more and more into information security, they often overlook ICS systems. Next to the end-user responsibility, we want to stress that a part of the responsibility is to be shared with the vendors and installation companies. We often see that they make no effort to secure these systems or offer no guidelines towards secure installation.

The loot

Disclaimer: We have removed all Personal Identifying Information from the screenshots below. We have not accessed any system; the screenshots were taken by Shodan. All screenshots listed below have been identified as originating from a system located in Belgium.

 

ics-1

The interface of a Tolsma storage technology climate control system

ics-2

The logon screen of a PoS system. While this system requires authentication, these versions of windows embedded often contain multiple vulnerabilities and should not be exposed unfiltered to the internet.

ics-3

The interface of a building heater system.

ics-4

The interface of a camera module for the Tolsma Storage Technology appliance.

ics-5

Again, an interface of a building heater system.

ics-6

The interface of an intercom system.

ics-7

The interface of a home automation system.

ics-8

The interface of a feeding machine for livestock.

ics-9

The interface of a Tritone Automatic Feeding System.

[1] https://www.wired.com/2014/11/countdown-to-zero-day-stuxnet/

[2] https://www.fireeye.com/blog/threat-research/2016/06/irongate_ics_malware.html

[3] https://www.shodan.io

[4] http://datanews.knack.be/ict/nieuws/ethisch-hacken-bijna-legaal-in-belgie-want-alles-zit-vol-lekken/article-normal-787153.html

Testimonial of Stefaan Truijen

Hi, I’m Stefaan Truijen and in 2014-2015 I did my master thesis at the department of computer science at KULeuven. I assessed the susceptibility of modern web browsers to RAM scrapers in collaboration with NVISO. Security had always been one of my passions, so I was excited to get started.

Writing a thesis is an intensive process. Happily, I was able to rely on both Arne (NVISO) and Raoul (KULeuven) throughout the entire year for advice/brainstorming.

First, I needed to get an overview of prior research on memory scraping. Arne supplied me with a couple of initial research documents and references, and I reviewed any new material I found with Arne and Raoul almost weekly.

After some preliminary tests, I had to determine how I would continue and I wanted to contribute at least a little bit to fighting memory scrapers. I was able to bounce a few ideas off Arne and Raoul. In the end we decided that, since I was unable to find any prior research that had already assessed the size of the problem – i.e. memory scraping web browsers – measuring the degree of susceptibility of each of the three most commonly used web browsers (Chrome, Firefox, IE) was the most interesting angle.

In order to get a sufficient amount of data to form a solid conclusion, I ran thousands of experiments. Of course, running thousands of experiments manually is not very efficient and it affects reproducibility of the results. Therefore I learned how to work with new tools. Most relevant were Selenium’s automated testing framework for web browsers and the Windows API. Whenever I had questions, Arne and Raoul gladly answered them.

Now that the dust has settled, I can say that I have acquired a deeper understanding of low level security, more specifically memory scraping, and the consequences of relatively relaxed memory and API access policies that I did not have before. I am very satisfied with the result of my thesis and NVISO played an important role in realizing it!

Testimonial of Nick Van Haver

Hi, I’m Nick Van Haver and I want to reflect briefly on my master thesis which I have worked out in cooperation with NVISO and the Ghent University. NVISO helped me in many ways while providing me with a lot of freedom to choose the course of my thesis. They showed me a lot of trust and respect, which I truly appreciate.

The topic of my thesis research was “The Detection of Client-side Vulnerabilities in Web Applications through the Browser”. This topic is deeply rooted in the field of web application security, and thus lead me far beyond its basics. At first I had quite some experience with the development of web applications, but far less with relation to their security aspects.

When looking into a new field or topic, it is hard to find the right sources and high quality references. The right resources can turn a week’s worth of work into a single day. NVISO provided me with these resources and handed me tools, enabling me to educate myself in the web application security field and to make the most out of my thesis. Thanks to NVISO, I had contact with some of the big names in the industry such as Google, Minded Security, Portswigger and many others. Furthermore they assisted me with their expertise in security during meetings.

In the end, my research resulted in a fairly high score of 16 out of 20. Because of these grades I graduated magna cum laude as a Civil Engineer in Computer Sciences. At the beginning of my thesis my knowledge on web application security was rather limited. Now I feel accomplished in this field of security and I now know where to find the most correct information when dealing with web application vulnerabilities. I now also feel more confident when contacting external parties.

I can highly recommend working with NVISO. Choosing to work together with them for your master thesis ensures you that the topic will be both challenging and interesting. You will receive the support and resources you need to achieve your goal. It really is a worthwhile experience! Once the results of my thesis are public, they will be shared with the community!