0% found this document useful (0 votes)
34 views

Linux Persistance

The document describes several techniques an attacker could use to maintain persistent access on a compromised Linux system. These include creating new user accounts, modifying SSH authorized keys, creating scheduled tasks using cron jobs or systemd timers, modifying shell configurations, using SUID binaries, and creating custom systemd services. The summary provides details on how to detect these techniques using Wazuh's file integrity monitoring and system auditing capabilities.

Uploaded by

roman16kov
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Linux Persistance

The document describes several techniques an attacker could use to maintain persistent access on a compromised Linux system. These include creating new user accounts, modifying SSH authorized keys, creating scheduled tasks using cron jobs or systemd timers, modifying shell configurations, using SUID binaries, and creating custom systemd services. The summary provides details on how to detect these techniques using Wazuh's file integrity monitoring and system auditing capabilities.

Uploaded by

roman16kov
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Linux Persistance (in progress)

User Account Creation


If attacker has compromised the host and want to maintain the persistence access by creating an normal user account , then we can user `useradd` like
so :

1 # create a user account with an home directory in /home/username


2 sudo useradd -m <username>
3 # to be able to login into the created account , an password should be set for that account
4 sudo passwd <username>
5 # now add the user to suoders group
6 sudo usermod -aG sudo <username>

Detect this persistence technique with Wazuh:


Cyber threat actors can modify existing account credentials to persist on compromised endpoints. Local accounts or users are stored in the
/etc/passwd file of Linux endpoints. The usermod , chage , and passwd commands modify existing user account details, such as username,

password, shells, and more. These commands modify the /etc/shadow , /etc/gshadow , /etc/passwd , /etc/group , and
/etc/login.defs configuration files containing user account information.

You can monitor file modifications using the Wazuh FIM module to detect this persistence technique. By default, Wazuh detects remote SSH
connections in case modified accounts are used to access compromised endpoints remotely.

Persistance using SSH Authorized Keys

For maintaining the Persistence access to the Machine , an adversary may modify the authorized_keys file to maintain persistence on the victim
host. Hers is how it goes . These file is usually found in <user-home/.ssh/authorized_keys> .

An adversary can generate the SSH keys using ssh-keygen it will generate the public key id_rsa.pub like so :

1 ssh-keygen -t rsa -b 2048


2 Your identification has been saved in /home/user/.ssh/id_rsa.
3 Your public key has been saved in /home/user/.ssh/id_rsa.pub.

for evading the detection , we can also replace the name at the end to something legitimate eg : ssh-rsa
AAAAB3NzaC1yc2EAAAADAQABAAABgQCwIqohDVyEsHt5l…… [email protected]

To detect this persistence technique with Wazuh, configure the file integrity monitoring (FIM) module to monitor the creation and modification
of the ~/.ssh/authorized_keys and /etc/ssh/sshd_config files. The Wazuh FIM module monitors selected file paths on a filesystem and
triggers alerts when files are created, modified, or deleted.

Persistence using Scheduled task


Persistence access to the machine can be done by creating the several specific schedule task , there usually two of creating the schedule task `cronjobs
modification/creaton` or `malicious timer modification/creation`

Cron Jobs
Cronjobs are the way of creating a schedule task in linux machine.

we can create our malicious cron job to give us persistence access , usually these are done by configuring the specific files , here are few of them :

– `/etc/crontab`

– `/etc/cron.d/*`

– `/etc/cron.{hourly,daily,weekly,monthly}/*`

– `/var/spool/cron/crontab/*`
crontab -e - це команда в Unix-подібних операційних системах, яка відкриває редактор для редагування вашого файлу cron таблиці.

Файл cron таблиці містить розклад завдань, які будуть автоматично виконуватися в певний час або періодично на вашій системі.

1 0 2 * * * /шлях_до_команди_або_скрипта

Запис 0 2 * * * вказує на те, що завдання буде виконуватися о 2:00 ранку щоденно, оскільки значення у стовпчику "Мінута" рівне 0, а у
стовпчику "Година" рівне 2. Зірочка (*) вказує на те, що конкретні значення в цих полях не враховуються, і завдання виконуватиметься
щоденно о 2:00 ранку.

Shell Configuration Modification


The shell in linux is the most crucial part of its environment , but it does load with lots of other configuration files , that are executed whenever the
shell start or ends.

Try to first modify the ~/.profile or /etc/profile to hide yourself without braking the shell normal configuration:

1 # Make the script at /opt/backdoor.sh executable:


2 chmod +x /opt/backdoor.sh
3 # Execute /opt/backdoor.sh:
4 /opt/backdoor.sh

To detect this persistence technique, monitor for changes in shell configuration scripts using the Wazuh FIM module.

Using SUID for Persistence

In the context of Linux system administration or security, SUID can be used for persistence by allowing a non-privileged user to execute a binary
with higher privileges. However, it’s important to note that this can be a significant security risk if misused or implemented without proper
safeguards.

Create a Script: First, write a script that performs the desired task. For example, a script to list contents of a root-owned directory:

1 #!/bin/bash ls /root
2 # Save and Make Executable: Save this script as listRootDir.sh and make it executable:
3 chmod +x listRootDir.sh
4 # Change Ownership: Change the ownership of the script to root:
5 sudo chown root:root listRootDir.sh
6 # Set SUID Bit: Set the SUID bit on the script:
7 sudo chmod u+s listRootDir.sh

rc.common/rc.local
Location: Typically, rc.local is located at /etc/rc.local .

Purpose: It’s executed by the init system at the end of the boot process.

Custom Commands: Administrators can place custom startup commands in this file.

Using rc.local for Persistence


1. Edit rc.local : Open the rc.local file with a text editor. You need root privileges to edit it.

1 sudo nano /etc/rc.local

Add Commands: Before the exit 0 line, add the commands or scripts you want to execute at startup.

Make rc.local Executable: If rc.local is not already executable, change its permissions:
1 sudo chmod +x /etc/rc.local

Reboot: Reboot your system to test if the script runs at startup.

Якщо ви хочете запустити спеціальний сервіс під час завантаження, ви можете додати рядок до rc.local :

1 sudo /usr/bin/myservice

To detect this persistence technique with Wazuh use:

Auditd: An auditing framework that collects and stores system events such as operating system calls, functions, and file access events. It is used to
monitor the creation, modification, or deletion of the /etc/rc.local file

Linux endpoint configuration:

1 # Install “auditd” using the following command:


2 apt install auditd -y
3 # Add the following auditd rules to the /etc/audit/rules.d/audit.rules file to detect the creation, modifica
4 echo "-w /etc/rc.local -p wa -k possible_rcscript_attack" >> /etc/audit/rules.d/audit.rules
5 # Reload the auditd rules file and verify the above configuration is applied:
6 auditctl -R /etc/audit/rules.d/audit.rules
7 auditctl -l

Append the following configuration to the Wazuh agent /var/ossec/etc/ossec.conf file. This configuration forwards auditd logs to the
Wazuh server and configures command monitoring.

1 <ossec_config>
2 <!-- Forwarding auditd logs to the Wazuh server -->
3 <localfile>
4 <log_format>audit</log_format>
5 <location>/var/log/audit/audit.log</location>
6 </localfile>
7
8 <!-- Command monitoring (command executes every 180 seconds) -->
9 <localfile>
10 <log_format>command</log_format>
11 <command>ps -ef | grep "[/]etc/rc.local" | awk '{print $3}'</command>
12 <alias>ppid of rc_local</alias>
13 <frequency>180</frequency>
14 </localfile>
15
16 <localfile>
17 <log_format>command</log_format>
18 <command>systemctl show rc-local.service --property=ActiveState | awk -F"=" '{print $2}'</command>
19 <alias>state of rc_local service</alias>
20 <frequency>180</frequency>
21 </localfile>
22 </ossec_config>

Systemd Services
Using systemd services is a modern and efficient way to achieve persistence in Linux. systemd is the init system and service manager in most
Linux distributions, responsible for bootstrapping the user space and managing system processes after booting. By creating a custom systemd
service, you can ensure that specific applications or scripts run automatically at system startup.

Creating a Custom systemd Service

1. Write Your Script: First, create the script you want to run at startup. For example, create a script named script.sh :

1 #!/bin/bash
2 echo "My custom service is running" > /tmp/custom_service.log
1 # Make sure to make your script executable:
2 chmod +x /path/to/my_script.sh
3 # Create a Service File: Create a new systemd service file in /etc/systemd/system/. For example, my_custom_se
4 sudo nano /etc/systemd/system/my_custom_service.service

Add the following content to the service file:

1 [Unit]
2 Description=My custom service
3 After=network.target
4
5 [Service]
6 Type=simple
7 ExecStart=/path/to/script.sh
8 Restart=on-abort
9
10 [Install]
11 WantedBy=multi-user.target

1 Description - короткий опис сервісу


2 After - визначає порядок запуску служб
3 Type - тип запуску служби, simple є найпоширенішим
4 ExecStart - команда для запуску
5 Restart - коли перезапускати сервіс
6 WantedBy - визначає ціль, до якої має бути приєднаний сервіс

Reload systemd Daemon: After creating the service file, reload the systemd daemon to read the new service file:

1 sudo systemctl daemon-reload

Enable and Start Your Service: Enable your service to start on boot, and then start the service immediately:

1 sudo systemctl enable my_custom_service.service


2 sudo systemctl start my_custom_service.service
3 # Check the Status: To check the status of your new service:
4 sudo systemctl status my_custom_service.service

Systemd Timers
This is yet another uncommon approach of getting persistence access to linux machine. so , what happens is , usually all the services within the linux
machine are triggered on boot time , they have specific init entry in boot process. but these services can be triggered at specific times also using
`timers`.

To see the timers within the machines we can using the following command :

1 systemctl list-timers

to create our malicious `timer` file persistence access , we would need two things :

1 Malicious `.service` File


2 Malicious `.timer` File
Backdooring user startup file
Backdooring a user’s startup file in Linux is a method used to achieve persistence by inserting commands into files that are automatically executed
when the user logs in. Commonly targeted files include ~/.bashrc , ~/.profile , or ~/.bash_profile for users who use the Bash shell.

1 nano ~/.bashrc
2 #Insert Command: Add your command at the end of the file.
3 echo "Shell opened at $(date)" >> ~/.shell_usage_log

To detect this persistence technique, monitor for changes in shell configuration scripts using the Wazuh FIM module.

You might also like