Windows malware on linux

Linux Malware Detect — антивирус для веб-серверов

Интернет уже не тот, что прежде — кругом враги. Тема обнаружения непосредственного заражения сайта и поиска вредоносных/зараженных скриптов на взломанном сайте рассмотрена слабо, попробуем это исправить.
Итак, представляем вашему вниманию Linux Malware Detect.

Linux Malware Detect (LMD) — это сканер для Linux, предназначенный для поиска веб-шеллов, спам-ботов, троянов, злонамеренных скриптов и прочих типичных угроз характерных для веб-пространств и особенно актуален для виртуальных шаред-хостинг платформ. Главное отличие от прочих Linux-антивирусов — его веб направленность, сканирование файлов веб-сайтов, ведь обычные антивирусы ориентируются на более глобальные угрозы уровня системы.

Что умеет

  • Поиск угроз по базе MD5 и распознавание типа угрозы (например, php.cmdshell.nan.296.HEX) по HEX-базе.
  • Статистический анализ файлов на наличие обфусцированных зловредов и инъекций.
  • Обнаружение установленного в системе ClamAV для использования его в качестве сканера.
  • Ручное и автоматическое (по крону) обновление сигнатур.
  • Ручное и автоматическое обновление версии самого скрипта.
  • Возможность сканирования недавно добавленных/измененных файлов (например за последние 2 дня).
  • Опция загрузки обнаруженных потенциальных угроз на официальный сайт для анализа.
  • Система отчетов.
  • Очистка файлов от вредоносных инъекций.
  • Крон-заготовки для запуска регулярного сканирования юзерспейсов или других директорий.
  • Наборы исключений по расширениям, сигнатурам и путям.
  • Возможность отправки результатов сканирования на e-mail.
  • Мониторинг в реальном времени созданных/модифицированных/измененных файлов при помощи inotify_watch: мониторинг выбранных пользователей, каталогов или файлов.
  • … и прочее.

Как это работает

Сканирование происходит с использованием собственного скрипта на базе grep, а если в системе установлен ClamAV — то при помощи clamscan. Аналогично с сигнатурами: программа имеет свою базу сигнатур, если же в системе установлен ClamAV, то использует дополнительно и его базу.

Источники сигнатур:
  1. Срез данных сети. Разработчик LMD является администратором хостинга на 35.000 сайтов, данные ежедневно анализируется и обрабатываются. Основной источник сигнатур.
  2. Данные сообщества собранные с антималвар-сайтов.
  3. ClamAV, взаимообмен сигнатурами.
  4. Данные, присылаемые пользователями.

Сигнатуры обновляются практически ежедневно, RSS-лента с обновлениями сигнатур присутствует на официальном сайте.

Результаты сканирования сохраняются в файл, а также могут высылаться на указанный в конфиге e-mail. Интеграции с популярными панелями управления, увы, нет, если же вы хостер — сообщения клиентам придется рассылать вручную.

Интеграция с популярными панелями ISPmanager и Cpanel была бы неплохим вкладом в сообщество (это в случае если кто желает).

Что это дает

Типичные примеры обнаружений

Отчет о сканировании выглядит следующим образом:

Установка

При запуске install.sh программа установки размещает файлы LMD в /usr/local/maldetect, заносит исполняемый скрипт в /usr/local/sbin и libinotifytools.so.0 в /usr/lib.

В процессе инсталляции автоматически создаются ежедневные крон-задания для обновления сигнатур и запуска сканирования. По умолчанию в конфигурации указаны типичные пути для сканирования вебспейсов популярных панелей управлений, таких как ensim, psa, DirectAdmin, cpanel, interworx и дефолтных apache-путей размещения сайтов (/var/www/html, /usr/local/apache/htdocs). Для ISPmanager путь /var/www/ придется добавлять вручную.

Настройка

Конфиг LMD находится в файле /usr/local/maldetect/conf.maldet.
Конфиг хорошо документирован и позволяет настроить все, что душе угодно.

На заметку:

ionice -c 3 добавленный к строкам запуска скриптов по поиску и сканированию файлов поможет предотвратить нагрузку на дисковую подсистему выставив наинизший приоритет i/o.

В файле /usr/local/maldetect/maldet
находим:

Стоит отметить, что данное решение — своего рода «костыль», данную опцию стоит добавить в апстрим.

Читайте также:  Windows 10 гаснет монитор при простое

Типичные команды

Запускаем сканирование указанного каталога:

По окончанию получаем результат вида:

Принудительно обновляем базы с rfxn.com:

Принудительно обновляем версию с rfxn.com:

Сканируем все изменные за последние X дней файлы (в данном случае 2) в указанном каталоге

Отправляем неизвестную уязвимость на rfxn.com:

Помещаем в карантин результаты сканирования SCANID (id из результатов сканирования)

Пытамся очистить результаты сканирования

Программа распространяется по лицензии GNU GPLv2.
Официальная страничка проекта: http://www.rfxn.com/projects/linux-malware-detect Linux Malware Detect.

Имею опыт использования и настройки, на все вопросы с удовольствием отвечу в комментариях.

Источник

Executing Windows malware in Windows Subsystem for Linux (Bashware)

A blogpost that shows a practical approach to setting up malware to run on Windows using the Linux subsystem and wine to avoid detection.

Origin Story

I did a talk recently at the Bangalore null/OWASP meetup where I spoke about and demoed the concept of the research done by Check Point Security folks, called Bashware.

Bashware (bash+(mal)ware) is the idea of running Windows binaries (malware) in the Windows Subsystem for Linux (WSL) using wine support. This allows for some programs (not all Windows PE executables though) to be run inside WSL while being shielded from system inspection tools like Antivirus solutions, process monitor etc.

While setting up the demo for this talk, I realised that the speed of execution that is shown in the video released by Check Point Security was very likely not possible as it took me couple of hours of setup and downloading/installing of components required to make this run from scratch. In the video, a binary called malware.exe is run and within a minute the binary does the following

  1. Enables WSL
  2. Enables Developer Mode
  3. Installs WSL
  4. Installs wine
  5. Executes nc.exe -lvp 1337 via wine

In my opinion, the malware.exe simply runs the last command while everything else is already setup on the system. Let’s go ahead and build a PoC and see what we happens.

Let’s build a PoC!

In any case, if you want to try setting this up, here are the commands that worked for me. This is 5 step process at the very least. You will need to be on a Windows 10 64 bit Edition machine with Windows 10 version higher than the Anniversary Update (version 1607).

Step 1: Enable WSL

The Windows Subsystem for Linux can be enabled either by using the dism binary using an elevated command prompt or using Powershell’s Enable-WindowsOptionalFeature module as shown below. A reboot is required after this step

Step 2: Enable Developer mode (Optional)

Developer Mode in Windows 10 allows developers to install and test unsigned applications and was required to install WSL, but post 16215, you no longer have to enable Developer Mode to install WSL. I ran into some installation issues though which did not recur once I had enabled Developer Mode, so including this step here.

To enable Developer Mode, go to Settings -> Update & Security -> For Developers and click on the Developer mode radio button and click Yes on the message box that is shown

To script this or to do this via a command prompt, we can use the reg command to add registry values directly. The following command sets the required values in the Windows registry (requires elevation).

Step 3: Install WSL and Linux components

This can be done via the Turn Windows features on or off applet as shown below

or using the command prompt with the lxrun command

Step 4: Install wine inside WSL

Wine (originally an acronym for “Wine Is Not an Emulator”) is a compatibility layer capable of running Windows applications on several POSIX-compliant operating systems, such as Linux, macOS, & BSD. Instead of simulating internal Windows logic like a virtual machine or emulator, Wine translates Windows API calls into POSIX calls on-the-fly, eliminating the performance and memory penalties of other methods and allowing you to cleanly integrate Windows applications into your desktop.

Basically, Wine allows you to run Windows programs on Linux by translating Windows API calls to Linux (POSIX) equivalent API calls. Not all Windows programs can be run using Wine though, however there are a large number of programs that do work.

Читайте также:  Засыпают usb порты linux

Anyways, Wine is required to run the Windows binary (malware) to complete this PoC for bashware. You can do this using a bash terminal in WSL. Open cmd and type bash and press enter to launch the WSL environment. In bash, type the following commands to enable 32 bit architecture support, add the Wine PPA, download and update the package lists from the repositories and finally install wine.

Step 5: Download and run netcat 64 bit using wine

This was the trickiest of all the steps. The original research article on the Check Point Security website does not mention the binary type that will be eventually executed, although there are hints throughout the article.

Looking at the video and pausing at 0:12 seconds I realized that the netcat binary used in the video was the original Hobbit version compiled by someone into its 64 bit equivalent on 26th December 2010. Using a little bit of Google search I found the exact binary that was used in the video, which I subsequently used in the demo as well.

So go ahead and grab a copy of netcat 1.11 from https://eternallybored.org/misc/netcat/

(You can compare the Date Modified of the files in the video and this download and chuckle along :D)

Finally, to run the netcat and complete the PoC, cd to the directory where you unzipped the download and run the following command (all in bash, obviously). You may very likely see multiple preloader: Warning: failed to reserve range 00007ffffe000000-00007fffffff0000 . You can ignore these warnings and proceed.

This will run the netcat binary inside WSL using wine. The netcat parameters in this command cause it to verbosely listen on port 1337 and execute and send STDIN, STDOUT and STDERR of cmd.exe back to the connecting client.

You can verify if the port is open using netstat or TCPView

From a different machine or another command prompt window on the same computer connect to the open port using another copy of netcat (I used the nmap version) as such:

Is this really stealthy?

Once the connection was established, I wanted to see if this can be detected by some common Windows system inspection tools. I used TCPView, Process Explorer and Process Monitor. The results were interesting as expected.

Using TcpView

TCPView provides a graphical UI to view all network connections, the teardowns and new connections being made along with the process information of the PID that created the connection.

In this case, TCPView was able to list the open port, attributing it to wineserver, but was unable to get more information.

Using Process Explorer

Process Explorer was able to detect the wine64-preloader and the wineserver, but beyond that very little information was available.

The process memory and network listening status was all that was available in Process Explorer. The error message shown in place of the path is shown when (amongst other things) the handle of a privileged process, opened with PROCESS_QUERY_LIMITED_INFORMATION, is used to call QueryFullProcessImageName

Читайте также:  Kde apps on windows

Using Process Monitor

I had better luck with Process Monitor in looking at the process and the execution path. I would highly recommend trying this out on your own setup as the number of entries is just too many to go into details.

The wine64 binary path (on the Windows Filesystem) was detected as well as several CreateFile , ReadFile and CloseFile references to nc64.exe by a process that had no name or path (!?). The LXCORE.SYS driver was also visible in the stack of the process with various API calls to execute and manage the wine64 invocation of nc64.exe .

Final Thoughts

In my opinion, the video and research published by the folks at Check Point Security had some glaring and obvious holes in it. But given the overall simplicity of execution and the absence of proper tools to inspect and analyze Windows binaries running through Wine through WSL (whew!), this can become very tricky very fast.

To be fair, it really is a lengthy process, requiring privileged execution, multiple reboots and Internet access. No wonder Microsoft downplayed the whole thing as is. However, it cannot be denied that this is a cool technique at camouflaging execution.

As is always with any untrusted sources, practice caution when opening email attachments or executing downloaded content.

Источник

Using linux to combat windows flash drive malware?

I just put an old flash drive which i used with a windows machine into my linux. I noticed many files, mostly exes which were never visible in windows (my windows does not hide hidden files and extensions). Most of those strange files had malware like names. I changed the properties of these files so that linux would allow me to delete them. It worked and now the drive seems to be fully clean.

If a windows malware in a flash drive can hide itself from windows, can it also hide itself from linux ? If not, then cleaning windows malware on a flash drive becomes easy.

7 Answers 7

Yes there’s a way to hide the a file from Windows’ and Linux’s file explorers, which is to start the file name with a dot . and set the h and s flags. In Windows that can be done by using the command line

Now the file cannot be seen by File Explorer, Nautilus, or Konqueror in their default settings on clean machines.

When you plug your flash disk in a Linux machine and open it using Nautilus, you may press Ctrl + H to show all hidden files. A better solution is to use your favorite shell to run this command in the flash disk’s mounted directory.

Note: If you «clean» the flash drive using Linux and then plug it back in the suspicious Windows machine, you can assume that it’s infected again.

Update: I’ll try to address your newly expressed concerns from a real-world and practical point of view.

First, in theory. There is a chance that the Linux machine is infected with malware that forces it to hide certain files (namely other malware files). But in reality, the chances are very slim. But like anything in security, you can never be sure.

Practically speaking, plugging your infected flash disk in a Linux machine and removing all the bad files (assuming you do know what all the bad files are) guarantees with a high probability that your flash disk is now clean. As long as you don’t plug it back in the infected Windows machine, it’s safe to use amongst other clean Windows machines (assuming you are sure about which machines are clean).

Источник

Оцените статью