Dump all memory linux

How do I dump physical memory in Linux?

How would one create a dump of the physical memory (RAM) in Linux? What software if any is available for this purpose? I have read that one should not write to a local disk but rather send the data over the network. Anyone know the peculiarities here? Would Ethernet work for this purpose, or are there any commands which minimize the amount of caching before sending to disk? WinHex on Windows has such functionality: I am looking for something similar on Linux.

4 Answers 4

Linux provides two virtual devices for this purpose, ‘ /dev/mem ‘ and ‘ /dev/kmem ‘, though many distributions disable them by default for security reasons. ‘ /dev/mem ‘ is linked to the physical system memory, whereas ‘ /dev/kmem ‘ maps to the entire virtual memory space, including any swap. Both devices work as regular files, and can be used with dd or any other file manipulation tool.

That leads to the ForensicsWiki page on Memory Imaging Tools with the Linux/Unix section,

  1. dd On Unix systems, the program dd can be used to capture the contents of physical memory using a device file (e.g. /dev/mem and /dev/kmem). In recent Linux kernels, /dev/kmem is no longer available. In even more recent kernels, /dev/mem has additional restrictions. And in the most recent, /dev/mem is no longer available by default, either. Throughout the 2.6 kernel series the trend has been to reduce direct access to memory via pseudo-device files. See, for example, the message accompanying this patch: http://lwn.net/Articles/267427/. On Red Hat systems (and derived distros such as CentOS), the crash driver can be loaded to create a pseudo-device for memory access («modprobe crash»).
  2. Second Look This commercial memory analysis product has the ability to acquire memory from Linux systems, either locally or from a remote target via DMA or over the network. It comes with pre-compiled Physical Memory Access Driver (PMAD) modules for hundreds of kernels from the most commonly used Linux distributions.
  3. Idetect (Linux)
  4. fmem (Linux)
    fmem is kernel module, that creates device /dev/fmem, similar to /dev/mem but without limitations. This device (physical RAM) can be copied using dd or other tool. Works on 2.6 Linux kernels. Under GNU GPL.
  5. Goldfish
    Goldfish is a Mac OS X live forensic tool for use only by law enforcement. Its main purpose is to provide an easy to use interface to dump the system RAM of a target machine via a Firewire connection. It then automatically extracts the current user login password and any open AOL Instant Messenger conversation fragments that may be available. Law Enforcement may contact goldfish.ae for download information.
Читайте также:  Astra linux перестал загружаться

See Also: Linux Memory Analysis.
There is also GDB commonly available on most Linuxes.
And, you are always advised to avoid writing over unknown memory — it can lead to system corruption.

Volatility seems to be working well and is Windows and Linux compatible.

Volatility supports memory dumps from all major 32- and 64-bit Windows versions and service packs including XP, 2003 Server, Vista, Server 2008, Server 2008 R2, and Seven. Whether your memory dump is in raw format, a Microsoft crash dump, hibernation file, or virtual machine snapshot, Volatility is able to work with it. We also now support Linux memory dumps in raw or LiME format and include 35+ plugins for analyzing 32- and 64-bit Linux kernels from 2.6.11 — 3.5.x and distributions such as Debian, Ubuntu, OpenSuSE, Fedora, CentOS, and Mandrake. We support 38 versions of Mac OSX memory dumps from 10.5 to 10.8.3 Mountain Lion, both 32- and 64-bit. Android phones with ARM processors are also supported.

They do not support capturing though. From the GitHub README: Volatility does not provide memory sample acquisition capabilities. For acquisition, there are both free and commercial solutions available.

Second Look is a good, easy way to dump memory in Linux: http://secondlookforensics.com/.

There also is a recently released kernel module you could try called LiME: http://code.google.com/p/lime-forensics/

As confirmation I was able to dump my CentOS 7.x VM’s memory using this method:

$ head /dev/mem | hexdump -C 00000000 53 ff 00 f0 53 ff 00 f0 53 ff 00 f0 53 ff 00 f0 |S. S. S. S. | 00000010 53 ff 00 f0 53 ff 00 f0 cc e9 00 f0 53 ff 00 f0 |S. S. S. | 00000020 a5 fe 00 f0 87 e9 00 f0 53 ff 00 f0 46 e7 00 f0 |. S. F. | 00000030 46 e7 00 f0 46 e7 00 f0 57 ef 00 f0 53 ff 00 f0 |F. F. W. S. | 00000040 22 00 00 c0 4d f8 00 f0 41 f8 00 f0 fe e3 00 f0 |". M. A. | 00000050 39 e7 00 f0 59 f8 00 f0 2e e8 00 f0 d4 ef 00 f0 |9. Y. | 00000060 a4 f0 00 f0 f2 e6 00 f0 6e fe 00 f0 53 ff 00 f0 |. n. S. | 00000070 ed ef 00 f0 53 ff 00 f0 c7 ef 00 f0 ed 57 00 c0 |. S. W..| 00000080 53 ff 00 f0 53 ff 00 f0 53 ff 00 f0 53 ff 00 f0 |S. S. S. S. | * 00000100 59 ec 00 f0 3d 00 c0 9f 53 ff 00 f0 ed 69 00 c0 |Y. =. S. i..| 00000110 53 ff 00 f0 53 ff 00 f0 53 ff 00 f0 53 ff 00 f0 |S. S. S. S. | * 00000180 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |. | 000afea0 00 00 00 00 00 00 00 00 aa aa aa 00 aa aa aa 00 |. | 000afeb0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |. | . . 000b0000 ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff |. | * 000c0000 55 aa 40 e9 62 0a 00 00 00 00 00 00 00 00 00 00 |U.@.b. | 000c0010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 49 42 |. IB| 000c0020 4d 00 9c 80 fc 0f 75 06 e8 4f 01 e9 bc 00 80 fc |M. u..O. | 

Given this 55aah occurring in the c0000h-effffh range it’s likely the PNP Expansion Header:

Читайте также:  Apache folder in linux

3.3 Devices with PnP Expansion Headers

All IPL devices with option ROMs must contain a valid option ROM header that resides between system memory addresses C0000h and EFFFFh on a 2k boundary and begins with 55AAh. A Device’s booting can only be controlled if it has a PnP Expansion Header. The Expansion Header, whose address resides within the standard option ROM header at offset +1Ah, contains important information used to configure the device. It also contains pointers to code in the device’s option ROM (BCV or BEV) that the BIOS will call to boot from the device. See Appendix A for the structure of the PnP Expansion Header. There are two ways an IPL device with a PnP Expansion Header can be booted. It must contain a BCV or a BEV.

References

Источник

Core dump (Русский)

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

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

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

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

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

Используя 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] , иначе опция будет проигнорирована.

Одного этого метода обычно достаточно для отключения записи дампов, если в системе нет других программ, включающих автоматические дампы, но дамп памяти всё равно генерируется в памяти и 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