systemd coredump что это

Core dump

A core dump is a file containing a process’s address space (memory) when the process terminates unexpectedly. Core dumps may be produced on-demand (such as by a debugger), or automatically upon termination. Core dumps are triggered by the kernel in response to program crashes, and may be passed to a helper program (such as systemd-coredump) for further processing. A core dump is not typically used by an average user, but may be passed on to developers upon request where it can be invaluable as a post-mortem snapshot of the program’s state at the time of the crash, especially if the fault is hard to reliably reproduce.

Contents

Disabling automatic core dumps

Users may wish to disable automatic core dumps for a number of reasons:

Using sysctl

sysctl can be used to set the kernel.core_pattern to nothing to disable core dump handling. Create this file

To apply the setting immediately, use sysctl :

Using systemd

Then reload systemd’s configuration.

This method alone is usually sufficient to disable userspace core dumps, so long as no other programs enable automatic core dumps on the system, but the coredump is still generated in memory and systemd-coredump run.

Using PAM limits

The maximum core dump size for users logged in via PAM is enforced by limits.conf. Setting it to zero disables core dumps entirely. [3]

Using ulimit

Command-line shells such as bash or zsh provide a builtin ulimit command which can be used to report or set resource limits of the shell and the processes started by the shell. See bash(1) § SHELL BUILTIN COMMANDS or zshbuiltins(1) for details.

To disable core dumps in the current shell:

Making a core dump

To generate a core dump of an arbitrary process, first install the gdb package. Then find the PID of the running process, for example with pgrep:

Attach to the process:

Then at the (gdb) prompt:

Where do they go?

Examining a core dump

Use coredumpctl to find the corresponding dump:

Pay attention to «Signal» row, that helps to identify crash cause. For deeper analysis you can examine the backtrace using gdb:

When gdb is started, use the bt command to print the backtrace:

See Debugging/Getting traces if debugging symbols are requested, but not found.

Источник

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

systemd coredump что это. Смотреть фото systemd coredump что это. Смотреть картинку systemd coredump что это. Картинка про systemd coredump что это. Фото systemd coredump что это

Эта статья призвана познакомить читателя с находящимся в арсенале systemd набором инструментов.

Когда наконец удается смириться с уходом systemd от тех принципов, что лежали в основе ветхозаветной System V с ее простыми текстовыми файлами и засильем скриптов, начинаешь видеть неоспоримые преимущества новой системы инициализации и поставляемых с ней инструментов. В этой статье мы поговорим о четырех из них, а также упомянем еще один, который вы наверняка уже знаете, но вряд ли использовали описанным здесь способом.

coredumpctl

Этот инструмент, как услужливо подсказывает его имя, используется для получения дампов памяти из журнала systemd.

Команда coredumpctl вернет общий список всех дампов памяти, в котором могут быть записи за несколько недель, а то и месяцев работы системы.

systemd coredump что это. Смотреть фото systemd coredump что это. Смотреть картинку systemd coredump что это. Картинка про systemd coredump что это. Фото systemd coredump что это

Рис. 1. coredumpctl выводит список всех дампов памяти, зарегистрированных в журнале

Эта команда выведет все детали последнего дампа с PID 1758. А поскольку журнал systemd охватывает более одной сессии (мой, например, начинается с мая), в нем могут оказаться несколько не связанных друг с другом дампов от процессов с одинаковым PID.

systemd coredump что это. Смотреть фото systemd coredump что это. Смотреть картинку systemd coredump что это. Картинка про systemd coredump что это. Фото systemd coredump что это

Рис. 2. Модификатор dump позволяет получить более подробную информацию о дампе памяти

Также есть возможность установить фильтр по имени исполняемого файла:

Как и в случае с PID, эта команда выведет информацию только о последнем дампе, поскольку в большинстве случаев нужен именно он.

В фильтре дампа памяти может использоваться PID, имя исполняемого файла, путь, который должен содержать как минимум одну косую черту (например, /usr/bin/name_of_executable), а также один или несколько общих предикатов (general predicates) journalctl. Последний вариант показан в следующем примере:

Помимо dump у сoredumpctl есть и другие опции. Для тех, кто хочет сразу начать отладку, следующая команда не только выведет всю информацию о дампе, но и откроет GNU debugger (gdb):

bootctl

А вы знаете, что загрузкой теперь управляет systemd-boot, а не GRUB? Да, это очередная функция, которую подмял под себя, кажется, уже не способный остановиться systemd. Правда, это пока касается только систем с UEFI.

Обучение настройке загрузчика выходит за рамки данной статьи (если вам действительно интересно, найти полезную информацию можно здесь), однако для установки пользовательской конфигурации загрузки необходимы хотя бы базовые знания bootctl.

(Если вы новичок в Linux, не пугайтесь. Вам, скорее всего, не придется делать ничего из представленного в данном разделе. Об этом позаботится ваш дистрибутив. Все, что здесь написано, в первую очередь предназначено для энтузиастов абсолютного контроля (например, пользователей Arch Linux). Эти люди не могут спать спокойно, пока в их системе остался хотя бы один параметр, который они не пробовали подкрутить.)

Для работы с bootctl нужны права суперпользователя, поэтому обращаться с этим инструментом нужно уважительно. Одно неосторожное движение — и ваша система перестанет загружаться.

Один из самых безобидных режимов bootctl — проверка статуса загрузки. Если /boot не указывает на раздел FAT EFI напрямую, нужно вручную с помощью опции —path= указать путь к загрузочному разделу EFI. Вот как выглядит команда для моей openSUSE:

systemd coredump что это. Смотреть фото systemd coredump что это. Смотреть картинку systemd coredump что это. Картинка про systemd coredump что это. Фото systemd coredump что это

Рис. 3. Инструмент bootctl позволяет просматривать и изменять настройки программы управления загрузкой

В выводе команды можно найти опции загрузки и расположение бинарного файла загрузчика (ESP).

Измененная конфигурация загрузки устанавливается с помощью команды:

Эта команда также сгенерирует бинарный файл systemd-boot, сохранит его в boot/path/to/efi/EFI/Boot и добавит соответствующий вызов в верхнюю часть списка приоритета загрузки.

Чтобы обновить systemd-boot, выполните:

Для удаления systemd-boot из раздела EFI используйте:

Будьте осторожны с последней командой.

systemd-cgtop, systemctl и systemd-cgls

Если классический top позволяет найти процессы, больше других нагружающие CPU и активнее потребляющие память, systemd-cgtop делает то же самое для контрольных групп (cgroups).

Cgroups представляет из себя механизм разбиения и изолирования ресурсов системы для предоставления их группам пользователей и задач. Например, вы можете применить cgroups для установки ограничений на потребление памяти и CPU в системе, где работают две группы пользователей. Полное описание cgroups с примерами можно найти здесь.

systemd использует cgroups для контроля своих служб, а systemd-cgtop позволяет убедиться, что все группы ведут себя прилично. Если кто-то все-таки начал безобразничать, можно одним махом завершить работу сразу всей группы, а не разыскивать и останавливать каждый процесс в отдельности.

Взгляните на рисунок 4, где изображен пример нормально работающей системы. Никто не злоупотребляет ресурсами, и числового обозначения в строке с итогами удостоились только общие показатели активности всех групп системы. При этом я мог бы избавиться, например, от auditd, веди он себя неподобающим образом. И поскольку система без этого сервиса не остановится, так и сделаю:

И… та-дам! Его больше нет!

systemd coredump что это. Смотреть фото systemd coredump что это. Смотреть картинку systemd coredump что это. Картинка про systemd coredump что это. Фото systemd coredump что это

Рис. 4 systemd-cgtop сообщает о поведении cgroups

В данном случае у auditd.service были две связанные с ним задачи, но их могут быть сотни, особенно у групп, используемых для конечных пользователей, поэтому systemctl очень удобен для работы с cgroups.

Кстати, чтобы посмотреть, какие процессы связаны с той или иной cgroup, попробуйте команду systemd-cgls /cgroup.name

И вы увидите все процессы, работающие в подгруппе NetworkManager.

Заключение

Мы рассмотрели лишь малую часть предназначенных для системного администрирования инструментов systemd. Их, конечно, намного больше, и в следующей статье мы поговорим еще о нескольких. Также стоит помнить, что настоящая сила многих инструментов скрыта в их многочисленных опциях.

Если вы хотите получше разобраться в вопросах, связанных с systemd, рекомендую начать с идущей в комплекте документации:

Источник

Linux: создание coredump памяти процесса, systemd-coredump и Debian

Возникла необходимость получить дамп РНР-процесса на Debian 9.

Рассмотрим механизм ядра, позволящий создать дамп, и настройку создания дампов в Linux.

Ниже будем говорить о создании дампа памяти процесса в Linux, а не дампа ядра при kernel panic – там он иной, см. Kdump на Arch Wiki.

Linux Core Dump

Ядро создаёт дамп памяти процесса, если он выполнил недопустимую операцию, и должен быть остановлен.

Для этого при выполнении такой операции ядро отправляет один из аварийных сигналов процессу, после чего процесс обрабатывает сигнал сам, или с помощью сторонних обработчиков, что запускает механизм ядра, который создаёт дамп.

Список таких сигналов задаётся в макросе SIG_KERNEL_COREDUMP_MASK :

Который используется в другом макросе – sig_kernel_coredump :

Который срабывает в случае Fatal-ошибок, и вызывает do_coredump() :

Ну а сама do_coredump() создаёт дамп.

Сигналы и создание дампа

Проверим работу дампа.

Берём простой код на Си:

Собираем, и запускаем:

Во второй консоли – отправляем один из сигналов, например SIGSEGV (Segmentation violation), код 11:

В окне с приложением проверяем:

Проверяем файл дампа:

Аналогично можно создать дамп практически любого процесса, например – запустим sleep :

GDB – создать core dump

GDB – прочитать core dump

kernel.core_pattern

Тут можно задать путь и имя файла, в который будет записан дамп, либо передать создание дампа внешнему обработчику, например systemd-coredump (рассмотрим ниже).

См. документацию Naming of core dump files тут>>>.

Из наиболее используемых опций тут:

Собственно файл /tmp/coredump-make_dump.2714790, который мы открыли в GDB, и состоит из kernel.core_pattern = /tmp/coredump-%e.%p :

limits.conf

Кроме имени файла – ядро проверит значение soft и hard лимитов для core в /etc/security/limits.conf :

Либо проверяем в рабочем окружении:

Лимиты конкретного процесса можно получить через его дескриптор в /proc :

fs.suid_dumpable

Определяется флагом fs.suid_dumpable :

Может принимать значение 0, 1 или 2, см. man proc:

systemd-coredump

На Arch Linux он используется по-умолчанию, на Debian 9 ставим из репозитория:

После установки настраиваем ядро – через пайп передаём создание дампа в systemd-coredump :

Создаём дамп какого-то процесса:

coredumpctl

Для работы с дампами через systemd-coredump – используем coredumpctl :

Сами файлы дампов systemd-coredump сохраняет в /var/lib/systemd/coredump :

Просмотреть дамп – передаём условие для MATCH, например – PID:

Источник

Systemd coredump что это

systemd-coredump, systemd-coredump.socket, systemd-coredump@.service — Acquire, save and process core dumps

Synopsis

DescriptionВ¶

Invocation of systemd-coredump В¶

The systemd-coredump executable does the actual work. It is invoked twice: once as the handler by the kernel, and the second time in the systemd-coredump@.service to actually write the data to the journal and process and save the core file.

When the kernel invokes systemd-coredump to handle a core dump, it runs in privileged mode, and will connect to the socket created by the systemd-coredump.socket unit, which in turn will spawn an unprivileged systemd-coredump@.service instance to process the core dump. Hence systemd-coredump.socket and systemd-coredump@.service are helper units which do the actual processing of core dumps and are subject to normal service management.

ConfigurationВ¶

Disabling coredump processingВ¶

Information about the crashed processВ¶

coredumpctl (1) can be used to retrieve saved core dumps independently of their location, to display information, and to process them e.g. by passing to the GNU debugger (gdb).

Data stored in the journal can be also viewed with journalctl (1) as usual (or from any other process, using the sd-journal (3) API). The relevant messages have MESSAGE_ID=fc2e22bc6ee647b6b90729ab34a250b1 :

The following fields are saved (if known) with the journal entry

The process number (PID), owner user number (UID), and group number (GID) of the crashed process.

The time of the crash as reported by the kernel (in Вµs since the epoch).

The system unit and slice names.

When the crashed process was in a container, this is the full path, as seen outside of the container.

The numerical UID of the user owning the login session or systemd user unit of the crashed process, and the user manager unit. Both fields are only present for user processes.

The terminating signal name (with the » SIG » prefix [1] ) and numerical value. (Both are included because signal numbers vary by architecture.)

The current working directory and root directory of the crashed process.

When the crashed process is in a container, those paths are relative to the root of the container’s mount namespace.

Information about open file descriptors, in the following format:

The destination of the /proc/ pid /exe symlink.

When the crashed process is in a container, that path is relative to the root of the container’s mount namespace.

Fields that map the per-process entries in the /proc/ filesystem: /proc/ pid /comm (the command name associated with the process), /proc/ pid /exe (the filename of the executed command), /proc/ pid /status (various metadata about the process), /proc/ pid /maps (memory regions visible to the process and their access permissions), /proc/ pid /limits (the soft and hard resource limits), /proc/ pid /mountinfo (mount points in the process’s mount namespace), /proc/ pid /environ (the environment block of the crashed process).

See proc (5) for more information.

The system hostname.

When the crashed process was in container, this is the container hostname.

For processes running in a container, the commandline of the process spawning the container (the first parent process with a different mount namespace).

When the core is stored in the journal, the core image itself.

When the core is stored externally, the path to the core file.

Set to » 1 » when the saved coredump was truncated. (A partial core image may still be processed by some tools, though obviously not all information is available.)

The following fields are saved (if known) with the external file listed in COREDUMP_FILENAME= as extended attributes:

See AlsoВ¶

[1] kill (1) expects signal names without the prefix; kill (2) uses the prefix; all systemd tools accept signal names both with and without the prefix.

Источник

Understand and configure core dumps on Linux

Every system needs running processes to fulfill its primary goal. But sometimes things go wrong and a process may crash. Depending on the configuration of the system a core dump is created. In other words, a memory snapshot of the crashed process is stored. The term core actually refers to the old magnetic core memory from older systems. Although this type of memory is no longer being used, we still use this term on Linux systems. Enough for history, let’s configure our Linux system to properly handle core dumps.

Linux and core dumps

Most Linux systems have core dumps enabled by default. As always, there is a tradeoff to make here. On one hand, we want to gather data for improved stability and troubleshooting. On the other, we want to limit the debug data and avoid leaking sensitive data.

The first option is good for machines where unstable programs need to be investigated, like the workstation of a developer. The second option is better suited for production systems storing or processing sensitive data.

Disable core dumps

It makes sense to disable any core dumps on Linux by default for all your systems. This is because the files take up disk space and may contain sensitive data. So if you don’t need the core dumps for troubleshooting purposes, disabling them is a safe option.

Option 1: ulimit via the configuration file

To disable core dumps we need to set a ulimit value. This is done via the /etc/security/limits.conf file and defines some shell specific restrictions.

Good to know is that there are soft and hard limits. A hard limit is something that never can be overridden, while a soft limit might only be applicable for specific users. If we would like to ensure that no process can create a core dump, we can set them both to zero. Although it may look like a boolean (0 = False, 1 = True), it actually indicates the allowed size.

The asterisk sign means it applies to all users. The second column states if we want to use a hard or soft limit, followed by the columns stating the setting and the value.

Option 2: configure ulimit via profile

The values for ulimit can also be set via /etc/profile or a custom file in the /etc/profile.d directory. The latter is preferred when it is available. For example by creating a file named /etc/profile.d/disable-coredumps.sh.

This command adds the setting to a new file and sets both the soft and hard limit to zero. Each user gets this value when logging in.

Besides ulimit settings, there are also kernel settings to consider. So choosing one of the options is the first step.

Option 3: disable via systemd

When using systemd and the systemd-coredump service, change the coredump.conf file. This file is most likely located at /usr/lib/sysctl.d/50-coredump.conf. As systemd has a set of files, ensure to check the others like:

Set the Storage setting to ‘none’. Then configure ProcessSizeMax to limited the maximum size to zero.

Typically it is sufficient to just reload the systemd configuration.

If this still creates a core dump, then reboot the system.

Disable setuid processes dumping their memory

Processes with elevated permissions (or the setuid bit), might be still able to perform a core dump, depending on your other settings. As these processes usually have more access, they might contain more sensitive data segments in memory. So time to change this as well. The behavior can be altered with a sysctl key, or directly via the /proc file system. For permanent settings, the sysctl command and configuration is typically used. A setting is called a ‘key’, which has a related value attached to it (also known as a key-value pair).

To disable program with the setuid bit to dump, set the fs.suid_dumpable to zero.

Reload the sysctl configuration with the -p flag to activate any changes you made.

Tip: Using sysctl you can tune your system and is a good way to harden the Linux kernel.

Enable core dumps

The primary reason to allow core dumps is for troubleshooting purposes. The dumped memory of the process can be used for debugging issues, usually by more experienced developers. A software vendor may ask to enable core dumps. Usually to discover why a process crashed in the first place and find the related routine that caused it.

Next step is to only allow ‘my-program-to-troubleshoot’ to create a core dump.

If you want to allow all processes to use core dumps, use the line above without the program, or set a system limit in /etc/security/limits.conf

Troubleshoot setuid binaries

Binaries that have a setuid bit set, can run with root permissions. This special type of access needs to be restricted as much as possible. Also for the creation of core dumps, it needs to be configured properly. This is done with the sysctl fs.suid_dumpable key.

So if you like to troubleshoot programs with a setuid bit set, you can temporarily change the fs.suid_dumpable to 1 or 2. Setting it to 2 is preferred as this makes the core dumps only readable to the root user. This is a good alternative for systems with sensitive data. Setting the option to 1 is better suited for personal development systems.

Create normal dump files

One of the big mysteries with Linux systems is where the core dumps are located. Linux has a trick in place to capture core dumps. This particular setting is done via the sysctl kernel.core_pattern setting or /proc/sys/kernel/core_pattern. Most systems will have a pipe ( | ) in this setting to indicate that a program needs to take care of the generated data. So if you wonder where your core dump goes, follow the pipe!

Core dumps on Ubuntu systems are typically going to Apport. For Red Hat based systems it may be redirected to Automatic Bug Reporting Tool (ABRT).

You can temporarily change this setting, by echoing “core” to that file, or use the sysctl utility.

An important note is that this change might not be enough. It depends also on your fs.suid_dumpable setting. A warning will be logged to your kernel logger if that is the case.

Sep 06 15:51:18 hardening kernel: Unsafe core_pattern used with suid_dumpable=2. Pipe handler or fully qualified core dump path required.

When needed set your core_pattern to a full path, optionally with variables defining who was running it, the PID, etc.

In this example, our dumps will contain the user id, program name, and process id.

Systemd core dumps

When using a modern Linux distribution you will most likely have systemd enabled. You might need to override settings via /etc/sysctl.d/50-coredump.conf and define how and where you want to store your core dumps.

Using systemd-coredump

Your kernel.core_pattern may be defined to use the systemd-coredump utility. The default path where core dumps are stored is then in /var/lib/systemd/coredump.

Testing your configuration

Most other tutorials just give you the settings to be configured. But how would you know things work as expected? You will need to test it!

Create a core dump

Option 1: Create an unstable program

Let’s create a simple program. Its primary goal is to crash when being executed and then optionally create a core dump. Install gcc on your system and create a file crash.c in your home directory.

This program will start the main function and return an integer value (number). However, it is dividing 1 by zero, which is not allowed and will crash. The next step is compiling our little buggy program.

systemd coredump что это. Смотреть фото systemd coredump что это. Смотреть картинку systemd coredump что это. Картинка про systemd coredump что это. Фото systemd coredump что это

Our unstable little program

Even the compiler shows our program contains a serious issue and displays a warning about it. Now let’s run it and see if this is the case.

systemd coredump что это. Смотреть фото systemd coredump что это. Смотреть картинку systemd coredump что это. Картинка про systemd coredump что это. Фото systemd coredump что это

From this single line, we can actually learn a few things. First of all that it quit with an exception, specifically referring to floating points. This is a decimal number format for programs, so it may indicate that something happened while doing some math. Another conclusion is that the core is dumped due to the (core dumped) addition at the end. If core dumps were disabled, this would not appear.

Great, so with this crash above we have now a dumped file, right? Not exactly. Depending on your Linux distribution things might not as simple as it looks. Each distribution deals differently with core dumps and the default settings. Most recent Linux distributions also use systemd now and the rules have slightly been changed with that as well. Depending on your configuration, you might need to search for your core dumps. So here are some tips to ensure everything is configured correctly.

Option 2: kill a running process

Instead of using a test program, you can also terminate an existing process. This is done by using the SIGSEGV, which is short for segmentation violation and also known as a segmentation fault.

If you replace PID with “$$” the current program (most likely your shell) will crash. Everything for science, right?

Option 3: using gdb

If you have the developer debugging tool gdb installed, then attach to a process of choice using its process ID (PID).

Then when at the gdb prompt, generate the core dump by invoking the generate-core-file instruction. After using this command, it should return you output.

Check ulimit settings

The ulimit settings define what may happen when a program crashes. So it is safe to first check this, for both root and a normal non-privileged user.

Check hard limit for core dumps:

Check soft limit as well:

Check the core pattern

Use the /proc file system to gather the value and change it temporarily during testing. If you prefer using sysctl, then query the kernel.core_pattern key.

It might show something like this:

In this case, a crash will be piped to the apport utility. So this means that crashes are going to be analyzed by Apport. Normally crashes are found in /var/crash, but may also be in /var/spool or /var/lib/systemd/coredump on other Linux distributions.

Check the journal (systemd)

In our case journalctl shows our crash, so that’s a start.

Sep 06 15:19:23 hardening kernel: traps: crash[22832] trap divide error ip:4004e5 sp:7fff4c2fc650 error:0 in crash[400000+1000]

After checking all these settings you should be able to create a nice core dump.

Conclusion

Core dumps can be useful for troubleshooting, but a disaster for leaking sensitive data. Disable core dumps when possible, and only enable them when really needed. In such case check if the files are stored safely, so normal users can’t see the data. And independently of what choice you made, always test if your configuration does work exactly as you expect it to work.

Do you have other tips regarding core dumps? Share them in the comments!

Keep learning

So you are interested in Linux security? Join the Linux Security Expert training program, a practical and lab-based training ground. For those who want to become (or stay) a Linux security expert.

Run automated security scans and increase your defenses. Lynis is an open source security tool to perform in-depth audits. It helps with system hardening, vulnerability discovery, and compliance.

Continue reading

No related posts found.

9 comments

I want to disable core dumps completely.
I followed the steps provided by you and did the changes.

1. appended in the /etc/security/limits.conf
* hard core 0

2. In /etc/sysctl.conf changed
fs.suid_dumpable=0

4. There are no extra files in /etc/security/limits.d/*conf
that overwrites the /etc/security/limits.conf entry.

6. core pattern is “cat /proc/sys/kernel/core_pattern”
|/opt/sonus/platform/core.sh %e %p %h %t
where core.sh is a script we have to simplify and write the cores

SO HERE using crash program I am still getting the core dump

7. But if core pattern is “cat /proc/sys/kernel/core_pattern” simply a file say
/opt/sonus/platform/core.%e %p %h %t
then cores are disabled

So when I am using pipe why am I getting core dumps even after disabling them.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *