Linux how to dump memory

How to dump memory image from linux system?

I know to dump memory images in Windows. (eg-dumpit) But I don’t know how to dump memory images in Linux. I want to get memory images in Linux and from Linux to Linux with ssh connection or something. How can I get in Linux?

Are you trying to get memory from a running process, kernel memory or raw physical memory? All are available but methods for access differ. See /dev/kmem, /dev/mem, /proc/kcore, /proc/$pid/maps and /proc/$pid/mem .

3 Answers 3

Linux

/dev/mem

On older Linux systems, the program dd can be used to read the contents of physical memory from the device file /dev/mem. On recent Linux systems, however, /dev/mem provides access only to a restricted range of addresses, rather than the full physical memory of a system. On other systems it may not be available at all. Throughout the 2.6 series of the Linux kernel, the trend was to reduce direct access to memory via pseudo-device files. See, for example, the message accompanying this patch: http://lwn.net/Articles/267427/.

/dev/crash

On Red Hat systems (and those running related distros such as Fedora or CentOS), the crash driver can be loaded to create pseudo-device /dev/crash for raw physical memory access (via command «modprobe crash»). This module can also be compiled for other Linux distributions with minor effort (see, for example, http://gleeda.blogspot.com/2009/08/devcrash-driver.html). When the crash driver is modified, compiled, and loaded on other systems, the resulting memory access device is not safe to image in its entirety. Care must be taken to avoid addresses that are not RAM-backed. On Linux, /proc/iomem exposes the correct address ranges to image, marked with «System RAM».

Second Look: Linux Memory Forensics

This commercial memory forensics product ships with a modified version of the crash driver and a script for safely dumping memory using the original or modified driver on any given Linux system.

fmem fmem — github repo

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.

LiME — Linux Memory Extractor

Linux Memory Extractor (LiME) is a Loadable Kernel Module (LKM), which allows the acquisition of volatile memory from Linux and Linux-based devices, such as those powered by Android. The tool supports dumping memory either to the file system of the device or over the network.

Читайте также:  Verifying dmi pool data linux

I found this example of fmem in use, which seems to be the easiest way to dump memory for analysis purposes, you can no longer use /dev/mem after the 2.6.x kernels, as I understand it.

fmem Example

$ ./run.sh . ----Memory areas: ----- reg00: base=0x000000000 ( 0MB), size= 1024MB, count=1: write-back reg01: base=0x0c8800000 ( 3208MB), size= 2MB, count=1: write-combining ----------------------- . Don't forget add "count https://askubuntu.com/questions/147978/how-can-i-dump-all-physical-memory-to-a-file">How can I dump all physical memory to a file?

LiME Example

For analyzing volatile memory there's also this page, titled: Linux Memory Analysis. There's a thorough example in this video tutorial that shows the use of LiME and Volatility to collect a memory dump and then analyze it, extracting the user's Bash history from the memory dump.

  • Using LiME & Volatility to analyze Linux memory

What else?

There's also this U&L Q&A titled: How can I dump the full system memory? which has additional examples and information.

)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter " data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f4.0%2f" data-se-share-sheet-license-name="CC BY-SA 4.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
)">edited Aug 10, 2018 at 9:29
answered Mar 15, 2014 at 2:38
Add a comment|
1

rekall

Check out the rekall framework, they have a linpmem application for this purpose: http://www.rekall-forensic.com/docs/Tools/index.html

The SANS rekall memory forensic cheatsheet has an example of how to dump memory under linux too:

# ./linpmem_2.0.1 -o linux.aff4

Источник

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

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

Источник

Linux how to dump memory

NAME

SYNOPSIS

memdump [-kv] [-b buffer_size] [-d dump_size] [-m map_file] [-p page_size]

DESCRIPTION

This program dumps system memory to the standard output stream, skipping over holes in memory maps. By default, the program dumps the contents of physical memory (/dev/mem). Output is in the form of a raw dump; if necessary, use the -m option to capture memory layout information. Output should be sent off-host over the network, to avoid changing all the memory in the file system cache. Use netcat, stunnel, or openssl, depending on your requirements. The size arguments below understand the k (kilo) m (mega) and g (giga) suffixes. Suffixes are case insensitive. Options -k Attempt to dump kernel memory (/dev/kmem) rather than physical memory. Warning: this can lock up the system to the point that you have to use the power switch (for example, Solaris 8 on 64-bit SPARC). Warning: this produces bogus results on Linux 2.2 kernels. Warning: this is very slow on 64-bit machines because the entire memory address range has to be searched. Warning: kernel virtual memory mappings change frequently. Depending on the operating system, mappings smaller than page_size or buffer_size may be missed or may be reported incorrectly. -b buffer_size (default: 0) Number of bytes per memory read operation. By default, the program uses the page_size value. Warning: a too large read buffer size causes memory to be missed on FreeBSD or Solaris. -d dump-size (default: 0) Number of memory bytes to dump. By default, the program runs until the memory device reports an end-of-file (Linux), or until it has dumped from /dev/mem as much memory as reported present by the kernel (FreeBSD, Solaris), or until pointer wrap- around happens. Warning: a too large value causes the program to spend a lot of time skipping over non-existent memory on Solaris systems. Warning: a too large value causes the program to copy non-existent data on FreeBSD systems. -m map_file Write the memory map to map_file, one entry per line. Specify -m- to write to the standard error stream. Each map entry consists of a region start address and the first address beyond that region. Addresses are separated by space, and are printed as hexadecimal numbers (0xhhhh). -p page_size (default: 0) Use page_size as the memory page size. By default the program uses the system page size. Warning: a too large page size causes memory to be missed while skipping over holes in memory. -v Enable verbose logging for debugging purposes. Multiple -v options make the program more verbose.

BUGS

On many hardware platforms the firmware (boot PROM, BIOS, etc.) takes away some memory. This memory is not accessible through /dev/mem. This program should produce output in a format that supports structure information such as ELF.

LICENSE

This software is distributed under the IBM Public License.

Источник

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