What is memory dump in linux

Linux Memory Analysis: How to Start and What You Need to Know

Are you ready to dive into the exciting world of memory analysis. No? Well that’s too bad because you need to know it. There’s an old saying in InfoSec, “The packet doesn’t lie.” Well the same is true for memory analysis. It simply is what it is and because of that, can provide a wealth of information concerning a systems state. In some ways it’s similar in nature to our previous “Threat Hunting with Bro IDS” article.

This will probably be a multi part series. With this first post covering the basics of capturing memory images in Linux using LiME and testing with Volatility. Which is a great start for memory analysis. And another article digging much deeper into using my favorite memory analyzer Volatility.

Working with memory dumps in Linux is rather different than when dealing with Windows. But don’t worry little Padawan, it’s almost certainly worth it. Ok so before we begin.

Here’s what will happen at a high level:

1) We’ll first make sure our Ubuntu 16.04 Server box is completely upgraded.
2) Next we will install the proper dependancies for both LiME and Volatility.
3) We’ll install and configure LiME.
4) Then we’ll install and configure Volatility.
5) Finally we’ll create a test memory dump for the memory analysis. And use it to test that Volatility is working.

First make sure we’re starting off in our home directory. In my case it’s
/home/i3carebears

System Update and Dependancies

Now let’s start the installation. We’ll start by making sure our system is up to date. Then that all of the dependancies needed have been installed.

sudo apt-get update sudo apt-get upgrade sudo apt-get install build-essential sudo apt-get install linux-headers-`uname -r` sudo apt-get install git python dwarfdump zip python-distorm3 python-crypto

Installing LiME for Linux Memory Analysis

Next let’s get LiME installed and configured.

git clone https://github.com/504ensicsLabs/LiME cd LiME/src/ make

We’re interested in the last line of the “make” output which shows us the kernel we need to use. In my case it’s lime-4.4.0-89-generic.ko. And now we can load our kernel module.

sudo insmod lime-4.4.0-89-generic.ko "path=/tmp/test.mem format=lime”

The above command has loaded LiME and created our test snapshot of the systems memory that we’ll use for the forensic test analysis and placed it in the /tmp directory with the name “test.mem”. The “format=lime” is the default LiME format that we’ll save the memory image in. Volatility can easily recognize the lime format so this works out best. See, linux memory analysis isn’t as tough as you thought!

Читайте также:  Usb modeswitch для linux

Installing Volatility

Now we need to create our Linux profile so that we can tell Volatility exactly what system/kernel we’re on. We begin by installing Volatility.

cd ../../ git clone https://github.com/volatilityfoundation/volatility cd volatility/tools/linux/ make clean make

Out next step is to locate our system map which tells Volatility how are memory analysis snapshot is structured. In Ubuntu this can typically be found in /boot/ so,

Creating Volatility Profile

We’ll be using the System.map-4.4.0-89-generic file as it matches our lime-4.4.0-89-generic.ko file. We saw this when we first installed LiME. Now we’re going zip up both the module.dwarf file made by Volatility and our System map which results in creating the profile we need for Volatility to work properly. This step is vital for our memory analysis to not have issues.

cd ../../ sudo zip volatility/plugins/overlays/linux/Ubuntu160403-040400-89.zip tools/linux/module.dwarf /boot/System.map-4.4.0-89-generic

Running Volatility

Now we’ll check to see that Volatility has everything it needs to run properly.

python vol.py --info | grep Linux

As we can see Volatility now has the proper profile to use. In my case it’s called LinuxUbuntu160403-040400-89×64.

Let’s look and see what kind of plugins we can have Volatility run on our Linux memory snapshot. To do this we’ll run the following command.

python ./vol.py --info | grep -i linux_

Now let’s pick an interesting plugin and run it against our saved memory snapshot located in /tmp. The linux_bash is pretty interesting because it should show us the Bash commands that were ran prior to taking our snapshot.

sudo python vol.py -f /tmp/test.mem --profile=LinuxUbuntu160403-040400-89x64 linux_bash

You’ll notice that in this case we needed to run the command as “sudo”. As a result of us creating the memory snapshot /tmp/test.mem we ran “insmod” under “sudo” but you could simply change the test.mem file permissions if you wanted to.

Читайте также:  Linux virbr0 what is

Sending Memory Dumps over Network

Although we won’t get into it in this article, I wanted to let you know that you can also send the memory snapshots over the network if you wanted to another box. There are a lot of options with this but a simple example would look like this.

sudo insmod lime-4.4.0-89-generic.ko "path=tcp:7777 format=lime" nc localhost 7777 > ram.lime

Finally, this has just a small taste into the wonders of Linux Memory Analysis. In another article we’ll start to deep dive into Memory Forensics using Volatility so make sure to follow me on Twitter at https://twitter.com/jamesbower to know when that comes out.

And as always, thank you for taking the time to read this. If you have any comments, questions, or critiques, please reach out to me on our FREE ML Security Discord Server – HERE

Источник

Core dump (Русский)

Состояние перевода: На этой странице представлен перевод статьи Core dump. Дата последней синхронизации: 15 февраля 2022. Вы можете помочь синхронизировать перевод, если в английской версии произошли изменения.

Дамп памяти (core dump) — это файл, в который записывается адресное пространство (память) процесса при его нештатном завершении. Дампы ядра могут создаваться по требованию (например, отладчиком) или автоматически при завершении процесса. Дампы памяти создаются ядром при сбое программы и могут быть переданы вспомогательной программе (например, systemd-coredump(8) ) для дальнейшей обработки. Дамп памяти обычно не используется обычным пользователем, но может быть передан разработчикам по их запросу, которым будет очень полезно иметь снимок состояния программы на момент сбоя, особенно если сбой трудно воспроизвести.

Отключение автоматических дампов памяти

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

  • Производительность: создание дампа для процессов, занимающих много памяти, может привести к трате системных ресурсов и задержке очистки памяти.
  • Дисковое пространство: дампы процессов, занимающих много памяти, могут занимать место на диске, равное, а то и большее, чем объём памяти процесса, если их не сжимать.
  • Безопасность: хотя дампы обычно может читать только root, они могут содержать конфиденциальные данные (например, пароли или криптографические ключи), которые записываются на диск после сбоя.

Используя sysctl

Можно использовать sysctl, чтобы изменить kernel.core_pattern для отключения дампов. Создайте файл:

kernel.core_pattern=/dev/null

Для немедленного применения изменений используйте команду sysctl :

# sysctl -p /etc/sysctl.d/50-coredump.conf

Используя systemd

Поведение systemd по умолчанию определено в файле /usr/lib/sysctl.d/50-coredump.conf , который прописывает kernel.core_pattern для вызова systemd-coredump . Он сохраняет дампы ядра для всех процессов в /var/lib/systemd/coredump . Поведение systemd-coredump можно переопределить, создав в /etc/systemd/coredump.conf.d/ файл ( coredump.conf(5) § DESCRIPTION ,, [1]):

/etc/systemd/coredump.conf.d/custom.conf

Примечание: Не забудьте прописать имя секции [Coredump] , иначе опция будет проигнорирована.

Читайте также:  Android debug bridge linux

Одного этого метода обычно достаточно для отключения записи дампов, если в системе нет других программ, включающих автоматические дампы, но дамп памяти всё равно генерируется в памяти и systemd-coredump всё равно запускается.

Используя PAM limits

Максимальный размер дампа памяти для пользователей, вошедших в систему через PAM, задаётся в файле limits.conf. Установка нулевого значения полностью отключает дампы памяти. [2]

Используя ulimit

Командные оболочки вроде bash и zsh имеют встроенную команду ulimit, которую можно использовать для просмотра или изменения ограничений на ресурсы оболочки и запускаемых ею процессов. Подробнее смотрите bash(1) § SHELL BUILTIN COMMANDS или zshbuiltins(1) .

Отключение дампов памяти в текущей командной оболочке:

Создание дампа памяти

Чтобы сгенерировать дамп памяти произвольного процесса, сначала установите пакет gdb . Затем найдите PID запущенного процесса, например, с помощью pgrep:

Подключитесь отладчиком к этому процессу:

И затем в отладчике выполните:

(gdb) generate-core-file Saved corefile core.2071 (gdb) quit

Теперь у вас есть дамп памяти в файле core.2071 .

Куда они попадают?

sysctl kernel.core_pattern определяет, куда отправляются автоматические дампы памяти. По умолчанию их принимает systemd-coredump, который настраивается через файл /etc/systemd/coredump.conf . По умолчанию он записывает дампы в /var/lib/systemd/coredump (опция Storage=external ), сжимая их с помощью zstd (опция Compress=yes ). Кроме того, можно настроить различные ограничения на размер хранилища.

Примечание: Значение по умолчанию для kernel.core_pattern задаётся в файле /usr/lib/sysctl.d/50-coredump.conf . Этот файл может быть замаскирован или переопределён для использования другого значения в соответствии с обычными правилами sysctl.d(5) .

Чтобы получить дамп памяти из журнала, смотрите coredumpctl(1) .

Изучение дампа памяти

Команда coredumpctl покажет список сохранённых дампов, среди которых можно найти нужный:

Для поиска нужного дампа можно использовать PID, имя исполняемого файла, путь к исполняемому файлу или предикат journalctl (подробнее: coredumpctl(1) и journalctl(1) ). Просмотр подробностей о дампах ядра:

# coredumpctl info соответствие 

Обратите внимание на строку «Signal», она поможет определить причину сбоя. Для более глубокого анализа вы можете изучить backtrace с помощью gdb:

# coredumpctl gdb соответствие 

После запуска gdb можно использовать команду bt для получения backtrace:

Если отладочные символы нужны, но не найдены, можно попробовать получить их, как описано в статье Отладка/Трассировка.

Удаление дампов памяти

Файлы дампов памяти, хранящиеся в /var/lib/systemd/coredump/ , будут автоматически очищаться командой systemd-tmpfiles —clean , которая запускается ежедневно с помощью systemd-tmpfiles-clean.timer . Дампы памяти настроены на хранение не менее 3 дней, смотрите systemd-tmpfiles —cat-config .

Смотрите также

  • american fuzzy lop — Инструмент для автоматизированного тестирования ядра и программ
  • Filesystem fuzzing — Статья LWN о тестировании файловых систем на наличие ошибок

Источник

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